From 79cbb84d61b8b7e0a5907646f9880dd1cfe96d09 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Mon, 2 Nov 2026 03:33:34 -0500 Subject: [PATCH] Snapshot for release 2026.11.2.1 (internal 03dbb32) --- .../ActivityArbiter.cs | 31 +- .../RynthCore.Plugin.RynthAi/BuildingMap.cs | 630 ++++++++++++ .../Combat/CombatManager.Hunt.cs | 46 + .../Combat/CombatManager.Offhand.cs | 38 +- .../Combat/CombatManager.cs | 87 +- .../Combat/OffhandPlanner.cs | 29 +- .../Combat/PetManager.cs | 4 + .../CorpseOpenController.cs | 23 +- .../Dashboard/InstrumentDashboard.cs | 17 +- .../Diagnostics/TickGuard.cs | 2 + .../DungeonGeometry.cs | 16 + .../DungeonPathfinder.cs | 2 +- .../ItemTool/ChestKeyLooter.cs | 496 ++++++++++ .../ItemTool/QuickGive.cs | 234 +++++ .../LegacyUi/LegacyAdvancedSettingsUi.cs | 5 + .../LegacyDashboardRenderer.Instrument.cs | 6 +- .../LegacyUi/LegacyDashboardRenderer.cs | 17 + .../LegacyUi/LegacyNavigationUi.cs | 12 + .../LegacyUi/LegacyUiSettings.cs | 21 + .../MagToolsCommands.cs | 2 + .../Meta/ExpressionEngine.cs | 2 + .../RynthCore.Plugin.RynthAi/NavRecovery.cs | 5 +- .../NavigationEngine.cs | 148 ++- .../RynthCore.Plugin.RynthAi/OutdoorHunt.cs | 591 +++++++++++ .../RynthCore.Plugin.RynthAi/PluginExports.cs | 36 + .../Raycasting/DungeonLOS.cs | 11 +- .../RynthAiCommands.cs | 167 +++- .../RynthAiPlugin.BoostNav.cs | 51 + .../RynthAiPlugin.ChestLoot.cs | 40 + .../RynthAiPlugin.Dashboard.cs | 3 + .../RynthAiPlugin.ItemTool.cs | 592 +++++++++++ .../RynthAiPlugin.LocalFeatures.cs | 2 + .../RynthAiPlugin.OutdoorHunt.cs | 452 +++++++++ .../RynthAiPlugin.Safety.cs | 5 + .../RynthAiPlugin.VTankHotkeys.cs | 6 +- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 36 +- .../ScriptInterface.cs | 6 +- .../UtilityBeltExtraCommands.cs | 8 +- .../RynthCore.Plugin.RynthNav/AvoidFilter.cs | 3 + .../RynthCore.Plugin.RynthNav/NavCoarse.cs | 80 +- .../RynthCore.Plugin.RynthNav/NavPathQuery.cs | 311 ++++++ .../PathInterface.cs | 63 +- .../PluginExports.cs | 5 +- .../RynthNavPlugin.Avoid.cs | 41 +- .../RynthNavPlugin.Blocked.cs | 66 +- .../RynthNavPlugin.Graph.cs | 29 +- .../RynthNavPlugin.PathApi.cs | 136 +++ .../RynthNavPlugin.Turn.cs | 64 +- .../RynthNavPlugin.cs | 132 ++- .../RynthCore.Plugin.RynthNav/WalkSteer.cs | 123 +++ .../RynthSortPlugin.cs | 11 + .../Sorting/InventoryReader.cs | 42 +- .../Sorting/SortInventory.cs | 47 +- .../Sorting/SortPlanner.cs | 6 + .../Views/SortPanel.cs | 120 ++- Plugins/Shared/RynthNavPathApi.cs | 53 +- .../Fakes/FakeHost.cs | 10 +- Tools/RynthCore.RynthAiHostTests/Program.cs | 5 + .../Tests/BoostNavTests.cs | 267 +++++ .../Tests/ChestLootTests.cs | 53 +- .../Tests/HuntBuildingTests.cs | 605 ++++++++++++ .../Tests/ItemToolTests.cs | 916 ++++++++++++++++++ .../Tests/LootClaimMismatchTests.cs | 30 + .../Tests/NavEngineTests.cs | 145 ++- .../Tests/OffhandTests.cs | 198 +++- .../Tests/OutdoorHuntTests.cs | 358 +++++++ .../Tests/PatrolModeTests.cs | 138 +++ .../Tests/PetRefillTests.cs | 13 + .../Tests/VTankHotkeyTests.cs | 1 + Tools/RynthNav.GraphTests/Program.cs | 492 +++++++++- .../RynthNav.GraphTests.csproj | 8 +- Tools/RynthNav.RouteTests/Program.cs | 1 + .../RynthNav.RouteTests.csproj | 2 + Tools/RynthNav.RouteTests/SteeringTests.cs | 212 ++++ Tools/RynthSort.Tests/PackColumnTests.cs | 173 ++++ Tools/RynthSort.Tests/PackTests.cs | 4 +- Tools/RynthSort.Tests/Program.cs | 4 + 77 files changed, 8622 insertions(+), 224 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Hunt.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/ItemTool/QuickGive.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.BoostNav.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/WalkSteer.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/BoostNavTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/PatrolModeTests.cs create mode 100644 Tools/RynthNav.RouteTests/SteeringTests.cs create mode 100644 Tools/RynthSort.Tests/PackColumnTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs b/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs index b04ec15..8a95f02 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ActivityArbiter.cs @@ -51,7 +51,7 @@ internal readonly struct ArbiterInputs /// Actively engaged (a live attack target), not merely "something is engageable". public readonly bool CombatEngaged; - /// BoostNavPriority — navigation preempts combat and looting. + /// BoostNavPriority: RynthAi only navigates (no combat, no looting), route or not. public readonly bool BoostNav; /// BoostLootPriority — looting preempts combat. public readonly bool BoostLoot; @@ -68,12 +68,18 @@ internal readonly struct ArbiterInputs /// looted until the area emptied (2026-10-03). /// public readonly bool LootStarved; + /// + /// The loot work is a container the player flagged with /ra lootthis. The one kind of + /// looting Boost Nav Priority still lets through (it is the player's own ask). + /// + public readonly bool ForcedLoot; public ArbiterInputs(bool macroRunning, bool wantBuffing, bool wantCombat, bool wantLooting, bool wantSalvaging, bool wantNav, bool combatEngaged = false, bool boostNav = false, bool boostLoot = false, - bool followActive = false, bool lootStarved = false) + bool followActive = false, bool lootStarved = false, bool forcedLoot = false) { + ForcedLoot = forcedLoot; MacroRunning = macroRunning; WantBuffing = wantBuffing; WantCombat = wantCombat; @@ -109,11 +115,22 @@ internal sealed class ActivityArbiter if (s.WantBuffing) return BotActivity.Buffing; // ── User priority overrides ──────────────────────────────────────── - // BoostNavPriority: nav outranks combat and looting. Only meaningful - // when there is actually a route to run, hence the WantNav guard — - // without it the flag just starved combat and the bot stood among mobs - // without hunting. - if (s.BoostNav && s.WantNav) return BotActivity.Navigating; + // BoostNavPriority (owner's rule, 2026-11-02): RynthAi ONLY navigates. No + // hunting, no looting, and no fighting back even with a monster on it: with + // a route (or a follow) it navigates, with nothing to navigate it stands + // idle. Buffing (above) still outranks it. This used to be guarded by + // WantNav, so with no route the flag did nothing and the bot hunted as + // usual; the player never noticed it was on and only saw that it would not + // loot (R-20261102-041824-3f7c). Two things still get a slot: a container + // the player flagged with /ra lootthis (looted with Boost Nav on, as with + // the macro off), and the salvage queue (an inventory chore, no fight). + if (s.BoostNav) + { + if (s.WantNav) return BotActivity.Navigating; + if (s.ForcedLoot && s.WantLooting) return BotActivity.Looting; + if (s.WantSalvaging) return BotActivity.Salvaging; + return BotActivity.Idle; + } // BoostLootPriority: looting outranks combat — EXCEPT while actively // engaged. A mob already swinging at you gets fought whatever the flag diff --git a/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs b/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs new file mode 100644 index 0000000..11d7476 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs @@ -0,0 +1,630 @@ +// BuildingMap: the buildings of the outdoor landblocks round the character, for the outdoor hunt. +// +// RynthNav's landscape map ends at a building's walls (2026-10-25: the hunt left every monster in a +// house alone). A building's rooms are EnvCells of its landblock (0xXXYY0100 up), joined by portal +// records like a dungeon's; a portal record whose other cell is 0xFFFF opens to the outside: a door +// (or a window). Here, per landblock, from cell.dat: +// - the cell graph and the room geometry (DungeonPathfinder.BuildGraph, DungeonGeometry from +// DungeonLOS's polygons), the same the Dungeon Patrol walks on; +// - its buildings: the groups of cells joined to each other (a building with two parts that +// only the outside joins is two); +// - each building's doors: its 0xFFFF portal polygons wide and tall enough to walk through with +// their foot at the floor (not a window), with a point a step inside and one a step outside; +// - walks inside a building between two spots (the cell path, laid through doorways and across +// rooms as the patrol lays them), kept out of the circles of portal objects standing inside. +// Cached per landblock (the last MaxBlocks). Tick thread. + +using System; +using System.Collections.Generic; +using System.IO; +using RynthCore.Plugin.RynthAi.Raycasting; +using Vec = RynthCore.Plugin.RynthAi.OutdoorHunt.Vec; +using PathResult = RynthCore.Plugin.RynthAi.OutdoorHunt.PathResult; +using PathStatus = RynthCore.Plugin.RynthAi.OutdoorHunt.PathStatus; + +namespace RynthCore.Plugin.RynthAi; + +internal sealed class BuildingMap : OutdoorHunt.IBuildings +{ + /// A door's outer point: this far out of it along its facing (RynthNav's map keeps its + /// agent radius from the walls; its way to the door ends on the map's edge in front of it). + internal const double OutsideMeters = 1.5; + /// A door's inner point: this far in, shortened (in 0.25 m steps) to stay on the cell's floor. + internal const double InnerLongest = 1.5, InnerShortest = 0.5; + /// An opening to the outside narrower or lower than this is not a door (a window, a vent). + internal const double MinDoorWidth = 0.8, MinDoorHeight = 1.5; + /// A door's foot at most this far above or below the floor just inside it (else a window). + internal const double DoorSillMax = 0.75; + /// A door's step out over a floor of the landblock at most this far below is no door from the ground. + internal const double StepOutBelow = 12.0; + /// Doors of one building whose centres are this close are one (a double door's two halves). + internal const double SameDoorMeters = 1.0; + /// A portal object's keep-out circle: its touch distance (1.9 m) and the corner the nav + /// reach can cut (the Dungeon Patrol's default, 3.5 m in all). + internal const double PortalKeepOutMeters = 3.5; + /// A portal counts on the floors within this height of it. + internal const double PortalLevelBand = 3.0; + /// A bend round a portal keeps this much more than its circle. + internal const double PortalBendMargin = 0.4; + internal const int MaxBlocks = 25; + + /// A portal object inside a building: its circle (world units). + internal readonly record struct PortalSpot(uint Id, double X, double Y, double Z, double R = PortalKeepOutMeters); + + internal sealed class Building + { + public int Id; + public uint Landblock; + public int Index; + public readonly List Cells = new(); + public readonly List Doors = new(); + /// Openings to the outside that aren't doors, and why (diagnostics). + public readonly List NotDoors = new(); + } + + /// One landblock's buildings. + internal sealed class Block + { + public uint Landblock; + public Dictionary Graph = new(); + public DungeonGeometry? Geo; + public readonly List Buildings = new(); + public readonly Dictionary ByCell = new(); + /// Portal records to the outside (cell, polygon key) the dats have, found polygon or not. + public int ExitRecords; + /// Openings to the outside shared by two cells, joined (JoinSharedOpenings). + public int SharedOpenings; + } + + private readonly DatDatabase? _cellDat; + private readonly Func? _los; + private readonly Func? _isDungeon; + private readonly Dictionary _blocks = new(); + private readonly Queue _order = new(); + + /// The portal objects round the character, in buildings and out (the plugin sets them): walks + /// inside keep out of them, and a door with one at its step in or out isn't offered. A different set + /// forgets the walks worked out round the last one. + public IReadOnlyList Portals + { + get => _portals; + set + { + var next = value ?? Array.Empty(); + bool same = next.Count == _portals.Count; + for (int i = 0; same && i < next.Count; i++) same = next[i] == _portals[i]; + if (!same) _walks.Clear(); + _portals = next; + } + } + private IReadOnlyList _portals = Array.Empty(); + + // Walks worked out (the rooms never change; a monster or the character a little way off is the same + // walk): asked several times a second, by several doors, and up to 3 ms each. + private readonly Dictionary<(uint, long, long, long, uint, long, long, long), PathResult> _walks = new(); + private const double WalkKeySpacing = 0.25; + private const int MaxWalks = 512; + internal int WalksWorkedOut { get; private set; } + private static long Key(double v) => (long)Math.Round(v / WalkKeySpacing); + + /// On the real dats: says which landblocks are dungeons (their cells are no building's). + public BuildingMap(DatDatabase? cellDat, Func? los, Func? isDungeon = null) + { + _cellDat = cellDat; + _los = los; + _isDungeon = isDungeon; + } + + internal DatDatabase? CellDat => _cellDat; + + /// A landblock built elsewhere (tests: a hand-built building). + internal void Add(Block block) + { + if (!_blocks.ContainsKey(block.Landblock)) _order.Enqueue(block.Landblock); + _blocks[block.Landblock] = block; + _walks.Clear(); + } + + /// The landblock's buildings, read from the dats the first time (null: no dats, or a dungeon). + internal Block? BlockFor(uint landblock) + { + if (_blocks.TryGetValue(landblock, out var b)) return b; + if (_cellDat == null || !_cellDat.IsLoaded) return null; + if (_isDungeon != null && _isDungeon(landblock)) b = null; + else + { + try { b = Load(landblock, _cellDat, _los?.Invoke()); } + catch { b = null; } + } + while (_order.Count >= MaxBlocks) _blocks.Remove(_order.Dequeue()); + _blocks[landblock] = b; + _order.Enqueue(landblock); + return b; + } + + private Building? Find(int id) + { + if (id <= 0) return null; + var blk = BlockFor((uint)id >> 12); + int idx = (id & 0xFFF) - 1; + return blk != null && idx >= 0 && idx < blk.Buildings.Count ? blk.Buildings[idx] : null; + } + + // ── OutdoorHunt.IBuildings ─────────────────────────────────────────────────────────────────── + + public int BuildingOf(uint cell) + { + if (!OutdoorHunt.IsIndoorCell(cell)) return 0; + var blk = BlockFor(cell >> 16); + return blk != null && blk.ByCell.TryGetValue(cell, out var b) ? b.Id : 0; + } + + /// The building's doors, less any a portal stands in front of (or behind). + public IReadOnlyList Doors(int building) + { + var b = Find(building); + if (b == null) return Array.Empty(); + if (Portals.Count == 0) return b.Doors; + var list = new List(b.Doors.Count); + foreach (var d in b.Doors) + if (!LegHitsPortal(d.Inner, d.At, Portals, out _) && !LegHitsPortal(d.At, d.Outside, Portals, out _) + && !InAnyPortal(d.Inner, Portals) && !InAnyPortal(d.Outside, Portals)) + list.Add(d); + return list; + } + + public string Name(int building) + { + var b = Find(building); + return b == null ? $"building {building}" : $"building {b.Landblock:X4}#{b.Index}"; + } + + public PathResult Inside(uint fromCell, Vec from, uint toCell, Vec to) + { + var key = (fromCell, Key(from.X), Key(from.Y), Key(from.Z), toCell, Key(to.X), Key(to.Y), Key(to.Z)); + if (_walks.TryGetValue(key, out var known)) return known; + var p = WorkOutInside(fromCell, from, toCell, to); + if (_walks.Count >= MaxWalks) _walks.Clear(); + _walks[key] = p; + WalksWorkedOut++; + return p; + } + + private PathResult WorkOutInside(uint fromCell, Vec from, uint toCell, Vec to) + { + var none = new PathResult(PathStatus.NoPath, Array.Empty(), 0, 0); + if ((fromCell >> 16) != (toCell >> 16)) return none; + var blk = BlockFor(fromCell >> 16); + if (blk == null) return none; + if (!blk.ByCell.TryGetValue(fromCell, out var bf) || !blk.ByCell.TryGetValue(toCell, out var bt) || bf != bt) return none; + var cells = DungeonPathfinder.FindPath(fromCell, toCell, blk.Graph); + if (cells.Count == 0) return none; + + var pts = DungeonPathfinder.BuildPathPoints(cells, blk.Graph, blk.Geo, null, + DungeonGeometry.WorldToNav(from.Y), DungeonGeometry.WorldToNav(from.X), from.Z, + DungeonGeometry.WorldToNav(to.Y), DungeonGeometry.WorldToNav(to.X), to.Z, out _); + var way = new List(pts.Count + 2) { from }; + foreach (var p in pts) + way.Add(new Vec(DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS), p.Z * 240.0, p.Doorway)); + way.Add(to); + + var geo = blk.Geo; + var cellsOf = bf.Cells; + Func? onFloor = geo == null ? null : v => geo.OnFloorOfAny(cellsOf, v.X, v.Y, v.Z); + Func? clear = geo == null ? null : (a, b) => geo.SegmentClear(cellsOf, a.X, a.Y, a.Z, b.X, b.Y, b.Z, 0.3); + var status = KeepOutOfPortals(way, Portals, onFloor, clear, out double gap); + if (status == PathStatus.NoPath) return none; + + double len = 0; + for (int i = 1; i < way.Count; i++) len += way[i - 1].DistanceTo(way[i]); + way.RemoveAt(0); + return new PathResult(status, way, len, gap); + } + + // ── Portals inside ─────────────────────────────────────────────────────────────────────────── + + private static bool SameLevel(PortalSpot p, double z) => Math.Abs(z - p.Z) <= PortalLevelBand; + + internal static bool InPortal(PortalSpot p, Vec v) => SameLevel(p, v.Z) && Sq(v.X - p.X) + Sq(v.Y - p.Y) < p.R * p.R - 1e-6; + + internal static bool InAnyPortal(Vec v, IReadOnlyList portals) + { + foreach (var p in portals) if (InPortal(p, v)) return true; + return false; + } + + /// The leg a-b passes inside a portal's circle (on its level): the first such portal. + internal static bool LegHitsPortal(Vec a, Vec b, IReadOnlyList portals, out PortalSpot hit) + { + hit = default; + foreach (var p in portals) + { + if (!SameLevel(p, a.Z) && !SameLevel(p, b.Z)) continue; + if (SegDist(a, b, p.X, p.Y, out _) < p.R - 1e-6) { hit = p; return true; } + } + return false; + } + + /// + /// Keeps the walk (start first, goal last; changed in place) out of the + /// portals' circles: a goal inside one ends the walk where it would go in (Partial, + /// from the goal); a leg through one is bent round it (a corner either side, else two: on the floor, + /// , legs clear of walls, ); a first leg that only + /// leaves the circle the start stands in is kept. NoPath when a leg can't be bent round. + /// + internal static PathStatus KeepOutOfPortals(List way, IReadOnlyList portals, + Func? onFloor, Func? legClear, out double gap) + { + gap = 0; + var status = PathStatus.Ok; + if (portals.Count == 0 || way.Count < 2) return status; + + var goal = way[^1]; + if (InAnyPortal(goal, portals)) + { + int k = way.Count - 1; + while (k > 0 && InAnyPortal(way[k], portals)) k--; + if (InAnyPortal(way[k], portals)) return PathStatus.NoPath; // all of it inside: nowhere to stand + // The leg way[k] -> way[k+1] goes in: the walk ends at its edge (a little short of it). + var a = way[k]; var b = way[k + 1]; + double t = EntryAlong(a, b, portals); + double len = a.FlatDistanceTo(b); + double back = len > 1e-9 ? Math.Min(t, Math.Max(0, t - 0.3 / len)) : 0; + var end = new Vec(a.X + (b.X - a.X) * back, a.Y + (b.Y - a.Y) * back, a.Z + (b.Z - a.Z) * back); + way.RemoveRange(k + 1, way.Count - k - 1); + if (end.FlatDistanceTo(a) > 0.05) way.Add(end); + if (way.Count < 2) return PathStatus.NoPath; + gap = way[^1].DistanceTo(goal); + status = PathStatus.Partial; + } + + // A corner on the way inside a circle (a doorway beside a portal): left out, and the legs either + // side of it bent round the portal instead (on the floor, clear of walls) or no way at all. + for (int i = way.Count - 2; i >= 1; i--) + if (InAnyPortal(way[i], portals)) way.RemoveAt(i); + + int guard = 0; + for (int i = 0; i + 1 < way.Count;) + { + var a = way[i]; var b = way[i + 1]; + if (!LegHitsPortal(a, b, portals, out var p)) { i++; continue; } + // The character stands in the slack ring round a portal: the first leg may lead it out. + if (i == 0 && InPortal(p, a) && MovesAway(a, b, p)) { i++; continue; } + if (++guard > 24) return PathStatus.NoPath; + var bend = Bend(a, b, p, portals, onFloor, legClear); + if (bend == null) return PathStatus.NoPath; + way.InsertRange(i + 1, bend); + } + return status; + } + + // The fraction along a-b where it first comes into a circle (1 when it never does). + private static double EntryAlong(Vec a, Vec b, IReadOnlyList portals) + { + double best = 1; + double dx = b.X - a.X, dy = b.Y - a.Y, l2 = dx * dx + dy * dy; + if (l2 < 1e-12) return 0; + foreach (var p in portals) + { + if (!SameLevel(p, b.Z)) continue; + // |a + t d - p|^2 = R^2: the smaller root in [0, 1]. + double fx = a.X - p.X, fy = a.Y - p.Y; + double bq = 2 * (fx * dx + fy * dy), c = fx * fx + fy * fy - p.R * p.R; + double disc = bq * bq - 4 * l2 * c; + if (disc < 0) continue; + double t = (-bq - Math.Sqrt(disc)) / (2 * l2); + if (t >= 0 && t < best) best = t; + } + return best; + } + + // The leg a-b gets no closer to p than a is (it leads away). + private static bool MovesAway(Vec a, Vec b, PortalSpot p) + { + double dx = b.X - a.X, dy = b.Y - a.Y; + return (a.X - p.X) * dx + (a.Y - p.Y) * dy >= 0; + } + + // Corners round portal p for the leg a-b: one corner either side (out from the leg's nearest + // approach), else two (a box round the circle's side); the shortest whose corners are on the floor, + // whose legs miss p and are clear of walls. Null when none is. + private static List? Bend(Vec a, Vec b, PortalSpot p, IReadOnlyList portals, + Func? onFloor, Func? legClear) + { + double dx = b.X - a.X, dy = b.Y - a.Y, len = Math.Sqrt(dx * dx + dy * dy); + if (len < 1e-6) return null; + dx /= len; dy /= len; + SegDist(a, b, p.X, p.Y, out double t); + double qx = a.X + (b.X - a.X) * t, qy = a.Y + (b.Y - a.Y) * t, qz = a.Z + (b.Z - a.Z) * t; + double ux = qx - p.X, uy = qy - p.Y, ul = Math.Sqrt(ux * ux + uy * uy); + if (ul < 0.05) { ux = -dy; uy = dx; } else { ux /= ul; uy /= ul; } + double r = p.R + PortalBendMargin; + + List? best = null; + double bestLen = double.MaxValue; + void Try(params Vec[] corners) + { + var pts = new List(corners.Length + 2) { a }; + pts.AddRange(corners); + pts.Add(b); + double l = 0; + bool startsIn = InPortal(p, a); // the character in the ring round it: its first leg must lead away + for (int k = 0; k + 1 < pts.Count; k++) + { + if (k == 0 && startsIn ? !MovesAway(pts[0], pts[1], p) : SegDist(pts[k], pts[k + 1], p.X, p.Y, out _) < p.R - 1e-6) return; + if (legClear != null && !legClear(pts[k], pts[k + 1])) return; + l += pts[k].FlatDistanceTo(pts[k + 1]); + } + foreach (var c in corners) + if (InAnyPortal(c, portals) || (onFloor != null && !onFloor(c))) return; + if (l < bestLen) { bestLen = l; best = new List(corners); } + } + // Corners at the circle's tangent distance on each side: r / cos of the half angle would be exact; + // the leg's ends are usually far enough that r out from the nearest approach clears it. + foreach (double side in new[] { 1.0, -1.0 }) + { + double sx = ux * side, sy = uy * side; + Try(new Vec(p.X + sx * r, p.Y + sy * r, qz)); + if (best != null) continue; + // A box: two corners beside the circle, before and after it along the leg. + Try(new Vec(p.X + sx * r - dx * r, p.Y + sy * r - dy * r, qz), new Vec(p.X + sx * r + dx * r, p.Y + sy * r + dy * r, qz)); + } + return best; + } + + // Flat distance from (px, py) to the segment a-b, and where along it (0..1) the nearest point is. + private static double SegDist(Vec a, Vec b, double px, double py, out double t) + { + double dx = b.X - a.X, dy = b.Y - a.Y, l2 = dx * dx + dy * dy; + t = l2 < 1e-12 ? 0 : Math.Clamp(((px - a.X) * dx + (py - a.Y) * dy) / l2, 0, 1); + return Math.Sqrt(Sq(a.X + dx * t - px) + Sq(a.Y + dy * t - py)); + } + + private static double Sq(double v) => v * v; + + // ── Reading a landblock ────────────────────────────────────────────────────────────────────── + + /// + /// A landblock's buildings from the dats: its cell graph, the room geometry (with DungeonLOS), and + /// the polygons of its portal records to the outside (other cell 0xFFFF). Without DungeonLOS no + /// door is known (the hunt then leaves its buildings alone, and walks out of one the way in). + /// + internal static Block Load(uint landblock, DatDatabase cellDat, DungeonLOS? los) + { + // A graph of its own (never DungeonPathfinder's cached one): shared openings add edges to it. + var graph = DungeonPathfinder.BuildGraph(landblock, cellDat); + var exits = ExitRecords(landblock, cellDat); + var exitPolys = new List<(uint, Vector3[])>(); + if (los == null || graph.Count == 0) + { + var bare = Build(landblock, graph, null, null, null, exitPolys); + bare.ExitRecords = exits.Count; + return bare; + } + var portals = new List<(uint, Vector3[])>(); + var walls = new List<(uint, Vector3[])>(); + var floors = new List<(uint, Vector3[])>(); + var want = new HashSet<(uint, ushort)>(exits); + foreach (var p in los.GetDungeonMapPolygons(landblock)) + { + if (p.Vertices == null) continue; + if (p.IsPortal) + { + portals.Add((p.CellId, p.Vertices)); + if (want.Contains((p.CellId, p.PolyKey))) exitPolys.Add((p.CellId, p.Vertices)); + } + else walls.Add((p.CellId, p.Vertices)); + } + foreach (var p in los.GetDungeonMapFloorPolygons(landblock)) + if (p.Vertices != null && !p.IsPortal) floors.Add((p.CellId, p.Vertices)); + var block = Build(landblock, graph, portals, floors, walls, exitPolys); + block.ExitRecords = exits.Count; + return block; + } + + /// Two openings to the outside this close (centres, and foot heights) are one opening seen from two cells. + internal const double SharedOpeningMeters = 1.0; + + /// + /// Openings to the outside that are the same opening from two cells (the walls of a fort, DF61: + /// the gatehouse and the wall beside it are separate groups of cells whose "outside" there is the + /// other's inside): each pair becomes an edge of (both ways), so the + /// geometry makes it a doorway and the two groups one building. Returns the openings left. + /// + internal static List<(uint Cell, Vector3[] Poly)> JoinSharedOpenings(Dictionary graph, + IReadOnlyList<(uint Cell, Vector3[] Poly)> exitPolys, out int joined) + { + joined = 0; + var info = new List<(uint Cell, Vector3[] Poly, bool Ok, double X, double Y, double Z)>(exitPolys.Count); + foreach (var (cell, poly) in exitPolys) + { + bool ok = DungeonGeometry.TryOpening(poly, out double x, out double y, out double z, out _, out _, out _, out _); + info.Add((cell, poly, ok, x, y, z)); + } + var used = new bool[info.Count]; + for (int i = 0; i < info.Count; i++) + { + if (!info[i].Ok || used[i]) continue; + for (int j = i + 1; j < info.Count; j++) + { + if (!info[j].Ok || used[j] || info[j].Cell == info[i].Cell) continue; + double dx = info[i].X - info[j].X, dy = info[i].Y - info[j].Y; + if (dx * dx + dy * dy > SharedOpeningMeters * SharedOpeningMeters || Math.Abs(info[i].Z - info[j].Z) > 0.5) continue; + if (!graph.TryGetValue(info[i].Cell, out var a) || !graph.TryGetValue(info[j].Cell, out var b)) continue; + if (!a.Neighbors.Contains(b.CellId)) a.Neighbors.Add(b.CellId); + if (!b.Neighbors.Contains(a.CellId)) b.Neighbors.Add(a.CellId); + used[i] = used[j] = true; + joined++; + break; + } + } + var left = new List<(uint, Vector3[])>(info.Count); + for (int i = 0; i < info.Count; i++) + if (!used[i]) left.Add((info[i].Cell, info[i].Poly)); + return left; + } + + /// Every portal record of the landblock's EnvCells whose other cell is 0xFFFF (the outside): (cell, polygon key). + internal static List<(uint Cell, ushort Poly)> ExitRecords(uint landblock, DatDatabase cellDat) + { + var list = new List<(uint, ushort)>(); + foreach (uint cellId in cellDat.GetLandblockCellIds(landblock)) + { + byte[]? data = cellDat.GetFileData(cellId); + if (data == null || data.Length < 36) continue; + try + { + using var ms = new MemoryStream(data); + using var r = new BinaryReader(ms); + r.ReadUInt32(); r.ReadUInt32(); r.ReadUInt32(); // id, flags, id again + byte numSurfaces = r.ReadByte(); + byte numPortals = r.ReadByte(); + r.ReadUInt16(); // visible cells + ms.Seek(numSurfaces * 2, SeekOrigin.Current); + r.ReadUInt16(); r.ReadUInt16(); // environment, cell structure + ms.Seek(28, SeekOrigin.Current); // position, rotation + for (int i = 0; i < numPortals && ms.Position + 8 <= ms.Length; i++) + { + r.ReadUInt16(); // flags + ushort poly = r.ReadUInt16(); + ushort other = r.ReadUInt16(); + r.ReadUInt16(); // other portal + if (other == 0xFFFF) list.Add((cellId, poly)); + } + } + catch { /* a malformed cell: no doors from it */ } + } + return list; + } + + /// + /// A landblock's buildings from its cell graph, its polygons (portal, floor and wall polygons as + /// DungeonGeometry.Build takes them; null portals: no geometry) and the polygons of its openings to + /// the outside (each in its cell): openings shared by two cells join them; the cells joined to each + /// other are a building; each opening wide and tall enough, its foot at the floor inside and the + /// ground (no floor of the landblock) under its step out, is a door (facing out of its cell). + /// + internal static Block Build(uint landblock, Dictionary graph, + IReadOnlyList<(uint, Vector3[])>? portals, IReadOnlyList<(uint, Vector3[])>? floors, + IReadOnlyList<(uint, Vector3[])>? walls, IReadOnlyList<(uint Cell, Vector3[] Poly)> exitPolys) + { + var exits = JoinSharedOpenings(graph, exitPolys, out int joined); + DungeonGeometry? geo = portals == null ? null + : DungeonGeometry.Build(graph, portals, floors ?? Array.Empty<(uint, Vector3[])>(), walls ?? Array.Empty<(uint, Vector3[])>()); + var block = new Block { Landblock = landblock, Graph = graph, Geo = geo, SharedOpenings = joined }; + + // Buildings: the cells joined to each other (union-find over the portal records, either way). + var parent = new Dictionary(graph.Count); + foreach (uint c in graph.Keys) parent[c] = c; + uint Root(uint x) + { + while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } + return x; + } + foreach (var n in graph.Values) + foreach (uint nb in n.Neighbors) + { + if (!parent.ContainsKey(nb)) continue; + uint ra = Root(n.CellId), rb = Root(nb); + if (ra != rb) parent[Math.Max(ra, rb)] = Math.Min(ra, rb); + } + var ids = new List(graph.Keys); + ids.Sort(); + var byRoot = new Dictionary(); + foreach (uint c in ids) + { + uint r = Root(c); + if (!byRoot.TryGetValue(r, out var b)) + { + b = new Building { Index = block.Buildings.Count, Landblock = landblock }; + b.Id = (int)((landblock & 0xFFFF) << 12) | (b.Index + 1); + byRoot[r] = b; + block.Buildings.Add(b); + } + b.Cells.Add(c); + block.ByCell[c] = b; + } + + foreach (var (cell, poly) in exits) + { + if (!block.ByCell.TryGetValue(cell, out var b) || !graph.TryGetValue(cell, out var node)) continue; + if (TryDoor(cell, node, poly, geo, b.Cells, out var door, out string why)) + { + bool same = false; + foreach (var d in b.Doors) + if (d.At.FlatDistanceTo(door.At) < SameDoorMeters && Math.Abs(d.At.Z - door.At.Z) < 1.0) { same = true; break; } + if (!same) b.Doors.Add(door); + } + else b.NotDoors.Add($"{cell:X8}: {why}"); + } + return block; + } + + /// + /// The door an opening to the outside makes, in : facing out of the cell (the + /// floor behind it is the cell's, else the cell's origin is behind it), its inner point on the cell's + /// floor, its outer point OutsideMeters out. False (and why) for one too narrow, too low, or with its + /// foot off the floor inside (a window). + /// + internal static bool TryDoor(uint cell, DungeonNavNode node, Vector3[] poly, DungeonGeometry? geo, IReadOnlyCollection buildingCells, + out OutdoorHunt.Door door, out string why) + { + door = default; + if (!DungeonGeometry.TryOpening(poly, out double x, out double y, out double z, out double nx, out double ny, out double width, out double top)) + { + why = "faces up or down (a shaft)"; + return false; + } + var inv = System.Globalization.CultureInfo.InvariantCulture; + if (width < MinDoorWidth) { why = string.Format(inv, "{0:F1} m wide", width); return false; } + if (top - z < MinDoorHeight) { why = string.Format(inv, "{0:F1} m tall", top - z); return false; } + + // Out of the cell: the floor behind the opening is the cell's. + int vote = 0; + if (geo != null && geo.HasFloor(cell)) + vote = geo.OnCellFloor(cell, x - nx * 0.75, y - ny * 0.75, z) ? 1 : geo.OnCellFloor(cell, x + nx * 0.75, y + ny * 0.75, z) ? -1 : 0; + if (vote == 0) + { + double cx = DungeonGeometry.NavToWorld(node.EW), cy = DungeonGeometry.NavToWorld(node.NS); + vote = (cx - x) * nx + (cy - y) * ny <= 0 ? 1 : -1; + } + if (vote < 0) { nx = -nx; ny = -ny; } + + // Its foot at the floor inside (a window's sill is a metre or more up). + double floor = z; + if (geo != null && geo.HasFloor(cell)) + { + bool found = false; + for (double s = 0.5; s <= InnerLongest + 1e-9 && !found; s += 0.25) + found = geo.TryFloorHeight(x - nx * s, y - ny * s, z, 2.5, out floor); + if (!found) { why = "no floor inside it"; return false; } + if (Math.Abs(z - floor) > DoorSillMax) { why = string.Format(inv, "its foot is {0:F1} m off the floor (a window)", z - floor); return false; } + } + + // The step out is onto the ground: no floor of the landblock under it, from 8 m below to just + // above (A9B4, A9B3: upper-storey doors onto the roof of the floor below, 4 m down; DF61: doors + // onto the top of a fort's wall, 5 to 10 m up). + if (geo != null && geo.TryFloorHeight(x + nx * OutsideMeters, y + ny * OutsideMeters, z - StepOutBelow / 2, StepOutBelow / 2 + 0.4, out double below)) + { + why = string.Format(inv, "its step out is over a floor {0:F1} m below (a roof, a balcony, another room)", z - below); + return false; + } + + // The inner point: as far in as InnerLongest that is on the building's floor. + double inS = -1; + if (geo != null) + { + for (double s = InnerLongest; s >= InnerShortest - 1e-9; s -= 0.25) + if (geo.OnFloorOfAny(buildingCells, x - nx * s, y - ny * s, floor)) { inS = s; break; } + if (inS < 0) { why = "no floor a step inside it"; return false; } + } + else inS = 1.0; + + door = new OutdoorHunt.Door(cell, + Inner: new Vec(x - nx * inS, y - ny * inS, floor, true), + At: new Vec(x, y, z, true), + Outside: new Vec(x + nx * OutsideMeters, y + ny * OutsideMeters, z, true)); + why = ""; + return true; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Hunt.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Hunt.cs new file mode 100644 index 0000000..f082ba0 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Hunt.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Outdoor hunting's monsters (OutdoorHunt, 2026-10-23): the ones combat would fight, by the same +/// filters as (the name list, the blacklist, ghosts, environment skips, +/// just killed, attackable, alive, Priority 0 ignored), out to maxYd instead of MonsterRange and +/// with no line of sight needed: the hunt walks round whatever is in the way. Ones in a building come +/// with their cell (since 2026-10-25 the hunt walks in through a door when it knows the building). +/// +public partial class CombatManager +{ + internal void HuntCandidates(double maxYd, List into) + { + into.Clear(); + int playerId = (int)_playerId; + if (playerId == 0) return; + if (!_host.TryGetObjectPosition((uint)playerId, out uint meCell, out float meX, out float meY, out float meZ)) return; + int forced = ForcedTargetId; + foreach (var wo in _worldFilter.GetLandscape()) + { + if (wo.Id == playerId || (int)wo.ObjectClass != (int)AcObjectClass.Monster) continue; + if (IsSpellProjectileName(wo.Name)) continue; + double dist = _worldFilter.DistanceFrom(meCell, meX, meY, meZ, wo.Id, out bool hasPos, out _, out _); + if (!hasPos || dist > maxYd) continue; + bool isForced = wo.Id != 0 && wo.Id == forced; + if (!isForced && IsUserBlacklistedName(wo.Name)) continue; + if (_blacklistManager.IsBlacklisted(wo.Id)) continue; + if (Ghosts.IsGhost(wo.Id)) continue; + if (IsEnvironmentSkipped(wo.Id)) continue; + if (_recentlyKilled.ContainsKey(wo.Id)) continue; + if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable((uint)wo.Id)) continue; + if (_worldFilter.GetHealthRatio(wo.Id) == 0f) continue; + int priority = isForced ? int.MaxValue : PriorityOf(wo.Id); + if (priority <= 0) continue; + if (!_host.TryGetObjectPosition((uint)wo.Id, out uint cell, out float lx, out float ly, out float lz)) continue; + // In a building's rooms (cell 0x0100 up): the hunt walks there through a door of the building + // (BuildingMap), or leaves it alone when it doesn't know the building. + var pos = new OutdoorHunt.Vec(((cell >> 24) & 0xFF) * 192.0 + lx, ((cell >> 16) & 0xFF) * 192.0 + ly, lz); + into.Add(new OutdoorHunt.Candidate(wo.Id, wo.Name, pos, dist, priority, cell)); + } + into.Sort((a, b) => a.Distance.CompareTo(b.Distance)); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs index 350a226..d08d882 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs @@ -54,6 +54,7 @@ public partial class CombatManager private (int Id, string Source) _lastOffPlan = (-1, ""); private DateTime _lastOffHoldLogAt = DateTime.MinValue; private readonly HashSet _offNoted = new(); + private const string DefaultOffhandSource = "Default offhand"; private void ResetOffhandState() { @@ -193,7 +194,7 @@ public partial class CombatManager } if (pick == 0 && OffhandRules.IsRuleItem(ruleVal)) { pick = ruleVal; source = $"Monsters rule '{rule!.Name}' offhand"; } if (pick == 0 && ruleVal == 0 && defaultRow != null && OffhandRules.IsRuleItem(defaultRow.OffhandId)) - { pick = defaultRow.OffhandId; source = "Default offhand"; } + { pick = defaultRow.OffhandId; source = DefaultOffhandSource; } if (pick != 0 && !_settings.ItemRules.Exists(r => r.Id == pick)) { NoteUnlisted(pick, source); @@ -214,19 +215,30 @@ public partial class CombatManager var wo = _worldFilter[r.Id]; if (wo == null) continue; if (IsShieldItem(wo)) list.Add(new OffhandCandidate(r.Id, wo.Name, true, r.Id == offInSlot)); - else if (IsOffhandWeaponItem(wo)) list.Add(new OffhandCandidate(r.Id, wo.Name, false, r.Id == offInSlot)); + else if (IsOffhandWeaponItem(wo)) list.Add(new OffhandCandidate(r.Id, wo.Name, false, r.Id == offInSlot, ListedElementOf(r.Id))); } return list; } + /// A weapon's element as the weapon choice reads it: the one set in the Items list, else its properties. + internal string ListedElementOf(int id) + { + var r = _settings.ItemRules.Find(x => x.Id == id); + string elem = WeaponElements.Normalize(r?.Element); + if (elem.Length == 0 && id != 0) elem = ElementTracker.Read(id, _worldFilter[id]?.Name).Element; + return elem; + } + /// The off hand to go with against . internal OffhandPlan OffhandPlanFor(WorldObject target, MonsterRule? rule, int mainId) { var (mode, pick, source) = OffhandChoiceFor(target, rule); int off = OffhandInSlot(); var kind = MainKindOf(_worldFilter[mainId]); + // A dual-wield pair goes on together: the off-hand weapon of the main weapon's element. + string mainElement = kind == MainHandKind.OneHandedMelee ? ListedElementOf(mainId) : ""; var plan = OffhandPlanner.Choose(mode, kind, mainId, ListedOffhand(off), DualWieldTrained, _settings.PreferDualWield, - _host.HasWieldItem, pick, source); + _host.HasWieldItem, pick, source, mainElement, explicitIsDefault: source == DefaultOffhandSource); // Nothing listed planned: put back what RynthAi took off itself, when the hands allow it. if (plan.Id == 0 && mode != OffhandMode.None && _stowedOffhandId != 0 && _stowedOffhandId != mainId) @@ -241,6 +253,26 @@ public partial class CombatManager return plan; } + /// + /// Dual wield: (the weapon choice) already swings in the off hand + /// beside , of another element. Its partner: another listed one-handed + /// weapon of the wanted element the character can wield now, for the main hand (null = none, + /// or the hands already hold the wanted element). + /// + private WorldObject? DualWieldPartnerFor(int wantedId, int inHand) + { + string elem = ListedElementOf(wantedId); + if (elem.Length == 0 || elem.Equals(ListedElementOf(inHand), StringComparison.OrdinalIgnoreCase)) return null; + foreach (var c in ListedCandidates()) + { + if (c.Id == wantedId || c.Id == inHand || c.Kind != CombatMode.Melee + || !c.Element.Equals(elem, StringComparison.OrdinalIgnoreCase)) continue; + if (_worldFilter[c.Id] is WorldObject wo && MainKindOf(wo) == MainHandKind.OneHandedMelee && IsOffhandWeaponItem(wo)) + return wo; + } + return null; + } + // ── Before a main wield ────────────────────────────────────────────────── private enum OffPrep { Ready, Busy, Blocked } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index e091dfd..59b7192 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -4622,12 +4622,27 @@ public partial class CombatManager : IDisposable DropTarget("combat disabled"); } - // Combat can run in Default/Combat, can interrupt navigation unless nav boost is on, - // and can interrupt looting unless loot boost is on. - // Buffing always blocks combat — if buffs drop, the character dies. + // Boost Nav Priority (owner's rule, 2026-11-02): RynthAi only navigates. No hunting and no + // fighting back, whatever BotAction says. canRun used to block combat only while the + // arbiter held "Navigating", so with no route (BotAction "Default") Think ran and the bot + // hunted as usual with the flag on (R-20261102-041824-3f7c). The scan above still runs: + // it is what tells the arbiter (and the once-per-session notice) a fight is being skipped. + if (_settings.BoostNavPriority) + { + StandDownForBoostNav(); + return; + } + if (_boostNavStoodDown) + { + _boostNavStoodDown = false; + _host.Log("[RynthAi] Combat: Boost Nav Priority is off - hunting again."); + } + + // Combat can run in Default/Combat, can interrupt navigation, and can interrupt looting + // unless loot boost is on. Buffing always blocks combat — if buffs drop, the character dies. bool canRun = _settings.BotAction == "Default" || _settings.BotAction == "Combat" - || (_settings.BotAction == "Navigating" && !_settings.BoostNavPriority) + || _settings.BotAction == "Navigating" || (_settings.BotAction == "Looting" && !_settings.BoostLootPriority); if (!canRun) return; @@ -4643,6 +4658,55 @@ public partial class CombatManager : IDisposable } } + // True while Boost Nav Priority holds combat down (logged once each way). + private bool _boostNavStoodDown; + + /// Host tests: combat is standing down for Boost Nav Priority. + internal bool BoostNavStoodDown => _boostNavStoodDown; + + /// + /// Boost Nav Priority (owner's rule, 2026-11-02), every combat tick while the flag is on: + /// nothing is attacked, and a fight the flag came on in the middle of is let go cleanly. The + /// target is dropped (which ends a kite or an environment approach), the server's melee or + /// missile attack is cancelled (or it keeps swinging and walking us to the mob), a held turn + /// is let go, and with Peace Mode When Idle the stance goes back to Peace as it does between + /// fights, so nav does not run in a combat stance. No mode change while buffing (it would + /// fizzle the cast), while a cast resolves, or while a nav recall wants Magic mode. + /// + private void StandDownForBoostNav() + { + int mode = CurrentCombatMode; + if (!_boostNavStoodDown) + { + _boostNavStoodDown = true; + _host.Log("[RynthAi] Combat: Boost Nav Priority is on - no hunting and no fighting back, RynthAi only navigates."); + // The flag came on mid-fight: end the server's attack even if our record of it is gone. + if (mode == CombatMode.Melee || mode == CombatMode.Missile) + ReleaseServerAttack("Boost Nav Priority", log: false); + } + if (activeTargetId != 0 || _lockedTargetId != 0) + DropTarget("Boost Nav Priority is on (RynthAi only navigates)"); + if (_serverAttackTargetId != 0) + ReleaseServerAttack("Boost Nav Priority", log: false); + ReleaseHeldTurn(); + + if (mode == CombatMode.NonCombat) { _idlePeaceAttempts = 0; return; } + if (!_settings.PeaceModeWhenIdle || _settings.BotAction == "Buffing" || BusyCount != 0 + || RynthClock.Now < _navMagicWantedUntil || IsCastInFlight()) + return; + bool peaceHeld; + try { peaceHeld = HoldIdlePeace?.Invoke() == true; } catch { peaceHeld = false; } + if (peaceHeld) return; + // The idle swap's backoff (ThinkCore): 500 ms for the first 4 sends, then doubling to 15 s. + double peaceDelayMs = Math.Min(15_000, 500 * Math.Pow(2, Math.Min(5, _idlePeaceAttempts / 4))); + if ((RynthClock.Now - _lastPeaceAttempt).TotalMilliseconds > peaceDelayMs + && _host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "Boost Nav Priority: RynthAi only navigates (Peace Mode When Idle)")) + { + _lastPeaceAttempt = RynthClock.Now; + _idlePeaceAttempts++; + } + } + /// /// Target selection, every tick. Candidates are the top monster-rule Priority among monsters /// inside MonsterRange (or among all scanned ones when none is inside it), ranked by the @@ -6126,7 +6190,8 @@ public partial class CombatManager : IDisposable if (inHand != 0 && inHand != targetWeaponId && (WieldedSlotOf(weaponObj) & OffhandRules.ShieldSlot) != 0 // the slot can read 0: WieldedSlotOf asks the weenie && _worldFilter[inHand] is WorldObject mainObj && MainKindOf(mainObj) == MainHandKind.OneHandedMelee - && _settings.ItemRules.Any(r => r.Id == inHand)) + && _settings.ItemRules.Any(r => r.Id == inHand) + && DualWieldPartnerFor(targetWeaponId, inHand) is not WorldObject) { if (_offNoted.Add($"dual:{targetWeaponId}:{inHand}")) _host.Log($"[EquipDiag] 0x{(uint)targetWeaponId:X8} '{weaponObj.Name}' is in the off hand beside 0x{(uint)inHand:X8} '{mainObj.Name}' — fighting with both (dual wield)"); @@ -6134,6 +6199,18 @@ public partial class CombatManager : IDisposable targetWeaponId = inHand; weaponObj = mainObj; } + // Dual wield, the chosen weapon in the off hand beside one of another element, its partner + // listed: the partner goes in the main hand and the pair fights together (the off hand stays). + else if (inHand != 0 && inHand != targetWeaponId + && (WieldedSlotOf(weaponObj) & OffhandRules.ShieldSlot) != 0 + && DualWieldPartnerFor(targetWeaponId, inHand) is WorldObject partnerObj) + { + if (_offNoted.Add($"pair:{targetWeaponId}:{partnerObj.Id}")) + _host.Log($"[EquipDiag] 0x{(uint)targetWeaponId:X8} '{weaponObj.Name}' is in the off hand: its partner 0x{(uint)partnerObj.Id:X8} '{partnerObj.Name}' goes in the main hand (dual wield pair)"); + weaponSource = $"dual wield pair (wanted 0x{(uint)targetWeaponId:X8} is in the off hand)"; + targetWeaponId = partnerObj.Id; + weaponObj = partnerObj; + } if (inHand != targetWeaponId && OffhandBlocksMain(targetWeaponId, _curOffhandMode)) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/OffhandPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/OffhandPlanner.cs index b5c8b4c..601bc4a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/OffhandPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/OffhandPlanner.cs @@ -21,7 +21,8 @@ internal enum OffhandMode internal enum MainHandKind { None, OneHandedMelee, TwoHanded, Launcher, Thrown, Caster } /// A listed item that can go in the off hand: a shield, or a one-handed melee weapon. -internal sealed record OffhandCandidate(int Id, string Name, bool IsShield, bool InOffhand); +/// A weapon's normalized element ("" = unknown, and for shields). +internal sealed record OffhandCandidate(int Id, string Name, bool IsShield, bool InOffhand, string Element = ""); /// The off hand to wield (0 = add nothing; what is there stays) and why. internal readonly record struct OffhandPlan(int Id, string Source); @@ -160,12 +161,17 @@ internal static class OffhandRules /// listed one-handed weapon instead only when is on and /// dual wield is possible. A thrown weapon gets a shield too (never a second weapon). /// "Best": the listed one already in the off hand, else list order. Only listed items count. +/// An off-hand weapon is first of all the main weapon's partner: one of the same element +/// (), so a matched pair goes on together when the element changes +/// (a dual-wield player with two pairs had only the main hand swap, 2026-11-02). With no listed +/// partner, the one in the off hand stays. The Default row's item pick gives way to a partner too +/// (); a pick for the monster itself does not. /// internal static class OffhandPlanner { public static OffhandPlan Choose(OffhandMode mode, MainHandKind main, int mainId, IReadOnlyList listed, bool dualWieldTrained, bool preferDualWield, bool canWieldOffhandWeapon, - int explicitId = 0, string explicitSource = "") + int explicitId = 0, string explicitSource = "", string mainElement = "", bool explicitIsDefault = false) { if (mode == OffhandMode.None) return new OffhandPlan(0, "Offhand None"); // A shield goes with a one-handed melee weapon, and with a thrown weapon too (ACE @@ -179,8 +185,9 @@ internal static class OffhandPlanner { if (c.Id == 0 || c.Id == mainId) continue; if (c.IsShield) { if (shield == null || (c.InOffhand && !shield.InOffhand)) shield = c; } - else if (weapon == null || (c.InOffhand && !weapon.InOffhand)) weapon = c; + else if (weapon == null || WeaponRank(c, mainElement) < WeaponRank(weapon, mainElement)) weapon = c; } + bool partner = weapon != null && IsPartner(weapon, mainElement); if (explicitId != 0) { @@ -189,6 +196,10 @@ internal static class OffhandPlanner if (c.Id != explicitId) continue; if (explicitId != mainId) { + // The Default row's weapon pick, another element than the main weapon's: the + // main weapon's partner goes with it instead. + if (!c.IsShield && dualOk && explicitIsDefault && partner && !IsPartner(c, mainElement)) + return new OffhandPlan(weapon!.Id, explicitSource + $"; the {mainElement} partner of the main weapon"); if (c.IsShield || dualOk) return new OffhandPlan(c.Id, explicitSource); } // The off-hand weapon picked is the main weapon this fight (chosen for the monster's @@ -207,15 +218,23 @@ internal static class OffhandPlanner case OffhandMode.Shield: return shield != null ? new OffhandPlan(shield.Id, "Shield") : new OffhandPlan(0, "Shield: none listed"); case OffhandMode.Weapon: - if (dualOk && weapon != null) return new OffhandPlan(weapon.Id, "Offhand weapon"); + if (dualOk && weapon != null) return new OffhandPlan(weapon.Id, partner ? $"Offhand weapon ({mainElement}, as the main weapon)" : "Offhand weapon"); if (shield != null) return new OffhandPlan(shield.Id, weapon == null ? "Offhand weapon: no second one-handed weapon listed; shield" : $"Offhand weapon: {why}; shield"); return new OffhandPlan(0, weapon == null ? "Offhand weapon: no second one-handed weapon listed" : $"Offhand weapon: {why}"); default: // Auto is the shield; dual wield only with "Prefer dual wield" on (owner, // 2026-10-01), so two swords listed for element switching don't start dual wielding. if (dualOk && weapon != null && preferDualWield) - return new OffhandPlan(weapon.Id, "Auto (dual wield preferred)"); + return new OffhandPlan(weapon.Id, partner ? $"Auto (dual wield preferred; {mainElement}, as the main weapon)" : "Auto (dual wield preferred)"); return shield != null ? new OffhandPlan(shield.Id, "Auto") : new OffhandPlan(0, "Auto: no shield listed"); } } + + /// Same element as the main weapon (both known). + private static bool IsPartner(OffhandCandidate c, string mainElement) => + mainElement.Length > 0 && c.Element.Equals(mainElement, StringComparison.OrdinalIgnoreCase); + + /// Lower is better: the main weapon's partner, then the one in the off hand, then list order. + private static int WeaponRank(OffhandCandidate c, string mainElement) => + (IsPartner(c, mainElement) ? 0 : 2) + (c.InOffhand ? 0 : 1); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs index 87ff8ed..9974287 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs @@ -277,6 +277,10 @@ internal sealed class PetManager if (!_petSeenSinceSummon) return; _assumePetActiveUntil = 0; } + // Boost Nav Priority (owner's rule, 2026-11-02): RynthAi only navigates, so there is no + // fight to summon for (a summoned pet attacks the monsters it was called for), and a + // cosmetic pet stays out. + if (_settings.BoostNavPriority) return; if (petOut) { // A cosmetic pet in the slot steps aside for the fight; wait for the dismiss to land. diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index dbbe499..6c1aed1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -488,6 +488,8 @@ public sealed partial class RynthAiPlugin _pendingLootCheckContainerId = sid; // And a chest to loot, if it turns out eligible (RynthAiPlugin.ChestLoot.cs). NoteContainerOpened(sid); + NoteChestKeyOpened(sid); // the Item Tool's chest looter waits for this + NoteManualChestOpened(sid); // Pickup with macro off (RynthAiPlugin.ChestLoot.cs) return; } @@ -722,6 +724,8 @@ public sealed partial class RynthAiPlugin WatchLateLandings(CorpseNowMs); TickDeferredClose(settings); TakeLootThisRequest(settings); // /ra lootthis (RynthAiPlugin.VTankHotkeys.cs) + TakeChestKeyRequest(); // the Item Tool's chest looter (RynthAiPlugin.ItemTool.cs) + TakeManualChest(settings); // Pickup with macro off (RynthAiPlugin.ChestLoot.cs) // ── Macro off / looting disabled / nav-boost — full stop and reset ── // Must come before the Buffing check so that turning off the macro always @@ -730,7 +734,7 @@ public sealed partial class RynthAiPlugin if ((!settings.IsMacroRunning || !settings.EnableLooting || BoostNavHoldsLoot(settings)) && !ForcedLootHolds()) { _lootSkipWhy = !settings.IsMacroRunning ? "the macro is off" - : !settings.EnableLooting ? "looting is off" : "Boost Nav Priority gives the tick to the route"; + : !settings.EnableLooting ? "looting is off" : "Boost Nav Priority is on (RynthAi only navigates)"; ResetCorpseTarget(); return; } @@ -2855,6 +2859,23 @@ public sealed partial class RynthAiPlugin return false; } + /// + /// Boost Nav Priority is passing by a corpse in range that would be looted with it off. For + /// the once-per-session notice only (RynthAiPlugin.BoostNav.cs), which calls it every + /// BoostNavLootCheckMs until it has spoken. The scan's loot-starvation mark is put back: it + /// belongs to HasLootWork's tick, not to this look. + /// + private bool BoostNavSkipsLoot(LegacyUiSettings settings) + { + if (!settings.IsMacroRunning || !settings.EnableLooting || !BoostNavHoldsLoot(settings)) return false; + if (IsLootingBlockedByPack(settings)) return false; + double maxMeters = GetCorpseApproachRangeMaxMeters(settings); + if (maxMeters <= 0.25) return false; + bool starved = _lootStarved; + try { return HasUnlootedCorpsesInRange(maxMeters); } + finally { _lootStarved = starved; } + } + /// /// Stop Looting When Pack Full: no free slot anywhere, or fewer than the weapon-swap /// reserve. Below the reserve the pickup gate refuses every item, so a new corpse was diff --git a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs index 73323b6..6fcbb73 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs @@ -79,6 +79,11 @@ internal interface IDashboardHost /// RynthSort's own window, shown or hidden. void ToggleSortWindow(); void StartPatrol(); + /// Outdoor hunting on or off (on the plugin tick), and whether it is on. + void ToggleHunt(); + bool HuntActive { get; } + /// The small Outdoor Hunt window (its two distances) open or closed. + void ToggleHuntPanel(); void ToggleSpells(); /// The Classic (retail) look: RynthCore's own face comes back for it. void UseClassicLook(); @@ -369,7 +374,10 @@ internal sealed unsafe class InstrumentDashboard ImGui.SetCursorScreenPos(min); // A click asks why it is doing that (or nothing): /ra why's diagnosis, in chat. if (ImGui.InvisibleButton("##activity", new Vector2(w, h))) _d.Command("/ra why"); - SafeImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + state + "\nClick: why it's doing that, in chat (/ra why)."); + // Boost Nav Priority (owner's rule, 2026-11-02): it reads Idle or Navigating, and says why. + SafeImGui.SetItemTooltip("Bot activity: " + activity + + (_r.BoostNav ? "\nBoost Nav Priority is on: RynthAi only navigates (no hunting, no looting)." : "") + + "\nMeta state: " + state + "\nClick: why it's doing that, in chat (/ra why)."); return y + h; } @@ -570,6 +578,7 @@ internal sealed unsafe class InstrumentDashboard (RynthIcons.GlobeHemisphereWest, "World", "World Map", "World Map: Dereth, with your position, the route and places"), (RynthIcons.Backpack, "Items", "Items", "Items"), (RynthIcons.Footprints, "Patrol", "", "Patrol. Click: start dungeon patrol. Right-click: the Patrol drawer (hazards and routes)."), + (RynthIcons.Crosshair, "Hunt", "", "Hunt. Click: start or stop hunting outdoors from here: walk from monster to monster round obstacles.\nRight-click: the Outdoor Hunt window (how far it looks for monsters, and how far it may roam)."), (RynthIcons.User, "Char", "", "Character. Click: RynthOracle's Character tab. Right-click: the character windows."), }; @@ -594,6 +603,7 @@ internal sealed unsafe class InstrumentDashboard bool lit = l.Label switch { "Patrol" => prefs.IsOpen(DashboardPrefs.PatrolDrawer), + "Hunt" => _d.HuntActive, "Char" => host.SetPanelOpen(OracleKey, RynthPanelOpen.Ask) == 1 || host.SetPanelOpen("Mini Remote", RynthPanelOpen.Ask) == 1, _ => host.SetPanelOpen(l.Key, RynthPanelOpen.Ask) == 1, }; @@ -636,6 +646,7 @@ internal sealed unsafe class InstrumentDashboard switch (label) { case "Patrol": _d.StartPatrol(); break; + case "Hunt": _d.ToggleHunt(); break; case "Char": if (host.SetPanelOpen(OracleKey, RynthPanelOpen.Ask) >= 0) _d.Command("/ro character"); else _d.Command("/rc miniremote section char"); @@ -650,6 +661,10 @@ internal sealed unsafe class InstrumentDashboard { prefs.ToggleDrawer(DashboardPrefs.PatrolDrawer); } + else if (label == "Hunt") + { + _d.ToggleHuntPanel(); + } else if (label == "Char") { ImGui.OpenPopup(CharId); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs index cbe540e..9107e73 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs @@ -25,6 +25,7 @@ internal enum TickStep QuestTracker, LocalFeatures, GiveQueue, + ItemTool, Jumper, Dashboard, // In world. @@ -112,6 +113,7 @@ internal sealed class TickGuard Add(TickStep.QuestTracker, "quest tracker", LogCat.Quests); Add(TickStep.LocalFeatures, "HUDs and panels", LogCat.Huds); Add(TickStep.GiveQueue, "give queue", LogCat.Inventory); + Add(TickStep.ItemTool, "item tool", LogCat.Inventory); Add(TickStep.Jumper, "jumper", LogCat.Jumper, essential: true); Add(TickStep.Dashboard, "dashboard window", LogCat.UI); diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs index 14f7639..b2e2f26 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs @@ -199,6 +199,22 @@ internal sealed class DungeonGeometry return true; } + /// + /// One portal polygon on its own (a building's door to the outside has no twin in another + /// cell): its centre at floor level (z = its lowest vertex), its horizontal facing (either way + /// round), its width and its top. False for a floor or ceiling portal (a shaft). + /// + internal static bool TryOpening(Vector3[] v, out double x, out double y, out double z, + out double nx, out double ny, out double width, out double top) + { + x = y = z = nx = ny = width = top = 0; + if (v == null || v.Length < 3 || !TryPortalPoly(v, out var pp)) return false; + x = pp.X; y = pp.Y; z = pp.Z; nx = pp.Nx; ny = pp.Ny; width = pp.Width; + top = double.MinValue; + foreach (var p in v) top = Math.Max(top, p.Z); + return true; + } + private static bool TryMatch(DungeonGeometry g, DungeonNavNode a, DungeonNavNode b, List aList, List bList, out DungeonDoorway door) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs index 69479a8..9196e0d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs @@ -114,7 +114,7 @@ internal static partial class DungeonPathfinder /// ushort otherPortalId /// ushort[numVisibleCells] ← skipped /// - private static Dictionary BuildGraph(uint landblockKey, DatDatabase cellDat) + internal static Dictionary BuildGraph(uint landblockKey, DatDatabase cellDat) { var nodes = new Dictionary(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs new file mode 100644 index 0000000..28b6f65 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/ChestKeyLooter.cs @@ -0,0 +1,496 @@ +// ============================================================================ +// ChestKeyLooter.cs - the Item Tool's chest looter. +// +// "Pick a chest. Pick a key. It just loots the chest based on the current loot profile until it's +// out of keys." A pure state machine: everything it touches goes through IChestKeyEnv (the plugin +// implements it, RynthAiPlugin.ItemTool.cs; the host tests fake it). +// +// One cycle: +// Ready -> KeyPending -> KeyOut -> OpenPending -> OpenOut -> Looting -> Waiting -> Ready ... +// * KeyPending/KeyOut: the key is used on the chest (AC's use-with-target). ACE walks the +// character to the chest first (Player.HandleActionUseWithTarget -> CreateMoveToChain), so +// there is no walking code here; the chest just has to be loaded and near (MaxStartMeters). +// The server's answer (UseDone + its WeenieError) says what happened: 0 and "The X has been +// unlocked." = unlocked (one use of the key is spent); 0x4AF LockAlreadyUnlocked (nothing +// spent); 0x4B2 KeyDoesntFitThisLock; 0x4B1 the chest is open; 0x4B0 not a lock. +// * OpenPending/OpenOut: the chest is used (opened). The server's ViewContents for it is the +// proof (ChestOpenedAt). +// * Looting: the chest is handed to the corpse looter (the CURRENT loot profile's rules, the +// same TickOpenCorpseLooting as a corpse) and this waits for it to finish and close it. +// * Waiting: a chest re-locks and regenerates on a timer after it was opened (ACE Chest.Reset, +// ResetInterval, default 120 s). The next cycle starts after RegenWaitMs; where the client +// reads the chest as locked it starts earlier. A key use that answers "already unlocked" on +// a later cycle means the timer has not run yet: it waits ProbeMs and asks again, at most +// MaxProbes times. +// +// Out of keys: the key item is gone (used up: "Your key is used up."; no other carried item has +// its name) after a cycle, or before one. A key with unlimited uses never runs out: MaxCycles +// ends the run. +// +// Never spams the server: one request at a time, each waits for its UseDone (AnswerMaxMs), the +// client must be free (HoldReason) and a failed step is retried a few times at most. +// ============================================================================ + +using System; +using System.Text.RegularExpressions; + +namespace RynthCore.Plugin.RynthAi.ItemTool; + +internal interface IChestKeyEnv +{ + /// Clock (ms). + long Now { get; } + string NameOf(int id); + /// The chest is in the client's object cache; meters = distance from the player (-1 unknown). + bool ChestLoaded(int chestId, out double meters); + /// + /// The key to use: while it is still carried, else another carried item + /// named (never worn, never ). 0 = none. + /// + int FindKey(int keyId, string keyName, int excludeId); + /// Why nothing may be sent now (combat, the client is busy, portal space, the server owes an answer); null = free. + string? HoldReason(); + bool HasUseDone { get; } + int UseDoneSeq(); + bool LastUseDone(out int seq, out uint error); + bool SendKey(int keyId, int chestId); + bool SendOpen(int chestId); + /// When the server last opened this chest for us (its ViewContents arrived); 0 = not since the plugin started. + long ChestOpenedAt(int chestId); + /// Hands the open chest to the corpse looter (the current loot profile). + void StartLooting(int chestId); + /// The corpse looter still has the chest (asked for, or its loot session is open). + bool Looting(int chestId); + /// Ends the loot session and closes the chest. + void AbortLooting(int chestId); + /// The client reads the chest as locked (true), unlocked (false) or doesn't know (null). + bool? ChestLockedHint(int chestId); + void Say(string text); + void Log(string text); +} + +internal sealed class ChestKeyLooter +{ + public enum Phase { Idle, Ready, KeyPending, KeyOut, OpenPending, OpenOut, Looting, Waiting } + + // ACE WeenieError codes of the key answers (UnlockerHelper.UseUnlocker). + internal const uint ErrTooBusy = 0x1D, ErrLockAlreadyUnlocked = 0x4AF, ErrCannotLockOrUnlock = 0x4B0, + ErrCannotLockWhatIsOpen = 0x4B1, ErrKeyDoesntFit = 0x4B2, ErrCannotUseThatItem = 0x58D; + + /// The chest must be loaded and no farther than this to start (the server walks the rest). + public const double MaxStartMeters = 25; + /// A step waits this long for the server's answer (the walk to the chest is part of it). + public const long AnswerMaxMs = 12_000; + /// After an answer, the chat line that goes with it gets this long to arrive. + public const long ChatSettleMs = 250; + /// After the chest's answer, it gets this long to read open before the open counts as failed. + public const long OpenSettleMs = 1500; + /// The next cycle starts this long after the chest was opened (ACE's default chest reset is 120 s). + public const long RegenWaitMs = 125_000; + /// A chest the client reads as locked is tried again this soon after it was opened. + public const long MinRelockMs = 15_000; + /// Asking a chest that was still unlocked again. + public const long ProbeMs = 30_000; + public const int MaxProbes = 8; + /// Nothing may go out for this long (combat, busy client...) before the run stops. + public const long HoldMaxMs = 90_000; + /// The loot session may take this long. + public const long LootMaxMs = 300_000; + /// The looter has this long to take the chest. + public const long LootStartMs = 8_000; + /// The chest is out of the object cache this long: it is gone. + public const long GoneMs = 5_000; + public const int MaxCycles = 300; + public const int MaxTimeouts = 3, MaxBusy = 8, MaxOpenFails = 3, MaxSendFails = 5, MaxRefusals = 3, MaxOpenElsewhere = 3; + private const long ThinkMs = 100, RetryMs = 1500, SendRetryMs = 1000, BusyBackoffMs = 2000; + private const long NoUseDoneFallbackMs = 3000; + + private static readonly Regex UnlockedText = new(@"\bhas been unlocked\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex KeyUsedUpText = new(@"^\s*Your key (?:is used up|has (?\d+) uses? left)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + + private readonly IChestKeyEnv _env; + + public ChestKeyLooter(IChestKeyEnv env) => _env = env; + + public int ChestId { get; private set; } + public string ChestName { get; private set; } = ""; + public int KeyId { get; private set; } + public string KeyName { get; private set; } = ""; + public Phase State { get; private set; } = Phase.Idle; + public bool Running => State != Phase.Idle; + /// Chests looted since the run started. + public int Looted { get; private set; } + /// The key's uses left, as the server last said (-1 unknown). + public int UsesLeft { get; private set; } = -1; + /// What the run did last, for the status line when it is not running. + public string LastResult { get; private set; } = ""; + + // Run state. + private long _lastThink, _nextTryAt, _goneSince, _holdSince; + private long _keySentAt, _openSentAt, _answeredAt, _lootStartedAt, _waitUntil, _openedAt; + private int _seqAtSend; + private bool _answerSeen, _sawUnlocked, _keyUsedUp, _lootSeen, _relockExpected; + private int _timeouts, _busy, _openFails, _sendFails, _probes, _refusals, _openElsewhere, _cycles, _keyUsesThisCycle; + private string _holdWhy = ""; + + public void SetChest(int id, string name) { if (!Running) { ChestId = id; ChestName = name; } } + public void SetKey(int id, string name) { if (!Running) { KeyId = id; KeyName = name; UsesLeft = -1; } } + public void Clear() { if (!Running) { ChestId = 0; ChestName = ""; KeyId = 0; KeyName = ""; UsesLeft = -1; LastResult = ""; } } + + /// Begins the run. False (with why, already said in chat) when it can't. + public bool Start(out string why) + { + why = ""; + if (Running) { why = "the chest looter is already running"; return false; } + if (ChestId == 0) { why = "pick a chest first (select it in the world, then 'Use selected as chest')"; return Refuse(why); } + if (KeyId == 0) { why = "pick a key first (select it in your pack, then 'Use selected as key')"; return Refuse(why); } + if (!_env.ChestLoaded(ChestId, out double meters)) { why = $"{ChestName} isn't loaded (out of view?); walk closer"; return Refuse(why); } + if (meters > MaxStartMeters) { why = $"{ChestName} is {meters:0} m away (more than {MaxStartMeters:0} m); walk closer"; return Refuse(why); } + int key = _env.FindKey(KeyId, KeyName, 0); + if (key == 0) { why = $"no '{KeyName}' in your packs"; return Refuse(why); } + KeyId = key; + + Looted = 0; _cycles = 0; _probes = 0; _relockExpected = false; _goneSince = 0; _holdSince = 0; + _timeouts = _busy = _openFails = _sendFails = _refusals = _openElsewhere = 0; + _lastThink = 0; _nextTryAt = 0; LastResult = ""; + State = Phase.Ready; + _env.Say($"[RynthAi] Chest looter: starting on {ChestName} with {KeyName}. It uses the key, opens the chest, loots it with the current loot profile and repeats until the key is used up. Stop: /ra itemtool chest stop."); + _env.Log($"[RynthAi] Chest looter: start chest 0x{(uint)ChestId:X8} '{ChestName}' key 0x{(uint)KeyId:X8} '{KeyName}' ({meters:0.0} m)"); + return true; + } + + private bool Refuse(string why) + { + _env.Say($"[RynthAi] Chest looter: can't start - {why}."); + return false; + } + + /// The player asked to stop (always works). + public void Stop(string why = "stopped") + { + if (!Running) { _env.Say("[RynthAi] Chest looter: not running."); return; } + Finish(why); + } + + private void Finish(string why) + { + Phase was = State; + State = Phase.Idle; + if (was == Phase.Looting && ChestId != 0) + { + try { _env.AbortLooting(ChestId); } catch { /* the stop must not throw */ } + } + LastResult = $"stopped: {why} ({Looted} chest(s) looted)"; + _env.Say($"[RynthAi] Chest looter {LastResult}."); + _env.Log($"[RynthAi] Chest looter: finish - {why}; looted {Looted}, cycles {_cycles}"); + } + + /// A chat line from the server (the key's answers). + public void OnChat(string? text) + { + if (!Running || string.IsNullOrEmpty(text) || text.Length > 160) return; + if (State is not (Phase.KeyOut or Phase.KeyPending)) return; + if (UnlockedText.IsMatch(text)) { _sawUnlocked = true; return; } + Match m = KeyUsedUpText.Match(text); + if (!m.Success) return; + if (m.Groups["n"].Success && int.TryParse(m.Groups["n"].Value, out int n)) UsesLeft = n; + else { _keyUsedUp = true; UsesLeft = 0; } + } + + /// One line for the panel. + public string Status + { + get + { + long now = _env.Now; + string key = KeyName.Length == 0 ? "no key" : UsesLeft >= 0 ? $"{KeyName} ({UsesLeft} use{(UsesLeft == 1 ? "" : "s")} left)" : KeyName; + string tail = $"{Looted} looted"; + if (_holdWhy.Length > 0 && State is Phase.KeyPending or Phase.OpenPending) + return $"Waiting: {_holdWhy} - {tail}."; + switch (State) + { + case Phase.Idle: return LastResult.Length > 0 ? $"Chest looter {LastResult}." : "Idle."; + case Phase.Waiting: + return $"Waiting for {ChestName} to re-lock ({Math.Max(0, (_waitUntil - now + 999) / 1000)} s) - {key}, {tail}."; + case Phase.Looting: return $"Looting {ChestName} - {key}, {tail}."; + case Phase.KeyPending or Phase.KeyOut: return $"Using {KeyName} on {ChestName} - {tail}."; + case Phase.OpenPending or Phase.OpenOut: return $"Opening {ChestName} - {key}, {tail}."; + default: return $"Starting - {tail}."; + } + } + } + + /// Call every plugin tick. + public void Tick() + { + if (State == Phase.Idle) return; + long now = _env.Now; + if (now - _lastThink < ThinkMs) return; + _lastThink = now; + + if (!_env.ChestLoaded(ChestId, out double meters)) + { + if (_goneSince == 0) _goneSince = now; + else if (now - _goneSince >= GoneMs) Finish($"{ChestName} is gone (out of view, or you left)"); + return; + } + _goneSince = 0; + + switch (State) + { + case Phase.Ready: TickReady(now, meters); break; + case Phase.KeyPending: TickKeyPending(now); break; + case Phase.KeyOut: TickKeyOut(now); break; + case Phase.OpenPending: TickOpenPending(now); break; + case Phase.OpenOut: TickOpenOut(now); break; + case Phase.Looting: TickLooting(now); break; + case Phase.Waiting: TickWaiting(now); break; + } + } + + // ── Phases ─────────────────────────────────────────────────────────────── + + private void TickReady(long now, double meters) + { + if (_cycles >= MaxCycles) { Finish($"reached {MaxCycles} cycles (a key with unlimited uses never runs out)"); return; } + int key = _env.FindKey(KeyId, KeyName, 0); + if (key == 0) { Finish($"out of keys - no '{KeyName}' left"); return; } + if (key != KeyId) + { + _env.Log($"[RynthAi] Chest looter: key 0x{(uint)KeyId:X8} is gone; using 0x{(uint)key:X8} '{KeyName}'"); + KeyId = key; + UsesLeft = -1; + } + if (meters > MaxStartMeters) { Finish($"{ChestName} is {meters:0} m away (more than {MaxStartMeters:0} m)"); return; } + _keyUsesThisCycle = 0; + _openFails = 0; + _sawUnlocked = false; + _keyUsedUp = false; + State = Phase.KeyPending; + } + + /// True while something holds the send; the run stops after HoldMaxMs of it. + private bool Held(long now) + { + string? why = _env.HoldReason(); + if (why == null) { _holdSince = 0; _holdWhy = ""; return false; } + _holdWhy = why; + if (_holdSince == 0) { _holdSince = now; _env.Log($"[RynthAi] Chest looter: waits - {why}"); } + else if (now - _holdSince >= HoldMaxMs) Finish($"waited {HoldMaxMs / 1000} s: {why}"); + return true; + } + + private bool Answered(long sentAt, out uint error) + { + error = 0; + long now = _env.Now; + if (!_env.HasUseDone) return now - sentAt >= NoUseDoneFallbackMs; + if (_env.UseDoneSeq() == _seqAtSend) return false; + if (_env.LastUseDone(out int seq, out uint err) && seq == _seqAtSend + 1) error = err; + return true; + } + + private void TickKeyPending(long now) + { + if (now < _nextTryAt) return; + if (Held(now)) return; + int key = _env.FindKey(KeyId, KeyName, _keyUsedUp ? KeyId : 0); + if (key == 0) { Finish($"out of keys - no '{KeyName}' left"); return; } + KeyId = key; + _keyUsedUp = false; + + _seqAtSend = _env.UseDoneSeq(); + _sawUnlocked = false; + if (!_env.SendKey(KeyId, ChestId)) + { + if (++_sendFails >= MaxSendFails) Finish("the client wouldn't send the key use"); + else _nextTryAt = now + SendRetryMs; + return; + } + _sendFails = 0; + _keySentAt = now; + _answerSeen = false; + State = Phase.KeyOut; + } + + private void TickKeyOut(long now) + { + if (!_answerSeen) + { + if (!Answered(_keySentAt, out uint e0)) + { + if (now - _keySentAt >= AnswerMaxMs) Retry(now, Phase.KeyPending, "no answer from the server to the key use"); + return; + } + _answerSeen = true; + _answeredAt = now; + _lastErr = e0; + return; // the chat line of this answer gets ChatSettleMs + } + if (now - _answeredAt < ChatSettleMs) return; + _answerSeen = false; + OnKeyAnswer(now, _lastErr); + } + + private uint _lastErr; + + private void OnKeyAnswer(long now, uint err) + { + switch (err) + { + case 0: + _keyUsesThisCycle++; + _busy = 0; + if (!_sawUnlocked) + _env.Log("[RynthAi] Chest looter: the key use was answered with no 'has been unlocked' line; trying the chest anyway"); + State = Phase.OpenPending; + _nextTryAt = now + 400; + return; + + case ErrLockAlreadyUnlocked: + // Nothing was spent. First time: the chest simply isn't locked - open it. After a + // looted chest: it has not re-locked (and regenerated) yet - ask again later. + if (!_relockExpected) + { + State = Phase.OpenPending; + _nextTryAt = now + 400; + return; + } + if (++_probes > MaxProbes) + { + Finish($"{ChestName} hasn't re-locked after {MaxProbes} tries ({(MaxProbes * ProbeMs + RegenWaitMs) / 60000} min): its reset timer may be longer, or it doesn't lock"); + return; + } + _env.Log($"[RynthAi] Chest looter: {ChestName} is still unlocked (not reset yet); asking again in {ProbeMs / 1000} s (try {_probes} of {MaxProbes})"); + EnterWaiting(now + ProbeMs); + return; + + case ErrKeyDoesntFit: + Finish($"that key doesn't fit {ChestName}"); + return; + case ErrCannotLockOrUnlock: + Finish($"the server says {ChestName} can't be unlocked with a key"); + return; + case ErrCannotLockWhatIsOpen: + if (++_openElsewhere >= MaxOpenElsewhere) { Finish($"{ChestName} stays open (someone else has it?)"); return; } + _env.Log($"[RynthAi] Chest looter: {ChestName} is open; trying again in 5 s"); + EnterWaiting(now + 5000); + return; + case ErrCannotUseThatItem: + // A key with no uses left: ACE deletes it. + _keyUsedUp = true; + _env.Log("[RynthAi] Chest looter: the server says the key can't be used (spent); looking for another"); + State = Phase.KeyPending; + _nextTryAt = now + SendRetryMs; + return; + case ErrTooBusy: + if (++_busy >= MaxBusy) { Finish("the server keeps answering 'too busy'"); return; } + _nextTryAt = now + BusyBackoffMs; + State = Phase.KeyPending; + return; + default: + if (++_refusals >= MaxRefusals) { Finish($"the server refused the key use (0x{err:X})"); return; } + _env.Log($"[RynthAi] Chest looter: the server answered the key use with error 0x{err:X}; trying again"); + _nextTryAt = now + RetryMs; + State = Phase.KeyPending; + return; + } + } + + private void Retry(long now, Phase back, string why) + { + if (++_timeouts >= MaxTimeouts) { Finish(why); return; } + _env.Log($"[RynthAi] Chest looter: {why}; trying again ({_timeouts} of {MaxTimeouts})"); + State = back; + _nextTryAt = now + RetryMs; + } + + private void TickOpenPending(long now) + { + if (now < _nextTryAt) return; + // Another opener already put it in front of us (the player, or the looter's own take). + if (_env.ChestOpenedAt(ChestId) > _keySentAt) { OnOpened(now); return; } + if (Held(now)) return; + _seqAtSend = _env.UseDoneSeq(); + if (!_env.SendOpen(ChestId)) + { + if (++_sendFails >= MaxSendFails) Finish("the client wouldn't send the open"); + else _nextTryAt = now + SendRetryMs; + return; + } + _sendFails = 0; + _openSentAt = now; + _answerSeen = false; + State = Phase.OpenOut; + } + + private void TickOpenOut(long now) + { + if (_env.ChestOpenedAt(ChestId) >= _openSentAt) { OnOpened(now); return; } + if (!_answerSeen && Answered(_openSentAt, out _)) { _answerSeen = true; _answeredAt = now; } + bool failed = _answerSeen ? now - _answeredAt >= OpenSettleMs : now - _openSentAt >= AnswerMaxMs; + if (!failed) return; + if (++_openFails >= MaxOpenFails) + { + Finish($"{ChestName} wouldn't open ({MaxOpenFails} tries: still locked, or someone else is using it)"); + return; + } + _env.Log($"[RynthAi] Chest looter: {ChestName} didn't open (try {_openFails} of {MaxOpenFails})"); + State = _keyUsesThisCycle == 0 || !_sawUnlocked ? Phase.KeyPending : Phase.OpenPending; + _nextTryAt = now + 2000; + } + + private void OnOpened(long now) + { + _openedAt = _env.ChestOpenedAt(ChestId); + if (_openedAt == 0) _openedAt = now; + _env.StartLooting(ChestId); + _lootSeen = _env.Looting(ChestId); + _lootStartedAt = now; + _timeouts = 0; + State = Phase.Looting; + } + + private void TickLooting(long now) + { + if (_env.Looting(ChestId)) + { + _lootSeen = true; + if (now - _lootStartedAt >= LootMaxMs) Finish($"looting {ChestName} took more than {LootMaxMs / 60000} minutes"); + return; + } + if (!_lootSeen && now - _lootStartedAt < LootStartMs) return; + if (!_lootSeen) { Finish($"the loot window never took {ChestName}"); return; } + + // The loot session ended and the chest is closed. + Looted++; + _cycles++; + _probes = 0; + _relockExpected = true; + _env.Say($"[RynthAi] Chest looter: looted {ChestName} ({Looted} so far)."); + int key = _env.FindKey(KeyId, KeyName, _keyUsedUp ? KeyId : 0); + if (key == 0) { Finish($"out of keys after {Looted} chest(s)"); return; } + if (_cycles >= MaxCycles) { Finish($"reached {MaxCycles} cycles (a key with unlimited uses never runs out)"); return; } + KeyId = key; + _keyUsedUp = false; // that was the old key; the one chosen now has not been used + EnterWaiting(Math.Max(now + 2000, _openedAt + RegenWaitMs)); + } + + private void EnterWaiting(long until) + { + _waitUntil = until; + State = Phase.Waiting; + } + + private void TickWaiting(long now) + { + // The key may leave the pack meanwhile (traded, dropped): nothing to wait for then. + if (_env.FindKey(KeyId, KeyName, _keyUsedUp ? KeyId : 0) == 0) { Finish($"out of keys - no '{KeyName}' left"); return; } + if (now >= _waitUntil) { State = Phase.Ready; return; } + if (_probes == 0 && now >= _openedAt + MinRelockMs && _env.ChestLockedHint(ChestId) == true) + { + _env.Log($"[RynthAi] Chest looter: {ChestName} reads locked again; next cycle"); + State = Phase.Ready; + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/ItemTool/QuickGive.cs b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/QuickGive.cs new file mode 100644 index 0000000..3f59643 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/ItemTool/QuickGive.cs @@ -0,0 +1,234 @@ +// ============================================================================ +// QuickGive.cs - the Item Tool's "Quick give". +// +// Tom picks an item in his pack and a target (a player or an NPC) in the world, presses Give, and +// every matching item in the packs is handed to that target, one give after another, until none +// is left or Stop. A pure state machine over IQuickGiveEnv (the plugin implements it, +// RynthAiPlugin.ItemTool.cs; the host tests fake it). +// +// This is NOT the profile give (actiontrygiveprofile, ItemGiver\ files, /ra ig): that one is +// locked to NPCs and a folder because a shared meta could run it. Quick give shares nothing with +// it but AC's give action itself (GiveObjectTo, one whole object per call), and it only starts +// from the Item Tool panel's button or a /ra itemtool command Tom types (the plugin checks the +// source before Start). +// +// Pacing: one give in flight at a time. The next goes after the last LANDED (the item left the +// pack, or its stack shrank) plus PaceMs; a give with no answer in ConfirmMs, or one the server +// refused (WeenieError / InventoryServerSaveFailed), counts as a refusal and the item is left out +// for the rest of the run. MaxRefusals in a row stop the run. +// +// Items are matched by exactly what Tom picked: the same weenie class id (when the engine can +// read it) and the same name. Nothing else is ever given. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi.ItemTool; + +/// What the picked item is: its weenie class id (0 = unreadable) and its exact name. +internal readonly record struct GiveItemKey(uint Wcid, string Name); + +internal interface IQuickGiveEnv +{ + long Now { get; } + /// The target is in the object cache: its current name and distance in metres (-1 unknown). + bool TargetLoaded(int targetId, out string name, out double meters); + bool InCombat(); + /// Why a give can't go out now (the client is busy, the server owes an answer); null = free. + string? HoldReason(); + /// The next carried (never worn) item matching that is not in . + bool NextItem(GiveItemKey key, ISet skip, out int itemId, out int count); + /// How many matching items are still carried (whole objects). + int CountCarried(GiveItemKey key); + /// The item left the pack, or its stack shrank below . + bool Landed(int itemId, int count); + /// AC's give action for the whole object. False when the engine refused to send it. + bool Send(int itemId, int targetId); + /// A count of the server's refusals so far (rises when one arrives). + int RefusalSeq(); + void Say(string text); + void Log(string text); +} + +internal sealed class QuickGive +{ + public enum Phase { Idle, Pending, InFlight } + + /// The target must be this near to start; it ends the run if it gets farther than . + public const double StartMeters = 10, StopMeters = 15; + public const long PaceMs = 350, ConfirmMs = 6000, RefuseBackoffMs = 1000, HoldMaxMs = 60_000, GoneMs = 1500; + public const int MaxRefusals = 3, MaxSendFails = 5, MaxGives = 2000; + private const long ThinkMs = 50; + + private readonly IQuickGiveEnv _env; + private readonly HashSet _skip = new(); + + public QuickGive(IQuickGiveEnv env) => _env = env; + + public int ItemId { get; private set; } + public GiveItemKey Item { get; private set; } + public int TargetId { get; private set; } + public string TargetName { get; private set; } = ""; + public Phase State { get; private set; } = Phase.Idle; + public bool Running => State != Phase.Idle; + /// Items (whole objects) the server took this run, and the units in them. + public int Given { get; private set; } + public int Units { get; private set; } + public string LastResult { get; private set; } = ""; + + private long _lastThink, _nextAt, _sentAt, _goneSince, _holdSince, _leftAt; + private int _inFlightId, _inFlightCount, _refusalSeqAtSend, _refusals, _sendFails, _left; + private string _holdWhy = ""; + + public void SetItem(int id, GiveItemKey key) { if (!Running) { ItemId = id; Item = key; } } + public void SetTarget(int id, string name) { if (!Running) { TargetId = id; TargetName = name; } } + public void Clear() { if (!Running) { ItemId = 0; Item = default; TargetId = 0; TargetName = ""; LastResult = ""; } } + + public bool Start(out string why) + { + why = ""; + if (Running) { why = "Quick give is already running"; return false; } + if (ItemId == 0 || Item.Name.Length == 0) { why = "pick an item first (select it in your pack, then 'Use selected as item')"; return Refuse(why); } + if (TargetId == 0) { why = "pick a target first (select the player or NPC in the world, then 'Use selected as target')"; return Refuse(why); } + if (!_env.TargetLoaded(TargetId, out string name, out double meters)) { why = $"{TargetName} isn't loaded (out of view?)"; return Refuse(why); } + if (!string.Equals(name, TargetName, StringComparison.OrdinalIgnoreCase)) { why = $"the target changed ('{TargetName}' is now '{name}'); pick it again"; return Refuse(why); } + if (meters < 0 || meters > StartMeters) { why = $"{TargetName} is {(meters < 0 ? "too far" : meters.ToString("0") + " m away")} (give range is {StartMeters:0} m); walk closer"; return Refuse(why); } + if (_env.InCombat()) { why = "you are in a fight"; return Refuse(why); } + int have = _env.CountCarried(Item); + if (have == 0) { why = $"no '{Item.Name}' in your packs"; return Refuse(why); } + + Given = 0; Units = 0; _refusals = 0; _sendFails = 0; _goneSince = 0; _holdSince = 0; _nextAt = 0; _lastThink = 0; _left = have; _leftAt = _env.Now; + _skip.Clear(); + LastResult = ""; + State = Phase.Pending; + _env.Say($"[RynthAi] Quick give: giving every '{Item.Name}' ({have} in your packs) to {TargetName}. Stop: /ra itemtool givestop."); + _env.Log($"[RynthAi] Quick give: start item '{Item.Name}' wcid 0x{Item.Wcid:X} x{have} -> 0x{(uint)TargetId:X8} '{TargetName}' ({meters:0.0} m)"); + return true; + } + + private bool Refuse(string why) + { + _env.Say($"[RynthAi] Quick give: can't start - {why}."); + return false; + } + + public void Stop(string why = "stopped") + { + if (!Running) { _env.Say("[RynthAi] Quick give: not running."); return; } + Finish(why); + } + + private void Finish(string why) + { + State = Phase.Idle; + _inFlightId = 0; + LastResult = $"stopped: {why} ({Given} item(s), {Units} unit(s) given to {TargetName})"; + _env.Say($"[RynthAi] Quick give {LastResult}."); + _env.Log($"[RynthAi] Quick give: finish - {why}; gave {Given} ({Units} units)"); + } + + public string Status + { + get + { + switch (State) + { + case Phase.Idle: return LastResult.Length > 0 ? $"Quick give {LastResult}." : "Idle."; + default: + string hold = _holdWhy.Length > 0 ? $" (waiting: {_holdWhy})" : ""; + return $"Giving '{Item.Name}' to {TargetName}: {Given} given ({Units} units), {_left} left{hold}."; + } + } + } + + public void Tick() + { + if (State == Phase.Idle) return; + long now = _env.Now; + if (now - _lastThink < ThinkMs) return; + _lastThink = now; + + // The target must stay the one Tom picked, loaded and near. + if (!_env.TargetLoaded(TargetId, out string name, out double meters)) + { + if (_goneSince == 0) _goneSince = now; + else if (now - _goneSince >= GoneMs) Finish($"{TargetName} is gone"); + return; + } + _goneSince = 0; + if (!string.Equals(name, TargetName, StringComparison.OrdinalIgnoreCase)) { Finish($"the target changed ('{TargetName}' is now '{name}')"); return; } + if (meters < 0 || meters > StopMeters) { Finish($"{TargetName} is out of give range ({(meters < 0 ? "position unknown" : meters.ToString("0") + " m")})"); return; } + if (_env.InCombat()) { Finish("a fight started"); return; } + + if (now - _leftAt >= 500) { _left = _env.CountCarried(Item); _leftAt = now; } + + if (State == Phase.InFlight) { TickInFlight(now); return; } + TickPending(now); + } + + private void TickPending(long now) + { + if (now < _nextAt) return; + string? why = _env.HoldReason(); + if (why != null) + { + _holdWhy = why; + if (_holdSince == 0) _holdSince = now; + else if (now - _holdSince >= HoldMaxMs) Finish($"waited {HoldMaxMs / 1000} s: {why}"); + return; + } + _holdSince = 0; + _holdWhy = ""; + + if (Given + _refusals >= MaxGives) { Finish($"reached {MaxGives} gives"); return; } + if (!_env.NextItem(Item, _skip, out int id, out int count)) + { + Finish(Given > 0 ? "done - no more of that item" : "no more of that item to give"); + return; + } + _refusalSeqAtSend = _env.RefusalSeq(); + if (!_env.Send(id, TargetId)) + { + if (++_sendFails >= MaxSendFails) Finish("the client wouldn't send the give"); + else _nextAt = now + RefuseBackoffMs; + return; + } + _sendFails = 0; + _inFlightId = id; + _inFlightCount = count; + _sentAt = now; + State = Phase.InFlight; + } + + private void TickInFlight(long now) + { + if (_env.Landed(_inFlightId, _inFlightCount)) + { + Given++; + Units += _inFlightCount; + _skip.Add(_inFlightId); // it is the target's now, whatever a stale inventory read still says + _refusals = 0; + _left = Math.Max(0, _left - 1); + State = Phase.Pending; + _nextAt = now + PaceMs; + return; + } + if (_env.RefusalSeq() != _refusalSeqAtSend) { Refused(now, "the server refused it"); return; } + if (now - _sentAt >= ConfirmMs) Refused(now, $"no answer in {ConfirmMs / 1000} s"); + } + + private void Refused(long now, string why) + { + _skip.Add(_inFlightId); + _env.Log($"[RynthAi] Quick give: 0x{(uint)_inFlightId:X8} not given - {why} ({_refusals + 1} of {MaxRefusals} in a row)"); + _inFlightId = 0; + if (++_refusals >= MaxRefusals) + { + Finish($"{MaxRefusals} refusals in a row (last: {why})"); + return; + } + State = Phase.Pending; + _nextAt = now + RefuseBackoffMs; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs index 710e717..69bc3c7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs @@ -789,6 +789,8 @@ internal sealed class LegacyAdvancedSettingsUi case "Navigation": ImGui.Checkbox("Boost Nav Priority", ref _settings.BoostNavPriority); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("RynthAi only navigates: no hunting, no looting, no fighting back (owner's rule, 2026-11-02). With no route it stands idle. Buffing and healing still run."); ImGui.SetNextItemWidth(120); ImGui.InputFloat("Nav point reach (yd)", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f"); _settings.FollowNavMin = LegacyUiSettings.ClampFollowNavMin(_settings.FollowNavMin); @@ -1100,6 +1102,9 @@ internal sealed class LegacyAdvancedSettingsUi ImGui.Checkbox("Learn Unknown Spells", ref _settings.ReadUnknownScrolls); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Loots scrolls of spells you don't know and can learn (magic school trained or\nspecialized, skill high enough), and reads them when it's safe. Scrolls already\nin your pack are read too."); + ImGui.Checkbox("Pickup with macro off", ref _settings.LootChestsMacroOff); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("A chest you open is looted by the loaded loot profile\neven with the macro or Looting off."); ImGui.Checkbox("Jump When Looting", ref _settings.LootJumpEnabled); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Hop (the keyboard jump) just before each pickup,\nso the server skips the bend-down. The hop has a fixed height."); diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs index 7e80a1b..65a6a72 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs @@ -22,7 +22,8 @@ internal readonly record struct DashboardReadout( bool Locked, float Opacity, string LootPath, bool TargetIsFight = false, - int LootMode = 0); + int LootMode = 0, + bool BoostNav = false); /// The loaded-files pickers: each list, and the entry in use. internal sealed record DashboardFiles( @@ -50,7 +51,8 @@ internal sealed partial class LegacyDashboardRenderer _playerHealth, _playerMaxHealth, _playerStamina, _playerMaxStamina, _playerMana, _playerMaxMana, _isLocked, _bgOpacity, !string.IsNullOrEmpty(_vendorProfilePath?.Invoke()) ? _vendorProfilePath!.Invoke() : _settings.CurrentLootPath ?? string.Empty, - LootMode: Loot.LootModes.Clamp(_settings.LootMode)); + LootMode: Loot.LootModes.Clamp(_settings.LootMode), + BoostNav: _settings.BoostNavPriority); } /// The five pickers' lists (copied under the lists' lock) and the entry in use. Any thread. diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index c9abe77..27ee1d5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -348,6 +348,13 @@ internal sealed partial class LegacyDashboardRenderer get => _rynthChatUi.OnSubmit; set => _rynthChatUi.OnSubmit = value; } + + /// The nav window's "Patrol this dungeon" button (shown while an area hold offers it). + public Action? StartPatrolHandler + { + get => _navigationUi.StartPatrol; + set => _navigationUi.StartPatrol = value; + } public void SetWorldObjectCache(WorldObjectCache cache) { _rynthRadarUi.SetWorldObjectCache(cache); @@ -1363,6 +1370,8 @@ internal sealed partial class LegacyDashboardRenderer DunPatrolWallDistance = s.DunPatrolWallDistance, DunPatrolLookInSize = s.DunPatrolLookInSize, DunPatrolSightYd = s.DunPatrolSightYd, + OutdoorHuntRange = s.OutdoorHuntRange, + OutdoorHuntRadius = s.OutdoorHuntRadius, T2Speed = s.T2Speed, T2WalkWithinYd = s.T2WalkWithinYd, T2DistanceTo = s.T2DistanceTo, @@ -1396,6 +1405,7 @@ internal sealed partial class LegacyDashboardRenderer BoostLootPriority = s.BoostLootPriority, LootOnlyRareCorpses = s.LootOnlyRareCorpses, LootJumpEnabled = s.LootJumpEnabled, + LootChestsMacroOff = s.LootChestsMacroOff, LootJumpHeight = s.LootJumpHeight, LootOwnership = s.LootOwnership, LootOwnCorpse = s.LootOwnCorpse, @@ -1628,6 +1638,9 @@ internal sealed partial class LegacyDashboardRenderer if (p.DunPatrolWallDistance is float patrolWalls) s.DunPatrolWallDistance = (float)Math.Clamp(patrolWalls, DungeonPatrolOptions.WallClearanceMin, DungeonPatrolOptions.WallClearanceMax); if (p.DunPatrolLookInSize is float patrolLookIn) s.DunPatrolLookInSize = (float)Math.Clamp(patrolLookIn, DungeonPatrolOptions.LookInRoomMin, DungeonPatrolOptions.LookInRoomMax); if (p.DunPatrolSightYd is float patrolSight) s.DunPatrolSightYd = (float)Math.Clamp(patrolSight, DungeonPatrolOptions.SightMin, DungeonPatrolOptions.SightMax); + // Outdoor hunt: absent (an older engine) = unchanged. + if (p.OutdoorHuntRange is float huntRange) s.OutdoorHuntRange = (float)Math.Clamp(huntRange, RynthAiPlugin.OutdoorHuntRangeMin, RynthAiPlugin.OutdoorHuntRangeMax); + if (p.OutdoorHuntRadius is float huntRadius) s.OutdoorHuntRadius = (float)Math.Clamp(huntRadius, 0, RynthAiPlugin.OutdoorHuntRadiusMax); s.T2Speed = p.T2Speed; s.T2WalkWithinYd = p.T2WalkWithinYd; s.T2DistanceTo = p.T2DistanceTo; @@ -1658,6 +1671,7 @@ internal sealed partial class LegacyDashboardRenderer s.BoostLootPriority = p.BoostLootPriority; s.LootOnlyRareCorpses = p.LootOnlyRareCorpses; s.LootJumpEnabled = p.LootJumpEnabled; + s.LootChestsMacroOff = p.LootChestsMacroOff; s.LootJumpHeight = p.LootJumpHeight; s.LootOwnership = p.LootOwnership; if (p.EscapeHazards is bool escape) s.EscapeHazards = escape; // absent = unchanged @@ -2001,6 +2015,8 @@ internal sealed partial class LegacyDashboardRenderer dst.DunPatrolWallDistance = tmp.DunPatrolWallDistance; dst.DunPatrolLookInSize = tmp.DunPatrolLookInSize; dst.DunPatrolSightYd = tmp.DunPatrolSightYd; + dst.OutdoorHuntRange = tmp.OutdoorHuntRange; + dst.OutdoorHuntRadius = tmp.OutdoorHuntRadius; dst.T2Speed = tmp.T2Speed; dst.T2DistanceTo = tmp.T2DistanceTo; dst.T2ReissueMs = tmp.T2ReissueMs; @@ -2042,6 +2058,7 @@ internal sealed partial class LegacyDashboardRenderer dst.LootOpenRetryMs = tmp.LootOpenRetryMs; dst.LootCorpseTimeoutMs = tmp.LootCorpseTimeoutMs; dst.LootJumpEnabled = tmp.LootJumpEnabled; + dst.LootChestsMacroOff = tmp.LootChestsMacroOff; dst.LootJumpHeight = tmp.LootJumpHeight; dst.SalvageOpenDelayFirstMs = tmp.SalvageOpenDelayFirstMs; dst.SalvageOpenDelayFastMs = tmp.SalvageOpenDelayFastMs; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs index 5f4d9aa..7809ea6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs @@ -14,6 +14,9 @@ internal sealed class LegacyNavigationUi public Action? OnSettingsChanged; + /// Starts the Dungeon Patrol here (set by the plugin; run on the plugin tick). + public Action? StartPatrol; + private readonly string[] _routeTypes = { "Once", "Circular", "Linear", "Follow" }; private readonly string[] _addModes = { "End", "Above", "Below" }; private int _addModeIdx = 0; @@ -45,6 +48,15 @@ internal sealed class LegacyNavigationUi SafeImGui.TextColored(statusColor, _settings.NavStatusLine); } + // Held in a dungeon by a route with nothing here (a landscape route, another dungeon's): + // the way to run here is the Dungeon Patrol, offered right under the status (2026-11-01). + if (_settings.NavAreaHoldOffersPatrol && StartPatrol != null) + { + if (ImGui.Button("Patrol this dungeon##navAreaPatrol", new Vector2(-1, 24))) + StartPatrol(); + SafeImGui.SetItemTooltip("The loaded route has no waypoint in this dungeon. Builds the Dungeon Patrol here and runs it (the same as the Patrol button)."); + } + ImGui.Spacing(); bool navActive = _settings.IsMacroRunning && _settings.EnableNavigation; if (navActive) diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index af4a22b..0748f48 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -71,6 +71,11 @@ public sealed class LegacyUiSettings public float DunPatrolWallDistance = 1.0f; // metres every patrol point keeps from walls where there is room public float DunPatrolLookInSize = 10.0f; // rooms this big (m) the patrol only skirts get a walk to their middle public float DunPatrolSightYd = 20.0f; // sweep: how far a monster notices you, so how far apart the lanes may be + // Outdoor hunt (/ra hunt, Settings > Navigation > Outdoor Hunt; OutdoorHunt, 2026-10-23): walk from monster to + // monster around obstacles on RynthNav's map, into buildings through their doors (2026-10-25). + // Hunt Range 192 by default since 2026-10-25: the radar's default range, so the hunt covers the radar. + public float OutdoorHuntRange = (float)OutdoorHunt.DefaultRangeYd; // yd from the character: how far the next monster may be + public float OutdoorHuntRadius = 0f; // yd from where the hunt started that its picks stay within (0 = anywhere) // On: macro start, loading a Circular or Linear route, and nav taking over again after a // pause that moved the character (combat, looting, buffing, doors) all head for the closest // waypoint on the route. Off: a pause carries on to the waypoint it was heading for, a macro @@ -140,6 +145,12 @@ public sealed class LegacyUiSettings public int LootOpenRetryMs = LootBaseline.OpenRetryMs; public int LootCorpseTimeoutMs = LootBaseline.CorpseTimeoutMs; public bool LootJumpEnabled = false; + /// + /// Pickup with macro off (2026-11-02, on by default): a chest the player opens is looted by the + /// loaded loot profile even with the macro or Looting off (like /ra lootthis). With both on the + /// macro's own chest looting takes it. + /// + public bool LootChestsMacroOff = true; public int LootJumpHeight = 10; // kept for old profiles and metas; jump-loot uses the keyboard tap jump (fixed height) public int SalvageOpenDelayFirstMs = 400; @@ -878,6 +889,12 @@ public sealed class LegacyUiSettings [JsonIgnore] public bool NavIsStuck = false; + /// Nav is held in a dungeon by a route none of whose waypoints is in it (a landscape + /// route, another dungeon's): the Dungeon Patrol is the way to run here, and the nav window + /// offers its button (NavigationEngine.AreaMismatchHold sets it, the hold ending clears it). + [JsonIgnore] + public bool NavAreaHoldOffersPatrol = false; + // Runtime-only: the object id of the portal/NPC the nav engine is actively // using (resolved by FirePortalNpcUse), or 0 when not using one. Lets the // marker renderer draw a ring + line to the portal's REAL position, since @@ -1159,6 +1176,9 @@ public sealed class SettingsBridgePayload public float? DunPatrolWallDistance { get; set; } public float? DunPatrolLookInSize { get; set; } public float? DunPatrolSightYd { get; set; } + // Outdoor hunt. Nullable: an engine that predates them doesn't send them. + public float? OutdoorHuntRange { get; set; } + public float? OutdoorHuntRadius { get; set; } // Absent from an older engine's payload: must not read as off. public bool YieldToVTank { get; set; } = true; public bool EnableRaycasting { get; set; } @@ -1353,6 +1373,7 @@ public sealed class SettingsBridgePayload public bool BoostLootPriority { get; set; } public bool LootOnlyRareCorpses { get; set; } public bool LootJumpEnabled { get; set; } + public bool LootChestsMacroOff { get; set; } = true; // an engine that doesn't know it leaves it on public int LootJumpHeight { get; set; } public int LootOwnership { get; set; } // Nullable, as CastBuffsOverItemBuffs: an engine that predates them doesn't send them, diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs index ff23ac0..d82bc87 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs @@ -275,6 +275,8 @@ public sealed partial class RynthAiPlugin ["rebuftimeremainingseconds"] = "RebuffSecondsRemaining", ["navclosestoprange"] = "NavCloseStopRange", ["follownavmin"] = "FollowNavMin", + ["outdoorhuntrange"] = "OutdoorHuntRange", + ["outdoorhuntradius"] = "OutdoorHuntRadius", // UtilityBelt AutoVendor options (/ub opt set AutoVendor.TestMode true) ["autovendor.enabled"] = "AutoVendorEnabled", ["autovendor.enablebuying"] = "AutoVendorEnableBuying", diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index 64c8fd8..2806eb0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3748,6 +3748,8 @@ internal sealed partial class ExpressionEngine ["NavRecoveryEnabled"] = (() => B(s.NavRecoveryEnabled), v => s.NavRecoveryEnabled = ToDouble(v) != 0), ["NavResumeNearest"] = (() => B(s.NavResumeNearest), v => s.NavResumeNearest = ToDouble(v) != 0), ["NavOffTrackYards"] = (() => F(s.NavOffTrackYards), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavOffTrackYards = Math.Clamp(f, 160f, 1000f); }), + ["OutdoorHuntRange"] = (() => F(s.OutdoorHuntRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.OutdoorHuntRange = (float)Math.Clamp(f, RynthAiPlugin.OutdoorHuntRangeMin, RynthAiPlugin.OutdoorHuntRangeMax); }), + ["OutdoorHuntRadius"] = (() => F(s.OutdoorHuntRadius), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.OutdoorHuntRadius = (float)Math.Clamp(f, 0, RynthAiPlugin.OutdoorHuntRadiusMax); }), ["NavMaxDetourAttempts"] = (() => I(s.NavMaxDetourAttempts), v => { if (int.TryParse(v, out int i)) s.NavMaxDetourAttempts = Math.Clamp(i, 1, 10); }), ["OpenDoorRange"] = (() => F(s.OpenDoorRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.OpenDoorRange = f; }), ["BoostNavPriority"] = (() => B(s.BoostNavPriority), v => s.BoostNavPriority = ToDouble(v) != 0), diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs b/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs index 76c2ec8..ed3268b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs @@ -215,9 +215,10 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner unsafe { // Resolved on every call: RynthNav may be missing, or reloaded since last time. - IntPtr p = _host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, RynthNavPathApiV1.InterfaceVersion); + // Version 1 (FindPath is all this needs): a RynthNav from before v2 answers it too. + IntPtr p = _host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, 1); var t = (RynthNavPathApiV1*)p; - if (t == null || t->Version < 1 || t->StructSize < (uint)sizeof(RynthNavPathApiV1) || t->FindPath == null) + if (t == null || t->Version < 1 || t->StructSize < RynthNavPathApiV1.SizeV1 || t->FindPath == null) { why = "RynthNav isn't loaded"; return null; diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index bf9e3cc..2c1b872 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -211,6 +211,16 @@ internal sealed class NavigationEngine private long _areaMismatchSince; private string _areaMessage = string.Empty; private string _areaAnnounced = string.Empty; + // The two places the last mismatch named ("the landscape", "in dungeon 0x5756"). + private string _areaRouteName = string.Empty; + private string _areaPlayerName = string.Empty; + // The look along the route for a waypoint in the character's area (TryCarryOnHere) runs once + // per route / landblock / indoors-or-out; a look that found none is not repeated on the + // 3 s rechecks. Null route = not looked yet. + private NavRouteParser? _areaScanRoute; + private uint _areaScanLb = uint.MaxValue; + private bool _areaScanInCell; + private bool _areaScanNone; // A route that walks INTO a portal has its last point on this side and the next // one on the other side. For a few seconds after reaching that last point, keep // walking on through it (the way the route came in) so the portal can fire, @@ -2460,6 +2470,12 @@ internal sealed class NavigationEngine _areaPlayerLb = uint.MaxValue; _areaRetryAt = 0; _areaMismatch = false; + // A new route, a teleport or a macro start: a hold that comes back says so again (a route + // loaded again over the same hold used to change nothing the player could see, 2026-11-01). + _areaAnnounced = string.Empty; + _areaScanRoute = null; + _areaScanNone = false; + _settings.NavAreaHoldOffersPatrol = false; } private string DescribeRecovery() @@ -2479,6 +2495,17 @@ internal sealed class NavigationEngine /// join those, so nothing is attempted; one chat line per mismatch. The check is /// recomputed only when the waypoint, the route or the character's landblock/cell /// kind changes, and resumes on its own when they match again (e.g. after a portal). + /// + /// Three cases (2026-11-01): + /// - At the route's own way out (the character stands at the last waypoint before the + /// change, a walk-in portal): walk on through it for a few seconds, then hold. + /// - Anywhere else (the character got here by a portal, a recall, a death, or loaded the + /// route here): the route is looked along, in the order it is walked, for the first + /// waypoint in the character's area, and nav carries on from there. A Circular route + /// whose loop starts with a recall cast in this dungeon goes on to that recall. + /// - No waypoint of the route is here: hold, and say once what to do (load a route for + /// here; in a dungeon, or press Patrol). + /// Nothing is ever walked in an area its waypoint isn't in. /// private bool AreaMismatchHold(NavRouteParser route, int idx, NavPoint pt) { @@ -2507,20 +2534,39 @@ internal sealed class NavigationEngine if (_areaMismatch) { if (!was) _areaMismatchSince = Now; + _areaRouteName = routeArea; + _areaPlayerName = playerArea; _areaMessage = $"Nav: this route is in a different area ({routeArea}) - you are {playerArea}. Navigation stopped."; if (_detour != null) EndDetour("the route is in a different area", success: false); } else if (was) { _areaAnnounced = string.Empty; + _settings.NavAreaHoldOffersPatrol = false; _host.Log($"Nav: the route's area matches again at waypoint [{idx}] - navigation resumes"); } } if (!_areaMismatch) return false; - if (Now - _areaMismatchSince < (long)AreaGraceMs && AreaGraceWalk(route, idx)) + if (AtAreaBoundary(route, idx)) + { + // The route's own way out: walk on through for the grace, then hold (the portal didn't fire). + if (Now - _areaMismatchSince < (long)AreaGraceMs && AreaGraceWalk(route, idx)) + return true; + } + else if (TryCarryOnHere(route, idx, cell, lb, inCell)) + { return true; + } + else if (_areaScanNone) + { + // Nothing of this route is here: say what to do instead of only "stopped". + _areaMessage = $"Nav: this route is in a different area ({_areaRouteName}) - you are {_areaPlayerName}, and nothing ahead on it is here. " + + (inCell ? "Navigation is waiting: load a route for this dungeon, or press Patrol to patrol it." + : "Navigation is waiting: load a route for here."); + _settings.NavAreaHoldOffersPatrol = inCell; + } // Hold: one chat line per mismatch. if (_areaMessage != _areaAnnounced) @@ -2531,10 +2577,108 @@ internal sealed class NavigationEngine } StopMovement(); _settings.NavIsStuck = true; - _settings.NavStatusLine = "Nav: route is in a different area - stopped"; + _settings.NavStatusLine = _areaScanNone + ? $"Nav: this route is for {_areaRouteName} - load a route for here{(inCell ? " or press Patrol" : "")}" + : "Nav: route is in a different area - stopped"; return true; } + /// + /// The character stands at (within AreaGraceNearYd of) the walk point just before + /// : the route's own way into the other area (a walk-in portal there). + /// + private bool AtAreaBoundary(NavRouteParser route, int idx) + { + int prev = PrevIndex(idx, route); + if (prev < 0 || !IsWalkTarget(route.Points[prev].Type)) return false; + if (!TryGetPos(out double ns, out double ew)) return false; + var p = route.Points[prev]; + return NavYd(p.NS - ns, p.EW - ew) <= AreaGraceNearYd; + } + + /// + /// The route looked along from in the order it is walked (a Circular + /// route round to the point before it, a Linear route to its end and back, a Once route to + /// its end) for the first waypoint in the character's area, of any kind (a recall cast here, + /// a portal used here, a point). Found: nav carries on from it, said once in chat, and true. + /// Not found: false, remembered () until the route or the + /// character's area changes. + /// + private bool TryCarryOnHere(NavRouteParser route, int idx, uint cell, uint lb, bool inCell) + { + if (ReferenceEquals(route, _areaScanRoute) && lb == _areaScanLb && inCell == _areaScanInCell && _areaScanNone) + return false; + _areaScanRoute = route; + _areaScanLb = lb; + _areaScanInCell = inCell; + _areaScanNone = false; + + // Only a clear Match counts: the dats are loaded by now (the current waypoint's check said + // Mismatch), so Unknown means a point off the map, which is nowhere to carry on from. + int found = -1, foundDir = _linearDir; + foreach (var (k, dir) in WalkOrderAfter(route, idx)) + { + var p = route.Points[k]; + if (_planner!.CheckArea(cell, p.NS, p.EW, out _, out _) != NavAreaCheck.Match) continue; + found = k; foundDir = dir; + break; + } + if (found < 0) + { + _areaScanNone = true; + return false; + } + + var to = route.Points[found]; + string msg = $"Nav: waypoint [{idx}] is in another area ({_areaRouteName}); [{found}] {to} is here ({PlaceName(_areaPlayerName)}) - carrying on from [{found}]."; + _host.WriteToChat(msg, 1); + _host.Log($"{msg} [cell 0x{cell:X8}]"); + + _settings.ActiveNavIndex = found; + if (route.RouteType == NavRouteType.Linear) _linearDir = foundDir; + _areaMismatch = false; + _areaAnnounced = string.Empty; + _settings.NavIsStuck = false; + _settings.NavAreaHoldOffersPatrol = false; + _settings.NavStatusLine = $"Nav: carrying on from [{found}], the route's next waypoint here"; + _closestDist = double.MaxValue; + _legStartNs = double.NaN; + _legStartEw = double.NaN; + _watchdogNs = double.NaN; + _watchdogEw = double.NaN; + _stuckCount = 0; + StopMovement(); + return true; + } + + /// + /// The waypoints after in the order nav walks them, each with the Linear + /// direction it is reached in. At most one lap; itself is not included. + /// + private IEnumerable<(int Idx, int Dir)> WalkOrderAfter(NavRouteParser route, int idx) + { + int n = route.Points.Count; + switch (route.RouteType) + { + case NavRouteType.Circular: + for (int s = 1; s < n; s++) yield return ((idx + s) % n, 1); + break; + case NavRouteType.Once: + for (int k = idx + 1; k < n; k++) yield return (k, 1); + break; + case NavRouteType.Linear: + int d = _linearDir >= 0 ? 1 : -1; + for (int k = idx + d; k >= 0 && k < n; k += d) yield return (k, d); + // ... then back from the far end: the points behind idx, reached heading the other way. + for (int k = idx - d; k >= 0 && k < n; k -= d) yield return (k, -d); + break; + } + } + + /// "in dungeon 0x5756" / "on the landscape" (CheckArea's wording) as a place: "dungeon 0x5756". + private static string PlaceName(string playerArea) + => playerArea.StartsWith("in ", StringComparison.Ordinal) || playerArea.StartsWith("on ", StringComparison.Ordinal) ? playerArea[3..] : playerArea; + /// /// Mismatch grace: when the character is at (within AreaGraceNearYd of) the last /// waypoint before the area change, keep walking a few yards on through it along the diff --git a/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs new file mode 100644 index 0000000..757468a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs @@ -0,0 +1,591 @@ +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Outdoor hunting (2026-10-23): walk from one monster to the next around obstacles. Pure: the plugin +/// (RynthAiPlugin.OutdoorHunt.cs) passes the character's position, the monsters combat would fight +/// (line of sight not needed: the walk goes round), a path function (RynthNav's navmesh, which holds +/// buildings, their insides, trees, rocks and slopes too steep to climb) and the clock, and installs the +/// route a asks for. Combat takes over by itself once a monster is within its +/// range and in sight (the arbiter ranks it above navigation); this is asked again only when nothing +/// else wants the character. +/// +/// The next monster is the one with the shortest walk (a higher Priority first), among the few nearest +/// in a straight line. A monster with no walkable way to it (on a cliff, in water, inside a closed +/// building) is left out for . Monsters are looked for out to +/// (Hunt Range); (Hunt Radius) keeps the picks within that far of where it started +/// (0 = anywhere). With nothing in range it waits where it is. +/// +/// Buildings (2026-10-25, Tom: "the entire radar range, also going inside houses"): RynthNav's map ends +/// at a building's walls, so a walk into one is RynthNav's way to the outside of one of its doors, then +/// the building's own rooms (: BuildingMap on cell.dat) to the monster; the door +/// giving the shortest walk in all is taken. From inside a building: a monster in the same building +/// through its rooms, one outdoors (or in another building) out through a door first. A building with +/// no door known is walked out of the way it was walked into (, the breadcrumbs). +/// +internal sealed class OutdoorHunt +{ + internal enum PathStatus { Ok, Partial, NoPath, NoMesh, Unavailable } + + /// A planned walk: the corners after the start (the last is the goal), its length, and for a + /// partial path how far its end is from the goal. + internal readonly record struct PathResult(PathStatus Status, IReadOnlyList Corners, double Length, double Gap); + + /// A spot (world units: x east, y north, z up). : a point lined up on a + /// doorway (walked through straight, NavPoint.Doorway). + internal readonly record struct Vec(double X, double Y, double Z, bool Door = false) + { + public double DistanceTo(Vec o) => Math.Sqrt((X - o.X) * (X - o.X) + (Y - o.Y) * (Y - o.Y) + (Z - o.Z) * (Z - o.Z)); + public double FlatDistanceTo(Vec o) => Math.Sqrt((X - o.X) * (X - o.X) + (Y - o.Y) * (Y - o.Y)); + } + + /// A monster combat would fight. : its landcell (a building's cells are 0x0100 up). + internal readonly record struct Candidate(int Id, string Name, Vec Pos, double Distance, int Priority, uint Cell = 0); + + /// + /// A building's door to the outside, in : its centre at floor level, + /// a step inside it (in Cell), a step out of it (on the + /// landscape, where RynthNav's way to or from the door ends or starts). + /// + internal readonly record struct Door(uint Cell, Vec Inner, Vec At, Vec Outside); + + /// What the hunt knows of the buildings round it: BuildingMap (cell.dat) in the plugin, fakes in the tests. + internal interface IBuildings + { + /// The building holding (any id but 0); 0 for a cell outdoors or one no known building holds. + int BuildingOf(uint cell); + /// The building's doors to the outside that can be walked through (none known: empty). + IReadOnlyList Doors(int building); + /// + /// The walk inside one building from (in fromCell) to + /// (in toCell), through its rooms and doorways and kept out of portals: corners after the start + /// (the last is the goal, or for Partial the nearest it gets), its length. NoPath when the two + /// don't join inside. + /// + PathResult Inside(uint fromCell, Vec from, uint toCell, Vec to); + /// A short name for log lines. + string Name(int building); + } + + /// A building's (or a dungeon's) cell, not the landscape's. + internal static bool IsIndoorCell(uint cell) => (cell & 0xFFFF) >= 0x0100; + + /// A walk planned by : the path, the door it leaves a building by and + /// the one it goes into a building by (null: none), the buildings (0: outdoors), why it failed. + internal readonly record struct HuntWalk(PathResult P, Door? Out = null, Door? In = null, int From = 0, int To = 0, string Why = ""); + + internal enum Act + { + /// Keep doing what the last decision said. + None, + /// Walk (replacing the hunt's route). + Walk, + /// Stand (take the hunt's route off): nothing to hunt and nowhere to go, or already at the + /// end of the walk to . + Idle, + } + + internal readonly record struct Decision(Act Act, IReadOnlyList? Corners = null, int TargetId = 0, string Why = ""); + + // Settings (the plugin copies them in before each Tick). + /// Hunt Range: 192 by default since 2026-10-25, the radar's own default range (Tom: "the entire radar range"). + public double RangeYd { get; set; } = DefaultRangeYd; + public const double DefaultRangeYd = 192; + public double RadiusYd { get; set; } = 0; + + /// A partial path whose end is within this of the monster still counts (the last step is combat's). + public double ReachYd { get; set; } = 3; + /// + /// A walk longer than this times Hunt Range is too far round: the first test hunt (10-23) chose a buff bot + /// 12 yd away inside a building, a 143 yd walk; the walk led her past Hunt Range from it, she gave up, + /// turned back, and chose it again, every second. + /// + public double MaxWalkFactor { get; set; } = 2.0; + /// + /// The plugin asks for monsters out to this times Hunt Range: new picks stay within Hunt Range, but the + /// one being walked to is kept while the walk round an obstacle takes the character further from it. + /// + public const double KeepFactor = 2.0; + /// A monster with no way to it is left out this long. + public double SkipSec { get; set; } = 120; + /// How many of the nearest monsters get a path asked for when choosing. + public int PickCandidates { get; set; } = 6; + public double PickEverySec { get; set; } = 1.0; + /// Plan again when the monster has moved this far from where the walk was planned to. + public double ReplanMovedYd { get; set; } = 4; + public double ReplanMinSec { get; set; } = 1.0; + /// Plan again at least this often while walking to a monster (it may have turned). + public double ReplanMaxSec { get; set; } = 8; + /// A walk this short: the character is already where the walk to the monster ends. + public double ArrivedYd { get; set; } = 2; + /// + /// At the end of the walk to a monster this long and combat hasn't taken it (the hunt is only asked + /// when nothing else wants the character): something stops combat, a wall or a fence between, and the + /// monster is left out for . a test character (10-23) stood at a wall re-walking 1 yd + /// every half second to a monster on its far side: the walk's end, 1.3 yd away, counted as reached. + /// + public double NoFightSec { get; set; } = 2; + + public bool Active { get; private set; } + public Vec Anchor { get; private set; } + public int TargetId { get; private set; } + /// The last thing worth a log line (the plugin logs it when it changes). + public string Note + { + get => _note; + private set { _note = value; _notes.Add(value); } + } + private string _note = ""; + private readonly List _notes = new(); + /// Every note since : one tick can have several (one left out, then the next chosen). + internal IReadOnlyList PendingNotes => _notes; + internal void ClearNotes() => _notes.Clear(); + + private Vec _plannedTo; + private DateTime _lastPlan = DateTime.MinValue, _lastPick = DateTime.MinValue; + private DateTime _arrivedSince = DateTime.MinValue; // at the walk's end with no fight since (NoFightSec) + private readonly Dictionary _skip = new(); + private readonly List<(Candidate C, HuntWalk W)> _viable = new(); + private Func _path = (_, _) => new PathResult(PathStatus.Unavailable, Array.Empty(), 0, 0); + private IBuildings? _buildings; + private int _meBuilding; // the building the character is in this tick (0: outdoors) + + public void Start(DateTime now, Vec at) + { + Active = true; + Anchor = at; + TargetId = 0; + _skip.Clear(); + _lastPlan = _lastPick = _arrivedSince = DateTime.MinValue; + Note = $"started at {at.X:0},{at.Y:0}"; + } + + public void Stop() + { + Active = false; + TargetId = 0; + WalkingOut = false; + _outTries = 0; + } + + /// Left out of the hunt for a while (no way to it, or combat gave up on it). + public void Skip(int id, DateTime now, double sec = -1) => _skip[id] = now.AddSeconds(sec < 0 ? SkipSec : sec); + + public bool IsSkipped(int id, DateTime now) + { + if (!_skip.TryGetValue(id, out var until)) return false; + if (now < until) return true; + _skip.Remove(id); + return false; + } + + /// + /// The next step. : the last walk ran out (arrived, or navigation stopped it). + /// : sorted nearest first. Called only when nothing else wants the character. + /// + public Decision Tick(DateTime now, Vec me, bool routeDone, IReadOnlyList candidates, Func path) + => Tick(now, me, 0, routeDone, candidates, path, null); + + /// + /// The next step, with the character's cell and the buildings round it + /// (, null = none known: monsters in buildings are left alone). In a + /// building no door of which is known, the walk back out the way in (). + /// + public Decision Tick(DateTime now, Vec me, uint meCell, bool routeDone, IReadOnlyList candidates, + Func path, IBuildings? buildings) + { + if (!Active) return new Decision(Act.None); + _path = path; + _buildings = buildings; + _now = now; + _meBuilding = 0; + if (IsIndoorCell(meCell)) + { + int inB = buildings?.BuildingOf(meCell) ?? 0; + if (inB == 0 || buildings!.Doors(inB).Count == 0) return Indoors(now, me, routeDone); + _meBuilding = inB; + WalkingOut = false; // the doors take it out from here + } + + // Still walking to a monster that is still there: plan again when it moved, the walk ran out, or a while passed. + if (TargetId != 0) + { + Candidate? t = null; + foreach (var c in candidates) + if (c.Id == TargetId) { t = c; break; } + if (t is Candidate target && InArea(target.Pos) && !IsSkipped(target.Id, now) && Plannable(target)) + { + double since = (now - _lastPlan).TotalSeconds; + bool moved = target.Pos.DistanceTo(_plannedTo) > ReplanMovedYd && since >= ReplanMinSec; + bool due = (routeDone && since >= 0.5) || since >= ReplanMaxSec; + if (!moved && !due) return new Decision(Act.None, TargetId: TargetId); + var w = PlanWalk(me, meCell, target.Pos, target.Cell); + var p = w.P; + if (Reaches(p)) + { + _plannedTo = target.Pos; + _lastPlan = now; + if (p.Length > ArrivedYd) + { + _arrivedSince = DateTime.MinValue; + return new Decision(Act.Walk, p.Corners, target.Id, $"to '{target.Name}' again ({p.Length:0} yd)"); + } + // Already at the walk's end: stand, no 1 yd walk (it ends at once and is planned + // again every half second); combat has NoFightSec to take the monster. + if (_arrivedSince == DateTime.MinValue) _arrivedSince = now; + if ((now - _arrivedSince).TotalSeconds < NoFightSec) return new Decision(Act.Idle, TargetId: target.Id); + Skip(target.Id, now); + Note = $"'{target.Name}': at the end of the walk to it for {NoFightSec:0} s and combat hasn't taken it " + + $"(a wall or a fence between?): left out for {SkipSec:0} s"; + } + else + { + Skip(target.Id, now); + Note = $"'{target.Name}' can't be reached any more ({Describe(p, w.Why)}): left out for {SkipSec:0} s"; + } + } + TargetId = 0; + _arrivedSince = DateTime.MinValue; + } + + // Choosing (at most once every PickEverySec): the few nearest, by the walk to them. + if ((now - _lastPick).TotalSeconds < PickEverySec) + return new Decision(Act.Idle); + _lastPick = now; + _viable.Clear(); + int asked = 0; + foreach (var c in candidates) + { + if (asked >= PickCandidates) break; + if (c.Distance > RangeYd) break; // nearest first + if (!InArea(c.Pos) || IsSkipped(c.Id, now) || !Plannable(c)) continue; + asked++; + var w = PlanWalk(me, meCell, c.Pos, c.Cell); + var p = w.P; + if (p.Status == PathStatus.Unavailable) return new Decision(Act.Idle, Why: "no pathfinder"); + if (Reaches(p)) _viable.Add((c, w)); + else + { + Skip(c.Id, now); + Note = $"'{c.Name}' left out for {SkipSec:0} s: {Describe(p, w.Why)}"; + } + } + if (_viable.Count > 0) + { + var best = _viable[0]; + for (int i = 1; i < _viable.Count; i++) + { + var v = _viable[i]; + if (v.C.Priority > best.C.Priority || (v.C.Priority == best.C.Priority && v.W.P.Length < best.W.P.Length)) best = v; + } + TargetId = best.C.Id; + _plannedTo = best.C.Pos; + _lastPlan = now; + Note = NextNote(best.C, best.W); + if (best.W.P.Length > ArrivedYd) + { + _arrivedSince = DateTime.MinValue; + return new Decision(Act.Walk, best.W.P.Corners, best.C.Id, Note); + } + _arrivedSince = now; // it's right here and combat hasn't taken it: NoFightSec, then left out + return new Decision(Act.Idle, TargetId: best.C.Id, Why: Note); + } + + // Nothing to hunt: wait where it is (no walk back to the start: Tom 10-23, "it shouldn't bother"). + string wait = $"nothing within Hunt Range ({RangeYd:0} yd){(RadiusYd > 0 ? $" inside Hunt Radius ({RadiusYd:0} yd)" : "")}: waiting here"; + if (_note != wait) Note = wait; + return new Decision(Act.Idle); + } + + // ── Indoors ────────────────────────────────────────────────────────────────────────────────── + // A building's rooms are off RynthNav's landscape map: it plans no walk from in there, and every + // monster came back "not on the map" (a test hunt 10-23, after combat chased one inside: the hunt left + // them all out and stood there). Combat still fights in there; for the walk back out, the way in. + // Since 2026-10-25 this is the fallback: Tick walks out through a door of a building it knows + // (IBuildings), and comes here only for one with no door known (or no building map at all). + + private readonly List _wayIn = new(); // [0] the last spot outdoors, then the steps inside + private bool _knowsOutdoors; + private Vec _lastOutdoors; + private DateTime _outPlannedAt = DateTime.MinValue; + private Vec _outEnd; + private int _outTries; + + /// A step of the way in is kept every this far. + public double StepYd { get; set; } = 1.5; + /// The walk out ends this far past the last spot outdoors (out of the doorway). + public double OutPastYd { get; set; } = 3; + /// Walks out that ended still inside, before giving up (waiting for the character to come out). + public int OutTriesMax { get; set; } = 3; + internal const int MaxSteps = 256; + + public bool WalkingOut { get; private set; } + internal int WayInSteps => _wayIn.Count; + + /// Every tick, whatever the character is doing: where it is, and whether that is in a building. + public void Track(Vec me, bool indoors) + { + if (!indoors) + { + _wayIn.Clear(); + _lastOutdoors = me; + _knowsOutdoors = true; + WalkingOut = false; + _outTries = 0; + return; + } + if (_wayIn.Count == 0) + { + if (!_knowsOutdoors) return; + _wayIn.Add(_lastOutdoors); + } + // Back near a step already on the way: the loop since is cut, so the way out stays the shortest known. + for (int i = 0; i < _wayIn.Count - 1; i++) + { + if (_wayIn[i].FlatDistanceTo(me) < StepYd) + { + _wayIn.RemoveRange(i + 1, _wayIn.Count - i - 1); + return; + } + } + if (_wayIn[^1].FlatDistanceTo(me) >= StepYd && _wayIn.Count < MaxSteps) _wayIn.Add(me); + } + + /// The walk back out: the steps in, newest first, the last spot outdoors, and past it; null when no way in is known. + internal List? WayOut(Vec me) + { + if (_wayIn.Count == 0) return null; + var way = new List(_wayIn.Count + 1); + for (int i = _wayIn.Count - 1; i >= 1; i--) + if (_wayIn[i].FlatDistanceTo(me) >= 1.0) way.Add(_wayIn[i]); + Vec door = _wayIn[0]; + way.Add(door); + Vec from = way.Count >= 2 ? way[^2] : me; + double dx = door.X - from.X, dy = door.Y - from.Y, len = Math.Sqrt(dx * dx + dy * dy); + if (len > 0.1) way.Add(new Vec(door.X + dx / len * OutPastYd, door.Y + dy / len * OutPastYd, door.Z)); + return way; + } + + /// + /// The hunt's step while the character is in a building (instead of , which plans on + /// the landscape): walk back out the way in. : the last walk ran out. + /// + public Decision Indoors(DateTime now, Vec me, bool routeDone) + { + if (!Active) return new Decision(Act.None); + if (WalkingOut) + { + if (!routeDone || (now - _outPlannedAt).TotalSeconds < 1) return new Decision(Act.None); + // The walk ran out. At its end and still inside counts against OutTriesMax; anywhere else + // (a fight took the character elsewhere, the walk was cut short) it is just planned again. + if (me.FlatDistanceTo(_outEnd) <= 2) _outTries++; + } + var way = _outTries >= OutTriesMax ? null : WayOut(me); + if (way == null) + { + string wait = _outTries >= OutTriesMax + ? $"inside a building: {OutTriesMax} walks out ended still inside: waiting" + : "inside a building and no way out known (the hunt never saw it outdoors): waiting"; + if (Note != wait) Note = wait; + WalkingOut = false; + return new Decision(Act.Idle); + } + WalkingOut = true; + _outPlannedAt = now; + _outEnd = way[^1]; + Note = $"inside a building: back out the way in ({way.Count} steps)"; + return new Decision(Act.Walk, way, TargetId, Note); + } + + private bool InArea(Vec p) => RadiusYd <= 0 || p.FlatDistanceTo(Anchor) <= RadiusYd; + + private bool Reaches(PathResult p) => + p.Corners.Count > 0 && (p.Status == PathStatus.Ok || (p.Status == PathStatus.Partial && p.Gap <= ReachYd)) + && p.Length <= RangeYd * MaxWalkFactor; + + private string Describe(PathResult p, string why = "") => p.Status switch + { + _ when p.Corners.Count > 0 && p.Length > RangeYd * MaxWalkFactor + && (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => $"a {p.Length:0} yd walk, too far round", + _ when why.Length > 0 => why, + PathStatus.Partial => $"the walk ends {p.Gap:0} yd short", + PathStatus.NoPath => "no walkable way", + PathStatus.NoMesh => "not on the map (indoors, or no map there)", + _ => p.Status.ToString(), + }; + + /// A monster in a building is hunted only when that building is known: its rooms, and a door + /// into it (or the character is in it already). + private bool Plannable(Candidate c) + { + if (!IsIndoorCell(c.Cell)) return true; + int b = _buildings?.BuildingOf(c.Cell) ?? 0; + return b != 0 && (b == _meBuilding || _buildings!.Doors(b).Count > 0); + } + + private string NextNote(Candidate c, HuntWalk w) + { + var b = _buildings; + string len = $"a {w.P.Length:0} yd walk"; + string away = $"({c.Distance:0} yd away)"; + static string At(Door d) => $"{d.At.X:0},{d.At.Y:0}"; + if (b == null || (w.From == 0 && w.To == 0)) return $"next: '{c.Name}', {len} {away}"; + if (w.Out is Door o && w.In is Door i) + return $"next: '{c.Name}', inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} out of {b.Name(w.From)} through the door at {At(o)}, " + + $"then in through the door at {At(i)} {away}"; + if (w.In is Door din) return $"next: '{c.Name}', inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} through the door at {At(din)} {away}"; + if (w.Out is Door dout) return $"next: '{c.Name}', {len} out of {b.Name(w.From)} through the door at {At(dout)} {away}"; + return $"next: '{c.Name}', inside {b.Name(w.To)} (cell {c.Cell:X8}), {len} through its rooms {away}"; + } + + // ── Walks into, out of and between buildings ─────────────────────────────────────────────────── + + /// Most door pairs tried for one walk between two buildings (each a RynthNav path). + internal const int MaxDoorPairs = 16; + /// A door whose step out is this far above or below RynthNav's ground there doesn't open + /// onto the ground (a balcony, the top of a wall). + public double DoorstepRiseYd { get; set; } = 1.5; + /// How long a doorstep's answer is kept. + public double DoorstepKeepSec { get; set; } = 60; + private readonly Dictionary<(uint, long, long), (bool Ok, DateTime Until)> _doorsteps = new(); + private DateTime _now; + + /// + /// The door's step out is on RynthNav's ground: the map's nearest point to it (a path from it to + /// itself) within ReachYd across and DoorstepRiseYd in height. Asked once per DoorstepKeepSec. + /// + private bool OnGround(Door d) + { + var key = (d.Cell, (long)Math.Round(d.Outside.X * 10), (long)Math.Round(d.Outside.Y * 10)); + if (_doorsteps.TryGetValue(key, out var known) && _now < known.Until) return known.Ok; + var p = _path(d.Outside, d.Outside); + if (p.Status == PathStatus.Unavailable) return true; // no pathfinder: the walk itself says so + bool ok = p.Status is PathStatus.Ok or PathStatus.Partial && p.Corners.Count > 0 + && p.Corners[^1].FlatDistanceTo(d.Outside) <= ReachYd + && Math.Abs(p.Corners[^1].Z - d.Outside.Z) <= DoorstepRiseYd; + if (_doorsteps.Count > 512) _doorsteps.Clear(); + _doorsteps[key] = (ok, _now.AddSeconds(DoorstepKeepSec)); + return ok; + } + + /// + /// The walk from (in meCell) to (in goalCell): on + /// RynthNav's map when both are outdoors; through the building's rooms when both are in one; else + /// out through a door of the building it is in and/or in through a door of the goal's, the door (or + /// pair) with the shortest walk in all. The corners run through each door's inner point, centre and + /// outer point (flagged Door). The walk's end (status, gap) is its last part's. + /// + internal HuntWalk PlanWalk(Vec me, uint meCell, Vec goal, uint goalCell) + { + var b = _buildings; + int from = b != null && IsIndoorCell(meCell) ? b.BuildingOf(meCell) : 0; + int to = b != null && IsIndoorCell(goalCell) ? b.BuildingOf(goalCell) : 0; + if (from == 0 && to == 0) return new HuntWalk(_path(me, goal)); + string why = ""; + if (from != 0 && from == to) + { + var inside = b!.Inside(meCell, me, goalCell, goal); + if (inside.Status is PathStatus.Ok or PathStatus.Partial && inside.Corners.Count > 0) + return new HuntWalk(inside, From: from, To: to); + why = $"no way to it through the rooms of {b.Name(from)}"; + // Its parts don't join inside: out by one door and in by another, as two buildings. + } + + // The ways out of the character's building (to each door's outer point) and into the goal's (from each door's outer point). + var outs = new List<(Door? D, PathResult P, double Cost)>(); + var ins = new List<(Door? D, PathResult P, double Cost)>(); + var none = new PathResult(PathStatus.Ok, Array.Empty(), 0, 0); + if (from == 0) outs.Add((null, none, 0)); + else + foreach (var d in b!.Doors(from)) + { + var p = b.Inside(meCell, me, d.Cell, d.Inner); + if (p.Status != PathStatus.Ok || !OnGround(d)) continue; + outs.Add((d, p, p.Length + d.Inner.DistanceTo(d.At) + d.At.DistanceTo(d.Outside))); + } + if (to == 0) ins.Add((null, none, 0)); + else + foreach (var d in b!.Doors(to)) + { + var p = b.Inside(d.Cell, d.Inner, goalCell, goal); + if (p.Status is not (PathStatus.Ok or PathStatus.Partial) || p.Corners.Count == 0 || !OnGround(d)) continue; + ins.Add((d, p, d.Outside.DistanceTo(d.At) + d.At.DistanceTo(d.Inner) + p.Length)); + } + if (outs.Count == 0 || ins.Count == 0) + { + if (why.Length == 0) + why = outs.Count == 0 ? $"no door of {b!.Name(from)} it can walk to" : $"no door of {b!.Name(to)} leads to it"; + return new HuntWalk(new PathResult(PathStatus.NoPath, Array.Empty(), 0, 0), From: from, To: to, Why: why); + } + + // Door pairs by the least their walk can be (the outdoor part at least the straight line): a + // pair that can't beat the best so far isn't asked for (each one is a RynthNav path). + var pairs = new List<(int O, int I, double Bound)>(); + for (int o = 0; o < outs.Count; o++) + for (int i = 0; i < ins.Count; i++) + { + Vec a = outs[o].D?.Outside ?? me, z = ins[i].D?.Outside ?? goal; + pairs.Add((o, i, outs[o].Cost + a.FlatDistanceTo(z) + ins[i].Cost)); + } + pairs.Sort((x, y) => x.Bound.CompareTo(y.Bound)); + + HuntWalk? best = null; + double bestLen = double.MaxValue; + bool unavailable = false; + int tried = 0; + foreach (var (o, i, bound) in pairs) + { + if (bound >= bestLen || tried >= MaxDoorPairs) break; + tried++; + var (dOut, pOut, cOut) = outs[o]; + var (dIn, pIn, cIn) = ins[i]; + Vec a = dOut?.Outside ?? me, z = dIn?.Outside ?? goal; + var land = _path(a, z); + if (land.Status == PathStatus.Unavailable) { unavailable = true; break; } + if (land.Status is not (PathStatus.Ok or PathStatus.Partial) || land.Corners.Count == 0) continue; + // Into a door: the way there must end at its doorstep (a door above the ground, on a + // balcony, leaves it the height of the floor short). + if (dIn != null && land.Gap > ReachYd) continue; + double len = cOut + land.Length + cIn; + if (len >= bestLen) continue; + var corners = new List(pOut.Corners.Count + land.Corners.Count + pIn.Corners.Count + 6); + if (dOut is Door x) { AddCorners(corners, pOut.Corners); AddCorner(corners, x.At); AddCorner(corners, x.Outside); } + AddCorners(corners, land.Corners); + PathResult whole; + if (dIn is Door y) + { + AddCorner(corners, y.Outside); AddCorner(corners, y.At); AddCorner(corners, y.Inner); + AddCorners(corners, pIn.Corners); + whole = new PathResult(pIn.Status, corners, len, pIn.Gap); + } + else whole = new PathResult(land.Status, corners, len, land.Gap); + best = new HuntWalk(whole, dOut, dIn, from, to); + bestLen = len; + } + if (best is HuntWalk found) return found; + if (unavailable) return new HuntWalk(new PathResult(PathStatus.Unavailable, Array.Empty(), 0, 0)); + if (why.Length == 0) + why = to != 0 ? $"no way to a door of {b!.Name(to)}" : $"no way to it from a door of {b!.Name(from)}"; + return new HuntWalk(new PathResult(PathStatus.NoPath, Array.Empty(), 0, 0), From: from, To: to, Why: why); + } + + /// Corners closer than this to the one before are one (RynthNav's way to a doorstep ends on it). + private const double SameCornerYd = 0.3; + + private static void AddCorner(List corners, Vec v) + { + if (corners.Count > 0 && corners[^1].DistanceTo(v) < SameCornerYd) + { + if (v.Door && !corners[^1].Door) corners[^1] = corners[^1] with { Door = true }; + return; + } + corners.Add(v); + } + + private static void AddCorners(List corners, IReadOnlyList more) + { + foreach (var v in more) AddCorner(corners, v); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs index db8f641..28687ab 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/PluginExports.cs @@ -757,6 +757,42 @@ public static unsafe class PluginExports catch { } } + // ── Item Tool (the engine's Item Tool panel: chest looter + Quick give) ───────────────── + // The panel polls the status JSON and posts its buttons' words. The command export is the + // panel's alone: a Quick give started through it is a button Tom pressed (the plugin treats + // chat lines from metas, scripts and the remote differently, RynthAiPlugin.ItemTool.cs). + + private static IntPtr _itemToolPtr = IntPtr.Zero; + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetItemToolJson", CallConvs = new[] { typeof(CallConvCdecl) })] + public static IntPtr GetItemToolJson() + { + try + { + string json = Runtime.Plugin?.BuildItemToolJson() ?? "{}"; + IntPtr newPtr = Marshal.StringToHGlobalAnsi(json); + IntPtr oldPtr = Interlocked.Exchange(ref _itemToolPtr, newPtr); + if (oldPtr != IntPtr.Zero) + Marshal.FreeHGlobal(oldPtr); + return newPtr; + } + catch + { + return IntPtr.Zero; + } + } + + [UnmanagedCallersOnly(EntryPoint = "RynthPluginItemToolCommand", CallConvs = new[] { typeof(CallConvCdecl) })] + public static void ItemToolCommand(IntPtr ansiArgs) + { + try + { + string args = ansiArgs != IntPtr.Zero ? (Marshal.PtrToStringAnsi(ansiArgs) ?? string.Empty) : string.Empty; + Runtime.Plugin?.QueueItemToolCommand(args.Trim(), trusted: true); + } + catch { /* never let a managed exception cross the native boundary */ } + } + private static IntPtr _patrolInfoPtr = IntPtr.Zero; [UnmanagedCallersOnly(EntryPoint = "RynthPluginGetPatrolInfoJson", CallConvs = new[] { typeof(CallConvCdecl) })] diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs index d7308a4..de48911 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs @@ -73,6 +73,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting public bool IsPortal; public bool IsFloor; // physics floor polygon — upward-facing, used by DungeonMapUiV2 public uint CellId; // full landcell id (0xXXYYNNNN) — for per-cell "explored" tracking + /// The polygon's key in its CellStruct (render polygons): what an EnvCell's portal + /// record names as its polygon (BuildingMap finds a building's doors by it). + public ushort PolyKey; } /// @@ -425,7 +428,8 @@ namespace RynthCore.Plugin.RynthAi.Raycasting CellY = envCell.PosY + globalOffsetY, CellZ = envCell.PosZ, IsPortal = poly.IsPortal, - CellId = cellId + CellId = cellId, + PolyKey = poly.Key, }); } } @@ -672,6 +676,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting // Index into the EnvCell's surface palette for the polygon's front (positive) side; // -1 when it has none (physics polygons carry -1). public short PosSurface = -1; + public ushort Key; // the polygon's key in its CellStruct } private CellGeometry GetCellGeometry(uint environmentId, uint cellStructIndex) @@ -837,7 +842,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting var poly = renderPolygons[i]; if (poly.VertexIds == null || poly.VertexIds.Count < 3) continue; - var cellPoly = new CellPolygon { IsPortal = portalIndices.Contains(poly.Key), PosSurface = poly.PosSurface }; + var cellPoly = new CellPolygon { IsPortal = portalIndices.Contains(poly.Key), PosSurface = poly.PosSurface, Key = poly.Key }; foreach (var vid in poly.VertexIds) { if (vertices.ContainsKey(vid)) @@ -870,7 +875,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting foreach (var poly in physicsPolys) { if (poly.VertexIds == null || poly.VertexIds.Count < 3) continue; - var cellPoly = new CellPolygon { PosSurface = poly.PosSurface }; + var cellPoly = new CellPolygon { PosSurface = poly.PosSurface, Key = poly.Key }; foreach (var vid in poly.VertexIds) { if (vertices.ContainsKey(vid)) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index 8490fd7..2fceb6a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -1151,6 +1151,48 @@ public sealed partial class RynthAiPlugin } } + /// + /// /ra navheading <degrees> <yards>: run to the point that far from here on that compass heading + /// (0 north, 90 east). Loads a one-point run-once route and turns navigation on. Lets a meta follow a + /// direction (a treasure map's "the site is to the northwest") with the nav engine, no keystrokes. + /// + private void HandleNavHeadingCommand(string[] parts) + { + var settings = _dashboard?.Settings; + if (settings == null) { ReplyFail("[RynthAi] Settings not ready."); return; } + if (parts.Length < 4 + || !double.TryParse(parts[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double deg) + || !double.TryParse(parts[3], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double yards) + || yards <= 0 || yards > 2000) + { + ReplyFail("[RynthAi] Usage: /ra navheading "); + return; + } + if (!Host.HasGetPlayerPose || !Host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _) + || !NavCoordinateHelper.TryGetNavCoords(Host, out double ns, out double ew)) + { + ReplyFail("[RynthAi] navheading: couldn't read where you are."); + return; + } + + double rad = deg * Math.PI / 180.0; + double unit = yards / 240.0; // nav coordinates are 240-yard units + var route = new NavRouteParser { RouteType = NavRouteType.Once }; + route.Points.Add(new NavPoint + { + Type = NavPointType.Point, + NS = ns + Math.Cos(rad) * unit, + EW = ew + Math.Sin(rad) * unit, + Z = z / 240.0, + }); + settings.CurrentNavPath = ""; + settings.CurrentRoute = route; + settings.ActiveNavIndex = 0; + settings.EnableNavigation = true; + Host.Log($"[RynthAi] navheading: {yards:0} yd on {deg:0}° -> NS {route.Points[0].NS:0.0000} EW {route.Points[0].EW:0.0000}"); + ReplyOk($"[RynthAi] Navigating {yards:0} yd on heading {deg:0}° (to NS {route.Points[0].NS:0.000} EW {route.Points[0].EW:0.000})."); + } + private void HandleAddNavPointCommand() { var settings = _dashboard?.Settings; @@ -2029,6 +2071,9 @@ public sealed partial class RynthAiPlugin // Interpretation — the point of D2/D3: name the most likely reason it isn't attacking. string why = !s.IsMacroRunning ? "macro is STOPPED (start it from the panel / command)." : + // Owner's rule (2026-11-02): with Boost Nav Priority on RynthAi only navigates. + _dashboard?.Settings?.BoostNavPriority == true + ? "Boost Nav Priority is on: RynthAi only navigates (no hunting, no looting). Turn it off to hunt and loot." : !s.EnableCombat ? "combat is disabled in settings." : s.BusyCount > 0 ? "AC busy>0 — waiting on a server action (cast/use/move); try /ra clearbusy if stuck." : forced != 0 && forced == s.ActiveTargetId && bySelection @@ -3101,6 +3146,7 @@ public sealed partial class RynthAiPlugin private void StopPatrolForServer() { _dunPatrolActive = false; + _dunPatrolRoute = null; var s = _dashboard?.Settings; if (s == null) return; s.EnableNavigation = false; @@ -3163,7 +3209,7 @@ public sealed partial class RynthAiPlugin } } - private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false) + private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false, bool followedIn = false) { // The one way into the dungeon patrol (the command, the dashboard button, a meta's "Patrol", the hazard // reroute): where a server's owners asked for it to be off (a Thread on DreamWeave) nothing is built (ServerPolicy). @@ -3359,7 +3405,9 @@ public sealed partial class RynthAiPlugin // and the hazard generation it already accounts for. OnTick rebuilds when a newer // hazard is sighted in this same landblock. _dunPatrolActive = true; + _dunPatrolRoute = route; _dunPatrolLandblock = landblockKey; + _dunPatrolFollowTriedLb = uint.MaxValue; _dunPatrolHazardVersion = _objectCache?.HazardVersion ?? 0; _dunPatrolSettings.MarkBuilt(patrolOptions); MarkPatrolPortals(portals); @@ -3367,7 +3415,11 @@ public sealed partial class RynthAiPlugin int hazardCount = hazards?.Count ?? 0; string hazardNote = hazardCount > 0 ? $", {hazardCount} hazard cell(s) avoided" : ""; string portalNote = portals.Count > 0 ? $", kept out of {portals.Count} portal(s)" : ""; - if (isRebuild && settingsChanged) + if (isRebuild && followedIn) + { + ChatLine($"[RynthAi] DunNav-Patrol: followed you into dungeon 0x{landblockKey:X4} → {route.Points.Count} waypoints, patrolling here{hazardNote}{portalNote}. Stop the macro or load a route to end it."); + } + else if (isRebuild && settingsChanged) { ChatLine($"[RynthAi] DunNav-Patrol: patrol settings changed → rebuilt from here, {route.Points.Count} waypoints ({patrolOptions.Describe()})."); } @@ -3404,18 +3456,40 @@ public sealed partial class RynthAiPlugin // A patrol running when the character enters a Thread on DreamWeave (or one that began before the world name // was known): stopped the moment it is (ServerPolicy). if (ServerPolicy.PatrolOff(Host)) { StopPatrolForServer(); ChatLine(ServerPolicy.PatrolOffMessage); return; } - if (_objectCache == null) return; var settings = _dashboard?.Settings; - // Patrol stopped, navigation disabled, or a different (recorded) route was loaded — - // stand down; we only own the auto-generated, file-less circular patrol. - if (settings == null || !settings.IsMacroRunning || !settings.EnableNavigation + // A different route was loaded in the patrol's place (a nav file, a meta's route, Save As + // made it a recorded route): stand down, and say so when it was replaced. We only own the + // auto-generated, file-less circular patrol. + bool replaced = settings != null && _dunPatrolRoute != null && !ReferenceEquals(settings.CurrentRoute, _dunPatrolRoute); + if (settings == null || replaced || !string.IsNullOrEmpty(settings.CurrentNavPath) || settings.CurrentRoute?.RouteType != NavRouteType.Circular) { + if (settings != null && (replaced || !string.IsNullOrEmpty(settings.CurrentNavPath))) + { + string what = PatrolReplacementName(settings); + Host.Log($"[RynthAi] DunNav-Patrol: ended - {what} is the route now."); + if (settings.CurrentRoute?.Points.Count > 0) + ChatLine($"[RynthAi] Dungeon Patrol ended: {what} is the route now. Press Patrol to patrol again."); + } _dunPatrolActive = false; + _dunPatrolRoute = null; return; } + // Macro stopped or navigation switched off: the patrol is paused, not ended. It stays the + // route, and starting again carries on with it (2026-11-01: a stop used to stand it down, + // so after a restart the patrol ran without its hazard reroutes or keep-the-waypoint rule). + if (!settings.IsMacroRunning || !settings.EnableNavigation) + { + _dunPatrolPrevRunningLb = uint.MaxValue; + _dunPatrolArrivedRunning = false; + return; + } + + // The character went into another dungeon while patrolling: the patrol follows (not after a death). + if (TickPatrolFollow(settings)) return; + if (_objectCache == null) return; var patrolOptions = PatrolOptionsFrom(settings); bool settingsChanged = _dunPatrolSettings.ShouldRebuild(patrolOptions, Environment.TickCount64); @@ -3441,6 +3515,87 @@ public sealed partial class RynthAiPlugin if (portalAppeared && _dunPatrolActive) MarkPatrolPortals(PatrolPortalsIn(_dunPatrolLandblock)); } + /// What the patrol was replaced with, for the chat line: "nav route 'X'", "the meta's route 'X'", "another route". + private static string PatrolReplacementName(LegacyUiSettings s) + { + string path = s.CurrentNavPath ?? string.Empty; + if (path.StartsWith("')}'"; + if (path.Length > 0) return $"nav route '{System.IO.Path.GetFileNameWithoutExtension(path)}'"; + return "another route"; + } + + /// What the Dungeon Patrol does when the character is in another dungeon than the one it was built for. + internal enum PatrolFollow + { + /// Nothing to do (same dungeon, not a dungeon, in portal space, already tried here). + None, + /// Build the patrol again here. + Follow, + /// Sent here by a death: say so, and leave it to the Patrol button. + AfterDeath, + /// Came here with the macro (or nav) off: say so, and leave it to the Patrol button. + CameWhileStopped, + } + + internal const long PatrolFollowDeathMs = 120_000; + + /// + /// The decision half of . The patrol follows the character through a + /// portal (or a recall) taken while it runs into another dungeon: patrolling is the mode, and the + /// patrol it had is for a dungeon it is no longer in (nav would only hold on it). Never into a + /// building on the landscape (not a dungeon landblock), never mid-portal, once per dungeon. Not + /// when a death sent the character there (a lifestone dungeon is no place to start hunting on its + /// own), nor when it got there with the macro off (an HP-failsafe recall, travelling by hand): + /// those say how to patrol here instead. + /// + internal static PatrolFollow DecidePatrolFollow(uint patrolLb, uint playerCell, bool isDungeonLandblock, + bool portaling, uint triedLb, long msSinceDeath, bool arrivedWhileRunning) + { + uint lb = playerCell >> 16; + if (playerCell == 0 || lb == patrolLb || (playerCell & 0xFFFF) < 0x0100) return PatrolFollow.None; + if (portaling || !isDungeonLandblock || lb == triedLb) return PatrolFollow.None; + if (msSinceDeath >= 0 && msSinceDeath < PatrolFollowDeathMs) return PatrolFollow.AfterDeath; + return arrivedWhileRunning ? PatrolFollow.Follow : PatrolFollow.CameWhileStopped; + } + + /// + /// Running patrol, character in another dungeon: builds the patrol there (or, after a death, says + /// how to). True when it acted (the caller's hazard/settings checks are for the old dungeon). + /// + private bool TickPatrolFollow(LegacyUiSettings settings) + { + if (!Host.HasGetPlayerPose || !Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _)) return false; + uint lb = cell >> 16; + if (_dunPatrolPrevRunningLb != uint.MaxValue && _dunPatrolPrevRunningLb != lb) _dunPatrolArrivedRunning = true; + _dunPatrolPrevRunningLb = lb; + if (lb == _dunPatrolLandblock) { _dunPatrolArrivedRunning = false; return false; } + if ((cell & 0xFFFF) < 0x0100) return false; + var cellDat = _raycast?.GeometryLoader?.CellDat; + if (cellDat == null || !cellDat.IsLoaded || _navPlanner == null) return false; // asked again next tick + bool portaling = (Host.HasIsPortaling && Host.IsPortaling()) || _deathHolding; + long sinceDeath = _lastDeathAt == 0 ? -1 : Environment.TickCount64 - _lastDeathAt; + var what = DecidePatrolFollow(_dunPatrolLandblock, cell, _navPlanner.IsDungeonLandblock(lb, cellDat), portaling, + _dunPatrolFollowTriedLb, sinceDeath, _dunPatrolArrivedRunning); + if (what == PatrolFollow.None) return false; + + uint was = _dunPatrolLandblock; + _dunPatrolFollowTriedLb = lb; + _dunPatrolArrivedRunning = false; + if (what != PatrolFollow.Follow) + { + string how = what == PatrolFollow.AfterDeath ? "after a death" : "with the macro off on the way"; + Host.Log($"[RynthAi] DunNav-Patrol: in dungeon 0x{lb:X4} {how}; the patrol was for 0x{was:X4} - not following."); + ChatLine($"[RynthAi] Dungeon Patrol: you are in dungeon 0x{lb:X4} ({how}); the patrol was for dungeon 0x{was:X4}. Press Patrol to patrol here."); + return true; + } + + Host.Log($"[RynthAi] DunNav-Patrol: the character went from dungeon 0x{was:X4} into 0x{lb:X4} - building the patrol here."); + BuildDunPatrol(isRebuild: true, followedIn: true); + if (!_dunPatrolActive || _dunPatrolLandblock != lb) + ChatLine($"[RynthAi] Dungeon Patrol: couldn't lay a patrol in dungeon 0x{lb:X4} from here. Press Patrol to try again."); + return true; + } + // ── Patrol-management info / actions (engine-side right-click flyout) ────── /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.BoostNav.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.BoostNav.cs new file mode 100644 index 0000000..7e8bb1e --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.BoostNav.cs @@ -0,0 +1,51 @@ +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +// Boost Nav Priority (owner's rule, 2026-11-02): with the flag on RynthAi ONLY navigates. No +// hunting, no looting, no fighting back; with nothing to navigate it stands idle. Buffing and +// vitals still run. The arbiter (ActivityArbiter.Decide) never picks Combat or Looting with the +// flag on, CombatManager.OnHeartbeat stands down (drops the target, ends the attack, lets go of a +// turn), the looter passes every corpse by (CorpseOpenController.BoostNavHoldsLoot) and no pet is +// summoned (PetManager). The flag comes on quietly from NavLootPrio or a hunting meta's SetOpt, and +// a player who never knew it was on saw only that the bot would not loot +// (R-20261102-041824-3f7c). So the first fight or corpse it skips says so, once per session. +public sealed partial class RynthAiPlugin +{ + internal const string BoostNavNotice = + "[RynthAi] Boost Nav Priority is on: RynthAi only navigates (no hunting, no looting). Turn it off to hunt and loot."; + + /// How often the corpse half of the notice looks for a corpse it would have looted. + internal const long BoostNavLootCheckMs = 2000; + + private bool _boostNavNoticeSaid; // once per session (reset at logout) + private long _boostNavLootCheckAt; // CorpseNowMs of the last corpse look + + /// + /// After the arbiter's decision, every tick: Boost Nav Priority is why a fight (combat on and a + /// monster to engage) or a corpse (looting on and one in range it would loot) is skipped. Says + /// so once per session, in chat and the log; nothing at all once said. + /// + private void NoteBoostNavSkip(LegacyUiSettings settings, bool wantCombat) + { + if (_boostNavNoticeSaid || !settings.IsMacroRunning || !settings.BoostNavPriority) return; + + string? skipped = null; + if (wantCombat) + skipped = "a fight"; + else if (settings.EnableLooting) + { + long now = CorpseNowMs; + if (now - _boostNavLootCheckAt >= BoostNavLootCheckMs) + { + _boostNavLootCheckAt = now; + if (BoostNavSkipsLoot(settings)) skipped = "a corpse"; + } + } + if (skipped == null) return; + + _boostNavNoticeSaid = true; + Host.Log($"{BoostNavNotice} (skipped {skipped})"); + Host.WriteToChat(BoostNavNotice, 2); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs index cf53700..b7fa6cc 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs @@ -272,4 +272,44 @@ public sealed partial class RynthAiPlugin FinishChestLoot(id, how, close: false, sayNothingMatched: false); return true; } + + // ── Pickup with macro off (2026-11-02) ───────────────────────────────────────────────────── + // A chest the player opens is looted by the loaded loot profile with the macro or Looting off + // (LootChestsMacroOff, on by default), the way /ra lootthis would. With both on the macro's + // own chest looting (above) takes it. Only a chest JudgeChest would loot: never a corpse, + // a vendor, a player, house storage or a pack the character carries. + + private const long ManualChestWaitMs = 3000; // for the chest's owner and name to be readable + private int _manualChestId; + private long _manualChestSince; + + /// OnViewObjectContents for a non-corpse container: a chest the player may have opened. + private void NoteManualChestOpened(int id) + { + _manualChestId = id; + _manualChestSince = CorpseNowMs; + } + + /// TickCorpseOpening, every tick: hands a chest the player opened to the looter (see above). + private void TakeManualChest(LegacyUiSettings settings) + { + int id = _manualChestId; + if (id == 0) return; + if (!settings.LootChestsMacroOff || (settings.IsMacroRunning && settings.EnableLooting) + || _chestKey?.Running == true || _forcedLootContainerId == id) + { + _manualChestId = 0; // off, the macro's own looting has it, or the chest looter does + return; + } + ChestVerdict verdict = JudgeChest(id, out string why); + if (verdict == ChestVerdict.Wait && CorpseNowMs - _manualChestSince < ManualChestWaitMs) return; + _manualChestId = 0; + if (verdict != ChestVerdict.Loot || LootThisRefusal(id) != null) + { + LootDiag($"[RynthAi] Pickup with macro off: not looting 0x{(uint)id:X8} ({(verdict == ChestVerdict.Loot ? LootThisRefusal(id) : why)})."); + return; + } + LootDiag($"[RynthAi] Pickup with macro off: looting the opened chest 0x{(uint)id:X8} by the loot profile."); + ForceLootOpenChest(id); + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs index 429cb1e..0f7a5ca 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs @@ -257,6 +257,9 @@ internal sealed class DashboardBridge : IDashboardHost public void SetAutoSort(bool on) => Queue(() => _p.SetDashAutoSort(on)); public void ToggleSortWindow() => Queue(() => _p.SendSortCommand(string.Empty)); public void StartPatrol() => Queue(_p.HandleDungeonNavPatrol); + public void ToggleHunt() => Queue(_p.ToggleHunt); + public bool HuntActive => _p.HuntActive; + public void ToggleHuntPanel() => _p.ToggleHuntPanel(); public void ToggleSpells() => _p.EnqueueRemoteCommand("spells", "toggle"); public void UseClassicLook() => _p.UseClassicLook(); public bool DrawMiniRemote(out Vector2 want) => _p.DrawDashMiniRemote(out want); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs new file mode 100644 index 0000000..31b63ee --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemTool.cs @@ -0,0 +1,592 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Text; +using RynthCore.Plugin.RynthAi.ItemTool; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +// The Item Tool (2026-10-17): two small tools in one engine panel (RynthCore's ItemToolFace), each +// picked, started and stopped by Tom himself. +// +// Chest looter - "Pick a chest. Pick a key. It just loots the chest based on the current loot +// profile until it's out of keys." ItemTool/ChestKeyLooter.cs is the state +// machine; this file is its host side. The key is used on the chest (AC's +// use-with-target, UseOnFor), the chest is opened (UseFor), and the open chest +// is handed to the corpse looter (RynthAiPlugin.ChestLoot.cs) the way /ra +// lootthis does it, so it runs with the macro off and Looting off too and +// uses the loot profile that is loaded. +// Quick give - ItemTool/QuickGive.cs. A rapid give of one picked item to one picked player +// or NPC. Separate from the profile give (actiontrygiveprofile / ItemGiver\ / +// /ra ig), which stays locked to NPCs and its folder: this one shares nothing +// with it but AC's give action (GiveObjectTo), and only starts from a source +// Tom controls (below). +// +// Commands (/ra itemtool ...; the panel sends the same words through RynthPluginItemToolCommand): +// chest set | key | start | stop | status | clear +// giveitem | givetarget | give | givestop | givestatus | clear +// stop (both) +// +// Threads: a chat command arrives on AC's thread and the panel's on the engine pump, but the tick +// is where everything runs: commands are queued and taken in TickItemTool. +// +// Who may start Quick give: only a line Tom typed (the chat bar, the RynthAi chat box) or the +// panel's button. A meta's /ra line, a script's SubmitCommand, a /ub delayed command and the +// remote "sendchat" run with _itemToolUntrusted set, and Start is refused for them (a shared meta +// must never hand a pack to someone's character). Stop is allowed from anywhere. +public sealed partial class RynthAiPlugin +{ + /// Clock (ms) of the Item Tool; tests replace it. + internal static Func ItemToolClock = static () => Environment.TickCount64; + + /// Set (this thread only) while a line that was not typed by the player runs. + [ThreadStatic] private static bool _itemToolUntrusted; + + private ChestKeyLooter? _chestKey; + private QuickGive? _quickGive; + private readonly ConcurrentQueue<(string Args, bool Trusted)> _itemToolCmds = new(); + private int _chestKeyForceId; // pump: the open chest to hand to the corpse looter + private int _chestKeyOpenedId; // OnViewObjectContents: the last non-corpse container the server opened + private long _chestKeyOpenedAt; + private long _itemToolBusySince; + private int _giveTargetClass; // what the picked target is (for the status line) + + private const long ItemToolBusyGraceMs = 2500; + private const uint ItemToolBfPlayer = 0x00000008, ItemToolBfAttackable = 0x00000010, ItemToolBfVendor = 0x00000200; + private const uint StypeBoolLocked = 3; // ACE PropertyBool.Locked + + /// Runs as a line the player did not type (see the header). + private static void RunItemToolUntrusted(Action action) + { + bool was = _itemToolUntrusted; + _itemToolUntrusted = true; + try { action(); } + finally { _itemToolUntrusted = was; } + } + + // ── Commands ───────────────────────────────────────────────────────────── + + /// "/ra itemtool ..." (DispatchRaCommand): queued, run on the next tick. + private void HandleItemToolCommand(string[] parts) + { + string args = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : ""; + QueueItemToolCommand(args, trusted: !_itemToolUntrusted); + } + + /// The panel's command (RynthPluginItemToolCommand): from a button Tom pressed. + internal void QueueItemToolCommand(string args, bool trusted) + { + if (_itemToolCmds.Count > 32) return; // a flood of commands is dropped, not queued + _itemToolCmds.Enqueue((args ?? "", trusted)); + } + + private void EnsureItemTool() + { + _chestKey ??= new ChestKeyLooter(new ChestEnv(this)); + _quickGive ??= new QuickGive(new GiveEnv(this)); + } + + /// Every plugin tick: the queued commands, then both state machines. + private void TickItemTool() + { + if (!_loginComplete || _objectCache == null || _playerId == 0) return; + if (_chestKey == null && _quickGive == null && _itemToolCmds.IsEmpty) return; + try + { + EnsureItemTool(); + while (_itemToolCmds.TryDequeue(out var cmd)) + RunItemToolCommand(cmd.Args, cmd.Trusted); + _chestKey!.Tick(); + _quickGive!.Tick(); + } + catch (Exception ex) + { + Host.Log($"[RynthAi] Item Tool tick threw {ex.GetType().Name}: {ex.Message}"); + try { _chestKey?.Stop("an internal error (see the log)"); } catch { } + try { _quickGive?.Stop("an internal error (see the log)"); } catch { } + } + } + + private void ResetItemTool() + { + while (_itemToolCmds.TryDequeue(out _)) { } + _chestKey = null; + _quickGive = null; + _chestKeyForceId = 0; + _chestKeyOpenedId = 0; + _chestKeyOpenedAt = 0; + } + + private void RunItemToolCommand(string args, bool trusted) + { + EnsureItemTool(); + string[] t = args.Split(' ', StringSplitOptions.RemoveEmptyEntries); + string verb = t.Length > 0 ? t[0].ToLowerInvariant() : ""; + string sub = t.Length > 1 ? t[1].ToLowerInvariant() : ""; + + switch (verb) + { + case "": + case "status": + ChatLine("[RynthAi] Item Tool - " + _chestKey!.Status + " | " + _quickGive!.Status); + ChatLine("[RynthAi] /ra itemtool chest set|key|start|stop|status and /ra itemtool giveitem|givetarget|give|givestop|givestatus"); + return; + case "stop": + if (_chestKey!.Running) _chestKey.Stop("stopped by you"); + if (_quickGive!.Running) _quickGive.Stop("stopped by you"); + if (!_chestKey.Running && !_quickGive.Running) ChatLine("[RynthAi] Item Tool: nothing is running."); + return; + case "clear": + _chestKey!.Clear(); + _quickGive!.Clear(); + ChatLine("[RynthAi] Item Tool: the picks are cleared (anything running keeps its own)."); + return; + case "chest": + RunChestCommand(sub); + return; + case "giveitem": PickGiveItem(); return; + case "givetarget": PickGiveTarget(); return; + case "givestatus": ChatLine("[RynthAi] Quick give - " + _quickGive!.Status); return; + case "givestop": _quickGive!.Stop("stopped by you"); return; + case "give": + if (!trusted) + { + ChatLine("[RynthAi] Quick give: it starts only from the Item Tool panel or a command you type yourself, not from a meta, script or remote line."); + return; + } + StartQuickGive(); + return; + default: + ChatLine($"[RynthAi] Item Tool: unknown '{args}'. Try /ra itemtool status."); + return; + } + } + + private void RunChestCommand(string sub) + { + var ck = _chestKey!; + switch (sub) + { + case "set": PickChest(); return; + case "key": PickKey(); return; + case "start": + if (!Host.HasUseObjectOn || !Host.HasGetSelectedItemId) + { + ChatLine("[RynthAi] Chest looter: this engine can't use an item on a target (needs plugin API with UseObjectOn)."); + return; + } + ck.Start(out _); + return; + case "stop": ck.Stop("stopped by you"); return; + case "clear": ck.Clear(); ChatLine("[RynthAi] Chest looter: chest and key cleared."); return; + case "": + case "status": + ChatLine("[RynthAi] Chest looter - " + ck.Status); + return; + default: + ChatLine("[RynthAi] Usage: /ra itemtool chest set|key|start|stop|status"); + return; + } + } + + // ── Picking ────────────────────────────────────────────────────────────── + + private uint SelectedForItemTool(string what) + { + if (!Host.HasGetSelectedItemId) { ChatLine("[RynthAi] Item Tool: this engine can't read the selected item."); return 0; } + uint sel = Host.GetSelectedItemId(); + if (sel == 0) ChatLine($"[RynthAi] Item Tool: select {what} in the game first."); + return sel; + } + + private string ItemToolName(int id) + { + string n = _objectCache?[id]?.Name ?? ""; + if (n.Length == 0 && Host.TryGetObjectName(unchecked((uint)id), out string hn)) n = hn; + return n.Length > 0 ? n : $"0x{(uint)id:X8}"; + } + + private void PickChest() + { + var ck = _chestKey!; + if (ck.Running) { ChatLine("[RynthAi] Chest looter: stop it before changing the chest."); return; } + uint sel = SelectedForItemTool("the chest in the world"); + if (sel == 0) return; + int id = unchecked((int)sel); + if (IsCarriedByPlayer(id)) { ChatLine("[RynthAi] Chest looter: that is in your pack; select the chest in the world."); return; } + string? refusal = LootThisRefusal(id); + if (refusal == null && IsCorpseLikeObject(id)) refusal = "that is a corpse (the corpse looter handles those)"; + if (refusal != null) { ChatLine($"[RynthAi] Chest looter: not that - {refusal}."); return; } + ck.SetChest(id, ItemToolName(id)); + ChatLine($"[RynthAi] Chest looter: chest = {ck.ChestName} (0x{sel:X8})."); + } + + private void PickKey() + { + var ck = _chestKey!; + if (ck.Running) { ChatLine("[RynthAi] Chest looter: stop it before changing the key."); return; } + uint sel = SelectedForItemTool("the key in your pack"); + if (sel == 0) return; + int id = unchecked((int)sel); + if (_objectCache?[id] is not WorldObject wo || !IsCarriedByPlayer(id)) { ChatLine("[RynthAi] Chest looter: the key must be in your pack; select it there."); return; } + if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) { ChatLine("[RynthAi] Chest looter: that is worn or wielded, not a key."); return; } + ck.SetKey(id, wo.Name); + ChatLine($"[RynthAi] Chest looter: key = {wo.Name} (0x{sel:X8}). Any other '{wo.Name}' you carry is used when this one runs out."); + } + + private void PickGiveItem() + { + var qg = _quickGive!; + if (qg.Running) { ChatLine("[RynthAi] Quick give: stop it before changing the item."); return; } + uint sel = SelectedForItemTool("the item in your pack"); + if (sel == 0) return; + int id = unchecked((int)sel); + if (_objectCache?[id] is not WorldObject wo || !IsCarriedByPlayer(id)) { ChatLine("[RynthAi] Quick give: the item must be in your pack; select it there."); return; } + if (WorldObjectCache.IsWieldedByPlayer(Host, wo)) { ChatLine("[RynthAi] Quick give: that is worn or wielded; take it off first."); return; } + qg.SetItem(id, new GiveItemKey(ItemToolWcid(id), wo.Name)); + ChatLine($"[RynthAi] Quick give: item = {wo.Name} (every '{wo.Name}' in your packs will go)."); + } + + private void PickGiveTarget() + { + var qg = _quickGive!; + if (qg.Running) { ChatLine("[RynthAi] Quick give: stop it before changing the target."); return; } + uint sel = SelectedForItemTool("the player or NPC in the world"); + if (sel == 0) return; + int id = unchecked((int)sel); + string? refusal = QuickGiveTargetRefusal(id, out int cls); + if (refusal != null) { ChatLine($"[RynthAi] Quick give: not that - {refusal}."); return; } + _giveTargetClass = cls; + qg.SetTarget(id, ItemToolName(id)); + ChatLine($"[RynthAi] Quick give: target = {(cls == (int)AcObjectClass.Player ? "PLAYER " : "")}{qg.TargetName} (0x{sel:X8})."); + } + + private uint ItemToolWcid(int id) + => Host.HasGetObjectWcid && Host.TryGetObjectWcid(unchecked((uint)id), out uint w) ? w : 0; + + /// Null when may be a Quick give target (a player or an NPC in the world). + internal string? QuickGiveTargetRefusal(int id, out int objectClass) + { + objectClass = 0; + if (_objectCache == null || _playerId == 0) return "not ready"; + if (unchecked((uint)id) == _playerId) return "that is you"; + if (IsCarriedByPlayer(id)) return "that is in your pack; select the player or NPC in the world"; + if (_objectCache[id] is not WorldObject wo) return "it isn't loaded"; + objectClass = ItemToolTargetClass(wo); + if (objectClass is (int)AcObjectClass.Player or (int)AcObjectClass.Npc or (int)AcObjectClass.Vendor) return null; + return $"Quick give hands items to a player or an NPC; that is '{wo.Name}'"; + } + + /// The object's class, the weenie bitfield first (as the meta engine reads it): player, vendor, NPC or what the cache says. + private int ItemToolTargetClass(WorldObject wo) + { + int cls = (int)wo.ObjectClass; + uint uid = unchecked((uint)wo.Id); + if (Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(uid, out uint bf)) + { + if ((bf & ItemToolBfPlayer) != 0) return (int)AcObjectClass.Player; + if ((bf & ItemToolBfVendor) != 0) return (int)AcObjectClass.Vendor; + if (cls == (int)AcObjectClass.Monster && (bf & ItemToolBfAttackable) == 0) return (int)AcObjectClass.Npc; + } + else if (cls == (int)AcObjectClass.Monster && Host.HasObjectIsAttackable && !Host.ObjectIsAttackable(uid)) + { + return (int)AcObjectClass.Npc; + } + return cls; + } + + private void StartQuickGive() + { + var qg = _quickGive!; + if (!Host.HasGiveObjectTo) { ChatLine("[RynthAi] Quick give: this engine has no give action (needs plugin API with GiveObjectTo)."); return; } + if (qg.TargetId != 0) + { + // The picked object must still be a player/NPC (the id could be reused after a long wait). + string? refusal = QuickGiveTargetRefusal(qg.TargetId, out int cls); + if (refusal != null && _objectCache?[qg.TargetId] != null) { ChatLine($"[RynthAi] Quick give: can't start - {refusal}."); return; } + _giveTargetClass = cls; + } + qg.Start(out _); + } + + // ── Hooks from the rest of the plugin ─────────────────────────────────── + + /// OnChatWindowText: the key's answers. + private void ItemToolChat(string text) => _chestKey?.OnChat(text); + + /// OnViewObjectContents for a non-corpse container: the chest looter's proof the chest opened. + private void NoteChestKeyOpened(int id) + { + _chestKeyOpenedId = id; + _chestKeyOpenedAt = ItemToolClock(); + } + + /// + /// TickCorpseOpening, every tick: the chest looter asked for its open chest to be looted. Like + /// /ra lootthis: the container is flagged so the loot tick runs for it with the macro or + /// Looting off, and taken as the loot container with no walk and no open. + /// + private void TakeChestKeyRequest() + { + int id = _chestKeyForceId; + if (id == 0) return; + _chestKeyForceId = 0; + + string? refusal = LootThisRefusal(id); + if (refusal != null) + { + ChatLine($"[RynthAi] Chest looter: not looting {ItemToolName(id)} - {refusal}."); + return; + } + ForceLootOpenChest(id); + } + + /// + /// Flags the open chest so the loot tick runs for it with the macro or + /// Looting off, and takes it as the loot container with no walk and no open (the chest looter, + /// Pickup with macro off). The caller checked . + /// + private void ForceLootOpenChest(int id) + { + _forcedLootContainerId = id; + if (_openedContainerId == id) return; // the macro's own chest check took it first + + long now = CorpseNowMs; + if (_targetCorpseId != 0 && _targetCorpseId != id) ResetCorpseTarget(); + if (_chestCandidateId != id) { _chestCandidateSince = now; _chestCandidateInvSeenAt = 0; } + TakeChestAsLootContainer(id, now); + PauseNavigationForCorpse(); + StopCorpseMovement(); + } + + /// The Item Tool panel's data (RynthPluginGetItemToolJson). + internal string BuildItemToolJson() + { + var ck = _chestKey; + var qg = _quickGive; + var sb = new StringBuilder(512); + sb.Append("{\"chest\":{"); + AppendJson(sb, "name", ck?.ChestName ?? ""); sb.Append(','); + AppendJson(sb, "key", ck?.KeyName ?? ""); sb.Append(','); + AppendJson(sb, "status", ck?.Status ?? "Idle."); sb.Append(','); + sb.Append("\"running\":").Append(ck?.Running == true ? "true" : "false").Append(','); + sb.Append("\"looted\":").Append(ck?.Looted ?? 0); + sb.Append("},\"give\":{"); + AppendJson(sb, "item", qg?.Item.Name ?? ""); sb.Append(','); + AppendJson(sb, "target", qg == null || qg.TargetId == 0 ? "" : (_giveTargetClass == (int)AcObjectClass.Player ? "PLAYER " : "") + qg.TargetName); sb.Append(','); + AppendJson(sb, "status", qg?.Status ?? "Idle."); sb.Append(','); + sb.Append("\"running\":").Append(qg?.Running == true ? "true" : "false").Append(','); + sb.Append("\"given\":").Append(qg?.Given ?? 0); + sb.Append("}}"); + return sb.ToString(); + } + + private static void AppendJson(StringBuilder sb, string key, string value) + { + sb.Append('"').Append(key).Append("\":\""); + foreach (char c in value) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\n': sb.Append("\\n"); break; + case '\r': break; + default: + if (c < 0x20) sb.Append(' '); + else sb.Append(c); + break; + } + } + sb.Append('"'); + } + + // ── The chest looter's host side ──────────────────────────────────────── + + private sealed class ChestEnv : IChestKeyEnv + { + private readonly RynthAiPlugin _p; + public ChestEnv(RynthAiPlugin p) => _p = p; + + private RynthCore.PluginSdk.RynthCoreHost Host => _p.Host; + + public long Now => ItemToolClock(); + public string NameOf(int id) => _p.ItemToolName(id); + + public bool ChestLoaded(int chestId, out double meters) + { + meters = -1; + var cache = _p._objectCache; + if (cache == null || cache[chestId] == null) return false; + double d = cache.Distance(unchecked((int)_p._playerId), chestId); + meters = d == double.MaxValue ? -1 : d; + return true; + } + + public int FindKey(int keyId, string keyName, int excludeId) + { + var cache = _p._objectCache; + if (cache == null) return 0; + if (keyId != 0 && keyId != excludeId && cache[keyId] is WorldObject cur && _p.IsCarriedByPlayer(keyId) + && !WorldObjectCache.IsWieldedByPlayer(Host, cur)) + return keyId; + foreach (var wo in cache.GetDirectInventory()) + { + if (wo.Id == excludeId || wo.Id == keyId) continue; + if (string.Equals(wo.Name, keyName, StringComparison.OrdinalIgnoreCase) && _p.IsCarriedByPlayer(wo.Id) + && !WorldObjectCache.IsWieldedByPlayer(Host, wo)) + return wo.Id; + } + return 0; + } + + public string? HoldReason() => _p.ItemToolHoldReason(yieldToLooter: true); + + public bool HasUseDone => Host.HasUseDoneSeq; + public int UseDoneSeq() => Host.HasUseDoneSeq ? Host.GetUseDoneSeq() : 0; + public bool LastUseDone(out int seq, out uint error) + { + seq = 0; error = 0; + return Host.HasGetLastUseDone && Host.TryGetLastUseDone(out seq, out error); + } + + public bool SendKey(int keyId, int chestId) + => Host.UseOnFor(unchecked((uint)keyId), unchecked((uint)chestId), "ItemTool", "Chest looter: the key on the chest", UseKind.Asked); + + public bool SendOpen(int chestId) + => Host.UseFor(unchecked((uint)chestId), "ItemTool", "Chest looter: open the chest", UseKind.Asked); + + public long ChestOpenedAt(int chestId) => _p._chestKeyOpenedId == chestId ? _p._chestKeyOpenedAt : 0; + + public void StartLooting(int chestId) => _p._chestKeyForceId = chestId; + + public bool Looting(int chestId) + => _p._chestKeyForceId == chestId + || (_p.IsChestLoot(chestId) && (_p._openedContainerId == chestId || _p._targetCorpseId == chestId)); + + public void AbortLooting(int chestId) + { + if (_p._chestKeyForceId == chestId) _p._chestKeyForceId = 0; + if (_p._forcedLootContainerId == chestId && !_p.IsChestLoot(chestId)) _p._forcedLootContainerId = 0; + if (_p.IsChestLoot(chestId) && (_p._openedContainerId == chestId || _p._targetCorpseId == chestId)) + _p.FinishChestLoot(chestId, "the chest looter was stopped", close: true, sayNothingMatched: false); + } + + public bool? ChestLockedHint(int chestId) + => Host.HasGetObjectBoolProperty && Host.TryGetObjectBoolProperty(unchecked((uint)chestId), StypeBoolLocked, out bool locked) ? locked : null; + + public void Say(string text) => _p.ChatLine(text); + public void Log(string text) => Host.Log(text); + } + + /// Why the Item Tool may not send now (null = free): combat, portal space, an unanswered action, a busy client. + private string? ItemToolHoldReason(bool yieldToLooter) + { + if (ActionPacer.IsPortaling(Host)) return "portal space"; + var settings = _dashboard?.Settings; + if (settings != null && settings.IsMacroRunning && settings.EnableCombat && _combatManager?.HasTargets == true) + return "combat"; + // Another loot session (a corpse) is open: let it finish. + if (yieldToLooter && (_openedContainerId != 0 || _targetCorpseId != 0) && !IsChestLoot(_openedContainerId != 0 ? _openedContainerId : _targetCorpseId)) + return "the corpse looter is busy"; + if (!ActionPacer.MayStart(Host, "ItemTool", HealNeed.None, out string why)) + return why.Length > 0 ? why : "the server owes an answer"; + long now = ItemToolClock(); + if (_busyCount > 0) + { + if (_itemToolBusySince == 0) _itemToolBusySince = now; + if (now - _itemToolBusySince < ItemToolBusyGraceMs) return $"the client is busy ({_busyCount})"; + } + else _itemToolBusySince = 0; + return null; + } + + // ── Quick give's host side ────────────────────────────────────────────── + + private sealed class GiveEnv : IQuickGiveEnv + { + private readonly RynthAiPlugin _p; + public GiveEnv(RynthAiPlugin p) => _p = p; + + private RynthCore.PluginSdk.RynthCoreHost Host => _p.Host; + + public long Now => ItemToolClock(); + + public bool TargetLoaded(int targetId, out string name, out double meters) + { + name = ""; meters = -1; + var cache = _p._objectCache; + if (cache == null || cache[targetId] is not WorldObject wo) return false; + name = _p.ItemToolName(targetId); + double d = cache.Distance(unchecked((int)_p._playerId), targetId); + meters = d == double.MaxValue ? -1 : d; + return true; + } + + public bool InCombat() + { + var settings = _p._dashboard?.Settings; + return settings != null && settings.IsMacroRunning && settings.EnableCombat && _p._combatManager?.HasTargets == true; + } + + public string? HoldReason() => _p.ItemToolHoldReason(yieldToLooter: false); + + /// The carried stacks (never worn or wielded) that are exactly the picked item. + private IEnumerable Matching(GiveItemKey key) + { + var cache = _p._objectCache; + if (cache == null) yield break; + var seen = new HashSet(); + foreach (var wo in cache.GetDirectInventory(forceRefresh: true)) + if (Matches(wo, key) && _p.InPlayerInventory(wo.Container) && seen.Add(wo.Id)) yield return wo; + foreach (var wo in cache.AllKnownObjects()) + if (!seen.Contains(wo.Id) && Matches(wo, key) && _p.IsCarriedByPlayer(wo.Id) && seen.Add(wo.Id)) yield return wo; + } + + private bool Matches(WorldObject wo, GiveItemKey key) + { + if (!string.Equals(wo.Name, key.Name, StringComparison.OrdinalIgnoreCase)) return false; + if (key.Wcid != 0 && _p.ItemToolWcid(wo.Id) != key.Wcid) return false; // the same weenie, not just the same name + return !WorldObjectCache.IsWieldedByPlayer(Host, wo); + } + + public bool NextItem(GiveItemKey key, ISet skip, out int itemId, out int count) + { + foreach (var wo in Matching(key)) + { + if (skip.Contains(wo.Id)) continue; + itemId = wo.Id; + count = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)); + return true; + } + itemId = 0; count = 0; + return false; + } + + public int CountCarried(GiveItemKey key) + { + int n = 0; + foreach (var _ in Matching(key)) n++; + return n; + } + + public bool Landed(int itemId, int count) + { + // As the give queue reads it (GiveLanded): gone from the cache, out of the packs, or a smaller stack. + if (_p._objectCache?[itemId] is not WorldObject wo) return true; + if (!_p.InPlayerInventory(wo.Container)) return true; + return Math.Max(1, wo.Values(LongValueKey.StackCount, 1)) < count; + } + + public bool Send(int itemId, int targetId) + => Host.GiveObjectTo(unchecked((uint)itemId), unchecked((uint)targetId), 0); // amount 0 = the whole object + + public int RefusalSeq() + => Host.HasGetLastWeenieError && Host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0; + + public void Say(string text) => _p.ChatLine(text); + public void Log(string text) => Host.Log(text); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs index 3990699..a85e1a5 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LocalFeatures.cs @@ -279,6 +279,7 @@ public sealed partial class RynthAiPlugin _huds?.Render(); RenderTranslateWindow(); RenderLootWhyWindow(); + RenderHuntPanel(); } catch (Exception ex) { @@ -327,6 +328,7 @@ public sealed partial class RynthAiPlugin _itemInfoUi?.Render(); _spellsUi?.Render(); RenderLootWhyWindow(); + RenderHuntPanel(); } catch (Exception ex) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs new file mode 100644 index 0000000..6e67856 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs @@ -0,0 +1,452 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.PluginSdk; +using Ui = RynthCore.Plugin.Shared.RynthUi.RynthUi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +/// +/// Outdoor hunting (OutdoorHunt, 2026-10-23): /ra hunt, the dashboard's Hunt button and Settings > +/// Navigation > Outdoor Hunt. Each walk is a Once route along RynthNav's path (RynthNav.Path v2: +/// portals and walls kept clear of), walked by the navigation engine like any route, with its stuck +/// recovery and doors; combat, looting and buffing take the character over as usual, and the hunt is +/// asked again only when the arbiter's last decision was navigation or nothing. Outdoors and in the +/// buildings outdoors (2026-10-25: BuildingMap, in through a door and out again); the Dungeon Patrol +/// hunts in dungeons, and starting one stops the other. +/// +public sealed partial class RynthAiPlugin +{ + private readonly OutdoorHunt _hunt = new(); + private readonly List _huntCandidates = new(); + private NavRouteParser? _huntRoute; // the route the hunt installed; another one loaded ends the hunt + private NavRecoveryPlanner? _huntDungeonCheck; + private BuildingMap? _huntBuildings; + private long _huntPortalsAt; + private string _huntNoteLogged = ""; + private const int HuntMaxCorners = 128; + private const int HuntPathFlags = RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance + | RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet; + private const uint HuntItemTypePortal = 0x00010000; + private const long HuntPortalRefreshMs = 1000; + + internal bool HuntActive => _hunt.Active; + + private void HandleHuntCommand(string[] parts) + { + // parts[0] = "ra", parts[1] = "hunt", parts[2] = what (before 10-23 evening this read parts[1], + // so "/ra hunt status" and "/ra hunt stop" toggled the hunt instead). + string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : ""; + switch (arg) + { + case "start": case "on": StartHunt(); break; + case "stop": case "off": StopHunt("stopped", say: true); break; + case "status": + ChatLine(_hunt.Active + ? $"[RynthAi] Outdoor hunt: on, {(_hunt.WalkingOut ? "walking back out of a building" : _hunt.TargetId != 0 ? $"walking to 0x{(uint)_hunt.TargetId:X8}" : "waiting")}. {_hunt.Note}" + : "[RynthAi] Outdoor hunt: off. /ra hunt to start it here."); + if (_dashboard?.Settings is { } st) ChatLine("[RynthAi] " + HuntSettingsText(st)); + break; + // Typed by hand, so they answer (/mt opt set outdoorhunt... is silent: metas send it all the time). + case "range": + case "radius": + SetHuntSetting(arg, parts.Length > 3 ? parts[3] : ""); + break; + case "panel": + case "settings": + ToggleHuntPanel(); + break; + case "": + if (_hunt.Active) StopHunt("stopped", say: true); else StartHunt(); + break; + default: + ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range | /ra hunt radius "); + break; + } + } + + private void SetHuntSetting(string what, string value) + { + var s = _dashboard?.Settings; + if (s == null) { ChatLine("[RynthAi] Settings not ready."); return; } + if (!double.TryParse(value, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double yd)) + { + ChatLine("[RynthAi] Outdoor hunt: " + HuntSettingsText(s) + $" /ra hunt {what} to change it."); + return; + } + double max = what == "range" ? OutdoorHuntRangeMax : OutdoorHuntRadiusMax; + double set = Math.Clamp(yd, what == "range" ? OutdoorHuntRangeMin : 0, max); + if (what == "range") s.OutdoorHuntRange = (float)set; else s.OutdoorHuntRadius = (float)set; + string capped = set != yd ? $" ({yd:0} is outside {(what == "range" ? OutdoorHuntRangeMin : 0):0}-{max:0})" : ""; + ChatLine("[RynthAi] Outdoor hunt set" + capped + ": " + HuntSettingsText(s) + (_hunt.Active ? " In use now." : "")); + } + + /// The two distances, each with what it does (Tom set Hunt Radius 2000 and saw no farther hunting: that one is the roaming limit). + private static string HuntSettingsText(LegacyUiSettings s) => + $"looks for monsters out to {s.OutdoorHuntRange:0} yd (Hunt Range), " + + (s.OutdoorHuntRadius > 0 ? $"and only within {s.OutdoorHuntRadius:0} yd of where it started (Hunt Radius)." : "anywhere it goes (Hunt Radius 0)."); + + // ── The Outdoor Hunt window (Tom 10-23: "we need a small panel to change the settings") ── + // Right-click the dashboard's Hunt button, or /ra hunt panel. Render thread: the sliders write the + // two settings straight into the live settings (as the other RynthAi windows do; the autosave + // picks them up), Start/Stop goes to the plugin tick. + private volatile bool _huntPanelOpen; + + public void ToggleHuntPanel() => _huntPanelOpen = !_huntPanelOpen; + + private void RenderHuntPanel() + { + if (!_huntPanelOpen) return; + var s = _dashboard?.Settings; + if (s == null) return; + // Resizable (the owner 11-01: "very small, hard to read, no way to resize it"): RynthUi's + // colours and 14 pt text, a remembered size, text that wraps to the width, full-width sliders. + float k = Math.Max(0.5f, Ui.Font(RynthUiFont.Ui14).FontSize / 14f); + ImGui.SetNextWindowSize(new Vector2(460 * k, 360 * k), ImGuiCond.FirstUseEver); + ImGui.SetNextWindowSizeConstraints(new Vector2(320 * k, 240 * k), new Vector2(1600 * k, 1200 * k)); + ImGui.PushStyleColor(ImGuiCol.WindowBg, Ui.WithAlpha(Ui.Background, 0xF2)); + ImGui.PushStyleColor(ImGuiCol.TitleBg, Ui.Color(RynthUiColor.TitleBar)); + ImGui.PushStyleColor(ImGuiCol.TitleBgActive, Ui.Color(RynthUiColor.TitleBar)); + ImGui.PushStyleColor(ImGuiCol.Border, Ui.Accent); + ImGui.PushStyleColor(ImGuiCol.Text, Ui.Text); + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(12 * k, 10 * k)); + bool open = true; + bool visible = ImGui.Begin("Outdoor Hunt##rynthhunt", ref open, ImGuiWindowFlags.NoCollapse); + ImGui.PopStyleVar(); + ImGui.PopStyleColor(5); + if (!open) _huntPanelOpen = false; + if (!visible) { ImGui.End(); return; } + try + { + using (Ui.PushFont(RynthUiFont.Ui14)) + HuntPanelBody(s, k); + } + finally { ImGui.End(); } + } + + private void HuntPanelBody(LegacyUiSettings s, float k) + { + ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(8 * k, 5 * k)); + ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(8 * k, 6 * k)); + try + { + bool on = _hunt.Active; + if (ImGui.Button(on ? "Stop hunting" : "Start hunting here", new Vector2(ImGui.GetContentRegionAvail().X, 0))) + QueueDashAction(ToggleHunt); + + string status = !on ? "Off." + : _hunt.WalkingOut ? "Walking back out of a building." + : _hunt.TargetId != 0 ? "Walking to a monster." + : "Waiting for a monster in range."; + using (Ui.PushFont(RynthUiFont.UiBold14)) + Wrapped(status, !on ? Ui.Mute : _hunt.TargetId != 0 || _hunt.WalkingOut ? Ui.Green : Ui.Highlight); + string note = _hunt.Note; + if (on && note.Length > 0) Wrapped(note, Ui.Text); + ImGui.Separator(); + + float range = s.OutdoorHuntRange; + if (HuntSlider("Hunt Range", "##huntrange", ref range, (float)OutdoorHuntRangeMin, (float)OutdoorHuntRangeMax, + "%.0f yd", "Max", (float)OutdoorHuntRangeMax, k)) + s.OutdoorHuntRange = range; + Wrapped("How far it goes for the next monster. It only knows the ones the game has shown you " + + "(roughly the landblocks round you), so past a few hundred yards it means all of them. " + + "Monsters in buildings too: in through a door, out by the nearest one.", Ui.Text); + ImGui.Spacing(); + + float radius = s.OutdoorHuntRadius; + if (HuntSlider("Hunt Radius", "##huntradius", ref radius, 0f, (float)OutdoorHuntRadiusMax, + radius < 1f ? "anywhere" : "%.0f yd", "Anywhere", 0f, k)) + s.OutdoorHuntRadius = radius < 1f ? 0f : radius; + Wrapped("How far from where it started it may roam. Anywhere: no limit.", Ui.Text); + ImGui.Spacing(); + Wrapped("Ctrl+click a slider to type a number.", Ui.Mute); + } + finally { ImGui.PopStyleVar(2); } + } + + /// A label, then a slider across the window with one preset button at its end. True when the value changed. + private static bool HuntSlider(string label, string id, ref float value, float min, float max, string format, + string presetLabel, float preset, float k) + { + using (Ui.PushFont(RynthUiFont.UiBold14)) ImGui.TextUnformatted(label); + float presetW = ImGui.CalcTextSize(presetLabel).X + 20 * k; + ImGui.SetNextItemWidth(Math.Max(80 * k, ImGui.GetContentRegionAvail().X - presetW - ImGui.GetStyle().ItemSpacing.X)); + bool changed = ImGui.SliderFloat(id, ref value, min, max, format, ImGuiSliderFlags.Logarithmic); + ImGui.SameLine(); + if (ImGui.Button(presetLabel + id + "_preset", new Vector2(presetW, 0))) { value = preset; changed = true; } + return changed; + } + + private static void Wrapped(string text, uint color) + { + ImGui.PushStyleColor(ImGuiCol.Text, color); + ImGui.TextWrapped(text); + ImGui.PopStyleColor(); + } + + /// The dashboard's Hunt button (on the plugin tick). + public void ToggleHunt() + { + if (_hunt.Active) StopHunt("stopped", say: true); + else StartHunt(); + } + + internal void StartHunt() + { + var s = _dashboard?.Settings; + if (s == null) { ChatLine("[RynthAi] Settings not ready."); return; } + if (!TryHuntPosition(out uint cell, out var me)) { ChatLine("[RynthAi] Outdoor hunt: no position yet."); return; } + if (InDungeon(cell)) { ChatLine("[RynthAi] Outdoor hunt is for outdoors; in a dungeon the Dungeon Patrol hunts (Patrol)."); return; } + // In a building: it can start when it knows the building's doors (and RynthNav plans from a doorstep). + if (OutdoorHunt.IsIndoorCell(cell) && !HuntKnowsBuilding(cell)) + { + ChatLine("[RynthAi] Outdoor hunt: start it outdoors (it doesn't know this building's doors; it finds its own way out of a building it went into)."); + return; + } + if (HuntPath(me, me).Status == OutdoorHunt.PathStatus.Unavailable) + { + ChatLine("[RynthAi] Outdoor hunt needs RynthNav 2026.10.23 or newer (its map shows the way round obstacles)."); + return; + } + if (!s.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge) + + _dunPatrolActive = false; // the hunt's route replaces the patrol's + CopyHuntSettings(s); + _hunt.Start(RynthClock.Now, me); + _huntRoute = new NavRouteParser { RouteType = NavRouteType.Once }; + s.CurrentNavPath = string.Empty; + s.CurrentRoute = _huntRoute; + s.ActiveNavIndex = 0; + s.EnableNavigation = true; + if (!s.IsMacroRunning) + { + s.IsMacroRunning = true; + _macroWasRunning = true; // no macro-start "nearest waypoint" pick: the hunt plans its own walks + } + ChatLine("[RynthAi] Outdoor hunt on: " + HuntSettingsText(s) + " /ra hunt range to change."); + } + + private void StopHunt(string why, bool say = false) + { + if (!_hunt.Active) { if (say) ChatLine("[RynthAi] Outdoor hunt is off."); return; } + _hunt.Stop(); + var s = _dashboard?.Settings; + if (s != null && ReferenceEquals(s.CurrentRoute, _huntRoute)) + { + s.CurrentRoute = new NavRouteParser(); + s.ActiveNavIndex = 0; + _navigationEngine?.Stop(); + } + _huntRoute = null; + Host.Log($"[RynthAi] Hunt: off ({why})"); + if (say) ChatLine($"[RynthAi] Outdoor hunt off ({why})."); + } + + /// Each plugin tick while logged in: the hunt's next walk, when nothing else wants the character. + private void TickOutdoorHunt() + { + if (!_hunt.Active) return; + var s = _dashboard?.Settings; + if (s == null) return; + if (!s.IsMacroRunning) { StopHunt("the macro stopped"); return; } + if (!ReferenceEquals(s.CurrentRoute, _huntRoute) || s.CurrentNavPath.Length > 0) + { + StopHunt("another route was loaded", say: true); + return; + } + if (!TryHuntPosition(out uint cell, out var me)) return; + if (InDungeon(cell)) { StopHunt("went into a dungeon", say: true); return; } + // A building's rooms (InDungeon said it isn't a dungeon): off RynthNav's landscape map. The way in + // is kept on every tick, a fight's chase included, for the walk back out of a building whose + // doors aren't known. + bool indoors = OutdoorHunt.IsIndoorCell(cell); + _hunt.Track(me, indoors); + // Only when the arbiter's last decision left the character free (a fight, loot, buffs, salvage come first). + if (_activity != BotActivity.Navigating && _activity != BotActivity.Idle) return; + + CopyHuntSettings(s); + var route = s.CurrentRoute; + bool routeDone = route.Points.Count == 0 || !s.EnableNavigation || s.ActiveNavIndex >= route.Points.Count; + // The buildings round it (cell.dat): into them through their doors, out of the one it is in. + // From inside, RynthNav must plan from a doorstep (RynthNav.Path v3); an older one: the way back out. + var buildings = HuntBuildings(); + if (buildings != null) RefreshHuntPortals(buildings); + OutdoorHunt.Decision d; + if (indoors && (buildings == null || HuntNavVersion() < 3)) + d = _hunt.Indoors(RynthClock.Now, me, routeDone); + else + { + // Out to twice Hunt Range: new picks stay inside it, the one being walked to is kept (OutdoorHunt.KeepFactor). + _combatManager?.HuntCandidates(_hunt.RangeYd * OutdoorHunt.KeepFactor, _huntCandidates); + d = _hunt.Tick(RynthClock.Now, me, cell, routeDone, _huntCandidates, HuntPath, buildings); + } + foreach (string note in _hunt.PendingNotes) + { + if (note == _huntNoteLogged) continue; + _huntNoteLogged = note; + Host.Log("[RynthAi] Hunt: " + note); + } + _hunt.ClearNotes(); + switch (d.Act) + { + case OutdoorHunt.Act.Walk when d.Corners != null: + InstallHuntRoute(s, d.Corners); + break; + case OutdoorHunt.Act.Idle when route.Points.Count > 0: + InstallHuntRoute(s, Array.Empty()); + break; + } + } + + private void InstallHuntRoute(LegacyUiSettings s, IReadOnlyList corners) + { + var route = new NavRouteParser { RouteType = NavRouteType.Once }; + foreach (var c in corners) + { + route.Points.Add(new NavPoint + { + Type = NavPointType.Point, + EW = (c.X / 24.0 - 1019.5) / 10.0, + NS = (c.Y / 24.0 - 1019.5) / 10.0, + Z = c.Z / 240.0, + Doorway = c.Door, // a building's door or a doorway inside: reached tightly, walked through straight + }); + } + _huntRoute = route; + s.CurrentNavPath = string.Empty; + s.CurrentRoute = route; + s.ActiveNavIndex = 0; + if (route.Points.Count > 0) s.EnableNavigation = true; + } + + private void CopyHuntSettings(LegacyUiSettings s) + { + _hunt.RangeYd = Math.Clamp(s.OutdoorHuntRange, OutdoorHuntRangeMin, OutdoorHuntRangeMax); + _hunt.RadiusYd = Math.Clamp(s.OutdoorHuntRadius, 0, OutdoorHuntRadiusMax); + } + + // Range up to 2000 (Tom 10-23): past what the client knows of (the landblocks round you) it means "every monster in sight". + internal const double OutdoorHuntRangeMin = 10, OutdoorHuntRangeMax = 2000, OutdoorHuntRadiusMax = 2000; + + /// The character's cell and world position (x = east, y = north, as RynthNav's map). + private bool TryHuntPosition(out uint cell, out OutdoorHunt.Vec at) + { + at = default; + cell = 0; + if (!Host.HasGetPlayerPose || !Host.TryGetPlayerPose(out cell, out float lx, out float ly, out float lz, out _, out _, out _, out _)) + return false; + at = new OutdoorHunt.Vec(((cell >> 24) & 0xFF) * 192.0 + lx, ((cell >> 16) & 0xFF) * 192.0 + ly, lz); + return true; + } + + /// In a dungeon (not a building's rooms, which a walk outdoors may pass through). + private bool InDungeon(uint cell) + { + if ((cell & 0xFFFF) < 0x0100) return false; + var cellDat = _raycast?.GeometryLoader?.CellDat; + if (cellDat == null || !cellDat.IsLoaded) return true; // can't tell: an indoor cell counts as a dungeon + _huntDungeonCheck ??= new NavRecoveryPlanner(Host, () => _raycast, () => _objectCache?.GetHazardCells()); + return _huntDungeonCheck.IsDungeonLandblock(cell >> 16, cellDat); + } + + /// The building map on the client's cell.dat (null until the dats are open). + private BuildingMap? HuntBuildings() + { + var cellDat = _raycast?.GeometryLoader?.CellDat; + if (cellDat == null || !cellDat.IsLoaded) return null; + if (_huntBuildings == null || !ReferenceEquals(_huntBuildings.CellDat, cellDat)) + { + _huntDungeonCheck ??= new NavRecoveryPlanner(Host, () => _raycast, () => _objectCache?.GetHazardCells()); + var check = _huntDungeonCheck; + _huntBuildings = new BuildingMap(cellDat, () => _raycast?.GeometryLoader?.DungeonLOS, lb => check.IsDungeonLandblock(lb, cellDat)); + } + return _huntBuildings; + } + + /// The character's building is known, with a door, and RynthNav plans from a doorstep. + private bool HuntKnowsBuilding(uint cell) + { + var map = HuntBuildings(); + if (map == null || HuntNavVersion() < 3) return false; + int b = map.BuildingOf(cell); + return b != 0 && map.Doors(b).Count > 0; + } + + /// + /// The portal objects the client knows (static and summoned: object class Portal, or an unclassified + /// object whose item type says portal), for the walks inside buildings to keep out of and the doors + /// to drop (a portal by a door's step out: RynthNav's way there may end in its circle, since its + /// goal is always allowed); between doors RynthNav keeps out of portals itself. Read again at most + /// once a second. + /// + private void RefreshHuntPortals(BuildingMap map) + { + long now = Environment.TickCount64; + if (now < _huntPortalsAt) return; + _huntPortalsAt = now + HuntPortalRefreshMs; + var list = new List(); + if (_objectCache != null && Host.HasGetObjectPosition) + { + foreach (var wo in _objectCache.GetLandscapeObjects()) + { + uint uid = unchecked((uint)wo.Id); + bool portal = wo.ObjectClass == AcObjectClass.Portal + || (wo.ObjectClass == AcObjectClass.Unknown && Host.TryGetItemType(uid, out uint type) && (type & HuntItemTypePortal) != 0); + if (!portal) continue; + if (!Host.TryGetObjectPosition(uid, out uint cell, out float x, out float y, out float z) || cell == 0) continue; + list.Add(new BuildingMap.PortalSpot(uid, ((cell >> 24) & 0xFF) * 192.0 + x, ((cell >> 16) & 0xFF) * 192.0 + y, z)); + } + } + list.Sort((a, b) => a.Id.CompareTo(b.Id)); // the same portals in the same order: the walks worked out stay + map.Portals = list; + } + + /// The "RynthNav.Path" version RynthNav serves (0: not loaded). 3 plans from a building's doorstep while inside. + private uint HuntNavVersion() + { + if (!Host.HasGetPluginInterface) return 0; + unsafe + { + var t = (RynthNavPathApiV1*)Host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, 2); + return t == null ? 0 : t->Version; + } + } + + /// RynthNav's way from to (RynthNav.Path v2), the start left off. + /// From v3 every start counts as on the landscape (the hunt plans from doorsteps, never from inside a building). + private OutdoorHunt.PathResult HuntPath(OutdoorHunt.Vec a, OutdoorHunt.Vec b) + { + var none = new OutdoorHunt.PathResult(OutdoorHunt.PathStatus.Unavailable, Array.Empty(), 0, 0); + if (!Host.HasGetPluginInterface) return none; + double[] buf = new double[HuntMaxCorners * 3]; + double[] info = new double[RynthNavPathApiV1.InfoLength]; + int count = 0; + int result; + unsafe + { + // Resolved on every call: RynthNav may be missing, or reloaded since last time. + IntPtr p = Host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, 2); + var t = (RynthNavPathApiV1*)p; + if (t == null || t->Version < 2 || t->StructSize < (uint)sizeof(RynthNavPathApiV1) || t->FindPathEx == null) + return none; + int flags = HuntPathFlags | (t->Version >= 3 ? RynthNavPathApiV1.PathStartOutdoors : 0); + fixed (double* pts = buf) + fixed (double* inf = info) + result = t->FindPathEx(a.X, a.Y, a.Z, b.X, b.Y, b.Z, flags, 0, pts, HuntMaxCorners, &count, inf); + } + var status = result switch + { + RynthNavPathApiV1.ResultOk => OutdoorHunt.PathStatus.Ok, + RynthNavPathApiV1.ResultPartial => OutdoorHunt.PathStatus.Partial, + RynthNavPathApiV1.ResultNoMesh => OutdoorHunt.PathStatus.NoMesh, + _ => OutdoorHunt.PathStatus.NoPath, + }; + var corners = new List(Math.Max(0, count - 1)); + for (int i = 1; i < count; i++) // corner 0 is the start + corners.Add(new OutdoorHunt.Vec(buf[i * 3], buf[i * 3 + 1], buf[i * 3 + 2])); + return new OutdoorHunt.PathResult(status, corners, info[0], info[5]); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs index db5f9d2..a3625fc 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs @@ -46,6 +46,9 @@ public sealed partial class RynthAiPlugin private long _deathHoldUntil; private bool _deathHolding; + // When the character was last seen dead (TickCount64; 0 = not this session). The Dungeon Patrol + // doesn't follow the character into a dungeon it was sent to by a death (TickDunPatrolHazardReroute). + private long _lastDeathAt; private const long DeathSettleMs = 5_000; /// @@ -92,6 +95,7 @@ public sealed partial class RynthAiPlugin if (dead) { _deathHoldUntil = long.MaxValue; + _lastDeathAt = now; _metaManager?.OnPlayerDeath(); // the meta's Death condition sees it after the hold } else if (_deathHoldUntil == long.MaxValue) @@ -113,6 +117,7 @@ public sealed partial class RynthAiPlugin RynthCore.Plugin.Shared.ActionPacer.Forget("death"); // the server dropped whatever was open _buffManager?.CancelPendingRecall("death"); // no /lifestone or macro restart after the respawn _buffManager?.ForgetPendingWield("death"); // a swap the death cut short is not a failed swap + StopHunt("died", say: true); // from the lifestone it would walk all the way back to where it started } else { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs index 541af83..2cc3ca6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs @@ -243,8 +243,10 @@ public sealed partial class RynthAiPlugin (s.BoostNavPriority, s.BoostLootPriority) = NextPriority(s.BoostNavPriority, s.BoostLootPriority, nav, loot, arg); dash!.SaveSettings(); string On(bool b) => b ? "on" : "off"; - ReplyOk(nav && loot ? $"[RynthAi] Boost Nav Priority {On(s.BoostNavPriority)}, Boost Loot Priority {On(s.BoostLootPriority)}." - : nav ? $"[RynthAi] Boost Nav Priority {On(s.BoostNavPriority)}." + // Owner's rule (2026-11-02): with Boost Nav on RynthAi only navigates; say so when it comes on. + string navOnly = nav && s.BoostNavPriority ? " RynthAi only navigates (no hunting, no looting)." : ""; + ReplyOk(nav && loot ? $"[RynthAi] Boost Nav Priority {On(s.BoostNavPriority)}, Boost Loot Priority {On(s.BoostLootPriority)}.{navOnly}" + : nav ? $"[RynthAi] Boost Nav Priority {On(s.BoostNavPriority)}.{navOnly}" : $"[RynthAi] Boost Loot Priority {On(s.BoostLootPriority)}."); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index 6db4750..696a926 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -119,6 +119,18 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // portalled to a different dungeon. private bool _dunPatrolActive; private uint _dunPatrolLandblock; + // The patrol's own route object: the patrol is the mode for as long as it is the loaded route + // (a macro stop or start leaves it; another route loaded in its place ends it, said in chat). + private NavRouteParser? _dunPatrolRoute; + // The dungeon the patrol last tried to follow the character into (once per dungeon). + private uint _dunPatrolFollowTriedLb = uint.MaxValue; + // The landblock seen on the last tick the patrol was running (MaxValue = not running then), and + // whether the character changed landblock while it ran: the patrol follows only through a + // portal taken while it runs, not to wherever the character went with the macro off. + private uint _dunPatrolPrevRunningLb = uint.MaxValue; + private bool _dunPatrolArrivedRunning; + // The nav engine's planner, for its dungeon-landblock test (null until login). + private NavRecoveryPlanner? _navPlanner; private int _dunPatrolHazardVersion; // The patrol settings (Settings > Navigation > Dungeon Patrol) the running patrol was built // with: a change rebuilds it once the settings settle (TickDunPatrolHazardReroute). @@ -350,6 +362,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase try { _sessionStats?.OnLogout(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats logout"); } try { OnLogoutMonsterStats(); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats logout"); } Loot.T11ItemSupport.Reset(); + _boostNavNoticeSaid = false; // the Boost Nav Priority notice: once per session // A real logout: the next OnLoginComplete is a fresh login, not a hot reload. ClearInGameMarker(); ServerPolicy.Forget(); // the next login's [REALM] line says whether the character is in a Thread @@ -451,6 +464,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase private void TeardownSession() { ObjectChangeTracker.Clear(); + ResetItemTool(); while (_engineCommands.TryDequeue(out _)) { } // a fellowship button's command is for this character only // The server drops whatever it was doing for this character at logout. RynthCore.Plugin.Shared.ActionPacer.Forget("logout"); @@ -569,6 +583,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _killClock.SessionStarted(); _dashboard.OnLoginComplete(); _dashboard.ChatSubmitHandler = HandleRynthChatSubmit; + _dashboard.StartPatrolHandler = () => QueueDashAction(HandleDungeonNavPatrol); EnsureTranslator(); EnsureItemInfoUi(); EnsureSpellsUi(); @@ -596,7 +611,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // Plans the detours: the dungeon cell graph indoors, RynthNav's navmesh outdoors. // Reads the raycast geometry and hazards through the fields, so it follows their // (re)creation; dropped with the engine at teardown. - _navigationEngine.SetRecoveryPlanner(new NavRecoveryPlanner(Host, () => _raycast, () => _objectCache?.GetHazardCells())); + _navPlanner = new NavRecoveryPlanner(Host, () => _raycast, () => _objectCache?.GetHazardCells()); + _navigationEngine.SetRecoveryPlanner(_navPlanner); if (_objectCache != null) _navigationEngine.SetWorldObjectCache(_objectCache); _navMarkerRenderer = new NavMarkerRenderer(Host, _dashboard.Settings) { @@ -1039,7 +1055,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "cancelrebuff": dash.RequestCancelForceRebuff(); break; case "clearbusy": HandleClearBusyCommand(); break; case "hideui": _hideUi = on; dash.SetUiHidden(on); break; // applied each tick in OnTick - case "sendchat": if (!string.IsNullOrEmpty(value)) HandleRynthChatSubmit(value); break; + case "sendchat": if (!string.IsNullOrEmpty(value)) RunItemToolUntrusted(() => HandleRynthChatSubmit(value)); break; // a remote line is never the player at the keyboard case "setsetting": ApplyRemoteSetting(value); break; // one advanced setting from the phone (clamped + persisted) case "hub": case "quests": @@ -1135,6 +1151,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase ["DunPatrolWallDistance"] = (DungeonPatrolOptions.WallClearanceMin, DungeonPatrolOptions.WallClearanceMax), ["DunPatrolLookInSize"] = (DungeonPatrolOptions.LookInRoomMin, DungeonPatrolOptions.LookInRoomMax), ["DunPatrolSightYd"] = (DungeonPatrolOptions.SightMin, DungeonPatrolOptions.SightMax), + ["OutdoorHuntRange"] = (OutdoorHuntRangeMin, OutdoorHuntRangeMax), ["OutdoorHuntRadius"] = (0, OutdoorHuntRadiusMax), ["T2Speed"] = (0.1, 5), ["T2WalkWithinYd"] = (1, 50), ["T2DistanceTo"] = (0.1, 10), ["T2ReissueMs"] = (100, 10000), ["T2MaxRangeYd"] = (50, 2000), ["T2MaxLandblocks"] = (1, 20), ["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600), ["RebuffIdleMarginMinutes"] = (0, 60), @@ -1634,6 +1651,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase Guard(TickStep.LocalFeatures, TickLocalFeatures); if (diag) Host.Log("[RynthAi] OnTick: after quest tracker"); Guard(TickStep.GiveQueue, DrainGiveQueue); + Guard(TickStep.ItemTool, TickItemTool); // the Item Tool: chest looter + Quick give (RynthAiPlugin.ItemTool.cs) if (diag) Host.Log("[RynthAi] OnTick: after drain give queue"); Guard(TickStep.Jumper, () => _jumper?.Tick()); if (diag) Host.Log("[RynthAi] OnTick: after jumper tick"); @@ -1786,6 +1804,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // looping through it — or with the Dungeon Patrol settings changed since. // Cheap no-op unless a new hazard cell was registered or a setting changed. TickDunPatrolHazardReroute(); + // Outdoor hunting's next walk (no-op unless /ra hunt is on). + TickOutdoorHunt(); }); // ── Activity arbiter — STEP 5: AUTHORITATIVE, full stop ── @@ -1896,9 +1916,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase boostNav: settings.BoostNavPriority, boostLoot: settings.BoostLootPriority, followActive: followActive, - lootStarved: lootStarved); + lootStarved: lootStarved, + forcedLoot: wantLoot && ForcedLootHolds()); _activity = _arbiter.Apply(in inputs, settings); _lootStarveTurn = lootStarved && _activity == BotActivity.Looting; + // Boost Nav Priority skipped a fight or a corpse: say so, once (RynthAiPlugin.BoostNav.cs). + NoteBoostNavSkip(settings, wantCombat); // Display only: what the Buffing slot is doing (ActivityArbiter.DisplayLabel), // and the decision for [HealLatency]'s "arbiter gave the tick to" part. if (_buffManager != null) @@ -2432,6 +2455,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (string.IsNullOrEmpty(text)) return; try { NoteServerPolicyChat(text); } catch { } // DreamWeave's Thread lines (ServerPolicy) try { NoteDoorServerText(text); } catch { } // "The door is locked!" (the door logic) + try { ItemToolChat(text); } catch { } // the key's answers (chest looter) try { _sessionStats?.OnChatWindowText(text); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "session stats chat"); } try { NoteMonsterStatsChat(text, chatType); } catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "monster stats chat"); } // The Meta Manager eats the reply to its own /myquests poll (only that). @@ -3920,8 +3944,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (parts.Length < 2) return; string cmd = parts[1].ToLower(); - int eat = 0; // not used for meta dispatch, but needed for shared helpers - DispatchRaCommand(cmd, parts, ref eat); + RunItemToolUntrusted(() => { int e = 0; DispatchRaCommand(cmd, parts, ref e); }); // a meta's line is never the player at the keyboard } /// @@ -4005,6 +4028,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "buffprofile": HandleBuffProfileCommand(parts); break; case "groundloot": HandleGroundLootCommand(parts); break; case "addnavpt": HandleAddNavPointCommand(); break; + case "navheading": HandleNavHeadingCommand(parts); break; case "nav": HandleNavCommand(parts); break; case "meta": HandleMetaCommand(parts); break; case "lua": ForwardLuaCommand(parts); break; @@ -4025,6 +4049,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "metamgr": QueueMetaMgrCommand(parts); Reply.Answered(); break; // Meta Manager: applied (and answered) on the next tick case "dunnav": HandleDungeonNavCommand(parts); break; case "dunnav-patrol": HandleDungeonNavPatrolCommand(parts); break; + case "hunt": HandleHuntCommand(parts); break; case "hazard": HandleHazardCommand(parts); break; case "lootparse": HandleLootParseCommand(trimmed); break; case "lootcheckinv": HandleLootCheckInventoryCommand(trimmed); break; @@ -4117,6 +4142,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (parts.Length >= 3 && parts[2].Equals("stop", StringComparison.OrdinalIgnoreCase)) CancelGiveQueue(); else HandleGiveCommand(parts, GiveItemMatch.Regex, partialPlayer: false, allItems: true); break; + case "itemtool": HandleItemToolCommand(parts); break; case "ig": HandleGiveProfileCommand(parts, partialPlayer: false); break; case "igp": HandleGiveProfileCommand(parts, partialPlayer: true); break; // use variants diff --git a/Plugins/RynthCore.Plugin.RynthAi/ScriptInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/ScriptInterface.cs index d41bfc9..59b3b4e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ScriptInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ScriptInterface.cs @@ -272,6 +272,8 @@ public sealed partial class RynthAiPlugin } /// A RynthLua script's ai.Command(text): handled as a typed line, but it answers as a script's - /// (quiet when it works, errors in chat; CommandReply.cs). - internal void ScriptSubmitCommand(string text) => Reply.AsScript(() => { HandleRynthChatSubmit(text); return true; }); + /// (quiet when it works, errors in chat; CommandReply.cs), and the Item Tool refuses it (a script's + /// line is never the player at the keyboard). + internal void ScriptSubmitCommand(string text) + => Reply.AsScript(() => { RunItemToolUntrusted(() => HandleRynthChatSubmit(text)); return true; }); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs index bb58a5c..dbf06af 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltExtraCommands.cs @@ -41,8 +41,12 @@ public sealed partial class RynthAiPlugin _delayedCommands.RemoveAt(i--); try { - if (fromMeta) RunAsMeta(() => { HandleRynthChatSubmit(cmd); return true; }); - else HandleRynthChatSubmit(cmd); + // A delayed line is never the player at the keyboard: the Item Tool refuses it. + RunItemToolUntrusted(() => + { + if (fromMeta) RunAsMeta(() => { HandleRynthChatSubmit(cmd); return true; }); + else HandleRynthChatSubmit(cmd); + }); } catch (Exception ex) { Log($"[RynthAi] /ub delay: '{cmd}' threw {ex.Message}"); } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/AvoidFilter.cs b/Plugins/RynthCore.Plugin.RynthNav/AvoidFilter.cs index fed568d..3e9c5b1 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/AvoidFilter.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/AvoidFilter.cs @@ -20,6 +20,9 @@ internal sealed class AvoidFilter : IDtQueryFilter public AvoidFilter(PortalAvoid avoid) { _avoid = avoid; } + /// The circles this filter keeps out of. + public PortalAvoid Portals => _avoid; + public bool PassFilter(long refs, DtMeshTile tile, DtPoly poly) { if (!_inner.PassFilter(refs, tile, poly)) return false; diff --git a/Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs b/Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs index 5bd3c16..1a55b9d 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs @@ -22,6 +22,8 @@ internal sealed class NavCoarse private int _idx; // portals crossed so far public double GoalEw { get; } public double GoalNs { get; } + /// The goal's height on the navmesh (NaN: not known, a route planned without a navmesh). + public double GoalUp { get; private set; } = double.NaN; public float Cost { get; } public int Count => _portals.Count; public int Crossed => _idx; @@ -57,12 +59,12 @@ internal sealed class NavCoarse internal sealed class Request { public int StartRegion, GoalRegion; - public float Sx, Sz, Gx, Gz; + public float Sx, Sz, Gx, Gz, Gy = float.NaN; public Dictionary StartLegs = new(), GoalLegs = new(); public static Request Measure(NavGraph g, Probe start, Probe goal) { - var r = new Request { StartRegion = start.Region, GoalRegion = goal.Region, Sx = start.Pt.X, Sz = start.Pt.Z, Gx = goal.Pt.X, Gz = goal.Pt.Z }; + var r = new Request { StartRegion = start.Region, GoalRegion = goal.Region, Sx = start.Pt.X, Sz = start.Pt.Z, Gx = goal.Pt.X, Gz = goal.Pt.Z, Gy = goal.Pt.Y }; foreach (int p in g.RegionPortals(start.Region)) r.StartLegs[p] = start.WalkTo(g.Portal(p)); if (start.Region != goal.Region) foreach (int p in g.RegionPortals(goal.Region)) r.GoalLegs[p] = goal.WalkTo(g.Portal(p)); @@ -76,7 +78,7 @@ internal sealed class NavCoarse List? route = g.FindRoute(q.StartRegion, q.Sx, q.Sz, q.GoalRegion, q.Gx, q.Gz, out float cost, out expanded, startLeg: p => q.StartLegs.TryGetValue(p, out float c) ? c : float.NaN, goalLeg: p => q.GoalLegs.TryGetValue(p, out float c) ? c : float.NaN); - return route == null ? null : new NavCoarse(g, route, q.StartRegion, q.Gx, q.Gz, cost); + return route == null ? null : new NavCoarse(g, route, q.StartRegion, q.Gx, q.Gz, cost) { GoalUp = q.Gy }; } /// @@ -195,6 +197,64 @@ internal sealed class NavCoarse return null; } + /// + /// Can a walk from end in , as far as the + /// graph tells? The start's own region, or one with border links (portals) on the start's + /// landmass. A region with no portal is a pocket nothing links into (ground fenced in by a + /// building's walls, a roof, the top of a rock): the route search can never reach it. + /// + public static bool Reachable(NavGraph g, int startRegion, int region) + { + if (region < 0) return false; + if (region == startRegion) return true; + if (g.RegionPortals(region).Length == 0) return false; + int cs = g.Component(startRegion), cr = g.Component(region); + // Components not built, or the start on a roof or a ledge of its own: any linked region. + if (cs < 0 || cr < 0 || g.ComponentSize(cs) < 8) return true; + return cs == cr; + } + + private const int ProbeMaxPolys = 16384; + + /// + /// The goal end of a route: the polygon nearest (, ), as + /// , when a walk from can end there; else + /// the nearest polygon within (then 96 units) that one can + /// (), with set; else the nearest polygon as + /// before (the search then finds no route). + /// + /// 11-01: a /loc on a spot fenced in by a building's walls (a pocket region of one polygon, no + /// portals, the open ground 0.2 m lower and under 6 m away) was the goal of every search: "route: + /// none ... (0 expanded)" from everywhere, and the walk fell back to heading straight for it, + /// into a bridge, round in circles. + /// + public static Probe? ProbeReachable(NavGraph g, DtNavMesh nav, DtNavMeshQuery q, double ew, double up, double ns, float reach, + IReadOnlyDictionary tileRegions, int startRegion, out bool moved) + { + moved = false; + Probe? first = ProbeNear(g, nav, q, ew, up, ns, reach, tileRegions); + if (first != null && Reachable(g, startRegion, first.Region)) return first; + var filter = new DtQueryDefaultFilter(); + var centre = new RcVec3f((float)ew, (float)up, (float)ns); + var polys = new long[ProbeMaxPolys]; + foreach (float r in new[] { reach, Math.Max(reach, 96f) }) + { + q.QueryPolygons(centre, new RcVec3f(r, 512, r), filter, polys, out int pc, polys.Length); + long bestRef = 0; RcVec3f bestPt = default; int bestRegion = -1; double best = double.MaxValue; + for (int i = 0; i < pc; i++) + { + int region = RegionOf(g, nav, polys[i], tileRegions); + if (!Reachable(g, startRegion, region)) continue; + if (q.ClosestPointOnPoly(polys[i], centre, out RcVec3f cp, out _).Failed()) continue; + // Flat distance first; height only breaks near-ties (a bridge deck over a road). + double d = Math.Sqrt((cp.X - ew) * (cp.X - ew) + (cp.Z - ns) * (cp.Z - ns)) + 0.05 * Math.Abs(cp.Y - up); + if (d < best) { best = d; bestRef = polys[i]; bestPt = cp; bestRegion = region; } + } + if (bestRef != 0) { moved = true; return new Probe(q, bestRef, bestPt, bestRegion); } + } + return first; + } + /// The graph region of a polygon of a loaded tile, or -1. public static int RegionOf(NavGraph g, DtNavMesh nav, long polyRef, IReadOnlyDictionary tileRegions) { @@ -211,7 +271,16 @@ internal sealed class NavCoarse /// ground is within units. /// public static Probe? ProbeFile(NavGraph g, string navDataDir, double ew, double up, double ns, float reach) + => ProbeFile(g, navDataDir, ew, up, ns, reach, -1, out _); + + /// + /// ; with a + /// (not -1) it picks ground a walk from there can end on + /// (). + /// + public static Probe? ProbeFile(NavGraph g, string navDataDir, double ew, double up, double ns, float reach, int startRegion, out bool moved) { + moved = false; int x = (int)Math.Floor(ew / 192.0), y = (int)Math.Floor(ns / 192.0); if (x < 0 || x > 255 || y < 0 || y > 255) return null; uint lb = (uint)((x << 8) | y); @@ -226,6 +295,9 @@ internal sealed class NavCoarse var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 2, maxPolys = 1 << 16 }; nav.Init(ref prm, 6); nav.AddTile(md, 0, 0, out _); - return ProbeNear(g, nav, new DtNavMeshQuery(nav), ew, float.IsFinite((float)up) ? up : 0, ns, reach, regions); + double u = float.IsFinite((float)up) ? up : 0; + return startRegion < 0 + ? ProbeNear(g, nav, new DtNavMeshQuery(nav), ew, u, ns, reach, regions) + : ProbeReachable(g, nav, new DtNavMeshQuery(nav), ew, u, ns, reach, regions, startRegion, out moved); } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs b/Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs new file mode 100644 index 0000000..b9059c5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs @@ -0,0 +1,311 @@ +using System; +using System.Collections.Generic; +using DotRecast.Core.Numerics; +using DotRecast.Detour; +using RynthCore.Plugin.Shared; + +namespace RynthNav.Routing; + +/// +/// The navmesh steps a walk is planned with, shared by RynthNav's own walker (Replan) and the +/// "RynthNav.Path" interface (Shared/RynthNavPathApi.cs) v2: the start snapped close up first and +/// only then wide, the corridor kept off portals with the plain filter as the fallback, the corners +/// bent round portals and pushed out from walls, and (FindPathEx, Raycast) the finished path's +/// length and end. Host-free (Detour only): the graph tests drive it on baked floors. Tick thread +/// in the plugin. World units in and out: x east, y north, z height (Detour's x, z, y). +/// +internal static class NavPathQuery +{ + public const int MaxPolys = 512; + /// FindPathEx's straight path before bends (FindPath v1's cap too). + public const int MaxStraightCorners = 256; + /// A path ending farther than this from the snapped goal didn't get there (partial). + public const double GoalSlackUnits = 6.0; + /// The tile box FindPath loads, and FindPathEx with maxTiles 0: at most a 5x5 block. + public const int DefaultMaxTiles = 25; + /// FindPathEx's maxTiles is held to this (a 7x7 block, ~14 MB of tile files the first time). + public const int MaxTilesCap = 49; + + /// The ground we stand on: the mesh keeps the agent radius (2 m) from walls, so close up it's within that, at our height. + public static readonly RcVec3f TightStartExtents = new(2.5f, 4, 2.5f); + /// Then the wide search, which can pick ground on the far side of a thin wall or a roof overhead. + public static readonly RcVec3f WideExtents = new(8, 64, 8); + private static readonly RcVec3f OnMeshExtents = new(0.5f, 24, 0.5f); + private static readonly RcVec3f PushExtents = new(0.3f, 24, 0.3f); + + /// + /// Whether RynthPluginQueryInterface hands out the "RynthNav.Path" table for a request: any version + /// from 1 up to the one built. The table is append-only, so a v1 caller gets the v2 table and uses + /// only the fields it knows (callers check Version and StructSize before a later field). + /// + public static bool ServesInterface(string? iface, uint version) => + iface == RynthNavPathApiV1.InterfaceName && version >= 1 && version <= RynthNavPathApiV1.InterfaceVersion; + + /// FindPathEx's maxTiles: 0 (or less) = the default 25, else at most . + public static int ClampMaxTiles(int maxTiles) => maxTiles <= 0 ? DefaultMaxTiles : Math.Min(maxTiles, MaxTilesCap); + + /// + /// The landblock box to load for a query from (sx, sy) to (gx, gy): both ends' landblocks and every one + /// between, plus a one-tile margin (room for a path that goes round). False when that is more than + /// ; with the box without the margin is + /// tried first (FindPathEx, Raycast), without it the answer is no (FindPath v1). + /// + public static bool TileBox(double sx, double sy, double gx, double gy, int maxTiles, bool shrinkMargin, + out int minX, out int minY, out int maxX, out int maxY) + { + int sLbX = Lb(sx), sLbY = Lb(sy), gLbX = Lb(gx), gLbY = Lb(gy); + for (int margin = 1; margin >= (shrinkMargin ? 0 : 1); margin--) + { + minX = Math.Max(0, Math.Min(sLbX, gLbX) - margin); maxX = Math.Min(255, Math.Max(sLbX, gLbX) + margin); + minY = Math.Max(0, Math.Min(sLbY, gLbY) - margin); maxY = Math.Min(255, Math.Max(sLbY, gLbY) + margin); + if ((maxX - minX + 1) * (maxY - minY + 1) <= maxTiles) return true; + } + minX = minY = maxX = maxY = 0; + return false; + } + + private static int Lb(double world) => (int)Math.Clamp(Math.Floor(world / 192.0), 0, 255); + + /// The polygon under (Detour axes): close up first, then the wide search. + public static long SnapStart(DtNavMeshQuery q, RcVec3f p, IDtQueryFilter filter, out RcVec3f pt) + { + q.FindNearestPoly(p, TightStartExtents, filter, out long r, out pt, out _); + if (r == 0) q.FindNearestPoly(p, WideExtents, filter, out r, out pt, out _); + return r; + } + + /// + /// The polygon corridor from sRef to gRef through ; when that doesn't reach + /// the goal and is set (the first filter keeps out of portals), planned + /// again through (). is + /// the last FindPath's (its partial flag included). + /// + public static int Corridor(DtNavMeshQuery q, long sRef, long gRef, RcVec3f sPt, RcVec3f gPt, + IDtQueryFilter first, IDtQueryFilter plain, bool fallback, Span polys, + out bool fellBack, out DtStatus status) + { + fellBack = false; + status = q.FindPath(sRef, gRef, sPt, gPt, first, polys, out int pc, polys.Length); + if ((pc == 0 || polys[pc - 1] != gRef) && fallback) + { + // No way round the portals to there: plan as before (the caller's steering keeps out of them). + status = q.FindPath(sRef, gRef, sPt, gPt, plain, polys, out pc, polys.Length); + fellBack = true; + } + return pc; + } + + /// On the mesh = inside a polygon (the nearest point on the mesh is the point itself), not merely near one. + public static bool OnMesh(DtNavMeshQuery q, IDtQueryFilter filter, double x, double y, float z) + { + q.FindNearestPoly(new RcVec3f((float)x, z, (float)y), OnMeshExtents, filter, out long r, out RcVec3f np, out _); + return r != 0 && Math.Abs(np.X - x) < 0.05 && Math.Abs(np.Z - y) < 0.05; + } + + /// + /// The path (east, north corners) bent round any portal it still crosses (big open-ground polygons + /// let it cut straight over one): with corners and legs only on the mesh + /// (a leg is on the mesh when every metre of it is). : the height to look at. + /// + public static List<(double X, double Y)> BendRoundPortals(DtNavMeshQuery q, PortalAvoid portals, List<(double X, double Y)> wps, + IDtQueryFilter filter, Func zAt) + { + bool OnMeshAt(double x, double y) => OnMesh(q, filter, x, y, zAt(x, y)); + bool LegOnMesh(double ax, double ay, double bx, double by) + { + double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay)); + int n = Math.Max(1, (int)Math.Ceiling(len)); + for (int k = 1; k < n; k++) + if (!OnMeshAt(ax + (bx - ax) * k / n, ay + (by - ay) * k / n)) return false; + return true; + } + return portals.Bend(wps, OnMeshAt, 12, LegOnMesh); + } + + /// + /// Walls: each corner the path turns round sits on the mesh's edge (the agent radius from a building); + /// push it out along the turn's outside bisector where the ground is + /// walkable (inside a polygon, not merely near it: near it, the moved corner could sit closer to the + /// wall than the body is wide). In place, first corner to last; the ends never move. Returns how many moved. + /// + public static int PushFromWalls(DtNavMeshQuery q, List<(double X, double Y)> wps, double clearance, + IDtQueryFilter filter, Func zAt) + { + if (clearance <= 0 || wps.Count <= 2) return 0; + int moved = 0; + for (int i = 1; i < wps.Count - 1; i++) + { + var (px, py) = wps[i]; var (ax, ay) = wps[i - 1]; var (bx, by) = wps[i + 1]; + double ux = ax - px, uy = ay - py, ul = Math.Sqrt(ux * ux + uy * uy); + double vx = bx - px, vy = by - py, vl = Math.Sqrt(vx * vx + vy * vy); + if (ul < 0.5 || vl < 0.5) continue; + double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy); + if (ol < 0.05) continue; // straight on: no corner to clear + double nx = px + ox / ol * clearance, ny = py + oy / ol * clearance; + q.FindNearestPoly(new RcVec3f((float)nx, zAt(nx, ny), (float)ny), PushExtents, filter, out long rr, out RcVec3f rp, out _); + if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) { wps[i] = (nx, ny); moved++; } + } + return moved; + } + + /// + /// "RynthNav.Path" FindPathEx on the tiles already loaded: from (sx, sy, sz) to (gx, gy, gz) with the + /// Path* ; (its circles already set) for + /// PathAvoidPortals, for PathWallClearance. At most + /// corners. Fills and returns its code: ResultOk, + /// ResultPartial (PathAllowPartial only), ResultNoPath, or ResultNoMesh (no mesh at either end). + /// + public static int FindPathEx(DtNavMeshQuery q, double sx, double sy, double sz, double gx, double gy, double gz, + int flags, int maxCorners, AvoidFilter? portals, double wallClearance, PathExResult r) + { + r.Reset(); + var plain = new DtQueryDefaultFilter(); + long sRef = SnapStart(q, new RcVec3f((float)sx, (float)sz, (float)sy), plain, out RcVec3f sPt); + if (sRef == 0) return r.Fail(RynthNavPathApiV1.ResultNoMesh, "no navmesh at the start"); + // The goal is looked up WITHOUT the portal circles; its polygon is always allowed (AllowB), as Replan. + q.FindNearestPoly(new RcVec3f((float)gx, (float)gz, (float)gy), WideExtents, plain, out long gRef, out RcVec3f gPt, out _); + if (gRef == 0) return r.Fail(RynthNavPathApiV1.ResultNoMesh, "no navmesh at the goal"); + + bool avoid = (flags & RynthNavPathApiV1.PathAvoidPortals) != 0 && portals != null && portals.Portals.Count > 0; + if (avoid) { portals!.AllowA = sRef; portals.AllowB = gRef; } + r.Portals = avoid ? portals!.Portals.Count : 0; + + Span polys = new long[MaxPolys]; + IDtQueryFilter first = avoid ? portals! : plain; + int pc = Corridor(q, sRef, gRef, sPt, gPt, first, plain, avoid, polys, out bool fellBack, out DtStatus st); + r.Polys = pc; r.FellBack = fellBack; + if (st.Failed() || pc == 0) return r.Fail(RynthNavPathApiV1.ResultNoPath, "no way on the navmesh"); + // Detour's partial result: the corridor ends at the polygon nearest the goal it could reach. + bool partial = st.IsPartial() || polys[pc - 1] != gRef; + + Span sp = new DtStraightPath[MaxStraightCorners]; + DtStatus sst = q.FindStraightPath(sPt, gPt, polys[..pc], pc, sp, out int spc, MaxStraightCorners, 0); + if (sst.Failed() || spc < 1) return r.Fail(RynthNavPathApiV1.ResultNoPath, "no straight path"); + r.Truncated = sst.Has(DtStatus.DT_BUFFER_TOO_SMALL); + RcVec3f end = sp[spc - 1].pos; + double slackE = end.X - gPt.X, slackN = end.Z - gPt.Z; + if (Math.Sqrt(slackE * slackE + slackN * slackN) > GoalSlackUnits) partial = true; + if (partial && (flags & RynthNavPathApiV1.PathAllowPartial) == 0) + return r.Fail(RynthNavPathApiV1.ResultNoPath, r.Truncated ? "more corners than it plans" : "the goal can't be reached"); + + var wps = new List<(double X, double Y)>(spc + 4); + var ox = new double[Math.Max(spc, 2)]; var oy = new double[ox.Length]; var oz = new double[ox.Length]; + for (int i = 0; i < spc; i++) + { + wps.Add((sp[i].pos.X, sp[i].pos.Z)); + ox[i] = sp[i].pos.X; oy[i] = sp[i].pos.Z; oz[i] = sp[i].pos.Y; + } + if (spc == 1) { wps.Add(wps[0]); ox[1] = ox[0]; oy[1] = oy[0]; oz[1] = oz[0]; } // start and goal in one spot + // Heights for the mesh tests at a bend or a pushed corner: the nearest straight-path corner's. + float ZAt(double x, double y) + { + int best = 0; double bd = double.MaxValue; + for (int i = 0; i < ox.Length; i++) + { + double d = (ox[i] - x) * (ox[i] - x) + (oy[i] - y) * (oy[i] - y); + if (d < bd) { bd = d; best = i; } + } + return (float)oz[best]; + } + + if (avoid) + { + int before = wps.Count; + wps = BendRoundPortals(q, portals!.Portals, wps, plain, ZAt); + r.Bent = wps.Count - before; + } + if ((flags & RynthNavPathApiV1.PathWallClearance) != 0) r.Pushed = PushFromWalls(q, wps, wallClearance, plain, ZAt); + + int limit = Math.Max(2, maxCorners); + if (wps.Count > limit) + { + if ((flags & RynthNavPathApiV1.PathAllowPartial) == 0) + return r.Fail(RynthNavPathApiV1.ResultNoPath, $"{wps.Count} corners, room for {limit}"); + wps.RemoveRange(limit, wps.Count - limit); // the first stretch of the way; plan again from its end + partial = true; r.Truncated = true; + } + + for (int i = 0; i < wps.Count; i++) + { + var (x, y) = wps[i]; + double z = double.NaN; + for (int k = 0; k < ox.Length && double.IsNaN(z); k++) + if (ox[k] == x && oy[k] == y) z = oz[k]; // a corner Detour gave: its own height + if (double.IsNaN(z)) z = HeightAt(q, plain, x, y, ZAt(x, y)); + r.Corners.Add((x, y, z)); + if (i > 0) + { + var a = r.Corners[i - 1]; + r.Length += Math.Sqrt((x - a.X) * (x - a.X) + (y - a.Y) * (y - a.Y) + (z - a.Z) * (z - a.Z)); + } + } + var last = r.Corners[^1]; + r.EndDistance = Math.Sqrt((gx - last.X) * (gx - last.X) + (gy - last.Y) * (gy - last.Y) + (gz - last.Z) * (gz - last.Z)); + r.Partial = partial; + r.Code = partial ? RynthNavPathApiV1.ResultPartial : RynthNavPathApiV1.ResultOk; + return r.Code; + } + + /// The mesh's height under (x, y) near ; the guess when there's no polygon there. + private static double HeightAt(DtNavMeshQuery q, IDtQueryFilter filter, double x, double y, float zGuess) + { + q.FindNearestPoly(new RcVec3f((float)x, zGuess, (float)y), OnMeshExtents, filter, out long r, out RcVec3f np, out _); + return r != 0 ? np.Y : zGuess; + } + + /// + /// "RynthNav.Path" Raycast on the tiles already loaded: a Detour raycast along the mesh surface from + /// the start's polygon (snapped as FindPathEx's start) toward the goal. RayClear when it reaches the + /// goal's spot (Detour's hit parameter 1 or more: no wall in the way), RayBlocked when it hits the + /// mesh's edge first (a wall, a building, a drop), ResultNoMesh when either end has no mesh. + /// : how far along it got (0..1; float.MaxValue = all the way). + /// + public static int Raycast(DtNavMeshQuery q, double sx, double sy, double sz, double gx, double gy, double gz, out float t) + { + t = 0; + var plain = new DtQueryDefaultFilter(); + long sRef = SnapStart(q, new RcVec3f((float)sx, (float)sz, (float)sy), plain, out RcVec3f sPt); + if (sRef == 0) return RynthNavPathApiV1.ResultNoMesh; + var goal = new RcVec3f((float)gx, (float)gz, (float)gy); + q.FindNearestPoly(goal, WideExtents, plain, out long gRef, out _, out _); + if (gRef == 0) return RynthNavPathApiV1.ResultNoMesh; + // The visited polygons aren't needed; a full buffer only sets a flag, the ray goes on. + Span visited = stackalloc long[64]; + DtStatus st = q.Raycast(sRef, sPt, goal, plain, out t, out _, visited, out _, visited.Length); + if (st.Failed()) return RynthNavPathApiV1.RayBlocked; + return t >= 1f ? RynthNavPathApiV1.RayClear : RynthNavPathApiV1.RayBlocked; + } +} + +/// FindPathEx's answer: the corners (east, north, height) and what the info array and the log line say. +internal sealed class PathExResult +{ + public int Code; + public readonly List<(double X, double Y, double Z)> Corners = new(); + /// The sum of the legs (3D), world units. + public double Length; + /// From the last corner to the requested goal (3D), world units. + public double EndDistance; + public bool Partial, Truncated, FellBack; + public int Polys, Portals, Bent, Pushed; + public string Note = ""; + + public void Reset() + { + Code = RynthNavPathApiV1.ResultNoPath; + Corners.Clear(); + Length = EndDistance = 0; + Partial = Truncated = FellBack = false; + Polys = Portals = Bent = Pushed = 0; + Note = ""; + } + + public int Fail(int code, string note) + { + Corners.Clear(); + Length = EndDistance = 0; + Partial = false; + Code = code; Note = note; + return code; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/PathInterface.cs b/Plugins/RynthCore.Plugin.RynthNav/PathInterface.cs index ceb58f6..0ac53c4 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/PathInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/PathInterface.cs @@ -2,6 +2,7 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using RynthCore.Plugin.Shared; +using RynthNav.Routing; namespace RynthCore.Plugin.RynthNav; @@ -10,20 +11,25 @@ namespace RynthCore.Plugin.RynthNav; /// table RynthPluginQueryInterface hands out. The functions run on the plugin pump /// thread (the caller's OnTick) and act on the current plugin instance, so the table /// survives a re-Init. frees it at RynthPluginShutdown. +/// Version 2 (2026-10-23) appends FindPathEx and Raycast; a caller asking for version 1 +/// gets the same table (it checks Version/StructSize before a field past the ones it knows). /// internal static unsafe class PathInterface { private static RynthNavPathApiV1* _table; + private static long _lastErrorLogMs; public static IntPtr Query(string iface, uint version) { - if (iface != RynthNavPathApiV1.InterfaceName || version != RynthNavPathApiV1.InterfaceVersion) return IntPtr.Zero; + if (!NavPathQuery.ServesInterface(iface, version)) return IntPtr.Zero; if (_table == null) { var t = (RynthNavPathApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthNavPathApiV1)); t->Version = RynthNavPathApiV1.InterfaceVersion; t->StructSize = (uint)sizeof(RynthNavPathApiV1); t->FindPath = &FindPath; + t->FindPathEx = &FindPathEx; + t->Raycast = &Raycast; _table = t; } return (IntPtr)_table; @@ -53,4 +59,59 @@ internal static unsafe class PathInterface return RynthNavPathApiV1.ResultNoMesh; } } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int FindPathEx(double sx, double sy, double sz, double gx, double gy, double gz, int flags, int maxTiles, + double* points, int maxPoints, int* count, double* info) + { + try + { + Clear(count, info); + var p = PluginExports.Runtime.Plugin; + if (p == null) return RynthNavPathApiV1.ResultNoMesh; + return p.InterfaceFindPathEx(sx, sy, sz, gx, gy, gz, flags, maxTiles, points, maxPoints, count, info); + } + catch (Exception ex) + { + Clear(count, info); // no half-written path counts + LogError("FindPathEx", ex); + return RynthNavPathApiV1.ResultNoMesh; + } + } + + /// FindPathEx's outputs before an answer: no corners, info all 0. + private static void Clear(int* count, double* info) + { + if (count != null) *count = 0; + if (info != null) for (int i = 0; i < RynthNavPathApiV1.InfoLength; i++) info[i] = 0; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int Raycast(double sx, double sy, double sz, double gx, double gy, double gz) + { + try + { + var p = PluginExports.Runtime.Plugin; + if (p == null) return RynthNavPathApiV1.ResultNoMesh; + return p.InterfaceRaycast(sx, sy, sz, gx, gy, gz); + } + catch (Exception ex) + { + LogError("Raycast", ex); + return RynthNavPathApiV1.ResultNoMesh; + } + } + + /// A failure inside an interface call, logged at most every 10 s (a caller may ask many times a second). + private static void LogError(string what, Exception ex) + { + try + { + long now = Environment.TickCount64; + if (now - _lastErrorLogMs < 10_000) return; + _lastErrorLogMs = now; + PluginExports.Runtime.Plugin?.LogFromExport($"[RynthNav] path interface: {what} failed: {ex.GetType().Name}: {ex.Message}"); + } + catch { /* never throw out of a native export */ } + } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs index 82d7f83..e200b17 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/PluginExports.cs @@ -14,8 +14,9 @@ public static unsafe class PluginExports { internal static readonly RynthPluginRuntime Runtime = new(); - // Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthNav.Path" v1 - // (RynthAi plans stuck-recovery detours with it). Fixed signature: void* (const char* iface, uint version). + // Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthNav.Path" v2, also + // handed to v1 callers (RynthAi plans stuck-recovery detours with FindPath, and its outdoor hunting + // walks with FindPathEx and Raycast). Fixed signature: void* (const char* iface, uint version). [UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })] private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version) { diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs index 206073a..a202367 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs @@ -46,7 +46,9 @@ public sealed partial class RynthNavPlugin long now = NowMs; if (!force && now < _nextAvoidMs) return; _nextAvoidMs = now + AvoidRefreshMs; - if (!_avoidPortals) { _avoid.Clear(); return; } + // What the walk ran into on this leg (RynthNavPlugin.Blocked.cs) is kept out of like a + // portal, whatever the portals setting. + if (!_avoidPortals) { _avoid.Set(_blockedSpots, Array.Empty()); return; } IReadOnlyList atlasPortals = AtlasPortalSpots(); var map = new List(); @@ -54,27 +56,38 @@ public sealed partial class RynthNavPlugin if (Math.Abs(sp.X - _wx) < AvoidNearUnits && Math.Abs(sp.Y - _wy) < AvoidNearUnits) map.Add(sp); var live = new List(); - if (Host.HasGetLiveObjectIds) - { - foreach (uint id in Host.GetLiveObjectIds()) - { - if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; - if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out _) || cell == 0) continue; - double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y; - if (Math.Abs(wx - _wx) > AvoidNearUnits || Math.Abs(wy - _wy) > AvoidNearUnits) continue; - Host.TryGetObjectName(id, out string name); - live.Add(new PortalAvoid.Spot(wx, wy, PortalAvoid.LiveRadius, name ?? "")); - } - } + LivePortalSpots(live, _wx - AvoidNearUnits, _wy - AvoidNearUnits, _wx + AvoidNearUnits, _wy + AvoidNearUnits); // The step's own target: walking into a portal (a route's portal step, a dungeon's entrance). bool portalLeg = _route != null && _routeIdx < _route.Count && _route[_routeIdx].UsePortal; + int portals = live.Count, mapPortals = map.Count; + map.AddRange(_blockedSpots); // after the live portals: one inside a live portal's circle adds nothing if (portalLeg) _avoid.Set(live, map, _gotoTew, _gotoTns, AvoidTargetUnits); else _avoid.Set(live, map); if (_avoid.Count != _avoidLogged) { _avoidLogged = _avoid.Count; - Host.Log($"[RynthNav] avoid: {_avoid.Count} portal(s) near you to keep out of ({live.Count} seen, {map.Count} from the Atlas){(portalLeg ? "; the step's own portal excepted" : "")}"); + string blocked = _blockedSpots.Count > 0 ? $", {_blockedSpots.Count} spot(s) it ran into" : ""; + Host.Log($"[RynthNav] avoid: {_avoid.Count} spot(s) near you to keep out of ({portals} portal(s) seen, {mapPortals} from the Atlas{blocked}){(portalLeg ? "; the step's own portal excepted" : "")}"); + } + } + + /// + /// Every portal object the client knows standing in the box (world units, edges included), as + /// circles of : exact positions. The walker's set and + /// FindPathEx's (RynthNavPlugin.PathApi.cs) both start from these. + /// + private void LivePortalSpots(List into, double minX, double minY, double maxX, double maxY) + { + if (!Host.HasGetLiveObjectIds) return; + foreach (uint id in Host.GetLiveObjectIds()) + { + if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; + if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out _) || cell == 0) continue; + double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y; + if (wx < minX || wx > maxX || wy < minY || wy > maxY) continue; + Host.TryGetObjectName(id, out string name); + into.Add(new PortalAvoid.Spot(wx, wy, PortalAvoid.LiveRadius, name ?? "")); } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs index cfbaa31..42668f6 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using DotRecast.Core.Numerics; using DotRecast.Detour; +using RynthNav.Routing; namespace RynthCore.Plugin.RynthNav; @@ -9,28 +11,38 @@ namespace RynthCore.Plugin.RynthNav; // little islands (Shoushi's plaza, where the Town Network drops you, 10-08); where the plan runs // out the walk heads straight for its goal for a moment (BlindPushTicks), and that, or a wall the // mesh doesn't show, used to mean running into it until the 30 s progress watchdog. Now: blocked -// for StuckWindowMs = turn away at an angle (alternating sides), plan again, and after -// StuckMaxTries on one leg without progress stop and say where. +// for StuckWindowMs = turn away toward open ground (WalkSteer.UnstickHeading), remember the spot as +// something to keep out of (the next plan bends round it, like round a portal), plan again, and +// after StuckMaxTries on one leg without progress stop and say where. +// +// 11-01, at a bridge the navmesh doesn't show (flat open ground in the tile, nothing in the way): +// it turned 120 degrees off, alternating sides, ran 1.6 s, planned the same path again and ran back +// into the same spot, four times in 20 s, then stopped. The remembered spots now make each new +// plan go round what it ran into. public sealed partial class RynthNavPlugin { private const long StuckWindowMs = 1200; // running this long... private const double StuckMoveUnits = 0.6; // ...and moved less than this = blocked (a run covers 4+ u/s) private const long UnstickMs = 1600; // then turn away from it and run this long (~0.5 s of it turning) - private const double UnstickAngleDeg = 120.0; // away from where it was heading, off to one side private const int StuckMaxTries = 4; // blocked this often on a leg without progress = stop + private const double BlockedAheadUnits = 3.5; // the remembered spot: this far ahead of where it stuck... + private const double BlockedRadiusUnits = 2.5; // ...this big (the character stays outside it) + private const int BlockedMaxSpots = 12; + private const double UnstickOpenUnits = 6.0; // a way out is open ground this far along it private bool _ranLastTick; // the walk asked to run last tick (not standing, not turning in place) private double _lastDriveDeg; private long _stuckWinMs, _unstickUntilMs; private double _stuckWx, _stuckWy, _unstickDeg; private int _stuckTries, _stuckSide = 1; + private readonly List _blockedSpots = new(); /// DriveTo for the walk's own steering: remembers that it ran and which way. private void WalkDrive(double deg) { - DriveTo(deg); + DriveTo(deg, _steerOpen); _lastDriveDeg = deg; - _ranLastTick = !_turnInPlace; + _ranLastTick = !_steerOpen.TurnInPlace; } /// @@ -53,11 +65,36 @@ public sealed partial class RynthNavPlugin return true; } + /// + /// A straight walk from (ax, ay) to (bx, by) stays on the navmesh (Detour's raycast along the + /// polygons from the one underfoot: no mesh edge, so at least the 2 m agent radius from every + /// wall it knows) and out of every circle being kept out of. False without a query or ground underfoot. + /// + private bool WalkableStraight(double ax, double ay, double bx, double by) + { + if (_query == null) return false; + for (int i = 0; i < _avoid.Count; i++) + { + PortalAvoid.Spot s = _avoid.Spots[i]; + if (PortalAvoid.SegmentDistance(s.X, s.Y, ax, ay, bx, by) < s.R + PortalAvoid.SteerMargin) return false; + } + // The default filter: the circles were checked above (the avoid filter drops every big + // polygon that merely reaches into one, which would read as a wall far from the line). + var filter = new DtQueryDefaultFilter(); + var start = new RcVec3f((float)ax, (float)_wz, (float)ay); + _query.FindNearestPoly(start, new RcVec3f(2.5f, 4, 2.5f), filter, out long sRef, out RcVec3f sPt, out _); + if (sRef == 0) return false; + Span path = stackalloc long[64]; + var st = _query.Raycast(sRef, sPt, new RcVec3f((float)bx, sPt.Y, (float)by), filter, out float t, out _, path, out _, 64); + return st.Succeeded() && t >= 1.0f; + } + /// A new leg (or goto): nothing blocked yet. private void ResetBlocked() { _ranLastTick = false; _stuckWinMs = 0; _unstickUntilMs = 0; _stuckTries = 0; + _blockedSpots.Clear(); } /// @@ -71,7 +108,7 @@ public sealed partial class RynthNavPlugin _ranLastTick = false; if (_unstickUntilMs > now) { - DriveTo(_unstickDeg); + DriveTo(_unstickDeg, _steerOpen); lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})"; return true; } @@ -97,12 +134,23 @@ public sealed partial class RynthNavPlugin FinishGoto($"stopped: blocked at {at} ({StuckMaxTries} tries to get round it; something in the way the map doesn't show) ({why})"); return true; } + // Remember what it ran into, so the next plans go round it (RefreshAvoid adds these). + double rad = _lastDriveDeg * Math.PI / 180.0; + if (_blockedSpots.Count >= BlockedMaxSpots) _blockedSpots.RemoveAt(0); + _blockedSpots.Add(new PortalAvoid.Spot(_wx + Math.Sin(rad) * BlockedAheadUnits, _wy + Math.Cos(rad) * BlockedAheadUnits, + BlockedRadiusUnits, "something in the way")); + RefreshAvoid(force: true); + _stuckSide = -_stuckSide; - _unstickDeg = ((_lastDriveDeg + 180.0 - _stuckSide * (180.0 - UnstickAngleDeg)) % 360.0 + 360.0) % 360.0; + _unstickDeg = WalkSteer.UnstickHeading(_lastDriveDeg, _stuckSide, h => + { + double r = h * Math.PI / 180.0; + return WalkableStraight(_wx, _wy, _wx + Math.Sin(r) * UnstickOpenUnits, _wy + Math.Cos(r) * UnstickOpenUnits); + }); _unstickUntilMs = now + UnstickMs; Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {StuckWindowMs / 1000.0:F1} s); " - + $"turning to {_unstickDeg:F0} and planning again ({_stuckTries}/{StuckMaxTries})"); - DriveTo(_unstickDeg); + + $"turning to {_unstickDeg:F0}, keeping out of that spot ({_blockedSpots.Count} so far) and planning again ({_stuckTries}/{StuckMaxTries})"); + DriveTo(_unstickDeg, _steerOpen); lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})"; return true; } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Graph.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Graph.cs index 1fce855..0b77a6e 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Graph.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Graph.cs @@ -29,7 +29,7 @@ public sealed partial class RynthNavPlugin private NavCoarse? _coarse; // the current leg's route (null = none, or none yet) private int _coarseRetry; // re-plans left before planning a route again private int _coarseOff; // re-plans in a row off the route - private bool _coarseAnnounced, _coarseNoRouteSaid; + private bool _coarseAnnounced, _coarseNoRouteSaid, _coarseGoalMovedSaid; private double _aimEw, _aimNs; // where the last re-plan aimed (the blind push follows it) private void LoadGraph() @@ -107,7 +107,7 @@ public sealed partial class RynthNavPlugin private void ResetCoarse() { - _coarse = null; _coarseRetry = 0; _coarseOff = 0; _coarseAnnounced = false; _coarseNoRouteSaid = false; + _coarse = null; _coarseRetry = 0; _coarseOff = 0; _coarseAnnounced = false; _coarseNoRouteSaid = false; _coarseGoalMovedSaid = false; _coarseTask = null; _coarseVersion++; } @@ -167,14 +167,24 @@ public sealed partial class RynthNavPlugin NavCoarse.Probe? target = null; int gx = (int)Math.Floor(_gotoTew / 192.0), gy = (int)Math.Floor(_gotoTns / 192.0); uint goalLb = gx is >= 0 and <= 255 && gy is >= 0 and <= 255 ? (uint)((gx << 8) | gy) : 0; + bool moved = false; try { + // Ground a walk from here can end on: the spot itself, or the nearest such ground + // when the spot is a pocket nothing links into (NavCoarse.ProbeReachable). target = _loadedTiles.Contains(goalLb) - ? NavCoarse.ProbeNear(g, _navMesh!, _query!, _gotoTew, _wz, _gotoTns, 40f, _tileRegions) - : NavCoarse.ProbeFile(g, NavDataDir, _gotoTew, _wz, _gotoTns, 40f); + ? NavCoarse.ProbeReachable(g, _navMesh!, _query!, _gotoTew, _wz, _gotoTns, 40f, _tileRegions, start.Region, out moved) + : NavCoarse.ProbeFile(g, NavDataDir, _gotoTew, _wz, _gotoTns, 40f, start.Region, out moved); } catch (Exception ex) { Host.Log($"[RynthNav] route: target tile unreadable: {ex.Message}"); } if (target == null) return; // no navmesh at the target: head straight, as without a graph + if (moved && !_coarseGoalMovedSaid) + { + _coarseGoalMovedSaid = true; + double off = Math.Sqrt((target.Pt.X - _gotoTew) * (target.Pt.X - _gotoTew) + (target.Pt.Z - _gotoTns) * (target.Pt.Z - _gotoTns)); + Host.Log($"[RynthNav] route: the spot itself can't be walked into (fenced-in ground, a roof or a rock); aiming at walkable ground {off:F0}u from it (region {target.Region})"); + if (off >= ArrivalUnits) Say($"goto: that exact spot can't be walked to; going to the nearest walkable ground, {off:F0} yd from it"); + } NavCoarse.Request req = NavCoarse.Request.Measure(g, start, target); int version = _coarseVersion, here = start.Region, goal = target.Region; @@ -209,6 +219,17 @@ public sealed partial class RynthNavPlugin NoLandRoute(); return; } + // On open ground (the start links to its neighbours, on a real landmass) and still no + // route though the goal end was already moved to ground a walk can end on: the graph + // knows of no way there. Heading straight for it then only runs into what's between + // (11-01: a bridge, then round in circles for minutes). Stop and say so. Standing in a + // pocket yourself (indoors, a roof), the way out may be narrower than the mesh shows: + // head for it as before. + if (g != null && g.RegionPortals(here).Length > 0 && g.ComponentSize(g.Component(here)) >= 8) + { + FinishGoto("stopped: the route graph has no walking way to that spot (nothing walkable within 96 yd of it links to where you are); pick a spot nearby"); + return; + } if (!_coarseNoRouteSaid) { _coarseNoRouteSaid = true; diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs new file mode 100644 index 0000000..d9d0a15 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using RynthNav.Routing; +using NavPathApi = RynthCore.Plugin.Shared.RynthNavPathApiV1; + +namespace RynthCore.Plugin.RynthNav; + +// "RynthNav.Path" version 2 (Shared/RynthNavPathApi.cs): FindPathEx and Raycast, for RynthAi's +// outdoor hunting (a path to a monster that keeps off portals and walls like RynthNav's own walks, +// the reachable point nearest a monster it can't get to, the path's length, and whether a straight +// walk is clear). Called by another plugin from its OnTick (the pump thread, as our OnTick), on the +// same navmesh and query object the walker uses; the walking itself is the caller's. The planning +// steps are NavPathQuery's (host-free, shared with Replan); this part loads the tiles, says whether +// the start is on the landscape at all, and keeps FindPathEx's own portal set. Tick thread. +public sealed partial class RynthNavPlugin +{ + /// A start this close to the player is the player's: the player's cell says whether it's on the landscape. + private const double PathStartIsPlayerUnits = 24.0; + + private readonly PathExResult _pathEx = new(); + + // FindPathEx's portals (PathAvoidPortals): the walker's sources (every portal object the client + // knows, the Atlas's where no live one stands) round the query, never a step's own portal excepted. + // Its own set, so a query never changes the walker's (or logs its "avoid:" line). + private readonly PortalAvoid _pathAvoid = new(); + private AvoidFilter? _pathAvoidFilter; + private readonly List _pathLive = new(), _pathLiveNear = new(), _pathMapNear = new(); + private long _pathLiveNextMs; + + private void ResetPathApi() + { + _pathLive.Clear(); _pathLiveNextMs = 0; + _pathAvoid.Clear(); + } + + /// + /// The start isn't on the landscape mesh: the player is in a dungeon (any world position then is a + /// dungeon's, not the land's), or in a building's cells and the start is where the player stands + /// (unless the caller says it is a spot outdoors, : PathStartOutdoors, v3). + /// + private bool PathStartOffLandscape(double sx, double sy, bool startOutdoors = false) + { + if ((_cellId & 0xFFFF) < 0x100) return false; // outdoors + if (InDungeon(_cellId) || !IsOnMap(_cellId)) return true; // a dungeon (the Atlas's, or one it doesn't know) + if (startOutdoors) return false; // a building's doorstep (RynthAi's hunt walking out) + double dx = sx - _wx, dy = sy - _wy; + return dx * dx + dy * dy <= PathStartIsPlayerUnits * PathStartIsPlayerUnits; + } + + /// FindPathEx's portal circles for a query from (sx, sy) to (gx, gy); live objects read again at most once a second. + private AvoidFilter PathPortals(double sx, double sy, double gx, double gy) + { + long now = NowMs; + if (now >= _pathLiveNextMs) + { + _pathLiveNextMs = now + AvoidRefreshMs; + _pathLive.Clear(); + LivePortalSpots(_pathLive, double.NegativeInfinity, double.NegativeInfinity, double.PositiveInfinity, double.PositiveInfinity); + } + double minX = Math.Min(sx, gx) - AvoidNearUnits, maxX = Math.Max(sx, gx) + AvoidNearUnits; + double minY = Math.Min(sy, gy) - AvoidNearUnits, maxY = Math.Max(sy, gy) + AvoidNearUnits; + _pathLiveNear.Clear(); _pathMapNear.Clear(); + foreach (PortalAvoid.Spot s in _pathLive) + if (s.X >= minX && s.X <= maxX && s.Y >= minY && s.Y <= maxY) _pathLiveNear.Add(s); + foreach (PortalAvoid.Spot s in AtlasPortalSpots()) + if (s.X >= minX && s.X <= maxX && s.Y >= minY && s.Y <= maxY) _pathMapNear.Add(s); + _pathAvoid.Set(_pathLiveNear, _pathMapNear); + return _pathAvoidFilter ??= new AvoidFilter(_pathAvoid); + } + + internal unsafe int InterfaceFindPathEx(double sx, double sy, double sz, double gx, double gy, double gz, + int flags, int maxTiles, double* points, int maxPoints, int* count, double* info) + { + long t0 = Stopwatch.GetTimestamp(); + if (count != null) *count = 0; + if (info != null) for (int i = 0; i < NavPathApi.InfoLength; i++) info[i] = 0; + int tiles = NavPathQuery.ClampMaxTiles(maxTiles); + PathExResult r = _pathEx; + r.Reset(); + + if (points == null || maxPoints < 2) r.Fail(NavPathApi.ResultNoPath, "no room for the corners"); + else if (!_hasPose) r.Fail(NavPathApi.ResultNoMesh, "no player position yet"); + else if (!IsFinite(sx) || !IsFinite(sy) || !IsFinite(sz) || !IsFinite(gx) || !IsFinite(gy) || !IsFinite(gz)) r.Fail(NavPathApi.ResultNoPath, "not a position"); + else if (PathStartOffLandscape(sx, sy, (flags & NavPathApi.PathStartOutdoors) != 0)) + r.Fail(NavPathApi.ResultNoMesh, InDungeon(_cellId) || !IsOnMap(_cellId) ? "in a dungeon" : "in a building"); + else if (!LoadPathBox(sx, sy, gx, gy, tiles, shrinkMargin: true)) r.Fail(NavPathApi.ResultNoPath, $"farther than {tiles} tiles hold"); + else + { + AvoidFilter? portals = (flags & NavPathApi.PathAvoidPortals) != 0 ? PathPortals(sx, sy, gx, gy) : null; + NavPathQuery.FindPathEx(_query, sx, sy, sz, gx, gy, gz, flags, maxPoints, portals, _wallClearance, r); + } + + int n = r.Code is NavPathApi.ResultOk or NavPathApi.ResultPartial ? r.Corners.Count : 0; + for (int i = 0; i < n; i++) + { + points[i * 3] = r.Corners[i].X; // east + points[i * 3 + 1] = r.Corners[i].Y; // north + points[i * 3 + 2] = r.Corners[i].Z; // height + } + if (count != null) *count = n; + if (info != null && n > 0) + { + info[0] = r.Length; + info[1] = r.Partial ? 1 : 0; + info[2] = r.Corners[n - 1].X; info[3] = r.Corners[n - 1].Y; info[4] = r.Corners[n - 1].Z; + info[5] = r.EndDistance; + } + + if ((flags & NavPathApi.PathQuiet) == 0) + { + double ms = Stopwatch.GetElapsedTime(t0).TotalMilliseconds; + string what = r.Code switch + { + NavPathApi.ResultOk => $"{n} corners, {r.Polys} polys, {r.Length:F0}u, ends {r.EndDistance:F1}u from the goal", + NavPathApi.ResultPartial => $"PARTIAL{(r.Truncated ? " (cut short)" : "")}: {n} corners, {r.Polys} polys, {r.Length:F0}u, ends {r.EndDistance:F0}u from the goal", + NavPathApi.ResultNoMesh => $"no navmesh: {r.Note}", + _ => $"no path: {r.Note}", + }; + string extras = ""; + if (r.Portals > 0) extras += $"; {r.Portals} portal(s) avoided{(r.FellBack ? " (no way round them: plain path)" : "")}{(r.Bent > 0 ? $", bent round {r.Bent}" : "")}"; + if (r.Pushed > 0) extras += $"; {r.Pushed} corner(s) {_wallClearance:0.#} m off the walls"; + Host.Log($"[RynthNav] path request ex (flags 0x{flags:X}): {what}{extras}; ({sx:F0},{sy:F0}) -> ({gx:F0},{gy:F0}), {_tileCount} tiles, {ms:F1} ms"); + } + return r.Code; + } + + internal int InterfaceRaycast(double sx, double sy, double sz, double gx, double gy, double gz) + { + if (!_hasPose) return NavPathApi.ResultNoMesh; + if (!IsFinite(sx) || !IsFinite(sy) || !IsFinite(sz) || !IsFinite(gx) || !IsFinite(gy) || !IsFinite(gz)) return NavPathApi.RayBlocked; + if (PathStartOffLandscape(sx, sy)) return NavPathApi.ResultNoMesh; + if (!LoadPathBox(sx, sy, gx, gy, NavPathQuery.DefaultMaxTiles, shrinkMargin: true)) return NavPathApi.RayBlocked; // too far to tell + return NavPathQuery.Raycast(_query, sx, sy, sz, gx, gy, gz, out _); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs index 4a0b565..440597d 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Turn.cs @@ -1,54 +1,44 @@ using System; +using RynthNav.Routing; namespace RynthCore.Plugin.RynthNav; -// Turning the way RynthAi's nav does it (NavigationEngine.DriveHeading, mode 0 heading servo): -// the heading is slewed toward the target at a capped rate rather than snapped onto it, and a big -// turn is made standing (autorun off) and the run resumes once lined up. The numbers are RynthAi's -// defaults (Nav Turn Rate 270 deg/s, Stop Turn Angle 20, Resume Turn Angle 10, Dead Zone 4). +// Turning: the heading servo is WalkSteer (host-free, tested in RynthNav.RouteTests). It slews the +// heading toward the target at a capped rate and turns standing (autorun off) for a big turn. +// Two settings: the walk over open ground (the goto's path, the blind push, stepping round +// something) makes corrections up to 50 degrees on the run and sends a turn at most 20 times a +// second; the close work (the Town Network's corridors, aiming into a portal, holding off one) +// keeps RynthAi's tight defaults (stop for anything over 20 degrees). public sealed partial class RynthNavPlugin { - private const double TurnRateDegPerSec = 270.0; - private const double TurnDeadZoneDeg = 4.0; - private const double StopTurnAngleDeg = 20.0; - private const double ResumeTurnAngleDeg = 10.0; + private readonly WalkSteer _steerOpen = new(); + private readonly WalkSteer _steerTight = WalkSteer.Legacy(); - private bool _turnInPlace; - private long _lastTurnMs; + /// The player's heading (0 = north, clockwise) from the pose quaternion, or NaN. + private double PlayerHeadingDeg() + { + // The quaternion, not GetPlayerHeading (that one is 0 = east, counter-clockwise). + if (Host.TryGetPlayerPose(out _, out _, out _, out _, out float qw, out _, out _, out float qz)) + return (-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) + 720.0) % 360.0; + return double.NaN; + } /// Turn toward (0 = north, clockwise) and run when lined up. - private void DriveTo(double desiredDeg) + private void DriveTo(double desiredDeg, WalkSteer? servo = null) { - desiredDeg = ((desiredDeg % 360.0) + 360.0) % 360.0; - double current = desiredDeg; - if (Host.TryGetPlayerPose(out _, out _, out _, out _, out float qw, out _, out _, out float qz)) - current = (-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) + 720.0) % 360.0; - - double error = desiredDeg - current; - if (error > 180.0) error -= 360.0; else if (error < -180.0) error += 360.0; - double abs = Math.Abs(error); - - long now = NowMs; - double dt = _lastTurnMs == 0 ? 33.0 : Math.Clamp(now - _lastTurnMs, 10, 200); - _lastTurnMs = now; - double maxStep = TurnRateDegPerSec * dt / 1000.0; - - // Run gate with hysteresis: stop to turn when far off, run again once close. - if (_turnInPlace) { if (abs <= ResumeTurnAngleDeg) _turnInPlace = false; } - else if (abs > StopTurnAngleDeg) _turnInPlace = true; - - if (abs > TurnDeadZoneDeg) - { - double next = current + Math.Clamp(error, -maxStep, maxStep); - Host.TurnToHeading((float)(((next % 360.0) + 360.0) % 360.0)); - } - AutoRun.Run(!_turnInPlace); + servo ??= _steerTight; + desiredDeg = WalkSteer.Norm(desiredDeg); + double current = PlayerHeadingDeg(); + if (double.IsNaN(current)) current = desiredDeg; + double turn = servo.Step(desiredDeg, current, NowMs, out bool run); + if (!double.IsNaN(turn)) Host.TurnToHeading((float)turn); + AutoRun.Run(run); } // SetAutoRun/StopCompletely for the goto, sent when they change (AutoRunGate.cs). private AutoRunGate? _autoRun; private AutoRunGate AutoRun => _autoRun ??= new AutoRunGate(on => Host.SetAutoRun(on), () => Host.StopCompletely(), () => NowMs); - /// A fresh start for the turn servo (a new goto, a teleport). - private void ResetTurn() { _turnInPlace = false; _lastTurnMs = 0; } + /// A fresh start for the turn servo (a new goto, a new leg). + private void ResetTurn() { _steerOpen.Reset(); _steerTight.Reset(); } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs index 9365c5c..ecc3444 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs @@ -42,6 +42,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase private const int MaxTiles = 256; private const int MaxCorridorTiles = 220; private const double ArrivalUnits = 7.0; + private const double CornerLookaheadUnits = 6.0; // a path corner is cut from this far out when the next is in plain view private const int PreviewMaxLandblocks = 3; // preview only targets this many landblocks away (a <= 6x6 tile box) private const int BlindPushTicks = 45; // ~1.5 s straight at the goal when the plan runs out short of it (crosses a seam) private const int NoProgressTicks = 30 * 30; // ~30 s without getting ProgressUnits closer to the leg's goal = give up @@ -189,6 +190,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase HideMarkers("logged out"); _meshView.Clear(); _meshDunLb = 0; _trip = null; _tripPath = null; + ResetPathApi(); OnLogoutTravel(); } @@ -283,7 +285,11 @@ public sealed partial class RynthNavPlugin : RynthPluginBase lock (_gate) _status = _tileCount > 0 ? $"{_tileCount} tiles @ 0x{centerLb:X4}" : $"no tile for 0x{centerLb:X4} — bake it"; } - // Feed the bake-ahead watcher: player landblock + goto-target landblock. + // Feed the bake-ahead watcher: player landblock + goto-target landblock. Written only when it + // changes (2026-11-02): every client rewrote it a few times a second, and Windows Defender scans + // each write. + private string _lastPosText = ""; + private void WritePosFile() { try @@ -291,7 +297,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase int pX = (int)((_cellId >> 24) & 0xFF), pY = (int)((_cellId >> 16) & 0xFF); int tX = pX, tY = pY; if (_gotoActive) { tX = (int)(_gotoTew / 192.0); tY = (int)(_gotoTns / 192.0); } - File.WriteAllText(Path.Combine(NavDataDir, "_player.txt"), $"{pX},{pY},{tX},{tY}"); + string text = $"{pX},{pY},{tX},{tY}"; + if (text == _lastPosText) return; + File.WriteAllText(Path.Combine(NavDataDir, "_player.txt"), text); + _lastPosText = text; } catch { } } @@ -314,6 +323,26 @@ public sealed partial class RynthNavPlugin : RynthPluginBase } } + /// + /// The "RynthNav.Path" interface's tiles: the box from (sx, sy) to (gx, gy) plus a one-tile margin + /// (; : without the margin when that + /// alone fits). False when it's more than ; else is + /// ready (made again when a tile was added). + /// + [System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(_query))] + private bool LoadPathBox(double sx, double sy, double gx, double gy, int maxTiles, bool shrinkMargin) + { + EnsureNavMesh(); + if (!NavPathQuery.TileBox(sx, sy, gx, gy, maxTiles, shrinkMargin, out int minX, out int minY, out int maxX, out int maxY)) return false; + bool changed = false; + for (int x = minX; x <= maxX; x++) + for (int y = minY; y <= maxY; y++) + changed |= !_loadedTiles.Contains((uint)((x << 8) | y)) && EnsureTile((uint)((x << 8) | y)); + if (changed || _query == null) _query = new DtNavMeshQuery(_navMesh!); + _tileCount = _loadedTiles.Count; + return true; + } + // Load every tile in the bounding box from player to target (the route corridor). private void LoadCorridorTo(double twx, double twy) { @@ -712,16 +741,14 @@ public sealed partial class RynthNavPlugin : RynthPluginBase lock (_gotoGate) { path = _gotoPath; idx = _gotoIdx; } if (path != null) { - while (idx < path.Count) - { - double ddew = path[idx].ew - _wx, ddns = path[idx].ns - _wy; - // A corner is reached close up (cornerReachMetres); only the path's end uses - // ArrivalUnits. 7 u for every corner turned early and cut across the inside of - // each one, into the building it was going round (10-01 20:15). - double reach = idx >= path.Count - 1 ? ArrivalUnits : _cornerReach; - if (Math.Sqrt(ddew * ddew + ddns * ddns) < reach) idx++; - else break; - } + // A corner is reached close up (cornerReachMetres); only the path's end uses + // ArrivalUnits. 7 u for every corner turned early and cut across the inside of + // each one, into the building it was going round (10-01 20:15). From + // CornerLookaheadUnits out, a corner is also passed once the next one can be walked to + // straight (the navmesh's raycast: the agent radius from every wall it knows, and out + // of the portal circles): the walk turns smoothly instead of overshooting each corner + // at run speed and turning back to it (11-01). + idx = PathFollow.Advance(path, idx, _wx, _wy, _cornerReach, ArrivalUnits, CornerLookaheadUnits, WalkableStraight); lock (_gotoGate) _gotoIdx = idx; } if (path == null || idx >= path.Count) @@ -805,6 +832,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // New leg: fresh progress watchdog, and the old leg's walkable end no longer counts. ResetHub(); ResetBlocked(); + ResetTurn(); _coarseHoldTicks = _graph != null ? CoarseHoldMaxTicks : 0; _nextAvoidMs = 0; _walkHaveLast = false; // a new leg starts where the last step's teleport put us @@ -975,8 +1003,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // The ground we stand on first: the mesh keeps the agent radius (2 m) from walls, so close // up it's within that, at our height. Only then the wide search, which can pick ground on // the far side of a thin wall or a roof overhead, and the walk then runs into that wall. - _query.FindNearestPoly(startP, new RcVec3f(2.5f, 4, 2.5f), filter, out long sRef, out RcVec3f sPt, out _); - if (sRef == 0) _query.FindNearestPoly(startP, new RcVec3f(8, 64, 8), filter, out sRef, out sPt, out _); + long sRef = NavPathQuery.SnapStart(_query, startP, filter, out RcVec3f sPt); // A failed plan drops the old one: StepGoto must not keep following a stale path. if (sRef == 0) { lock (_gate) _status = "off navmesh"; lock (_gotoGate) _gotoPath = null; return; } @@ -990,7 +1017,12 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // the target is too far to be loaded yet (that probe jitters and must stay a last resort). double aimEw = steer?.Ew ?? _gotoTew, aimNs = steer?.Ns ?? _gotoTns; _aimEw = aimEw; _aimNs = aimNs; - var targetP = steer is { } st ? new RcVec3f(st.Ew, st.Up, st.Ns) : new RcVec3f((float)_gotoTew, (float)_wz, (float)_gotoTns); + // The route's last stretch ends on the ground its search ended on: the spot itself, or the + // nearest ground a walk can end on when the spot is fenced in (NavCoarse.ProbeReachable). + // Planned to the spot itself, the nearest polygon is the fenced-in one again. + var targetP = steer is { } st ? new RcVec3f(st.Ew, st.Up, st.Ns) + : _coarse != null && !double.IsNaN(_coarse.GoalUp) ? new RcVec3f((float)_coarse.GoalEw, (float)_coarse.GoalUp, (float)_coarse.GoalNs) + : new RcVec3f((float)_gotoTew, (float)_wz, (float)_gotoTns); AvoidFilter avoid = WalkFilter(); avoid.AllowA = sRef; avoid.AllowB = 0; // The goal is looked up WITHOUT the portal circles: the goal's polygon is always allowed @@ -1002,15 +1034,11 @@ public sealed partial class RynthNavPlugin : RynthPluginBase if (gRef == 0) gRef = FindGoalToward(aimEw, aimNs, out gPt); if (gRef == 0) { lock (_gate) _status = "no tile ahead — bake the route"; lock (_gotoGate) _gotoPath = null; return; } - Span p = new long[512]; + Span p = new long[NavPathQuery.MaxPolys]; avoid.AllowB = gRef; - _query.FindPath(sRef, gRef, sPt, gPt, avoid, p, out int pc, 512); - if ((pc == 0 || p[pc - 1] != gRef) && _avoid.Count > 0) - { - // No way round the portals to there: plan as before; steering still keeps out of them. - _query.FindPath(sRef, gRef, sPt, gPt, filter, p, out pc, 512); - if (!_avoidFallbackSaid) { _avoidFallbackSaid = true; Host.Log("[RynthNav] avoid: no path round the portals here; steering round them instead"); } - } + // No way round the portals to there: planned as before; steering still keeps out of them. + int pc = NavPathQuery.Corridor(_query, sRef, gRef, sPt, gPt, avoid, filter, _avoid.Count > 0, p, out bool fellBack, out _); + if (fellBack && !_avoidFallbackSaid) { _avoidFallbackSaid = true; Host.Log("[RynthNav] avoid: no path round the portals here; steering round them instead"); } Span sp = new DtStraightPath[512]; _query.FindStraightPath(sPt, gPt, p[..pc], pc, sp, out int spc, 512, 0); if (spc < 2) { lock (_gate) _status = "no path"; lock (_gotoGate) _gotoPath = null; return; } @@ -1022,49 +1050,17 @@ public sealed partial class RynthNavPlugin : RynthPluginBase var wps = new List<(double, double)>(spc); for (int i = 0; i < spc; i++) wps.Add((sp[i].pos.X, sp[i].pos.Z)); // Round any portal the path still crosses (big open-ground polygons let it cut straight over one). + // Every mesh test at our own height (the walker plans from where it stands). + float wz = (float)_wz; if (_avoid.Count > 0) { - var q = _query; - float wz = (float)_wz; int before = wps.Count; - // On the mesh = inside a polygon (the nearest point on the mesh is the point itself), - // not merely near one; a leg is on the mesh when every metre of it is. - bool OnMesh(double x, double y) - { - q.FindNearestPoly(new RcVec3f((float)x, wz, (float)y), new RcVec3f(0.5f, 24, 0.5f), filter, out long r, out RcVec3f np, out _); - return r != 0 && Math.Abs(np.X - x) < 0.05 && Math.Abs(np.Z - y) < 0.05; - } - bool LegOnMesh(double ax, double ay, double bx, double by) - { - double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay)); - int n = Math.Max(1, (int)Math.Ceiling(len)); - for (int k = 1; k < n; k++) - if (!OnMesh(ax + (bx - ax) * k / n, ay + (by - ay) * k / n)) return false; - return true; - } - wps = _avoid.Bend(wps, OnMesh, 12, LegOnMesh); + wps = NavPathQuery.BendRoundPortals(_query, _avoid, wps, filter, (_, _) => wz); if (wps.Count != before) Host.Log($"[RynthNav] avoid: path bent round {wps.Count - before} portal(s)"); } // Walls: each corner the path turns round sits on the mesh's edge (the agent radius from a // building); push it out along the turn's outside bisector where the ground is walkable. - if (_avoidWalls && _wallClearance > 0 && wps.Count > 2) - { - var q2 = _query; - for (int i = 1; i < wps.Count - 1; i++) - { - var (px, py) = wps[i]; var (ax, ay) = wps[i - 1]; var (bx, by) = wps[i + 1]; - double ux = ax - px, uy = ay - py, ul = Math.Sqrt(ux * ux + uy * uy); - double vx = bx - px, vy = by - py, vl = Math.Sqrt(vx * vx + vy * vy); - if (ul < 0.5 || vl < 0.5) continue; - double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy); - if (ol < 0.05) continue; // straight on: no corner to clear - double nx = px + ox / ol * _wallClearance, ny = py + oy / ol * _wallClearance; - // Only onto walkable ground itself (inside a polygon), not merely near it: near it, - // the moved corner could sit closer to the wall than the body is wide. - q2.FindNearestPoly(new RcVec3f((float)nx, (float)_wz, (float)ny), new RcVec3f(0.3f, 24, 0.3f), filter, out long rr, out RcVec3f rp, out _); - if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) wps[i] = (nx, ny); - } - } + if (_avoidWalls) NavPathQuery.PushFromWalls(_query, wps, _wallClearance, filter, (_, _) => wz); lock (_gotoGate) { _gotoPath = wps; _gotoIdx = 0; } int rem = (int)Math.Sqrt((_gotoTew - _wx) * (_gotoTew - _wx) + (_gotoTns - _wy) * (_gotoTns - _wy)); string via = _coarse != null && _coarse.Count > 0 ? $", route {_coarse.Crossed}/{_coarse.Count}" : ""; @@ -1075,8 +1071,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // Called by another plugin from its OnTick: the same pump thread as our OnTick, so // the navmesh is touched on the tick thread only. Loads the tiles covering start and // goal (plus a one-tile margin) and plans on the same query object goto uses. - private const int InterfaceMaxTiles = 25; // at most a 5x5 block of tiles per call - private const double InterfaceGoalSlackUnits = 6.0; // a path ending farther than this from the goal is partial + // Version 2 (FindPathEx, Raycast): RynthNavPlugin.PathApi.cs. internal unsafe int InterfaceFindPath(double sx, double sy, double sz, double gx, double gy, double gz, double* points, int maxPoints, int* count) @@ -1088,18 +1083,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase return Shared.RynthNavPathApiV1.ResultNoPath; // Tiles for both ends and everything between (plus a margin), capped. - EnsureNavMesh(); - int sLbX = (int)(sx / 192.0), sLbY = (int)(sy / 192.0); - int gLbX = (int)(gx / 192.0), gLbY = (int)(gy / 192.0); - int minX = Math.Max(0, Math.Min(sLbX, gLbX) - 1), maxX = Math.Min(255, Math.Max(sLbX, gLbX) + 1); - int minY = Math.Max(0, Math.Min(sLbY, gLbY) - 1), maxY = Math.Min(255, Math.Max(sLbY, gLbY) + 1); - if ((maxX - minX + 1) * (maxY - minY + 1) > InterfaceMaxTiles) return Shared.RynthNavPathApiV1.ResultNoPath; - bool changed = false; - for (int x = minX; x <= maxX; x++) - for (int y = minY; y <= maxY; y++) - changed |= !_loadedTiles.Contains((uint)((x << 8) | y)) && EnsureTile((uint)((x << 8) | y)); - if (changed || _query == null) _query = new DtNavMeshQuery(_navMesh!); - _tileCount = _loadedTiles.Count; + if (!LoadPathBox(sx, sy, gx, gy, NavPathQuery.DefaultMaxTiles, shrinkMargin: false)) return Shared.RynthNavPathApiV1.ResultNoPath; var filter = new DtQueryDefaultFilter(); var startP = new RcVec3f((float)sx, (float)sz, (float)sy); @@ -1120,7 +1104,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase var last = sp[spc - 1].pos; double slackE = last.X - gPt.X, slackN = last.Z - gPt.Z; - if (Math.Sqrt(slackE * slackE + slackN * slackN) > InterfaceGoalSlackUnits) return Shared.RynthNavPathApiV1.ResultNoPath; + if (Math.Sqrt(slackE * slackE + slackN * slackN) > NavPathQuery.GoalSlackUnits) return Shared.RynthNavPathApiV1.ResultNoPath; for (int i = 0; i < spc; i++) { diff --git a/Plugins/RynthCore.Plugin.RynthNav/WalkSteer.cs b/Plugins/RynthCore.Plugin.RynthNav/WalkSteer.cs new file mode 100644 index 0000000..86b5956 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/WalkSteer.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; + +namespace RynthNav.Routing; + +/// +/// The goto's heading servo, host-free (RynthNavPlugin.Turn.cs feeds it the player's heading and +/// sends what it asks for; RynthNav.RouteTests walks it along made-up paths). +/// +/// The heading is slewed toward the wanted one at a capped rate; a big turn is made standing +/// (autorun off) and the run resumes once lined up. Until 11-01 it stopped to turn for anything +/// over 20 degrees and sent a turn every tick (~45 a second): every path corner and every shift +/// of the aim stopped the run, a "bounces left and right with a lot of stopping" walk (11-01, 862 +/// turns and 21 stops in 107 s). Now: running, corrections up to are +/// made on the move, small ones () are left alone, and a turn goes +/// out at most every . +/// +internal sealed class WalkSteer +{ + public double TurnRateDegPerSec = 270.0; + public double DeadZoneDeg = 4.0; // standing: closer than this is lined up + public double RunDeadZoneDeg = 6.0; // running: closer than this isn't worth a turn + public double StopTurnAngleDeg = 50.0; // farther off than this: stop and turn standing + public double ResumeTurnAngleDeg = 20.0; // ...and run again once this close + public long MinTurnIntervalMs = 50; // at most 20 turns a second + + public bool TurnInPlace { get; private set; } + private long _lastTurnMs; + + /// The servo as it was before 11-01 (for comparison in the tests). + public static WalkSteer Legacy() => new() + { RunDeadZoneDeg = 4.0, StopTurnAngleDeg = 20.0, ResumeTurnAngleDeg = 10.0, MinTurnIntervalMs = 0 }; + + public void Reset() { TurnInPlace = false; _lastTurnMs = 0; _lastCallMs = 0; _held = false; } + + /// Signed smallest difference a - b, in -180..180. + public static double Diff(double a, double b) + { + double e = (a - b) % 360.0; + if (e > 180.0) e -= 360.0; else if (e < -180.0) e += 360.0; + return e; + } + + public static double Norm(double deg) => ((deg % 360.0) + 360.0) % 360.0; + + /// + /// One tick: wanted and current heading (0 = north, clockwise). Returns the heading to turn to + /// now, or NaN for none; is whether to run. + /// + public double Step(double desiredDeg, double currentDeg, long nowMs, out bool run) + { + double error = Diff(Norm(desiredDeg), Norm(currentDeg)); + double abs = Math.Abs(error); + + // Run gate with hysteresis: stop to turn when far off, run again once close. + if (TurnInPlace) { if (abs <= ResumeTurnAngleDeg) TurnInPlace = false; } + else if (abs > StopTurnAngleDeg) TurnInPlace = true; + run = !TurnInPlace; + + // The slew covers the time since the last call, or since the last turn when the calls in + // between wanted one and were held back by the rate limit (as before 11-01 with no limit). + long since = _held ? nowMs - _lastTurnMs : nowMs - _lastCallMs; + bool first = _lastCallMs == 0; + _lastCallMs = nowMs; + _held = false; + double dead = TurnInPlace ? DeadZoneDeg : RunDeadZoneDeg; + if (abs <= dead) return double.NaN; + if (_lastTurnMs != 0 && nowMs - _lastTurnMs < MinTurnIntervalMs) { _held = true; return double.NaN; } + double dt = first ? 33.0 : Math.Clamp(since, 10, 200); + _lastTurnMs = nowMs; + double maxStep = TurnRateDegPerSec * dt / 1000.0; + return Norm(currentDeg + Math.Clamp(error, -maxStep, maxStep)); + } + + private long _lastCallMs; + private bool _held; + + /// + /// Which way to step round something the walk ran into: away from + /// on (+1 clockwise, -1 counter-clockwise) first, the first heading the + /// navmesh shows open ground along (), else straight back. Before 11-01 it + /// was always 120 degrees off, alternating sides, open or not (into the bank of the river beside + /// a bridge, then back into the bridge). + /// + public static double UnstickHeading(double headingDeg, int side, Func? open) + { + side = side >= 0 ? 1 : -1; + foreach (double off in new[] { 100.0, 130.0, 70.0, 160.0 }) + foreach (int s in new[] { side, -side }) + { + double h = Norm(headingDeg + s * off); + if (open == null || open(h)) return h; + } + return Norm(headingDeg + 180.0); + } +} + +/// +/// Which path corner the walk heads for (host-free). A corner is passed when the walk is within +/// cornerReach of it, or, from lookahead out, as soon as the corner after it can be +/// walked to in a straight line (clear: the navmesh's raycast, which keeps the agent radius +/// from every wall, and no portal circle on the way). Before 11-01 only the first: each corner was +/// run to within 1.5 m, overshot at run speed and turned back to. +/// +internal static class PathFollow +{ + public static int Advance(IReadOnlyList<(double X, double Y)> path, int idx, double x, double y, + double cornerReach, double arrival, double lookahead, + Func? clear) + { + while (idx < path.Count) + { + bool last = idx >= path.Count - 1; + double d = Dist(path[idx].X, path[idx].Y, x, y); + if (d < (last ? arrival : cornerReach)) { idx++; continue; } + if (!last && clear != null && d < lookahead && clear(x, y, path[idx + 1].X, path[idx + 1].Y)) { idx++; continue; } + break; + } + return idx; + } + + private static double Dist(double ax, double ay, double bx, double by) => Math.Sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); +} diff --git a/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs b/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs index 2794055..b154c4a 100644 --- a/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthSort/RynthSortPlugin.cs @@ -84,6 +84,9 @@ public sealed class RynthSortPlugin : RynthPluginBase { Warnings = () => _warnings, Character = () => _identityKnown ? _character : string.Empty, + Icons = IconsOn, + CanSelect = () => Host.HasSelectItem, + SelectInGame = id => Host.HasSelectItem && Host.SelectItem(id), }; // No bar button of its own: opened from the engine Inventory window's Sort button, the // Scripts menu or /rsort. @@ -244,6 +247,14 @@ public sealed class RynthSortPlugin : RynthPluginBase } } + // Item icons in script windows need op level 2 (engines from 2026-09-30); asked until it says yes. + private bool _icons; + private bool IconsOn() + { + if (!_icons) _icons = Host.HasUi && Host.TryGetUiInfo(out RynthCore.PluginSdk.UiInfoNative info) && info.OpLevel >= 2; + return _icons; + } + private void TryStartCharacter(long now) { _nextIdentityTryMs = now + IdentityRetryMs; diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs index f06a133..b78797a 100644 --- a/Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/InventoryReader.cs @@ -76,10 +76,15 @@ internal sealed class InventoryReader if (isContainer) { // A side pack holds items; foci (containers that hold none) aren't packs or items. - if (capRead && cap > 0) + // A container whose capacity can't be read yet but that has items in it is a pack + // too (foci never hold any): leaving it out would number every pack below it one + // too high against the pack column. Its capacity stays 0 (the planner's 24). + uint[]? inside = null; + if (!capRead) inside = Contents(host, id); + if (IsSidePack(wielded: false, capRead, cap, inside?.Length ?? 0)) { - var pack = new SortPack { Id = id, Capacity = cap, Name = host.TryGetObjectName(id, out string pn) ? pn : string.Empty }; - foreach (uint inner in Contents(host, id)) + var pack = new SortPack { Id = id, Capacity = capRead ? cap : 0, Name = host.TryGetObjectName(id, out string pn) ? pn : string.Empty }; + foreach (uint inner in inside ?? Contents(host, id)) { if (inner == 0) continue; uint it = host.TryGetItemType(inner, out uint itt) ? itt : 0; @@ -98,10 +103,41 @@ internal sealed class InventoryReader foreach (SortPack p in inv.Packs) if (host.TryGetContainerOrder(p.Id, false, ref _order, out n)) p.ApplyOrder(_order, n); if (host.TryGetContainerOrder(player, true, ref _order, out n)) inv.ApplyPackOrder(_order, n); + else inv.OrderSource = PackOrderSource.NotSeen; } + NoteOrderSource(host, inv); return inv; } + private PackOrderSource? _loggedSource; + private int _loggedPacks = -1; + + /// One log line whenever where the pack numbers come from changes (a runtime fact the window can't show the log). + private void NoteOrderSource(RynthCoreHost host, SortInventory inv) + { + if (_loggedSource == inv.OrderSource && _loggedPacks == inv.Packs.Count) return; + _loggedSource = inv.OrderSource; + _loggedPacks = inv.Packs.Count; + try { host.Log("[RynthSort] " + OrderSourceLine(inv)); } catch { } + } + + /// The log line for (pure). + internal static string OrderSourceLine(SortInventory inv) => inv.OrderSource switch + { + PackOrderSource.Known => $"pack numbers follow the pack column, top first ({inv.Packs.Count} packs, {inv.ColumnEntries} entries in the column with foci)", + PackOrderSource.Mismatch => $"pack numbers by object id: the engine's pack column list ({inv.ColumnEntries} entries) lacks {inv.MissingFromColumn} of {inv.Packs.Count} packs", + PackOrderSource.NotSeen => $"pack numbers by object id: the engine has no pack column list for this character (it loaded after the login with nothing saved); {inv.Packs.Count} packs", + _ => $"pack numbers by object id: this engine has no slot orders (plugin API 80); {inv.Packs.Count} packs", + }; + + /// + /// Whether a container in the main pack is a side pack RynthSort lists (pure): never a worn or + /// wielded one; one whose capacity reads holds items (above 0; a focus holds none); one whose + /// capacity can't be read yet counts when it has items in it (foci never do). + /// + internal static bool IsSidePack(bool wielded, bool capRead, int capacity, int itemsInside) => + !wielded && (capRead ? capacity > 0 : itemsInside > 0); + /// The slot holds in (the engine's slot order), or -1. public int SlotOf(RynthCoreHost host, uint container, uint itemId) { diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs index e31f546..dd5f922 100644 --- a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortInventory.cs @@ -32,6 +32,12 @@ internal sealed class SortPack /// nothing is reordered in this pack. /// public bool OrderKnown; + /// + /// Where it sits in the pack column, 1 = the top, counting foci too (the column shows both); + /// 0 when the column's order isn't known. Its pack number counts packs only, so the two differ + /// when a focus sits above it. + /// + public int ColumnSlot; /// /// Puts in (the pack's slot order) when that names @@ -118,11 +124,26 @@ internal readonly struct SortSlot public bool IsPack => Capacity > 0; } +/// Where the side packs' numbers come from (what the window tells the player). +internal enum PackOrderSource +{ + /// The engine has no slot orders (before plugin API 80): numbered by object id. + NoEngine, + /// The engine hasn't seen the server's pack list for this character (an engine that + /// loaded after the login and had nothing saved): numbered by object id until the next login. + NotSeen, + /// The engine's pack list doesn't name every pack read: numbered by object id. + Mismatch, + /// The pack column's order, top first. + Known, +} + /// /// The character's packs: the main pack and the side packs, pack 1 first. With the engine's slot /// order (API v80) that is the pack column on screen, top first (); -/// else GetContainerContents' order, by object id. Rules keep the pack's id either way, so a -/// pack keeps its rules whatever its number. +/// else GetContainerContents' order, by object id (which is also the order the engine's own +/// Inventory panel falls back to). Rules keep the pack's id either way, so a pack keeps its +/// rules whatever its number. /// internal sealed class SortInventory { @@ -136,21 +157,39 @@ internal sealed class SortInventory public readonly List Slots = new(); /// are in the pack column's order, top first. public bool PackOrderKnown; + /// Why the packs are numbered the way they are. + public PackOrderSource OrderSource = PackOrderSource.NoEngine; + /// With : how many packs read the list lacks. + public int MissingFromColumn; + /// Entries in the pack column's list (packs and foci) the last time it was read; -1 = no list. + public int ColumnEntries = -1; /// /// Puts in the pack column's order: is the main /// pack's side-slot list (packs and foci, top first). Only when it names every pack read; else - /// the packs keep their order and is false. + /// the packs keep their order, is false and + /// says how many it lacks. Each pack's + /// is its place in the list (foci counted). /// public bool ApplyPackOrder(IReadOnlyList order, int count) { PackOrderKnown = false; + MissingFromColumn = 0; + ColumnEntries = count; + foreach (SortPack p in Packs) p.ColumnSlot = 0; var rank = new Dictionary(count); for (int i = 0; i < count; i++) rank.TryAdd(order[i], i); foreach (SortPack p in Packs) - if (!rank.ContainsKey(p.Id)) return false; + if (!rank.ContainsKey(p.Id)) MissingFromColumn++; + if (MissingFromColumn > 0) + { + OrderSource = PackOrderSource.Mismatch; + return false; + } Packs.Sort((a, b) => rank[a.Id].CompareTo(rank[b.Id])); + foreach (SortPack p in Packs) p.ColumnSlot = rank[p.Id] + 1; PackOrderKnown = true; + OrderSource = PackOrderSource.Known; return true; } diff --git a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs index c4e1138..783b180 100644 --- a/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthSort/Sorting/SortPlanner.cs @@ -96,6 +96,8 @@ internal sealed class PackLine public bool OrderKnown; /// Items out of place in it (0 = in order; only counted when the order is known and ordering is on). public int OutOfPlace; + /// Its place in the pack column, 1 = top, foci counted (); 0 = not known. + public int ColumnSlot; /// "Sack (12/24) - Salvage, Gems". public string Label => $"{Name} ({Used}/{Capacity}) - {Summary}"; @@ -123,6 +125,8 @@ internal sealed class SortView public PackLine Main = new(); /// The packs are numbered top to bottom as the pack column shows them (else by object id). public bool PackOrderKnown; + /// Why the packs are numbered as they are (). + public PackOrderSource OrderSource = PackOrderSource.NoEngine; /// The pass could put items in order (the engine reads slot orders and ordering is on). public bool Ordering; /// Items a rule wants moved that can't go yet (settling, pack full, pack missing, main full). @@ -428,6 +432,7 @@ internal sealed class SortPlanner Summary = p.Summary(), OrderKnown = p.OrderKnown, OutOfPlace = ordering && p.OrderKnown ? PackOrder.OutOfPlace(p.Items, kindFirst) : 0, + ColumnSlot = p.ColumnSlot, }; private static void FillPacks(SortView view, SortInventory inv, bool ordering, bool kindFirst) @@ -437,6 +442,7 @@ internal sealed class SortPlanner view.Main = LineOf(inv.Main, MainCapacityFallback, ordering, kindFirst); view.Main.Name = "Main pack"; view.PackOrderKnown = inv.PackOrderKnown; + view.OrderSource = inv.OrderSource; view.Ordering = ordering; foreach (SortPack p in inv.Packs) view.Packs.Add(LineOf(p, SideCapacityFallback, ordering, kindFirst)); } diff --git a/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs b/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs index 67abec0..cba5d33 100644 --- a/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs +++ b/Plugins/RynthCore.Plugin.RynthSort/Views/SortPanel.cs @@ -8,9 +8,10 @@ namespace RynthCore.Plugin.RynthSort.Views; /// /// The RynthSort window: the auto-sort box and status, the job buttons, then one collapsing -/// section per side pack ("Pack 1: Sack (12/24) - Components", top pack first) holding that -/// pack's warnings and its rules (A-Z), a section for rules whose pack isn't carried, and the -/// settings. A rule is one row (on/off box, its classes and names); selecting it opens its +/// section per side pack ("Pack 1: Sack (12/24) - Components", top pack first) holding a line +/// that says which pack in the game it is (its icon, "Select in game", and its place in the +/// pack column), that pack's warnings and its rules (A-Z), a section for rules whose pack isn't +/// carried, and the settings. A rule is one row (on/off box, its classes and names); selecting it opens its /// editor beneath: the classes and names as chips (click one to take it out), a class picker and /// a name box to add, the pack it sends to, and Remove. Recorded on the pump thread, replayed by /// the engine. @@ -29,6 +30,15 @@ internal sealed class SortPanel public Func> Warnings = () => Array.Empty(); /// The character (blank before login). public Func Character = () => string.Empty; + /// The engine draws item icons in script windows (op level 2). + public Func Icons = () => false; + /// The engine can select objects (else no Select button). + public Func CanSelect = () => false; + /// Selects an object in the game (Host.SelectItem); false when it couldn't. + public Func SelectInGame = _ => false; + + private uint _selectedPack; + private string _selectNote = string.Empty; public SortPanel(SortController c, Action save) { @@ -78,6 +88,14 @@ internal sealed class SortPanel w.TextColored(UiColors.Amber, "RynthAi's AutoCram also moves loot out of the main pack; turn one of them off"); foreach (string warning in Warnings()) w.TextColored(UiColors.Amber, warning); + string numbering = NumberingNote(view); + if (numbering.Length > 0) + { + w.PushStyleColor(UiFormat.ColText, UiColors.Grey); + w.TextWrapped(numbering); + w.PopStyleColor(); + } + Dictionary> byPack = Group(rules, view); Dictionary> conflicts = Conflicts(rules, view); for (int i = 1; i <= view.Packs.Count; i++) @@ -121,10 +139,11 @@ internal sealed class SortPanel if (attention) w.PushStyleColor(UiFormat.ColText, UiColors.Amber); bool open = w.CollapsingHeader($"Pack {number}: {p.Label}", $"pack.{p.Id:X8}", defaultOpen: true); if (attention) w.PopStyleColor(); - w.Tooltip(PackTooltip(view)); + w.Tooltip(PackHeaderTooltip(view, number)); if (!open) return; w.Indent(RowIndent); + DrawWhere(w, view, p, number); if (full) w.TextColored(UiColors.Amber, "This pack is full: items for it wait where they are"); foreach (string line in warnings) w.TextColored(UiColors.Amber, line); packRules.Sort(SortRules.CompareForList); @@ -150,6 +169,36 @@ internal sealed class SortPanel w.Unindent(RowIndent); } + /// The pack's first line: its icon, Select in game, and where it is in the pack column. + private void DrawWhere(UiWindow w, SortView view, PackLine p, int number) + { + if (Icons()) + { + w.Image(UiFormat.IconKindObject, p.Id, WhereIcon, WhereIcon); + w.SameLine(); + } + if (CanSelect()) + { + uint id = p.Id; + string name = p.Name; + w.SmallButton("Select in game", $"select.{id:X8}", () => + { + _selectedPack = id; + _selectNote = SelectInGame(id) ? $"Selected: the game has your {name} selected now" : "The game didn't take the selection"; + }); + w.Tooltip(SelectTooltip); + w.SameLine(); + } + w.TextDisabled(WhereText(view, p, number)); + if (_selectedPack == p.Id && _selectNote.Length > 0) w.TextDisabled(_selectNote); + } + + private const float WhereIcon = 20f; + + internal const string SelectTooltip = + "Selects this pack in the game, as clicking it in your inventory would, so the game shows you which one it is " + + "(its name in the selection bar). Nothing moves."; + private void DrawMissing(UiWindow w, SortView view, List rules, List missing) { w.PushStyleColor(UiFormat.ColText, UiColors.Amber); @@ -310,13 +359,66 @@ internal sealed class SortPanel internal static string PackTooltip(SortView view) => view.PackOrderKnown ? PackTooltipTopDown : PackTooltipListOrder; internal const string PackTooltipTopDown = - "Packs are numbered from the top of the pack column (foci don't count). " - + "A rule remembers the pack you pick, so adding, moving or emptying packs doesn't change where items go."; + "Pack 1 is the top pack in your inventory's pack column, pack 2 the one below it, and so on (foci don't count). " + + "A rule remembers the pack itself, so moving, adding or emptying packs never sends items to the wrong one."; internal const string PackTooltipListOrder = - "A rule remembers the pack you pick, so adding, moving or emptying packs doesn't change where items go. " - + "Pack numbers count your side packs (not foci) in the client's list order, oldest pack first, " - + "which can differ from the pack column on screen: go by the name and what's in it."; + "Right now the pack numbers here may not match your inventory's pack column (they go oldest pack first): " + + "go by the pack's name, its item count and what's in it, or open the pack here and use Select in game. " + + "A rule remembers the pack itself, so items still go to the right one."; + + /// The header's tooltip: which pack in the game this is, in plain words. + internal static string PackHeaderTooltip(SortView view, int number) + { + PackLine p = view.Packs[number - 1]; + string what = $"Your {p.Name}: {p.Used} of {p.Capacity} items ({p.Summary})."; + string where = view.PackOrderKnown + ? $"It is the {Ordinal(number)} pack from the top of your inventory's pack column{SlotAside(p, number)}." + : "Its place in your inventory's pack column isn't known right now, so its number may not match the column."; + return what + " " + where + " Open it here and use Select in game to see it picked out in the game.\n\n" + PackTooltip(view); + } + + /// The pack's first line: "2nd pack from the top of the pack column - 14/24 items", or that it isn't known. + internal static string WhereText(SortView view, PackLine p, int number) + { + if (view.PackOrderKnown) + return $"{Ordinal(number)} pack from the top of the pack column - {p.Used}/{p.Capacity} items"; + return $"Place in the pack column not known - {p.Used}/{p.Capacity} items"; + } + + /// + /// " (the game's own inventory window also shows the focus above it, so there it is the 3rd entry)" + /// when foci sit above it in the column: the retail window lists foci among the packs; RynthCore's + /// Inventory panel lists them after the packs, so there the pack number is the row. + /// + private static string SlotAside(PackLine p, int number) + { + if (p.ColumnSlot <= number) return string.Empty; + int foci = p.ColumnSlot - number; + return $" (the game's own inventory window also shows the {(foci == 1 ? "focus" : foci + " foci")} above it, so there it is the {Ordinal(p.ColumnSlot)} entry)"; + } + + /// Above the packs when their numbers aren't the pack column's: why, in plain words; else empty. + internal static string NumberingNote(SortView view) + { + if (view.Packs.Count == 0 || view.PackOrderKnown) return string.Empty; + string why = view.OrderSource switch + { + PackOrderSource.NotSeen => "RynthCore hasn't seen your pack list since this character logged in (it was reloaded after the login). Log out and back in once to fix it.", + PackOrderSource.Mismatch => "RynthCore's pack list is missing a pack you carry. Log out and back in once to fix it.", + _ => "this RynthCore can't read the pack column's order (it needs plugin API 80).", + }; + return "Pack numbers here go oldest pack first, not in your pack column's order: " + why + + " Until then go by each pack's name and contents, or use Select in game."; + } + + /// 1st, 2nd, 3rd, 4th ... 11th, 12th, 13th ... 21st. + internal static string Ordinal(int n) + { + int t = n % 100; + string suffix = t is >= 11 and <= 13 ? "th" : (n % 10) switch { 1 => "st", 2 => "nd", 3 => "rd", _ => "th" }; + return n.ToString(System.Globalization.CultureInfo.InvariantCulture) + suffix; + } /// " - in order", " - 3 to put in order", " - order not known": a pack's order as the window says it (empty when ordering is off). internal static string OrderNote(SortView view, PackLine p, string lead) diff --git a/Plugins/Shared/RynthNavPathApi.cs b/Plugins/Shared/RynthNavPathApi.cs index 6c59ff7..f0a6d5c 100644 --- a/Plugins/Shared/RynthNavPathApi.cs +++ b/Plugins/Shared/RynthNavPathApi.cs @@ -28,7 +28,7 @@ public unsafe struct RynthNavPathApiV1 { public const string PluginName = "RynthNav"; public const string InterfaceName = "RynthNav.Path"; - public const uint InterfaceVersion = 1; + public const uint InterfaceVersion = 3; /// FindPath: a full path was found. public const int ResultOk = 1; @@ -37,6 +37,10 @@ public unsafe struct RynthNavPathApiV1 /// FindPath: no navmesh at one of the ends (tile not baked, indoors, or no pose yet). public const int ResultNoMesh = -1; + /// The table's size up to FindPath (version 1): what a v1 caller checks StructSize against, + /// so an older RynthNav's smaller table still passes. + public static uint SizeV1 => (uint)(2 * sizeof(uint) + sizeof(nint)); + public uint Version; // InterfaceVersion of the table RynthNav filled public uint StructSize; // sizeof(RynthNavPathApiV1) as RynthNav built it @@ -47,4 +51,51 @@ public unsafe struct RynthNavPathApiV1 /// and the corner count into *count. Returns ResultOk, ResultNoPath or ResultNoMesh. /// public delegate* unmanaged[Cdecl] FindPath; + + // ── Version 2 (2026-10-23): RynthAi's outdoor hunting walks to monsters on these ── + + /// FindPathEx flag: keep off portals (their circles) and bend around them, as RynthNav's own walks do. + public const int PathAvoidPortals = 1; + /// FindPathEx flag: push corners out from walls by RynthNav's wall clearance, as its own walks do. + public const int PathWallClearance = 2; + /// FindPathEx flag: when the goal can't be reached, a path to the reachable point nearest it (ResultPartial). + public const int PathAllowPartial = 4; + /// FindPathEx flag: no log line for this query (a caller asking several times a second). + public const int PathQuiet = 8; + /// FindPathEx with PathAllowPartial: the path ends at the reachable point nearest the goal (info[2..4]), info[5] from it. + public const int ResultPartial = 2; + /// Raycast: the straight walk stays on the navmesh. + public const int RayClear = 1; + /// Raycast: something is in the way (a wall, a building, a drop, the mesh's edge). + public const int RayBlocked = 0; + /// FindPathEx: doubles written to info. + public const int InfoLength = 6; + + /// + /// FindPath with options: (sx, sy, sz) to (gx, gy, gz), flags (Path* above), maxTiles the + /// tile box it may load (0 = RynthNav's default of 25), the corners into points / *count as + /// FindPath, and info (InfoLength doubles): [0] path length (the sum of its legs), [1] 1 when + /// partial, [2..4] the path's last corner, [5] the distance from that corner to the goal. Returns + /// ResultOk, ResultPartial (PathAllowPartial only), ResultNoPath or ResultNoMesh; ResultNoMesh also in a + /// dungeon or a building's cells (the landscape mesh doesn't hold them). + /// + public delegate* unmanaged[Cdecl] FindPathEx; + + /// + /// Whether walking straight from (sx, sy, sz) to (gx, gy, gz) stays on the navmesh (a Detour raycast + /// along the mesh surface): RayClear, RayBlocked or ResultNoMesh. + /// + public delegate* unmanaged[Cdecl] Raycast; + + // ── Version 3 (2026-10-25): RynthAi's hunt walks out of buildings through their doors ── + // No new functions: a v3 RynthNav knows this flag (an older one ignores it and answers ResultNoMesh + // for a start near the player while the player is in a building). + + /// + /// FindPathEx flag: the start is a spot on the landscape (a building's doorstep), planned from even + /// while the player stands in a building's cells. Without it a start within 24 units of the player + /// is the player's own spot and, in a building, refused (ResultNoMesh). In a dungeon it is refused + /// either way. + /// + public const int PathStartOutdoors = 16; } diff --git a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs index d0720ab..41b927d 100644 --- a/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs +++ b/Tools/RynthCore.RynthAiHostTests/Fakes/FakeHost.cs @@ -130,6 +130,9 @@ internal static unsafe class FakeHost public static bool AttackSendCalls; /// Every melee or missile attack (kind, target, height, power), in order (opt-in with ). public static readonly List<(string Kind, uint Target, int Height, float Power)> AttackCalls = new(); + /// Opt-in (set before Create): wires CancelAttack; calls are counted in . + public static bool CancelAttackCalls; + public static int CancelAttacks; /// Opt-in: wires SetMotion; calls land in . public static bool SetMotionCalls; /// Every SetMotion (motion, on), in order (opt-in with ). @@ -307,7 +310,7 @@ internal static unsafe class FakeHost Vitals = default; BaseVitals = default; WorldName = ""; AccountName = ""; HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0; Logs.Clear(); Chat.Clear(); ChatTypes.Clear(); ChatCommands.Clear(); AfterCastSpell = null; - AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; + AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); CancelAttackCalls = false; CancelAttacks = 0; Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null; Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1; RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true; VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0; @@ -431,6 +434,8 @@ internal static unsafe class FakeHost } if (CombatModeCalls) api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl])&ChangeCombatMode; + if (CancelAttackCalls) + api.CancelAttackFn = (IntPtr)(delegate* unmanaged[Cdecl])&CancelAttack; if (TargetVitals.Count > 0) api.GetTargetVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl])&GetTargetVitals; if (LiveObjectsCalls) @@ -872,6 +877,9 @@ internal static unsafe class FakeHost [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); Sent.Add(AutoRun ? "autorun on" : "autorun off"); return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int CancelAttack() { CancelAttacks++; return 1; } + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] private static int MeleeAttack(uint target, int height, float power) { AttackCalls.Add(("melee", target, height, power)); return 1; } diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index e805a58..51a02f7 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -88,13 +88,17 @@ internal static class Program VTankYieldTests.Register(runner); OffhandTests.Register(runner); HandSwapTests.Register(runner); + OutdoorHuntTests.Register(runner); + HuntBuildingTests.Register(runner); FloodPerfTests.Register(runner); LootSalvageTests.Register(runner); LootCorpseTests.Register(runner); LootRetryTimingTests.Register(runner); LootClaimMismatchTests.Register(runner); + BoostNavTests.Register(runner); LootNothingLineTests.Register(runner); ChestLootTests.Register(runner); + ItemToolTests.Register(runner); OwnCorpseTests.Register(runner); UseRefusalTests.Register(runner); CorpseKillerTests.Register(runner); @@ -170,6 +174,7 @@ internal static class Program SkCombatAddonTests.Register(runner); DoorTests.Register(runner); ServerPolicyTests.Register(runner); + PatrolModeTests.Register(runner); BlankLoadTests.Register(runner); GiveProfileTests.Register(runner); TinkerTests.Register(runner); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BoostNavTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BoostNavTests.cs new file mode 100644 index 0000000..fcb5ea5 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BoostNavTests.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Boost Nav Priority, owner's rule (2026-11-02): with the flag on RynthAi ONLY navigates. No hunting, +// no looting, and no fighting back even with a monster attacking it; with a route (or a follow) it +// navigates, with nothing to navigate it stands idle. Buffing and vitals still run, buffing on top. +// R-20261102-041824-3f7c: the flag came on through NavLootPrio (or a hunting meta), there was no +// route, and the arbiter's WantNav-guarded clause let combat win, so the bot hunted as usual and the +// player never noticed the flag; they only saw that it would not loot. The first fight or corpse +// the flag skips now says so in chat, once per session. +internal static class BoostNavTests +{ + private const uint Player = 0x50000F51; + private const uint Lb = 0xA9B40000; + private const uint Mob = 0x80000451; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + r.Add("boost nav (owner, 2026-11-02): the arbiter never picks Combat or Looting with the flag on, route or not; buffing stays on top", ArbiterRule); + r.Add("boost nav: no route, a monster attacking: never Combat or Looting, no attack sent, no target locked", NoRouteNeverFights); + r.Add("boost nav: with a route: Navigating every tick, no attack sent even with a monster on top", RouteNavigatesOnly); + r.Add("boost nav: turned on mid-fight: the target is dropped, the server attack cancelled, the stance back to Peace", MidFightDisengages); + r.Add("boost nav: turned off again: hunting resumes (target locked, attack sent)", OffResumesHunting); + r.Add("boost nav: the skipped fight is said in chat and the log once per session, never with the flag off", NoticeOncePerSession); + } + + // ── 1. The pure rule ────────────────────────────────────────────────────── + + private static BotActivity D(bool buff = false, bool combat = false, bool loot = false, bool salv = false, bool nav = false, + bool engaged = false, bool boostNav = true, bool boostLoot = false, bool starved = false, + bool forced = false, bool follow = false) + => ActivityArbiter.Decide(new ArbiterInputs(true, buff, combat, loot, salv, nav, + combatEngaged: engaged, boostNav: boostNav, boostLoot: boostLoot, followActive: follow, + lootStarved: starved, forcedLoot: forced)); + + private static void ArbiterRule() + { + // Every combination of combat / engaged / loot / loot-starved / Boost Loot, no route: Idle. + for (int bits = 0; bits < 32; bits++) + { + bool combat = (bits & 1) != 0, engaged = (bits & 2) != 0, loot = (bits & 4) != 0, + starved = (bits & 8) != 0, boostLoot = (bits & 16) != 0; + var noRoute = D(combat: combat, engaged: engaged, loot: loot, starved: starved, boostLoot: boostLoot); + Check.Eq(noRoute, BotActivity.Idle, $"no route (combat={combat} engaged={engaged} loot={loot} starved={starved} boostLoot={boostLoot}): Idle"); + var route = D(combat: combat, engaged: engaged, loot: loot, starved: starved, boostLoot: boostLoot, nav: true); + Check.Eq(route, BotActivity.Navigating, $"a route (combat={combat} engaged={engaged} loot={loot}): Navigating"); + } + Check.Eq(D(combat: true, engaged: true, nav: true, follow: true), BotActivity.Navigating, "a follow is navigating too"); + Check.Eq(D(buff: true, combat: true, nav: true), BotActivity.Buffing, "buffing still outranks it"); + Check.Eq(D(buff: true, combat: true), BotActivity.Buffing, "buffing with no route too"); + Check.Eq(D(loot: true, forced: true), BotActivity.Looting, "a /ra lootthis container is still looted (no route)"); + Check.Eq(D(loot: true, forced: true, nav: true), BotActivity.Navigating, "with a route nav keeps the tick, as before"); + Check.Eq(D(salv: true, combat: true), BotActivity.Salvaging, "the salvage queue (an inventory chore) still runs"); + Check.Eq(D(combat: true, nav: true, boostNav: false), BotActivity.Combat, "flag off: combat outranks nav as usual"); + Check.Eq(D(loot: true, boostNav: false), BotActivity.Looting, "flag off: looting as usual"); + Check.Eq(ActivityArbiter.ToBotAction(BotActivity.Idle), "Default", "Idle shows as Default (the dashboard reads Idle)"); + } + + // ── A melee rig, ticked the way OnTick ticks it ─────────────────────────── + + private sealed class Rig + { + public readonly LegacyUiSettings S; + public readonly CombatManager C; + public bool Route; + public readonly List Decisions = new(); + + public Rig(float mobY) + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.AttackSendCalls = true; + FakeHost.CancelAttackCalls = true; + FakeHost.CombatModeCalls = true; + FakeHost.CombatModeValue = CombatMode.Melee; + Place(Player, "Me", 96, 96, creature: false); + Place(Mob, "Drudge Skulker", 96, mobY); + FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f); + FakeHost.HeadingDeg = 0; + S = new LegacyUiSettings + { + MonsterRange = 50, IsMacroRunning = true, EnableCombat = true, EnableLooting = true, + MonsterRules = new List { new() { Name = "Default" } }, + }; + var host = FakeHost.Create(Player); + var cache = FakeHost.MakeCache(host, Player, new[] { Mob }); + C = new CombatManager(host, S, cache); + C.SetPlayerId(Player); + C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore()); + C.ScanNearbyTargets(); + } + + /// One tick: the arbiter decides from combat's own wants (as OnTick does), writes + /// BotAction, and combat ticks. The attack cadence runs on the real clock, so it is reset. + public BotActivity Tick() + { + bool wantCombat = S.EnableCombat && C.HasEngageableTarget; + var inputs = new ArbiterInputs(S.IsMacroRunning, false, wantCombat, false, false, Route, + combatEngaged: C.IsUnderCloseAttack, boostNav: S.BoostNavPriority, boostLoot: S.BoostLootPriority); + BotActivity act = ActivityArbiter.Decide(in inputs); + S.BotAction = ActivityArbiter.ToBotAction(act); + LastAttackCmd.SetValue(C, DateTime.MinValue); + C.OnHeartbeat(); + Decisions.Add(act); + return act; + } + + public void Ticks(int n) { for (int i = 0; i < n; i++) Tick(); } + + /// Ticks until an attack reaches the server (false if none does in 40 ticks). + public bool TickToAttack() + { + int before = FakeHost.AttackCalls.Count; + for (int i = 0; i < 40 && FakeHost.AttackCalls.Count == before; i++) Tick(); + return FakeHost.AttackCalls.Count > before; + } + + private static readonly FieldInfo LastAttackCmd = typeof(CombatManager).GetField("lastAttackCmd", Any)!; + } + + private static void Place(uint id, string name, float x, float y, bool creature = true) + { + FakeHost.Names[id] = name; + FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f); + if (creature) FakeHost.ItemTypes[id] = 0x10; + } + + private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal)); + + // ── 2. No route ─────────────────────────────────────────────────────────── + + private static void NoRouteNeverFights() + { + var rig = new Rig(mobY: 97.5f); // 1.5 m: on top of us, the "attacking me" case + rig.S.BoostNavPriority = true; + Check.True(rig.C.HasEngageableTarget && rig.C.IsUnderCloseAttack, "rig: a monster close enough to be attacking"); + rig.Ticks(60); + Check.False(rig.Decisions.Any(a => a is BotActivity.Combat or BotActivity.Looting), "never Combat or Looting"); + Check.True(rig.Decisions.All(a => a == BotActivity.Idle), "Idle the whole time (nothing to navigate)"); + Check.Eq(FakeHost.AttackCalls.Count, 0, "no attack sent"); + Check.Eq(rig.C.activeTargetId, 0, "no target locked"); + Check.True(rig.C.BoostNavStoodDown, "combat stands down for the flag"); + Check.True(Logged("Boost Nav Priority is on - no hunting and no fighting back"), "and the log says why"); + Check.True(rig.C.HasEngageableTarget, "the scan still runs (it is what the notice reads)"); + } + + // ── 3. A route ──────────────────────────────────────────────────────────── + + private static void RouteNavigatesOnly() + { + var rig = new Rig(mobY: 97.5f); + rig.S.BoostNavPriority = true; + rig.Route = true; + rig.Ticks(60); + Check.True(rig.Decisions.All(a => a == BotActivity.Navigating), "Navigating every tick"); + Check.Eq(rig.S.BotAction, "Navigating", "BotAction says Navigating"); + Check.Eq(FakeHost.AttackCalls.Count, 0, "no attack sent"); + Check.Eq(rig.C.activeTargetId, 0, "no target locked"); + } + + // ── 4. Mid-fight ────────────────────────────────────────────────────────── + + private static void MidFightDisengages() + { + var rig = new Rig(mobY: 99f); // 3 m north + Check.True(rig.TickToAttack(), "flag off: the fight starts (an attack goes out)"); + Check.Eq((uint)rig.C.activeTargetId, Mob, "the Drudge is the target"); + Check.Eq(rig.Decisions[^1], BotActivity.Combat, "in Combat"); + int attacks = FakeHost.AttackCalls.Count; + int cancels = FakeHost.CancelAttacks; + FakeHost.CombatModeRequests.Clear(); + + rig.S.BoostNavPriority = true; // NavLootPrio, or a meta's SetOpt navpriorityboost + Check.Eq(rig.Tick(), BotActivity.Idle, "the next tick: Idle, not Combat"); + Check.Eq(rig.C.activeTargetId, 0, "the target is dropped"); + Check.True(FakeHost.CancelAttacks > cancels, "the server's attack is cancelled (no more swings, no walk to the mob)"); + Check.True(Logged("DropTarget 0x80000451: Boost Nav Priority is on"), "the drop is logged with the reason"); + Check.True(FakeHost.CombatModeRequests.Contains(CombatMode.NonCombat), "Peace Mode When Idle: back to Peace, no stance left up"); + + FakeHost.CombatModeValue = CombatMode.NonCombat; // the server lands the swap + int modeAsks = FakeHost.CombatModeRequests.Count; + rig.Ticks(60); + Check.Eq(FakeHost.AttackCalls.Count, attacks, "no attack after the flag came on"); + Check.Eq(rig.C.activeTargetId, 0, "nothing re-locked"); + Check.Eq(FakeHost.CombatModeRequests.Count, modeAsks, "in Peace: no more mode changes"); + Check.False(rig.Decisions.Skip(rig.Decisions.Count - 60).Any(a => a == BotActivity.Combat), "never Combat again while it is on"); + } + + // ── 5. Off again ────────────────────────────────────────────────────────── + + private static void OffResumesHunting() + { + var rig = new Rig(mobY: 99f); + rig.S.BoostNavPriority = true; + rig.Ticks(20); + Check.Eq(FakeHost.AttackCalls.Count, 0, "on: nothing attacked"); + + rig.S.BoostNavPriority = false; + Check.True(rig.TickToAttack(), "off: an attack goes out again"); + Check.Eq((uint)rig.C.activeTargetId, Mob, "the Drudge is locked"); + Check.True(rig.Decisions.Contains(BotActivity.Combat), "the arbiter gives Combat the tick again"); + Check.False(rig.C.BoostNavStoodDown, "combat no longer stands down"); + Check.True(Logged("Boost Nav Priority is off - hunting again"), "logged once it is off"); + // Looting coming back once the flag is off: LootClaimMismatchTests' Boost Nav test. + } + + // ── 6. The notice ───────────────────────────────────────────────────────── + + private static RynthAiPlugin Plugin() + { + var p = new RynthAiPlugin(); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi }); + return p; + } + + private static void Note(RynthAiPlugin p, LegacyUiSettings s, bool wantCombat) + => typeof(RynthAiPlugin).GetMethod("NoteBoostNavSkip", Any)!.Invoke(p, new object[] { s, wantCombat }); + + private static int NoticeCount() => FakeHost.Chat.Count(c => c == RynthAiPlugin.BoostNavNotice); + + private static void NoticeOncePerSession() + { + FakeHost.Reset(); + FakeHost.Create(Player); + var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, EnableLooting = false }; + var p = Plugin(); + + Note(p, s, wantCombat: true); + Check.Eq(NoticeCount(), 0, "flag off: nothing said"); + + s.BoostNavPriority = true; + Note(p, s, wantCombat: false); + Check.Eq(NoticeCount(), 0, "flag on, nothing skipped (no monster, looting off): nothing said"); + + s.IsMacroRunning = false; + Note(p, s, wantCombat: true); + Check.Eq(NoticeCount(), 0, "macro off: nothing said"); + s.IsMacroRunning = true; + + Note(p, s, wantCombat: true); + Check.Eq(NoticeCount(), 1, "the first skipped fight: said in chat"); + Check.Eq(RynthAiPlugin.BoostNavNotice, + "[RynthAi] Boost Nav Priority is on: RynthAi only navigates (no hunting, no looting). Turn it off to hunt and loot.", + "the owner's wording"); + Check.True(Logged(RynthAiPlugin.BoostNavNotice + " (skipped a fight)"), "and in the log, with what was skipped"); + Check.Eq(FakeHost.ChatTypes[FakeHost.Chat.IndexOf(RynthAiPlugin.BoostNavNotice)], 2, "in the warning colour"); + + for (int i = 0; i < 50; i++) Note(p, s, wantCombat: true); + s.BoostNavPriority = false; Note(p, s, true); + s.BoostNavPriority = true; Note(p, s, true); + Check.Eq(NoticeCount(), 1, "once per session: not again, not even after the flag goes off and on"); + + var next = Plugin(); // a new session (a login or a reload starts a new plugin instance) + Note(next, s, wantCombat: true); + Check.Eq(NoticeCount(), 2, "a new session says it again, once"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs index 0a94b91..70e402f 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ChestLootTests.cs @@ -39,7 +39,9 @@ internal static class ChestLootTests r.Add("chest loot: your own side pack opened -> nothing taken", OwnSidePackNotLooted); r.Add("chest loot: house storage (HouseOwner set) -> nothing taken", HouseStorageNotLooted); r.Add("chest loot: house storage by name (engine without the HouseOwner read) -> nothing taken", HouseStorageByNameNotLooted); - r.Add("chest loot: Looting off -> nothing taken, the loot check still runs", LootingOffNothing); + r.Add("chest loot: Looting off and Pickup with macro off off -> nothing taken, the loot check still runs", LootingOffNothing); + r.Add("chest loot: Pickup with macro off (on by default) loots an opened chest with the macro off or Looting off", PickupWithMacroOff); + r.Add("chest loot: Pickup with macro off never takes from house storage or your own side pack", PickupWithMacroOffRefuses); r.Add("chest loot: reopening the chest loots it again (never marked done)", ReopenLootsAgain); r.Add("chest loot: a salvage-only item is left when no UST is carried, as on corpses", SalvageWithoutUstLeft); r.Add("chest loot: opened mid-fight it waits for combat, then is looted if still open", ChestWaitsForCombat); @@ -317,6 +319,7 @@ internal static class ChestLootTests var host = FakeHost.Create(Player); var bot = new Bot(host); bot.S.EnableLooting = false; + bot.S.LootChestsMacroOff = false; bot.Create(Chest, Gem, Spoon); bot.ServerOpens(Chest); @@ -329,6 +332,54 @@ internal static class ChestLootTests "the old loot check of a natively opened container still runs (chat: " + string.Join(" | ", FakeHost.Chat) + ")"); } + // Owner, 2026-11-02: "even with looting and the macro off, it should pick up items from a chest when + // it's open that match the loaded loot profile ... (Pickup with macro off)", on by default. + private static void PickupWithMacroOff() + { + Check.True(new LegacyUiSettings().LootChestsMacroOff, "on by default"); + foreach (bool macroOff in new[] { true, false }) + { + BaseWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + if (macroOff) bot.S.IsMacroRunning = false; else bot.S.EnableLooting = false; + string what = macroOff ? "macro off" : "Looting off"; + bot.Create(Chest, Gem, Spoon); + + bot.ServerOpens(Chest); + bot.TickUntil(() => bot.Moved(Gem)); + Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), $"{what}: the gem is picked up (moves: {Moves()})"); + Check.False(bot.Moved(Spoon), $"{what}: the spoon matches nothing and stays"); + Check.False(FakeHost.Uses.Contains(Chest), $"{what}: no open sent"); + Check.False(FakeHost.AutoRunCalls.Any(on => on), $"{what}: no walk"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Pickup with macro off: looting the opened chest")), $"{what}: logged"); + } + } + + private static void PickupWithMacroOffRefuses() + { + BaseWorld(); + FakeHost.InstanceIds[(Chest, 32)] = 0x50000ABC; // house storage + var host = FakeHost.Create(Player); + var bot = new Bot(host); + bot.S.IsMacroRunning = false; + bot.Create(Chest, Gem, Spoon); + bot.ServerOpens(Chest); + bot.TickFor(300); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken out of house storage"); + Check.True(FakeHost.Logs.Any(l => l.Contains("Pickup with macro off: not looting") && l.Contains("house storage")), "the reason is logged"); + + BaseWorld(); + FakeHost.Containers[Chest] = Player; // a side pack the character carries + host = FakeHost.Create(Player); + bot = new Bot(host); + bot.S.IsMacroRunning = false; + bot.Create(Chest, Gem, Spoon); + bot.ServerOpens(Chest); + bot.TickFor(300); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "nothing taken out of your own side pack"); + } + private static void ReopenLootsAgain() { BaseWorld(); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs new file mode 100644 index 0000000..6210219 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HuntBuildingTests.cs @@ -0,0 +1,605 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.Raycasting; +using RynthCore.RynthAiTests.Harness; +using V3 = RynthCore.Plugin.RynthAi.Raycasting.Vector3; +using Vec = RynthCore.Plugin.RynthAi.OutdoorHunt.Vec; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The outdoor hunt into buildings (2026-10-25, Tom: "the entire radar range, also going inside houses"). +// RynthNav's map ends at a building's walls: a walk into one is RynthNav's way to the outside of a door, +// then the building's rooms (BuildingMap, cell.dat); from inside, out through a door first. +// - pure (OutdoorHunt with a fake building map and a straight-line RynthNav): which monster, which +// door, the corners, the log line, the fallbacks; +// - BuildingMap on a hand-built house (doors, windows, a shared opening, portals inside); +// - BuildingMap on the real dats when they are on this PC (Holtburg A9B4 / A9B3, DF61). +internal static class HuntBuildingTests +{ + private const string AcDir = @"C:\Turbine\Asheron's Call"; + + public static void Register(Runner r) + { + r.Add("hunt buildings: a monster inside is picked when its walk is the shortest; the walk goes to the door, through it, then the rooms", IntoBuilding); + r.Add("hunt buildings: of a building's two doors, the one giving the shorter walk (the other's way round never asked for)", NearerDoor); + r.Add("hunt buildings: from inside, a monster outdoors is walked to out through the nearer door, then on RynthNav's map", OutOfBuilding); + r.Add("hunt buildings: inside a building with no door known (or none known at all): back out the way in", NoDoorFallsBack); + r.Add("hunt buildings: one in the same building through its rooms; one in another building out of one door and in by another", SameAndOtherBuilding); + r.Add("hunt buildings: a door whose step out isn't on the ground is never used; a building it doesn't know is left alone", DoorOffTheGround); + r.Add("building map: a hand-built house: its door faces out, a window and a slit are no doors, a shared opening joins two buildings", HandBuiltHouse); + r.Add("building map: a portal inside: walks bend round it, one to a monster in its circle stops at its edge, a door it stands at isn't offered", PortalInside); + r.Add("building map (real dats): Holtburg A9B4/A9B3: doors found, each step out off every floor and each step in on one, a walk from a door to every room", RealHoltburg); + r.Add("building map (real dats): DF61 (a test hunt's): openings shared by two cell groups joined, doors onto the wall tops left out, walks through", RealDf61); + r.Add("hunt buildings (real dats): into Holtburg's A9B4#0 from outdoors and back out, a portal in its rooms kept out of", RealHuntHoltburg); + } + + // ── Fakes ──────────────────────────────────────────────────────────────────────────────────── + + private static readonly DateTime T0 = new(2026, 10, 25, 12, 0, 0); + private static Vec V(double x, double y, double z = 0) => new(x, y, z); + private static Vec D(double x, double y, double z = 0) => new(x, y, z, true); + + private const uint Outdoors = 0xA9B4003Au; + private static OutdoorHunt.Candidate C(int id, Vec at, Vec me, uint cell = Outdoors, string? name = null) + => new(id, name ?? $"Monster {id}", at, at.DistanceTo(me), 1, cell); + + /// A west-facing door at (x, y) of cell: inner point 1.5 east, outer 1.5 west. + private static OutdoorHunt.Door West(uint cell, double x, double y) => new(cell, D(x + 1.5, y), D(x, y), D(x - 1.5, y)); + private static OutdoorHunt.Door East(uint cell, double x, double y) => new(cell, D(x - 1.5, y), D(x, y), D(x + 1.5, y)); + + /// Buildings as cells to building ids and doors; inside, a straight walk (NoPath between buildings or cells kept apart). + private sealed class FakeBuildings : OutdoorHunt.IBuildings + { + public readonly Dictionary Of = new(); + public readonly Dictionary> DoorsOf = new(); + public readonly HashSet<(uint, uint)> Apart = new(); + public int InsideCalls; + public int BuildingOf(uint cell) => Of.TryGetValue(cell, out int b) ? b : 0; + public IReadOnlyList Doors(int b) => DoorsOf.TryGetValue(b, out var l) ? l : new List(); + public OutdoorHunt.PathResult Inside(uint fc, Vec f, uint tc, Vec t) + { + InsideCalls++; + int b = BuildingOf(fc); + if (b == 0 || b != BuildingOf(tc) || Apart.Contains((fc, tc)) || Apart.Contains((tc, fc))) + return new(OutdoorHunt.PathStatus.NoPath, Array.Empty(), 0, 0); + return new(OutdoorHunt.PathStatus.Ok, new[] { t }, f.DistanceTo(t), 0); + } + public string Name(int b) => $"house {b}"; + } + + /// RynthNav: a straight walk, with per-goal overrides; every goal asked for is noted. + private sealed class Nav + { + public readonly Dictionary<(double, double), OutdoorHunt.PathResult> Overrides = new(); + /// The map's ground at a doorstep (a path from a spot to itself): its height there. + public readonly Dictionary<(double, double), double> Ground = new(); + public readonly List<(Vec A, Vec B)> Asked = new(); + public OutdoorHunt.PathResult Path(Vec a, Vec b) + { + Asked.Add((a, b)); + if (a.X == b.X && a.Y == b.Y && Ground.TryGetValue((b.X, b.Y), out double gz)) + return new(OutdoorHunt.PathStatus.Ok, new[] { V(b.X, b.Y, gz) }, Math.Abs(gz - b.Z), Math.Abs(gz - b.Z)); + if (Overrides.TryGetValue((b.X, b.Y), out var o)) return o; + return new(OutdoorHunt.PathStatus.Ok, new[] { b with { Door = false } }, a.DistanceTo(b), 0); + } + public void Around(Vec to, double length) => + Overrides[(to.X, to.Y)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(to.X - 5, to.Y + 8), to with { Door = false } }, length, 0); + public int Walks => Asked.Count(q => q.A != q.B); + } + + private static List Sorted(params OutdoorHunt.Candidate[] c) => c.OrderBy(x => x.Distance).ToList(); + private static int Idx(IReadOnlyList c, Vec v) + { + for (int i = 0; i < c.Count; i++) if (c[i] == v) return i; + return -1; + } + + private static string Pts(IReadOnlyList? c) => c == null ? "(none)" : string.Join(" ", c.Select(v => $"{v.X:0.#},{v.Y:0.#}{(v.Door ? "D" : "")}")); + + // A house: cells 0101 (west room) and 0102 (east room), x 1020..1030, y 995..1005; doors given per test. + private const uint RoomW = 0xA9B40101, RoomE = 0xA9B40102, House2 = 0xA9B40110; + + private static FakeBuildings House(params OutdoorHunt.Door[] doors) + { + var b = new FakeBuildings(); + b.Of[RoomW] = 1; b.Of[RoomE] = 1; + b.DoorsOf[1] = doors.ToList(); + return b; + } + + // ── Pure ───────────────────────────────────────────────────────────────────────────────────── + + private static void IntoBuilding() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + var house = House(West(RoomW, 1020, 1000)); + var inside = V(1025, 1000); + var list = Sorted(C(1, inside, me, RoomW), C(2, V(1000, 1040), me)); + var d = h.Tick(T0, me, Outdoors, true, list, nav.Path, house); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 1, $"walks to the one inside (25 yd walk) before the one 40 yd away in the open: {d.Act} {d.TargetId}"); + var want = new[] { D(1018.5, 1000), D(1020, 1000), D(1021.5, 1000), inside }; + Check.True(d.Corners != null && d.Corners.SequenceEqual(want), "to the door's step out, through it, a step in, then the rooms to it: " + Pts(d.Corners)); + Check.True(h.Note.StartsWith("next: 'Monster 1', inside house 1") && h.Note.Contains($"cell {RoomW:X8}") + && h.Note.Contains("a 25 yd walk through the door at 1020,1000"), "logged: " + h.Note); + + // The same building behind a long way round (RynthNav: 150 yd to the door): too far round (over 2x Hunt Range 60). + var far = new OutdoorHunt { RangeYd = 60 }; + far.Start(T0, me); + var nav2 = new Nav(); + nav2.Around(V(1018.5, 1000), 150); + d = far.Tick(T0, me, Outdoors, true, Sorted(C(1, inside, me, RoomW), C(2, V(1000, 1040), me)), nav2.Path, house); + Check.True(d.TargetId == 2 && far.IsSkipped(1, T0.AddSeconds(5)), $"a 150 yd walk into it is too far round: the other one ({d.TargetId})"); + } + + private static void NearerDoor() + { + // East of the house; the west door is round the far side (RynthNav: 45 yd), the east door is 13.5 yd away. + var me = V(1045, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + var west = West(RoomW, 1020, 1000); + var east = East(RoomE, 1030, 1000); + nav.Around(west.Outside, 45); + var house = House(west, east); + var d = h.Tick(T0, me, Outdoors, true, Sorted(C(1, V(1027, 1000), me, RoomE)), nav.Path, house); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners!.Contains(east.At) && !d.Corners!.Contains(west.At), "through the east door: " + Pts(d.Corners)); + Check.True(h.Note.Contains("through the door at 1030,1000"), "logged with that door: " + h.Note); + Check.False(nav.Asked.Any(q => q.A != q.B && q.B.X == west.Outside.X && q.B.Y == west.Outside.Y), + "the west door's way round is never asked for (it can't beat the east door even in a straight line)"); + Check.Eq(nav.Walks, 1, "one RynthNav walk for the pick (and a look at each doorstep)"); + } + + private static void OutOfBuilding() + { + var me = V(1022, 1000); + var h = new OutdoorHunt(); + h.Start(T0, V(990, 1000)); + var nav = new Nav(); + var west = West(RoomW, 1020, 1000); + var east = East(RoomE, 1030, 1000); + var house = House(west, east); + var target = V(990, 1000); + var d = h.Tick(T0, me, RoomW, true, Sorted(C(1, target, me)), nav.Path, house); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 1, $"walks to it from inside: {d.Act}"); + var want = new[] { D(1021.5, 1000), D(1020, 1000), D(1018.5, 1000), target }; + Check.True(d.Corners != null && d.Corners.SequenceEqual(want), "a step in front of the west door, through it, its step out, then RynthNav's way: " + Pts(d.Corners)); + Check.True(nav.Asked.Any(q => q.A == west.Outside && q.B == target), "RynthNav asked from the west door's step out"); + Check.True(h.Note.Contains("out of house 1 through the door at 1020,1000") && !h.WalkingOut, "logged, not the way-back-out walk: " + h.Note); + + // A monster east: out through the east door (the nearer one for that walk). + var h2 = new OutdoorHunt(); + h2.Start(T0, me); + d = h2.Tick(T0, me, RoomW, true, Sorted(C(2, V(1060, 1000), me)), new Nav().Path, house); + Check.True(d.Corners != null && d.Corners.Contains(east.At) && !d.Corners.Contains(west.At), "east one: out of the east door: " + Pts(d.Corners)); + } + + private static void NoDoorFallsBack() + { + var h = new OutdoorHunt(); + h.Start(T0, V(990, 1000)); + h.Track(V(1018, 1000), indoors: false); // the last spot outdoors, at the door + h.Track(V(1020, 1000), indoors: true); + h.Track(V(1022, 1000), indoors: true); + var noDoors = House(); // known rooms, no door + var nav = new Nav(); + var d = h.Tick(T0, V(1022, 1000), RoomW, true, Sorted(C(1, V(990, 1000), V(1022, 1000))), nav.Path, noDoors); + Check.True(d.Act == OutdoorHunt.Act.Walk && h.WalkingOut && h.Note.Contains("back out the way in"), $"no door known: back out the way in ({d.Act}, {h.Note})"); + Check.True(d.Corners != null && d.Corners.Contains(V(1018, 1000)), "along the way in: " + Pts(d.Corners)); + Check.Eq(nav.Asked.Count, 0, "no RynthNav walk from inside"); + + var h2 = new OutdoorHunt(); + h2.Start(T0, V(990, 1000)); + h2.Track(V(1018, 1000), indoors: false); + h2.Track(V(1021, 1000), indoors: true); + d = h2.Tick(T0, V(1021, 1000), RoomW, true, Sorted(C(1, V(990, 1000), V(1021, 1000))), nav.Path, null); + Check.True(d.Act == OutdoorHunt.Act.Walk && h2.WalkingOut, "no building map at all: the same"); + } + + private static void SameAndOtherBuilding() + { + var me = V(1022, 1000); + var west = West(RoomW, 1020, 1000); + var house = House(west, East(RoomE, 1030, 1000)); + var h = new OutdoorHunt(); + h.Start(T0, me); + var d = h.Tick(T0, me, RoomW, true, Sorted(C(1, V(1028, 1002), me, RoomE)), new Nav().Path, house); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners!.SequenceEqual(new[] { V(1028, 1002) }), "same building: through its rooms only: " + Pts(d.Corners)); + Check.True(h.Note.Contains("through its rooms"), "logged: " + h.Note); + + // Another house north, its door on its south wall at (1025, 1030), step out (1025, 1028.5). + house.Of[House2] = 2; + var south = new OutdoorHunt.Door(House2, D(1025, 1031.5), D(1025, 1030), D(1025, 1028.5)); + house.DoorsOf[2] = new List { south }; + var h2 = new OutdoorHunt(); + h2.Start(T0, me); + var goal = V(1025, 1035); + d = h2.Tick(T0, me, RoomW, true, Sorted(C(2, goal, me, House2)), new Nav().Path, house); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners![^1] == goal && d.Corners.Contains(south.At) + && Idx(d.Corners, south.Outside) > Idx(d.Corners, west.Outside), "out of this house, across, in by the other's door: " + Pts(d.Corners)); + Check.True(h2.Note.Contains("inside house 2") && h2.Note.Contains("out of house 1") && h2.Note.Contains("in through the door at 1025,1030"), "logged: " + h2.Note); + + // Two parts of one building that only the outside joins: out by one door and in by another. + house.Apart.Add((RoomW, RoomE)); + var h3 = new OutdoorHunt(); + h3.Start(T0, me); + d = h3.Tick(T0, me, RoomW, true, Sorted(C(3, V(1028, 1000), me, RoomE)), new Nav().Path, house); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners!.Contains(west.At) && d.Corners.Contains(D(1030, 1000)), "rooms not joined inside: out of the west door, in at the east: " + Pts(d.Corners)); + } + + private static void DoorOffTheGround() + { + var me = V(1000, 1000); + var balcony = new OutdoorHunt.Door(RoomW, D(1021.5, 1000, 4), D(1020, 1000, 4), D(1018.5, 1000, 4)); + var nav = new Nav(); + nav.Ground[(1018.5, 1000)] = 0; // the ground under the balcony's step out is 4 below it + var house = House(balcony); + var h = new OutdoorHunt(); + h.Start(T0, me); + h.ClearNotes(); + var d = h.Tick(T0, me, Outdoors, true, Sorted(C(1, V(1025, 1000, 4), me, RoomW), C(2, V(1000, 1040), me)), nav.Path, house); + Check.True(d.TargetId == 2 && h.IsSkipped(1, T0.AddSeconds(5)), $"the only door is a balcony's: the one inside is left out ({d.TargetId})"); + Check.True(h.PendingNotes.Any(n => n.Contains("Monster 1") && n.Contains("no door of house 1 leads to it")), "and says why: " + string.Join(" | ", h.PendingNotes)); + + // With a door on the ground too: that one. + var ground = East(RoomE, 1030, 1000); + var house2 = House(balcony, ground); + var h2 = new OutdoorHunt(); + h2.Start(T0, me); + d = h2.Tick(T0, me, Outdoors, true, Sorted(C(1, V(1025, 1000, 4), me, RoomW)), nav.Path, house2); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners!.Contains(ground.At) && !d.Corners.Contains(balcony.At), "the ground door, round the far side: " + Pts(d.Corners)); + + // A monster in a building the map doesn't know: left alone (no walk, not left out, no log line). + var h3 = new OutdoorHunt(); + h3.Start(T0, me); + h3.ClearNotes(); + d = h3.Tick(T0, me, Outdoors, true, Sorted(C(1, V(1010, 1000), me, 0xA9B40150), C(2, V(1000, 1030), me)), new Nav().Path, house); + Check.True(d.TargetId == 2 && !h3.IsSkipped(1, T0), $"an unknown building's monster is passed over ({d.TargetId})"); + Check.False(h3.PendingNotes.Any(n => n.Contains("Monster 1")), "without a word: " + string.Join(" | ", h3.PendingNotes)); + } + + // ── A hand-built house ─────────────────────────────────────────────────────────────────────── + + private const uint Lb = 0xA9B4; + private const uint CellA = 0xA9B40100, CellB = 0xA9B40101, CellC = 0xA9B40102, CellD = 0xA9B40103; + + private static V3[] Rect(double x0, double y0, double x1, double y1, double z = 0) => new[] + { + new V3((float)x0, (float)y0, (float)z), new V3((float)x1, (float)y0, (float)z), + new V3((float)x1, (float)y1, (float)z), new V3((float)x0, (float)y1, (float)z), + }; + + /// An upright quad from (x0, y0) to (x1, y1), z0 to z1: a wall's opening. + private static V3[] Upright(double x0, double y0, double x1, double y1, double z0 = 0, double z1 = 3) => new[] + { + new V3((float)x0, (float)y0, (float)z0), new V3((float)x1, (float)y1, (float)z0), + new V3((float)x1, (float)y1, (float)z1), new V3((float)x0, (float)y0, (float)z1), + }; + + private static DungeonNavNode Node(uint id, double cx, double cy) => + new() { CellId = id, EW = DungeonGeometry.WorldToNav(cx), NS = DungeonGeometry.WorldToNav(cy), Z = 0 }; + + /// + /// House 1: A (100..110 x 100..110) and B (110..130 x 100..120), joined by a 4 m opening at x 110, + /// y 103..107; a door in A's west wall (x 100, y 103..106), a window in A's north wall (foot 1 m + /// up), a 0.5 m slit in B's east wall. House 2: C (200..210) and D (210..220), no portal record + /// between them but one opening at x 210 that each sees as its way out; a door in C's west wall. + /// + private static BuildingMap.Block HouseBlock() + { + var graph = new Dictionary + { + [CellA] = Node(CellA, 105, 105), [CellB] = Node(CellB, 120, 110), + [CellC] = Node(CellC, 205, 105), [CellD] = Node(CellD, 215, 105), + }; + graph[CellA].Neighbors.Add(CellB); graph[CellB].Neighbors.Add(CellA); + var ab = Upright(110, 103, 110, 107); + var portals = new List<(uint, V3[])> { (CellA, ab), (CellB, ab.Reverse().ToArray()) }; + var floors = new List<(uint, V3[])> + { + (CellA, Rect(100, 100, 110, 110)), (CellB, Rect(110, 100, 130, 120)), + (CellC, Rect(200, 100, 210, 110)), (CellD, Rect(210, 100, 220, 110)), + }; + var walls = new List<(uint, V3[])>(); + var door = Upright(100, 103, 100, 106); + var window = Upright(103, 110, 105, 110, 1.0, 2.8); + var slit = Upright(130, 110, 130, 110.5); + var shared = Upright(210, 103, 210, 107); + var doorC = Upright(200, 103, 200, 106); + var exits = new List<(uint, V3[])> + { + (CellA, door), (CellA, window), (CellB, slit), + (CellC, shared), (CellD, shared.Reverse().ToArray()), (CellC, doorC), + }; + foreach (var e in exits) portals.Add(e); + return BuildingMap.Build(Lb, graph, portals, floors, walls, exits); + } + + private static void HandBuiltHouse() + { + var blk = HouseBlock(); + Check.Eq(blk.Buildings.Count, 2, "two buildings (C and D joined by the opening they share)"); + Check.Eq(blk.SharedOpenings, 1, "one shared opening joined"); + var h1 = blk.ByCell[CellA]; + Check.True(blk.ByCell[CellB] == h1 && blk.ByCell[CellC] == blk.ByCell[CellD] && blk.ByCell[CellC] != h1, "A+B and C+D"); + Check.Eq(h1.Doors.Count, 1, "house 1: one door"); + var d = h1.Doors[0]; + Check.True(d.Cell == CellA && Math.Abs(d.At.X - 100) < 0.01 && Math.Abs(d.At.Y - 104.5) < 0.01, $"in A's west wall: {d.At}"); + Check.True(d.Outside.X < 100 && Math.Abs(d.Outside.X - (100 - BuildingMap.OutsideMeters)) < 0.01, $"its step out is west, outside: {d.Outside}"); + Check.True(d.Inner.X > 100 && blk.Geo!.OnCellFloor(CellA, d.Inner.X, d.Inner.Y, 0), $"its step in is on A's floor: {d.Inner}"); + Check.True(d.Inner.Door && d.At.Door && d.Outside.Door, "all three lined up on the door (Door)"); + Check.True(h1.NotDoors.Any(n => n.Contains("window")) && h1.NotDoors.Any(n => n.Contains("0.5 m wide")), "the window and the slit aren't doors: " + string.Join(" | ", h1.NotDoors)); + var h2 = blk.ByCell[CellC]; + Check.True(h2.Doors.Count == 1 && Math.Abs(h2.Doors[0].At.X - 200) < 0.01, $"house 2: only its west door (the shared opening is inside it now): {h2.Doors.Count}"); + Check.True(blk.Geo!.TryGetDoorway(CellC, CellD, out _), "and the shared opening is a doorway between C and D"); + + var map = new BuildingMap(null, null); + map.Add(blk); + Check.True(map.BuildingOf(CellA) != 0 && map.BuildingOf(CellA) == map.BuildingOf(CellB) && map.BuildingOf(0xA9B4003A) == 0, "BuildingOf: a cell's house; outdoors 0"); + Check.Eq(map.Name(map.BuildingOf(CellA)), "building A9B4#0", "named by landblock and index"); + var goal = V(125, 115); + var p = map.Inside(CellA, d.Inner, CellB, goal); + Check.True(p.Status == OutdoorHunt.PathStatus.Ok && p.Corners[^1] == goal, $"a walk from the door into B: {p.Status}"); + var way = new List { d.Inner }; + way.AddRange(p.Corners); + bool throughOpening = false; + for (int i = 0; i + 1 < way.Count; i++) + { + var a = way[i]; var b = way[i + 1]; + if ((a.X - 110) * (b.X - 110) > 0) continue; // this leg doesn't cross x 110 + double t = (110 - a.X) / (b.X - a.X), y = a.Y + (b.Y - a.Y) * t; + if (y >= 103 && y <= 107) throughOpening = true; + } + Check.True(throughOpening, "through the opening between A and B: " + Pts(way)); + var p2 = map.Inside(CellC, h2.Doors[0].Inner, CellD, V(217, 105)); + Check.True(p2.Status == OutdoorHunt.PathStatus.Ok, $"house 2: C to D through the shared opening ({p2.Status})"); + Check.Eq(map.Inside(CellA, d.Inner, CellC, V(205, 105)).Status, OutdoorHunt.PathStatus.NoPath, "no walk inside from one house to the other"); + } + + private static void PortalInside() + { + var blk = HouseBlock(); + var map = new BuildingMap(null, null); + map.Add(blk); + var door = blk.ByCell[CellA].Doors[0]; + int house = map.BuildingOf(CellA); + var portal = new BuildingMap.PortalSpot(0x7A9B4001, 118, 105, 0); + map.Portals = new[] { portal }; + + var goal = V(126, 105); + var p = map.Inside(CellA, door.Inner, CellB, goal); + var way = new List { door.Inner }; + way.AddRange(p.Corners); + double nearest = double.MaxValue; + for (int i = 0; i + 1 < way.Count; i++) nearest = Math.Min(nearest, SegDist(way[i], way[i + 1], portal.X, portal.Y)); + Check.True(p.Status == OutdoorHunt.PathStatus.Ok && p.Corners[^1] == goal, $"walks on past it ({p.Status})"); + Check.True(nearest >= portal.R - 0.01, $"never inside its {portal.R} m circle (nearest {nearest:F2} m): {Pts(way)}"); + + var inCircle = V(120, 106); + p = map.Inside(CellA, door.Inner, CellB, inCircle); + Check.True(p.Status == OutdoorHunt.PathStatus.Partial && p.Gap > 0, $"a monster in its circle: the walk ends short ({p.Status}, gap {p.Gap:F1})"); + Check.True(p.Corners.Count > 0 && Math.Sqrt(Math.Pow(p.Corners[^1].X - portal.X, 2) + Math.Pow(p.Corners[^1].Y - portal.Y, 2)) >= portal.R - 0.01, + $"at its edge, not in it: {Pts(p.Corners)}"); + + Check.Eq(map.Doors(house).Count, 1, "a portal across the room: the door is still offered"); + map.Portals = new[] { new BuildingMap.PortalSpot(0x7A9B4002, 101, 104.5, 0) }; + Check.Eq(map.Doors(house).Count, 0, "a portal at the door: the door isn't offered"); + map.Portals = new[] { new BuildingMap.PortalSpot(0x7A9B4003, 97, 104.5, 0) }; + Check.Eq(map.Doors(house).Count, 0, "one outdoors by its step out: nor then (RynthNav's way to the step could end in its circle)"); + map.Portals = new[] { new BuildingMap.PortalSpot(0x7A9B4004, 90, 104.5, 0) }; + Check.Eq(map.Doors(house).Count, 1, "one farther off outdoors: it is (RynthNav's way keeps out of that one)"); + + // A corridor 2 m wide with a portal in it: no way round. + var corridor = new List { V(0, 0), V(20, 0) }; + var status = BuildingMap.KeepOutOfPortals(corridor, new[] { new BuildingMap.PortalSpot(1, 10, 0, 0) }, v => Math.Abs(v.Y) <= 1, null, out _); + Check.Eq(status, OutdoorHunt.PathStatus.NoPath, "a portal across a narrow corridor: no way past it"); + // Standing in the ring round a portal (combat took it there): the walk past it steps away round it first. + var ring = new[] { new BuildingMap.PortalSpot(1, 10, 0, 0) }; + var past = new List { V(12, 0), V(0, 0) }; + Check.Eq(BuildingMap.KeepOutOfPortals(past, ring, null, null, out _), OutdoorHunt.PathStatus.Ok, "from inside its ring, a walk past it: " + Pts(past)); + Check.True(past.Count > 2 && (past[1].X - 10) * (past[1].X - 12) > 0 && Math.Abs(past[1].Y) > 3, "its first step leads away from it: " + Pts(past)); + for (int i = 1; i + 1 < past.Count; i++) + Check.True(SegDist(past[i], past[i + 1], 10, 0) >= 3.5 - 0.01, $"then keeps out of the circle (leg {i})"); + // A corner of the way in the circle (a doorway beside it): left out, the legs bent round instead. + var beside = new List { V(0, 0), V(10, 1), V(20, 0) }; + Check.Eq(BuildingMap.KeepOutOfPortals(beside, ring, null, null, out _), OutdoorHunt.PathStatus.Ok, "a corner in the circle: still a way"); + Check.True(!beside.Any(v => BuildingMap.InPortal(ring[0], v)) && Enumerable.Range(0, beside.Count - 1).All(i => SegDist(beside[i], beside[i + 1], 10, 0) >= 3.5 - 0.01), + "no corner or leg in it: " + Pts(beside)); + var other = new List { V(0, 0), V(20, 0) }; + Check.Eq(BuildingMap.KeepOutOfPortals(other, new[] { new BuildingMap.PortalSpot(1, 10, 0, 8) }, v => Math.Abs(v.Y) <= 1, null, out _), + OutdoorHunt.PathStatus.Ok, "one on the floor above (8 m up) doesn't count"); + } + + /// On one of the cells' floors, or within 0.25 m of it (an opening's centre is on the seam between two floors). + private static bool NearFloor(DungeonGeometry geo, IReadOnlyCollection cells, Vec v) + { + for (double dx = -0.25; dx <= 0.25; dx += 0.25) + for (double dy = -0.25; dy <= 0.25; dy += 0.25) + if (geo.OnFloorOfAny(cells, v.X + dx, v.Y + dy, v.Z + 0.1)) return true; + return false; + } + + private static double SegDist(Vec a, Vec b, double px, double py) + { + double dx = b.X - a.X, dy = b.Y - a.Y, l2 = dx * dx + dy * dy; + double t = l2 < 1e-12 ? 0 : Math.Clamp(((px - a.X) * dx + (py - a.Y) * dy) / l2, 0, 1); + return Math.Sqrt(Math.Pow(a.X + dx * t - px, 2) + Math.Pow(a.Y + dy * t - py, 2)); + } + + // ── The real dats ──────────────────────────────────────────────────────────────────────────── + + private static GeometryLoader? _geo; + private static bool _geoTried; + private static GeometryLoader? Dats() + { + if (_geoTried) return _geo; + _geoTried = true; + if (!Directory.Exists(AcDir)) return null; + var g = new GeometryLoader(); + if (!g.Initialize(AcDir) || g.CellDat == null || g.DungeonLOS == null) return null; + return _geo = g; + } + + /// A spot on the cell's floor: the middle of its biggest upward floor polygon (in doubles). + private static bool FloorSpot(GeometryLoader g, BuildingMap.Block blk, uint cell, out Vec spot) + { + spot = default; + double bestArea = 0; + foreach (var p in g.DungeonLOS.GetDungeonMapFloorPolygons(blk.Landblock)) + { + if (p.CellId != cell || p.Vertices == null || p.Vertices.Length < 3 || !DungeonGeometry.IsUpwardFloor(p.Vertices)) continue; + double ox = p.Vertices[0].X, oy = p.Vertices[0].Y, area = 0, sx = 0, sy = 0, sz = 0; + for (int i = 0; i < p.Vertices.Length; i++) + { + var a = p.Vertices[i]; var b = p.Vertices[(i + 1) % p.Vertices.Length]; + area += ((double)a.X - ox) * ((double)b.Y - oy) - ((double)b.X - ox) * ((double)a.Y - oy); + sx += a.X; sy += a.Y; sz += a.Z; + } + area = Math.Abs(area) / 2; + if (area <= bestArea) continue; + int n = p.Vertices.Length; + var c = new Vec(sx / n, sy / n, sz / n); + if (!blk.Geo!.OnCellFloor(cell, c.X, c.Y, c.Z + 0.1)) continue; + bestArea = area; + spot = c; + } + return bestArea > 0.5; + } + + private static void CheckDoorsAndWalks(GeometryLoader g, BuildingMap.Block blk, string label, out int doors, out int rooms, out int walks) + { + doors = rooms = walks = 0; + var map = new BuildingMap(null, null); + map.Add(blk); + var geo = blk.Geo!; + foreach (var b in blk.Buildings) + { + foreach (var d in b.Doors) + { + doors++; + Check.False(geo.TryFloorHeight(d.Outside.X, d.Outside.Y, d.Outside.Z - 6, 6.4, out _), + $"{label} {map.Name(b.Id)} door {d.Cell:X8} at {d.At.X:F1},{d.At.Y:F1}: its step out is over no floor"); + Check.True(geo.OnFloorOfAny(b.Cells, d.Inner.X, d.Inner.Y, d.Inner.Z), $"{label} {map.Name(b.Id)} door {d.Cell:X8}: its step in is on the floor"); + Check.True(d.Inner.FlatDistanceTo(d.Outside) > 1.9 && d.Inner.FlatDistanceTo(d.At) + d.At.FlatDistanceTo(d.Outside) < d.Inner.FlatDistanceTo(d.Outside) + 0.01, + $"{label} door {d.Cell:X8}: in, door, out in a line"); + } + if (b.Doors.Count == 0) continue; + var d0 = b.Doors[0]; + foreach (uint c in b.Cells) + { + if (!FloorSpot(g, blk, c, out var spot)) continue; + rooms++; + var p = map.Inside(d0.Cell, d0.Inner, c, spot); + if (p.Status == OutdoorHunt.PathStatus.Ok) walks++; + else Check.True(false, $"{label} {map.Name(b.Id)}: no walk from door {d0.Cell:X8} to {c:X8} ({p.Status})"); + } + } + } + + private static void RealHoltburg() + { + var g = Dats(); + if (g == null) { Check.True(true, "no dats on this PC: skipped"); return; } + var a9b4 = BuildingMap.Load(0xA9B4, g.CellDat, g.DungeonLOS); + Check.True(a9b4.Graph.Count == 138 && a9b4.Buildings.Count == 15, $"A9B4 (Holtburg): {a9b4.Graph.Count} cells in {a9b4.Buildings.Count} buildings"); + Check.True(a9b4.Buildings.All(b => b.Doors.Count > 0), "every building in it has a door: " + string.Join(" ", a9b4.Buildings.Select(b => b.Doors.Count))); + var b0 = a9b4.Buildings[0]; + Check.True(b0.Cells.Count == 17 && b0.Doors.Count == 3, $"A9B4#0: 17 cells, 3 doors ({b0.Cells.Count}, {b0.Doors.Count})"); + Check.True(b0.NotDoors.Any(n => n.Contains("window")), "and a window that isn't one"); + var b4 = a9b4.Buildings[4]; + Check.True(b4.NotDoors.Count(n => n.Contains("step out is over a floor")) == 2, "A9B4#4: its two upper-storey doors onto the roof below aren't doors: " + string.Join(" | ", b4.NotDoors)); + CheckDoorsAndWalks(g, a9b4, "A9B4", out int doors, out int rooms, out int walks); + Check.True(doors >= 30 && rooms >= 60 && walks == rooms, $"A9B4: {doors} doors, a walk from a door to all {rooms} rooms with a floor ({walks})"); + Console.WriteLine($" A9B4: {a9b4.Graph.Count} cells, {a9b4.Buildings.Count} buildings, {doors} doors ({a9b4.Buildings.Sum(b => b.NotDoors.Count)} openings out that are not), {walks}/{rooms} rooms walked to from a door"); + + var a9b3 = BuildingMap.Load(0xA9B3, g.CellDat, g.DungeonLOS); + CheckDoorsAndWalks(g, a9b3, "A9B3", out doors, out rooms, out walks); + Check.True(a9b3.Buildings.Count == 2 && doors == 4 && walks == rooms && rooms > 0, $"A9B3: {a9b3.Buildings.Count} buildings, {doors} doors, {walks}/{rooms} rooms walked to"); + Console.WriteLine($" A9B3: {a9b3.Buildings.Count} buildings, {doors} doors, {walks}/{rooms} rooms walked to"); + var empty = BuildingMap.Load(0xA8B3, g.CellDat, g.DungeonLOS); + Check.Eq(empty.Buildings.Count, 0, "A8B3: no buildings"); + } + + private static void RealDf61() + { + var g = Dats(); + if (g == null) { Check.True(true, "no dats on this PC: skipped"); return; } + var blk = BuildingMap.Load(0xDF61, g.CellDat, g.DungeonLOS); + Check.True(blk.SharedOpenings >= 5 && blk.Buildings.Count == 6, $"DF61: {blk.SharedOpenings} shared openings joined, {blk.Graph.Count} cells in {blk.Buildings.Count} buildings (11 groups before)"); + int wallTops = blk.Buildings.Sum(b => b.NotDoors.Count(n => n.Contains("step out is over a floor"))); + Check.True(wallTops >= 5, $"{wallTops} openings onto the wall tops aren't doors"); + CheckDoorsAndWalks(g, blk, "DF61", out int doors, out int rooms, out int walks); + Check.True(doors >= 8 && walks == rooms && rooms >= 15, $"DF61: {doors} doors, {walks}/{rooms} rooms walked to"); + Console.WriteLine($" DF61: {blk.Graph.Count} cells, {blk.SharedOpenings} shared openings joined, {blk.Buildings.Count} buildings, {doors} doors, {wallTops} wall-top openings left out, {walks}/{rooms} rooms walked to"); + } + + private static void RealHuntHoltburg() + { + var g = Dats(); + if (g == null) { Check.True(true, "no dats on this PC: skipped"); return; } + var map = new BuildingMap(null, null); + var blk = BuildingMap.Load(0xA9B4, g.CellDat, g.DungeonLOS); + map.Add(blk); + var b0 = blk.Buildings[0]; + // The room farthest from the first door, and a spot 30 yd out from that door. + var d0 = b0.Doors[0]; + uint room = 0; Vec spot = default; double far = -1; + foreach (uint c in b0.Cells) + if (FloorSpot(g, blk, c, out var s) && s.FlatDistanceTo(d0.At) > far) { far = s.FlatDistanceTo(d0.At); room = c; spot = s; } + Check.True(room != 0, $"a room of A9B4#0 to hunt in: {room:X8} at {spot.X:F1},{spot.Y:F1},{spot.Z:F1}"); + var outward = new Vec(d0.Outside.X - d0.At.X, d0.Outside.Y - d0.At.Y, 0); + double ol = Math.Sqrt(outward.X * outward.X + outward.Y * outward.Y); + var me = new Vec(d0.At.X + outward.X / ol * 30, d0.At.Y + outward.Y / ol * 30, d0.At.Z); + var nav = new Nav(); + var h = new OutdoorHunt(); + h.Start(T0, me); + var d = h.Tick(T0, me, 0xA9B4002Au, true, Sorted(C(1, spot, me, room)), nav.Path, map); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners != null && d.Corners[^1] == spot, $"walks in to it: {d.Act}"); + Check.True(h.Note.Contains("inside building A9B4#0") && h.Note.Contains("through the door at"), "logged: " + h.Note); + Console.WriteLine(" " + h.Note); + int door = d.Corners!.ToList().FindIndex(v => b0.Doors.Any(x => x.At == v)); + Check.True(door > 0, "through one of its doors: " + Pts(d.Corners)); + foreach (var v in d.Corners.Skip(door + 1)) + Check.True(NearFloor(blk.Geo!, b0.Cells, v), $"every corner past the door is on the building's floor ({v.X:F1},{v.Y:F1},{v.Z:F1})"); + + // From that room back out to a monster 40 yd out of the door: through a door, then on the map. + var outside = new Vec(d0.At.X + outward.X / ol * 40, d0.At.Y + outward.Y / ol * 40, d0.At.Z); + var h2 = new OutdoorHunt(); + h2.Start(T0, spot); + d = h2.Tick(T0, spot, room, true, Sorted(C(2, outside, spot)), new Nav().Path, map); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.Corners![^1] == outside && h2.Note.Contains("out of building A9B4#0 through the door at"), "and back out: " + h2.Note); + Console.WriteLine(" " + h2.Note); + var exit = b0.Doors.FirstOrDefault(x => d.Corners!.Contains(x.At)); + Check.True(exit.Cell != 0 && Idx(d.Corners!, exit.Outside) == Idx(d.Corners!, exit.At) + 1, "door, then its step out: " + Pts(d.Corners)); + + // A portal in the middle of the walk's longest leg: kept out of, or no walk at all; never through it. + var way = new List { d0.Inner }; + var direct = map.Inside(d0.Cell, d0.Inner, room, spot); + way.AddRange(direct.Corners); + int longest = 0; + for (int i = 1; i + 1 < way.Count; i++) + if (way[i].FlatDistanceTo(way[i + 1]) > way[longest].FlatDistanceTo(way[longest + 1])) longest = i; + var la = way[longest]; var lb = way[longest + 1]; + Check.True(la.FlatDistanceTo(lb) >= 4, $"the walk in has a leg of 4 m or more ({la.FlatDistanceTo(lb):F1})"); + var mid = new Vec((la.X + lb.X) / 2, (la.Y + lb.Y) / 2, (la.Z + lb.Z) / 2); + var portal = new BuildingMap.PortalSpot(1, mid.X, mid.Y, mid.Z, 1.5); + map.Portals = new[] { portal }; + var round = map.Inside(d0.Cell, d0.Inner, room, spot); + if (round.Status != OutdoorHunt.PathStatus.NoPath) + { + var w2 = new List { d0.Inner }; + w2.AddRange(round.Corners); + double nearest = double.MaxValue; + for (int i = 0; i + 1 < w2.Count; i++) nearest = Math.Min(nearest, SegDist(w2[i], w2[i + 1], portal.X, portal.Y)); + Check.True(nearest >= portal.R - 0.01, $"a 1.5 m portal at {mid.X:F1},{mid.Y:F1}: the walk keeps {nearest:F2} m from it ({round.Status}): {Pts(w2)}"); + Console.WriteLine($" a 1.5 m portal at {mid.X:F1},{mid.Y:F1}: {round.Status}, the walk keeps {nearest:F2} m from it, {w2.Count - 1} corners (was {way.Count - 1})"); + } + else Check.True(true, "a portal where the walk can't get round it: no walk"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs new file mode 100644 index 0000000..3abca30 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ItemToolTests.cs @@ -0,0 +1,916 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading; +using RynthCore.Loot; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.ItemTool; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.Loot; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The Item Tool (2026-10-17): the chest looter ("pick a chest, pick a key, it loots the chest with +// the current loot profile until it is out of keys") and Quick give (a rapid give of one picked +// item to one picked player or NPC). The state machines run here on a fake environment with a +// clock the test moves; the plugin glue (commands, who may start Quick give, the loot hand-over, +// the give path) runs on the fake host. The existing profile give (GiveTests, ExpressionTests) is +// untouched: Quick give shares nothing with it. +internal static class ItemToolTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + public static void Register(Runner r) + { + // Chest looter state machine + r.Add("chest looter: key, open, loot, wait for the re-lock, repeat until the key is used up", ChestHappyPath); + r.Add("chest looter: the next cycle waits for the chest's regen timer", ChestWaitsForRegen); + r.Add("chest looter: a chest that was unlocked is opened without spending the key; later 'already unlocked' answers are probes, bounded", ChestAlreadyUnlockedProbes); + r.Add("chest looter: a second key of the same name takes over when the first is gone", ChestSwitchesKey); + r.Add("chest looter: wrong key, not a lock, chest open elsewhere -> stops with the reason", ChestKeyErrors); + r.Add("chest looter: chest gone, no answer, chest won't open, looter never starts -> bounded, says why", ChestBoundedFailures); + r.Add("chest looter: combat/busy holds every send, then the run stops after the cap", ChestHoldsThenStops); + r.Add("chest looter: can't start without a chest, a key, a loaded near chest; Stop always works and ends the loot session", ChestStartRefusalsAndStop); + r.Add("chest looter: a key that never runs out is cut off at MaxCycles", ChestMaxCycles); + // Quick give state machine + r.Add("quick give: one give at a time, each after the last landed, paced; done when none is left", GiveOneAtATime); + r.Add("quick give: a refused item is left out; three refusals in a row stop it", GiveRefusals); + r.Add("quick give: stops when the target vanishes, changes, moves away or a fight starts", GiveStopConditions); + r.Add("quick give: refuses to start with the target far, unloaded, no item or in a fight; busy client waits", GiveStartRefusals); + // 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: 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); + } + + // ── Fake environments ──────────────────────────────────────────────────── + + private sealed class ChestEnv : IChestKeyEnv + { + public long T = 1_000_000; + public long Now => T; + public bool Loaded = true; + public double Meters = 3; + public bool Unlimited; // FindKey always finds the key + public readonly HashSet Keys = new() { 11 }; + public string KeyName = "Aged Key"; + public string? Hold; + public bool HasUseDone { get; set; } = true; + public int Seq; + public uint LastErr; + public readonly List Said = new(), Logs = new(), Sent = new(); + public long OpenedAt; + public bool LootingNow, LootPending; + public int LootStarts, Aborts; + public bool? Locked; + public bool SendFails; + /// > 0: the corpse looter is played: it takes a requested chest and lets go this long after. + public long AutoLootMs; + public bool IgnoreStart; // StartLooting does nothing (the looter never takes the chest) + private long _lootEnd; + + // The server's script for the next key use / open: filled by the test, run on send. + public Func? OnKey; // returns an error to answer with (null = no answer) + public Func? OnOpen; // true = the chest opens + + public ChestKeyLooter Looter = null!; + + public string NameOf(int id) => "x"; + public bool ChestLoaded(int chestId, out double meters) { meters = Meters; return Loaded; } + public int FindKey(int keyId, string keyName, int excludeId) + { + if (Unlimited) return keyId != 0 ? keyId : 11; + if (keyId != 0 && keyId != excludeId && Keys.Contains(keyId)) return keyId; + foreach (int k in Keys) if (k != excludeId && k != keyId) return k; + return 0; + } + public string? HoldReason() => Hold; + public int UseDoneSeq() => Seq; + public bool LastUseDone(out int seq, out uint error) { seq = Seq; error = LastErr; return true; } + public bool SendKey(int keyId, int chestId) + { + if (SendFails) return false; + Sent.Add("key " + keyId); + uint? ans = OnKey?.Invoke(keyId); + if (ans != null) { LastErr = ans.Value; Seq++; } + return true; + } + public bool SendOpen(int chestId) + { + if (SendFails) return false; + Sent.Add("open"); + bool opens = OnOpen?.Invoke() ?? true; + if (opens) OpenedAt = T + 1; + LastErr = 0; Seq++; + return true; + } + public long ChestOpenedAt(int chestId) => OpenedAt; + public void StartLooting(int chestId) { LootStarts++; if (!IgnoreStart) LootPending = true; } + public bool Looting(int chestId) => LootPending || LootingNow; + public void AbortLooting(int chestId) { Aborts++; LootPending = LootingNow = false; } + public bool? ChestLockedHint(int chestId) => Locked; + public void Say(string text) => Said.Add(text); + public void Log(string text) => Logs.Add(text); + + /// Advances the clock in 100 ms steps, ticking, until done or the time is up. + public void Run(long ms, Func? until = null) + { + long end = T + ms; + while (T < end && (until == null || !until())) + { + T += 100; + if (AutoLootMs > 0) + { + if (LootPending) { LootPending = false; LootingNow = true; _lootEnd = T + AutoLootMs; } + else if (LootingNow && T >= _lootEnd) LootingNow = false; + } + Looter.Tick(); + } + } + } + + private static ChestEnv NewChest(out ChestKeyLooter looter) + { + var env = new ChestEnv(); + looter = new ChestKeyLooter(env); + env.Looter = looter; + looter.SetChest(500, "Mana Forge Chest"); + looter.SetKey(11, "Aged Key"); + return env; + } + + /// A server for the chest: the key unlocks (and chats), the chest opens, the loot session runs a little and ends. + private static void Serve(ChestEnv env, ChestKeyLooter looter, int usesPerKey = 1, bool spendKey = true) + { + int uses = usesPerKey; + env.OnKey = key => + { + looter.OnChat("The Mana Forge Chest has been unlocked."); + if (spendKey) + { + uses--; + if (uses <= 0) { looter.OnChat("Your key is used up."); env.Keys.Remove(key); uses = usesPerKey; } + else looter.OnChat($"Your key has {uses} uses left."); + } + return 0u; + }; + } + + private static string Said(ChestEnv env) => string.Join(" | ", env.Said); + + // ── Chest looter ───────────────────────────────────────────────────────── + + private static void ChestHappyPath() + { + var env = NewChest(out var ck); + env.Keys.Clear(); env.Keys.Add(11); + Serve(env, ck); + env.AutoLootMs = 1000; + Check.True(ck.Start(out _), "starts with a chest, a key and the chest near"); + Check.True(env.Said.Any(s => s.Contains("starting on Mana Forge Chest with Aged Key")), "says what it will do"); + + env.Run(60_000, () => !ck.Running); + Check.Eq(string.Join(",", env.Sent), "key 11,open", "the key goes on the chest, then the chest is opened"); + Check.Eq(env.LootStarts, 1, "the open chest is handed to the looter once"); + + // The loot session ran and ended; the key was the last use, so the run ends out of keys. + Check.False(ck.Running, "stopped"); + Check.Eq(ck.Looted, 1, "one chest looted"); + Check.True(Said(env).Contains("out of keys after 1 chest(s)"), "says it is out of keys (" + Said(env) + ")"); + Check.Eq(env.Sent.Count, 2, "nothing more sent"); + } + + private static void ChestWaitsForRegen() + { + var env = NewChest(out var ck); + env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12); // two keys of the same name + Serve(env, ck); + env.AutoLootMs = 1000; + ck.Start(out _); + env.Run(5000, () => env.LootStarts > 0); + env.Run(3000, () => ck.State == ChestKeyLooter.Phase.Waiting); + Check.True(ck.Running, "a second key is carried: the run goes on"); + Check.Eq(ck.State, ChestKeyLooter.Phase.Waiting, "waiting for the chest to re-lock"); + Check.True(ck.Status.Contains("Waiting for Mana Forge Chest to re-lock"), "the status says so: " + ck.Status); + int sentBefore = env.Sent.Count; + long openedAt = env.OpenedAt; + + env.Run(ChestKeyLooter.RegenWaitMs - 20_000); + Check.Eq(env.Sent.Count, sentBefore, "nothing sent while the regen timer runs"); + env.Run(40_000, () => env.Sent.Count > sentBefore); + Check.True(env.Sent.Count > sentBefore, "the next key goes after the wait"); + Check.True(env.T - openedAt >= ChestKeyLooter.RegenWaitMs - 1000, $"not before {ChestKeyLooter.RegenWaitMs} ms after the open ({env.T - openedAt})"); + + env.Run(60_000, () => !ck.Running); + // The second key is spent too -> out of keys. + Check.False(ck.Running, "out of keys after the second chest"); + Check.Eq(ck.Looted, 2, "two chests looted"); + } + + private static void ChestAlreadyUnlockedProbes() + { + var env = NewChest(out var ck); + env.Unlimited = true; + env.AutoLootMs = 1000; + bool unlocked = false; + env.OnKey = _ => unlocked ? ChestKeyLooter.ErrLockAlreadyUnlocked : 0u; // first: unlocks; later: the chest never re-locks + ck.Start(out _); + env.Run(3000, () => env.LootStarts > 0); + unlocked = true; + env.Run(3000, () => ck.State == ChestKeyLooter.Phase.Waiting); + Check.Eq(env.Sent.Where(s => s.StartsWith("key")).Count(), 1, "one key use so far"); + env.Run(ChestKeyLooter.RegenWaitMs + 2000); + Check.True(env.Sent.Count(s => s.StartsWith("key")) >= 2, "after the regen wait the key is tried again"); + Check.Eq(env.Sent.Count(s => s == "open"), 1, "'already unlocked' on a later cycle does NOT open the empty chest again"); + env.Run(ChestKeyLooter.ProbeMs * (ChestKeyLooter.MaxProbes + 2)); + Check.False(ck.Running, "gave up after the probes"); + Check.Eq(env.Sent.Count(s => s.StartsWith("key")), 1 + ChestKeyLooter.MaxProbes + 1, "bounded: first use + one per probe"); + Check.True(Said(env).Contains("hasn't re-locked"), "says the chest never re-locked: " + Said(env)); + + // First cycle on a chest that was never locked: opened, no key spent. + var env2 = NewChest(out var ck2); + env2.AutoLootMs = 1000; + env2.OnKey = _ => ChestKeyLooter.ErrLockAlreadyUnlocked; + ck2.Start(out _); + env2.Run(3000, () => env2.LootStarts > 0); + Check.Eq(string.Join(",", env2.Sent), "key 11,open", "'already unlocked' on the first cycle -> opens it"); + } + + private static void ChestSwitchesKey() + { + var env = NewChest(out var ck); + env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12); + Serve(env, ck); + env.AutoLootMs = 1000; + ck.Start(out _); + env.Run(3000, () => env.LootStarts > 0); + Check.Eq(ck.KeyId, 11, "starts with the picked key"); + env.Run(3000, () => ck.State == ChestKeyLooter.Phase.Waiting); + env.Run(ChestKeyLooter.RegenWaitMs + 5000, () => env.Sent.Count(s => s.StartsWith("key")) >= 2); + Check.Eq(env.Sent.Last(s => s.StartsWith("key")), "key 12", "the other key of the same name is used once the first is gone"); + Check.Eq(ck.KeyId, 12, "remembered"); + } + + private static void ChestKeyErrors() + { + foreach (var (err, text) in new[] + { + (ChestKeyLooter.ErrKeyDoesntFit, "doesn't fit"), + (ChestKeyLooter.ErrCannotLockOrUnlock, "can't be unlocked with a key"), + }) + { + var env = NewChest(out var ck); + env.OnKey = _ => err; + ck.Start(out _); + env.Run(5000, () => !ck.Running); + Check.False(ck.Running, $"error 0x{err:X} stops the run"); + Check.True(Said(env).Contains(text), $"says why ({text}): " + Said(env)); + Check.Eq(env.Sent.Count, 1, "one try, no retry of a hopeless key"); + } + + // The chest is open elsewhere: three waits, then it stops. + var e3 = NewChest(out var c3); + e3.OnKey = _ => ChestKeyLooter.ErrCannotLockWhatIsOpen; + c3.Start(out _); + e3.Run(60_000, () => !c3.Running); + Check.False(c3.Running, "a chest that stays open ends the run"); + Check.Eq(e3.Sent.Count, ChestKeyLooter.MaxOpenElsewhere, "bounded tries"); + + // 'Too busy' backs off and is bounded. + var e4 = NewChest(out var c4); + e4.OnKey = _ => ChestKeyLooter.ErrTooBusy; + c4.Start(out _); + e4.Run(120_000, () => !c4.Running); + Check.False(c4.Running, "endless 'too busy' ends the run"); + Check.Eq(e4.Sent.Count, ChestKeyLooter.MaxBusy, "bounded tries"); + } + + private static void ChestBoundedFailures() + { + // The chest goes out of view. + var env = NewChest(out var ck); + env.OnKey = _ => null; + ck.Start(out _); + env.Run(500); + env.Loaded = false; + env.Run(ChestKeyLooter.GoneMs + 1000, () => !ck.Running); + Check.False(ck.Running, "stopped when the chest is gone"); + Check.True(Said(env).Contains("is gone"), "says so"); + + // The server never answers the key use. + var e2 = NewChest(out var c2); + e2.OnKey = _ => null; + c2.Start(out _); + e2.Run(120_000, () => !c2.Running); + Check.False(c2.Running, "no answer ends the run"); + Check.Eq(e2.Sent.Count, ChestKeyLooter.MaxTimeouts, "after that many tries"); + Check.True(Said(e2).Contains("no answer"), "says why: " + Said(e2)); + + // The chest never opens. + var e3 = NewChest(out var c3); + Serve(e3, c3, usesPerKey: 99); + e3.Keys.Add(12); + e3.OnOpen = () => false; + c3.Start(out _); + e3.Run(120_000, () => !c3.Running); + Check.False(c3.Running, "a chest that won't open ends the run"); + Check.True(Said(e3).Contains("wouldn't open"), "says why: " + Said(e3)); + Check.Eq(e3.Sent.Count(s => s == "open"), ChestKeyLooter.MaxOpenFails, "bounded opens"); + + // The looter never takes the chest. + var e4 = NewChest(out var c4); + Serve(e4, c4); + e4.IgnoreStart = true; // the corpse looter refused it + c4.Start(out _); + e4.Run(ChestKeyLooter.LootStartMs + 8000, () => !c4.Running); + Check.False(c4.Running, "stopped"); + Check.True(Said(e4).Contains("never took"), "says why: " + Said(e4)); + + // The loot session never ends. + var e5 = NewChest(out var c5); + Serve(e5, c5); + c5.Start(out _); + e5.Run(3000, () => e5.LootStarts > 0); + e5.LootPending = false; e5.LootingNow = true; + e5.Run(ChestKeyLooter.LootMaxMs + 5000, () => !c5.Running); + Check.False(c5.Running, "a stuck loot session is cut off"); + Check.Eq(e5.Aborts, 1, "and the session is ended"); + } + + private static void ChestHoldsThenStops() + { + var env = NewChest(out var ck); + Serve(env, ck); + env.Hold = "combat"; + ck.Start(out _); + env.Run(ChestKeyLooter.HoldMaxMs - 5000); + Check.Eq(env.Sent.Count, 0, "nothing is sent while combat holds"); + Check.True(ck.Status.Contains("combat"), "the status says why it waits: " + ck.Status); + env.Hold = null; + env.Run(3000, () => env.Sent.Count > 0); + Check.True(env.Sent.Count > 0, "it goes on when the hold ends"); + + var e2 = NewChest(out var c2); + e2.Hold = "the client is busy (1)"; + c2.Start(out _); + e2.Run(ChestKeyLooter.HoldMaxMs + 5000, () => !c2.Running); + Check.False(c2.Running, "a hold that never ends stops the run"); + Check.Eq(e2.Sent.Count, 0, "without sending anything"); + Check.True(Said(e2).Contains("waited"), "says why: " + Said(e2)); + } + + private static void ChestStartRefusalsAndStop() + { + var env = new ChestEnv(); + var ck = new ChestKeyLooter(env); + env.Looter = ck; + Check.False(ck.Start(out string why), "no chest"); + Check.True(why.Contains("pick a chest"), why); + ck.SetChest(500, "Chest"); + Check.False(ck.Start(out why), "no key"); + Check.True(why.Contains("pick a key"), why); + ck.SetKey(11, "Aged Key"); + env.Meters = 40; + Check.False(ck.Start(out why), "chest too far"); + Check.True(why.Contains("40 m away"), why); + env.Meters = 3; env.Loaded = false; + Check.False(ck.Start(out why), "chest not loaded"); + env.Loaded = true; env.Keys.Clear(); + Check.False(ck.Start(out why), "key gone"); + Check.True(why.Contains("no 'Aged Key'"), why); + Check.True(env.Said.Count(s => s.Contains("can't start")) == 5, "each refusal is said in chat"); + + // Stop works in every phase and ends a loot session. + env.Keys.Add(11); + Serve(env, ck); + ck.Start(out _); + env.Run(3000, () => env.LootStarts > 0); + env.LootPending = false; env.LootingNow = true; + env.Run(300); + Check.Eq(ck.State, ChestKeyLooter.Phase.Looting, "looting"); + ck.Stop("stopped by you"); + Check.False(ck.Running, "stopped"); + Check.Eq(env.Aborts, 1, "the loot session is ended and the chest closed"); + Check.True(Said(env).Contains("stopped by you"), "says it stopped"); + ck.Stop(); // already stopped + Check.True(Said(env).Contains("not running"), "stopping a stopped looter says so"); + Check.False(ck.Running, "and does nothing"); + } + + private static void ChestMaxCycles() + { + var env = NewChest(out var ck); + env.Unlimited = true; + env.AutoLootMs = 300; + env.Locked = true; // the client reads the chest locked again at once; MinRelockMs still applies + Serve(env, ck, spendKey: false); + ck.Start(out _); + env.Run(60_000_000, () => !ck.Running); + Check.False(ck.Running, "ended"); + Check.Eq(ck.Looted, ChestKeyLooter.MaxCycles, "after MaxCycles chests"); + string said = Said(env); + Check.True(said.Contains($"{ChestKeyLooter.MaxCycles} cycles"), "says why: " + said.Substring(Math.Max(0, said.Length - 200))); + } + + // ── Quick give state machine ───────────────────────────────────────────── + + private sealed class GiveEnv : IQuickGiveEnv + { + public long T = 5_000_000; + public long Now => T; + public string TargetName = "Town Crier"; + public bool Loaded = true; + public double Meters = 2; + public bool Combat; + public string? Hold; + public readonly List Items = new() { 1, 2, 3 }; // carried, in order + public readonly Dictionary Counts = new(); + public readonly List<(long At, int Item)> Sent = new(); + public readonly HashSet Takes = new(); // items the server accepts (empty = all) + public readonly HashSet Refuses = new(); // items it refuses with an error + public bool Silent; // never answers + public int Refusals; + public readonly List Said = new(), Logs = new(); + public QuickGive Gv = null!; + public int PendingLand; // item in flight, lands after LandMs + public long LandAt; + public long LandMs = 200; + + public bool TargetLoaded(int targetId, out string name, out double meters) { name = TargetName; meters = Meters; return Loaded; } + public bool InCombat() => Combat; + public string? HoldReason() => Hold; + public bool NextItem(GiveItemKey key, ISet skip, out int itemId, out int count) + { + foreach (int i in Items) + if (!skip.Contains(i)) { itemId = i; count = Counts.TryGetValue(i, out int c) ? c : 1; return true; } + itemId = 0; count = 0; return false; + } + public int CountCarried(GiveItemKey key) => Items.Count; + public bool Landed(int itemId, int count) => !Items.Contains(itemId); + public bool Send(int itemId, int targetId) + { + Sent.Add((T, itemId)); + if (Silent) return true; + if (Refuses.Contains(itemId)) { Refusals++; return true; } + PendingLand = itemId; LandAt = T + LandMs; + return true; + } + public int RefusalSeq() => Refusals; + public void Say(string text) => Said.Add(text); + public void Log(string text) => Logs.Add(text); + + public void Run(long ms, Func? until = null) + { + long end = T + ms; + while (T < end && (until == null || !until())) + { + T += 50; + if (PendingLand != 0 && T >= LandAt) { Items.Remove(PendingLand); PendingLand = 0; } + Gv.Tick(); + } + } + } + + private static GiveEnv NewGive(out QuickGive qg) + { + var env = new GiveEnv(); + qg = new QuickGive(env); + env.Gv = qg; + qg.SetItem(1, new GiveItemKey(0x1234, "Mana Mote")); + qg.SetTarget(900, "Town Crier"); + return env; + } + + private static void GiveOneAtATime() + { + var env = NewGive(out var qg); + Check.True(qg.Start(out _), "starts"); + Check.True(env.Said[0].Contains("Town Crier") && env.Said[0].Contains("Mana Mote"), "the start line names the target and the item: " + env.Said[0]); + env.Run(20_000, () => !qg.Running); + Check.Eq(string.Join(",", env.Sent.Select(s => s.Item)), "1,2,3", "each item once, in order"); + for (int i = 1; i < env.Sent.Count; i++) + Check.True(env.Sent[i].At - env.Sent[i - 1].At >= env.LandMs + QuickGive.PaceMs - 50, $"give {i + 1} waited for the last to land and the pace ({env.Sent[i].At - env.Sent[i - 1].At} ms)"); + Check.Eq(qg.Given, 3, "three given"); + Check.False(qg.Running, "done"); + Check.True(env.Said.Last().Contains("done"), "says it is done: " + env.Said.Last()); + Check.True(qg.Status.Contains("3 item(s)"), "the status keeps the result: " + qg.Status); + } + + private static void GiveRefusals() + { + // One refused item is skipped; the others go. + var env = NewGive(out var qg); + env.Refuses.Add(2); + qg.Start(out _); + env.Run(30_000, () => !qg.Running); + Check.Eq(string.Join(",", env.Sent.Select(s => s.Item)), "1,2,3", "item 2 refused once, not retried; item 3 given"); + Check.Eq(qg.Given, 2, "two given"); + Check.False(qg.Running, "it ends when only the refused one is left"); + + // Three in a row stop it. + var e2 = NewGive(out var q2); + e2.Items.Clear(); e2.Items.AddRange(new[] { 1, 2, 3, 4, 5 }); + foreach (int i in e2.Items) e2.Refuses.Add(i); + q2.Start(out _); + e2.Run(60_000, () => !q2.Running); + Check.False(q2.Running, "stopped"); + Check.Eq(e2.Sent.Count, QuickGive.MaxRefusals, "after that many refusals in a row, not the whole pack"); + Check.True(e2.Said.Last().Contains("refusals in a row"), "says why: " + e2.Said.Last()); + + // No answer at all counts as a refusal after the confirm timeout. + var e3 = NewGive(out var q3); + e3.Silent = true; + q3.Start(out _); + e3.Run(120_000, () => !q3.Running); + Check.False(q3.Running, "stopped"); + Check.Eq(e3.Sent.Count, QuickGive.MaxRefusals, "unanswered gives are bounded the same way"); + Check.True(e3.Sent[1].At - e3.Sent[0].At >= QuickGive.ConfirmMs, "each waited the confirm time before the next"); + } + + private static void GiveStopConditions() + { + void Case(string name, Action change, string expect) + { + var env = NewGive(out var qg); + env.Items.Clear(); env.Items.AddRange(Enumerable.Range(1, 30)); + qg.Start(out _); + env.Run(600); + Check.True(qg.Running, name + ": running before"); + change(env); + env.Run(5000, () => !qg.Running); + Check.False(qg.Running, name + ": stops"); + Check.True(env.Said.Last().Contains(expect), $"{name}: says '{expect}' ({env.Said.Last()})"); + } + Case("vanishes", e => e.Loaded = false, "is gone"); + Case("renamed", e => e.TargetName = "Somebody Else", "the target changed"); + Case("moves away", e => e.Meters = 30, "out of give range"); + Case("fight", e => e.Combat = true, "a fight started"); + + // A target that comes back within the grace is fine. + var env2 = NewGive(out var q2); + env2.Items.Clear(); env2.Items.AddRange(Enumerable.Range(1, 30)); + q2.Start(out _); + env2.Run(300); + env2.Loaded = false; env2.Run(500); env2.Loaded = true; env2.Run(500); + Check.True(q2.Running, "a flicker shorter than the grace doesn't stop it"); + q2.Stop("stopped by you"); + Check.False(q2.Running, "Stop always works"); + } + + private static void GiveStartRefusals() + { + var env = NewGive(out var qg); + env.Meters = 12; + Check.False(qg.Start(out string why), "target 12 m away"); + Check.True(why.Contains("give range is 10 m"), why); + env.Meters = 2; env.Loaded = false; + Check.False(qg.Start(out why), "target not loaded"); + env.Loaded = true; env.TargetName = "Other"; + Check.False(qg.Start(out why), "target is someone else now"); + env.TargetName = "Town Crier"; env.Combat = true; + Check.False(qg.Start(out why), "in a fight"); + env.Combat = false; env.Items.Clear(); + Check.False(qg.Start(out why), "nothing to give"); + Check.False(qg.Running, "never started"); + Check.Eq(env.Sent.Count, 0, "nothing sent"); + + var e2 = new GiveEnv(); var q2 = new QuickGive(e2); e2.Gv = q2; + Check.False(q2.Start(out why), "no item picked"); + q2.SetItem(1, new GiveItemKey(1, "X")); + Check.False(q2.Start(out why), "no target picked"); + + // The client is busy: the give waits, then goes. + var e3 = NewGive(out var q3); + e3.Hold = "the client is busy (1)"; + q3.Start(out _); + e3.Run(2000); + Check.Eq(e3.Sent.Count, 0, "nothing while the client is busy"); + e3.Hold = null; + e3.Run(500, () => e3.Sent.Count > 0); + Check.True(e3.Sent.Count > 0, "it goes when the client is free"); + } + + // ── Plugin glue ────────────────────────────────────────────────────────── + + private const uint Player = 0x50000E01; + private const uint Chest = 0x7A9B4101; + private const uint Key = 0x80290001, Key2 = 0x80290002; + private const uint Gem = 0x80290101; + private const uint Npc = 0x80290200, Bystander = 0x80290201, Monster = 0x80290202, Corpse = 0x80290203; + private const uint Mote1 = 0x80290301, Mote2 = 0x80290302, Mote3 = 0x80290303, WornMote = 0x80290304, OtherMote = 0x80290305, ClonedMote = 0x80290306; + + private sealed class Bot + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() + { + IsMacroRunning = false, // the Item Tool works with the macro off + EnableLooting = false, + EnableCombat = false, + LootOwnership = 0, + LootContentSettleMs = 0, + LootEmptyCorpseMs = 0, + StopLootingWhenPackFull = false, + GiveQueueIntervalMs = 0, + }; + public readonly WorldObjectCache Cache; + + public Bot(RynthCoreHost host, string profile, params uint[] objects) + { + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + Set("_dashboard", dash); + Cache = new WorldObjectCache(host); + Cache.SetPlayerId(Player); + Set("_objectCache", Cache); + Set("_playerId", Player); + Set("_initialized", true); + Set("_loginComplete", true); + S.CurrentLootPath = profile; + foreach (uint id in objects) Cache.OnCreateObject(id); + Cache.Tick(); + } + + public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!; + public object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a); + + /// One plugin tick's worth: the Item Tool, then the loot tick (what OnTick runs). + public void Tick() + { + Call("TickItemTool"); + Set("_activity", BotActivity.Looting); + Call("TickCorpseOpening"); + } + + public void TickUntil(Func done, int max = 600) + { + for (int i = 0; i < max && !done(); i++) { Tick(); Thread.Sleep(10); } + } + + public void ServerOpens(uint container) + { + FakeHost.GroundContainer = container; + P.OnViewObjectContents(container); + P.OnUpdateObjectInventory(container); + } + + public void ServerCloses(uint container) + { + if (FakeHost.GroundContainer == container) FakeHost.GroundContainer = 0; + P.OnStopViewingObjectContents(container); + } + + /// The player types / presses: a trusted command. + public void Cmd(string args) => P.QueueItemToolCommand(args, trusted: true); + } + + private static string ProfilePath(string name) + { + string path = System.IO.Path.Combine(Program.TempRoot, name); + var p = new LootProfile { Name = "itemtool" }; + var gems = new LootRule { Name = "Gems", Action = LootAction.Keep }; + gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem }); + p.Rules.Add(gems); + p.Save(path); + return path; + } + + private static void BaseWorld() + { + FakeHost.Reset(); + FakeHost.SalvageCalls = true; + FakeHost.WeaponCalls = true; + FakeHost.CloseContainerCalls = true; + FakeHost.UseOnCalls = true; + FakeHost.GiveCalls = true; + FakeHost.ServerGates = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.WeenieErrorCalls = true; + var pose = (0x1048002Au, 100f, 100f, 0f); + FakeHost.Names[Player] = "Dargoth Hera"; + FakeHost.Positions[Player] = pose; + FakeHost.PlayerPose = pose; + + FakeHost.Names[Chest] = "Mana Forge Chest"; + FakeHost.ItemTypes[Chest] = 0x200; + FakeHost.Positions[Chest] = (pose.Item1, 102f, 100f, 0f); + FakeHost.NotAttackable.Add(Chest); + FakeHost.Containers[Chest] = 0; + FakeHost.Names[Key] = "Aged Key"; FakeHost.ItemTypes[Key] = 0x1000; FakeHost.Containers[Key] = Player; + FakeHost.Names[Key2] = "Aged Key"; FakeHost.ItemTypes[Key2] = 0x1000; FakeHost.Containers[Key2] = Player; + FakeHost.Names[Gem] = "Black Opal"; FakeHost.ItemTypes[Gem] = 0x800; FakeHost.Containers[Gem] = Chest; FakeHost.Appraised.Add(Gem); + + FakeHost.Names[Npc] = "Town Crier"; FakeHost.ItemTypes[Npc] = 0x10; FakeHost.NotAttackable.Add(Npc); + FakeHost.Positions[Npc] = (pose.Item1, 101f, 100f, 0f); + FakeHost.Names[Bystander] = "Some Player"; FakeHost.ItemTypes[Bystander] = 0x10; FakeHost.Bitfields[Bystander] = 0x8; // BF_PLAYER + FakeHost.Positions[Bystander] = (pose.Item1, 101f, 101f, 0f); + FakeHost.Names[Monster] = "Drudge Lurker"; FakeHost.ItemTypes[Monster] = 0x10; + FakeHost.Positions[Monster] = (pose.Item1, 103f, 100f, 0f); + FakeHost.Bitfields[Monster] = 0x10; // BF_ATTACKABLE: a monster, not an NPC + foreach (var (id, name) in new[] { (Mote1, "Mana Mote"), (Mote2, "Mana Mote"), (Mote3, "Mana Mote"), (WornMote, "Mana Mote"), (OtherMote, "Lesser Mana Mote"), (ClonedMote, "Mana Mote") }) + { + FakeHost.Names[id] = name; FakeHost.Containers[id] = Player; FakeHost.ItemTypes[id] = 0x80; + FakeHost.Wcids[id] = 0x1111; + } + FakeHost.Wcids[ClonedMote] = 0x2222; // same name, a different weenie: not the picked item + FakeHost.Wielded[WornMote] = 0x8000; + } + + private static Bot MakeBot(string profile = "itemtool-chest.json") + { + var host = FakeHost.Create(Player); + return new Bot(host, ProfilePath(profile), Chest, Key, Key2, Gem, Npc, Bystander, Monster, Mote1, Mote2, Mote3, WornMote, OtherMote, ClonedMote); + } + + private static string Chat() => string.Join(" | ", FakeHost.Chat); + + private static void PluginChestRun() + { + BaseWorld(); + var bot = MakeBot(); + FakeHost.SelectedItem = Chest; + bot.Cmd("chest set"); + bot.Tick(); + FakeHost.SelectedItem = Key; + bot.Cmd("chest key"); + bot.Tick(); + Check.True(Chat().Contains("chest = Mana Forge Chest") && Chat().Contains("key = Aged Key"), "picks are confirmed in chat: " + Chat()); + Check.False(bot.S.IsMacroRunning, "the macro is off"); + + // The server: the key unlocks (chat + UseDone), the chest opens (ViewContents + contents + UseDone). + FakeHost.OnUseObjectOn = (src, tgt) => + { + Check.Eq(src, Key, "the key is the source"); + Check.Eq(tgt, Chest, "the chest is the target"); + bot.Call("ItemToolChat", "The Mana Forge Chest has been unlocked."); + bot.Call("ItemToolChat", "Your key is used up."); + FakeHost.Containers.Remove(Key); // the key is consumed + FakeHost.UseDone(0); + }; + FakeHost.OnUseObject = id => + { + if (id != Chest) return; + FakeHost.UseDone(0); + bot.ServerOpens(Chest); + }; + bot.Cmd("chest start"); + // Key2 has the same name: it goes on after the first, so the run continues until it is spent too. + bot.TickUntil(() => FakeHost.Uses.Contains(Chest)); + Check.Eq(FakeHost.UsesOn.Count, 1, "one key use"); + Check.True(FakeHost.Uses.Contains(Chest), "then the chest is used (opened)"); + bot.TickUntil(() => FakeHost.ExternalMoves.Any(m => m.Id == Gem), 800); + Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the loot profile's gem is taken (macro off, Looting off)"); + FakeHost.Containers[Gem] = Player; + int closes = FakeHost.Closes.Count; + bot.TickUntil(() => FakeHost.Closes.Count > closes); + Check.True(FakeHost.Closes.Contains(Chest), "the chest is closed when done"); + bot.ServerCloses(Chest); + bot.TickUntil(() => Chat().Contains("looted Mana Forge Chest"), 200); + Check.True(Chat().Contains("looted Mana Forge Chest (1 so far)"), "says it looted: " + Chat()); + Check.True(Chat().Contains("Chest looter stopped") || Chat().Contains("Waiting") || bot.Get("_chestKey").Running, "the second key keeps it going"); + + // Take the second key away: the next check ends the run, out of keys. + FakeHost.Containers.Remove(Key2); + bot.TickUntil(() => !bot.Get("_chestKey").Running, 400); + Check.False(bot.Get("_chestKey").Running, "stopped"); + Check.True(Chat().Contains("out of keys"), "says it is out of keys: " + Chat()); + Check.Eq(bot.Get("_forcedLootContainerId"), 0, "the forced-loot flag is cleared"); + } + + private static void PluginChestPicks() + { + BaseWorld(); + var bot = MakeBot("itemtool-picks.json"); + FakeHost.SelectedItem = 0; + bot.Cmd("chest set"); bot.Tick(); + Check.True(Chat().Contains("select the chest in the world"), "nothing selected: " + Chat()); + FakeHost.Chat.Clear(); + FakeHost.SelectedItem = Key; + bot.Cmd("chest set"); bot.Tick(); + Check.True(Chat().Contains("in your pack"), "a pack item is not a chest: " + Chat()); + FakeHost.Chat.Clear(); + FakeHost.SelectedItem = Chest; + bot.Cmd("chest key"); bot.Tick(); + Check.True(Chat().Contains("must be in your pack"), "a world object is not a key: " + Chat()); + FakeHost.Chat.Clear(); + FakeHost.SelectedItem = WornMote; + bot.Cmd("chest key"); bot.Tick(); + Check.True(Chat().Contains("worn or wielded"), "worn gear is not a key: " + Chat()); + + // House storage is never a chest. + FakeHost.Chat.Clear(); + FakeHost.Names[Corpse] = "Storage"; + FakeHost.Positions[Corpse] = (0x1048002Au, 101f, 99f, 0f); + FakeHost.Containers[Corpse] = 0; + bot.Cache.OnCreateObject(Corpse); bot.Cache.Tick(); + FakeHost.SelectedItem = Corpse; + bot.Cmd("chest set"); bot.Tick(); + Check.True(Chat().Contains("house storage"), "storage is refused: " + Chat()); + + // Start with nothing picked says what is missing and sends nothing. + FakeHost.Chat.Clear(); + bot.Cmd("chest start"); bot.Tick(); + Check.True(Chat().Contains("pick a chest first"), "start without a chest: " + Chat()); + Check.Eq(FakeHost.UsesOn.Count + FakeHost.Uses.Count, 0, "nothing sent to the server"); + FakeHost.Chat.Clear(); + bot.Cmd("chest stop"); bot.Tick(); + Check.True(Chat().Contains("not running"), "stop when idle: " + Chat()); + } + + private static void PluginQuickGive() + { + BaseWorld(); + var bot = MakeBot("itemtool-give.json"); + FakeHost.SelectedItem = Mote1; + bot.Cmd("giveitem"); + bot.Tick(); + FakeHost.SelectedItem = Npc; + bot.Cmd("givetarget"); + bot.Tick(); + Check.True(Chat().Contains("item = Mana Mote") && Chat().Contains("target = Town Crier"), "picks are confirmed: " + Chat()); + bot.Cmd("give"); + bot.Tick(); + Check.True(Chat().Contains("giving every 'Mana Mote'") && Chat().Contains("to Town Crier"), "the start line names item and target: " + Chat()); + bot.TickUntil(() => !bot.Get("_quickGive").Running, 1500); + Check.False(bot.Get("_quickGive").Running, "done"); + var given = FakeHost.Gives.Select(g => g.Item).ToArray(); + Check.Eq(string.Join(",", given.OrderBy(x => x).Select(x => x.ToString("X8"))), string.Join(",", new[] { Mote1, Mote2, Mote3 }.Select(x => x.ToString("X8"))), "exactly the three plain Mana Motes: not the worn one, 'Lesser Mana Mote' or the other weenie"); + Check.True(FakeHost.Gives.All(g => g.Target == Npc && g.Amount == 0), "all to the NPC, whole objects, with AC's give action"); + Check.Eq(FakeHost.ExternalMoves.Count, 0, "no MoveItemExternal"); + Check.True(Chat().Contains("Quick give stopped: done"), "ends with a result line: " + Chat()); + } + + private static void PluginGiveTrust() + { + BaseWorld(); + var bot = MakeBot("itemtool-trust.json"); + FakeHost.SelectedItem = Mote1; bot.Cmd("giveitem"); bot.Tick(); + FakeHost.SelectedItem = Npc; bot.Cmd("givetarget"); bot.Tick(); + FakeHost.Chat.Clear(); + + // A meta's /ra line. + bot.Call("HandleRaCommand", "/ra itemtool give"); + bot.Tick(); + Check.Eq(FakeHost.Gives.Count, 0, "a meta line gives nothing"); + Check.True(Chat().Contains("only from the Item Tool panel or a command you type yourself"), "and says why: " + Chat()); + Check.False(bot.Get("_quickGive").Running, "not running"); + + // A script's SubmitCommand. + FakeHost.Chat.Clear(); + bot.P.ScriptSubmitCommand("/ra itemtool give"); + bot.Tick(); + Check.Eq(FakeHost.Gives.Count, 0, "a script line gives nothing"); + Check.False(bot.Get("_quickGive").Running, "not running"); + + // A typed line (the chat bar): runs. + int eat = 0; + bot.P.OnChatBarEnter("/ra itemtool give", ref eat); + bot.Tick(); + Check.Eq(eat, 1, "the line is eaten"); + Check.True(bot.Get("_quickGive").Running, "a typed line starts it"); + + // Stop from a meta works. + bot.Call("HandleRaCommand", "/ra itemtool givestop"); + bot.Tick(); + Check.False(bot.Get("_quickGive").Running, "a meta can stop it"); + // The panel's button. + FakeHost.Gives.Clear(); + bot.Cmd("give"); + bot.TickUntil(() => FakeHost.Gives.Count > 0, 100); + Check.True(FakeHost.Gives.Count > 0, "the panel's button starts it"); + bot.Cmd("stop"); bot.Tick(); + Check.False(bot.Get("_quickGive").Running, "/ra itemtool stop ends it"); + } + + private static void PluginGiveTargets() + { + BaseWorld(); + var bot = MakeBot("itemtool-targets.json"); + FakeHost.SelectedItem = Monster; bot.Cmd("givetarget"); bot.Tick(); + Check.True(Chat().Contains("player or an NPC"), "a monster is refused: " + Chat()); + FakeHost.Chat.Clear(); + FakeHost.SelectedItem = Mote2; bot.Cmd("givetarget"); bot.Tick(); + Check.True(Chat().Contains("in your pack"), "a pack item is refused: " + Chat()); + FakeHost.Chat.Clear(); + FakeHost.SelectedItem = Player; bot.Cmd("givetarget"); bot.Tick(); + Check.True(Chat().Contains("that is you"), "you are refused: " + Chat()); + FakeHost.Chat.Clear(); + FakeHost.SelectedItem = Bystander; bot.Cmd("givetarget"); bot.Tick(); + Check.True(Chat().Contains("target = PLAYER Some Player"), "a player is allowed and shown as one: " + Chat()); + FakeHost.SelectedItem = Mote1; bot.Cmd("giveitem"); bot.Tick(); + FakeHost.Chat.Clear(); + bot.Cmd("give"); bot.Tick(); + Check.True(Chat().Contains("giving every 'Mana Mote'") && Chat().Contains("to Some Player"), "the start line names the player: " + Chat()); + bot.Cmd("stop"); bot.Tick(); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootClaimMismatchTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootClaimMismatchTests.cs index f58031a..b33a7a2 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootClaimMismatchTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootClaimMismatchTests.cs @@ -42,6 +42,7 @@ internal static class LootClaimMismatchTests r.Add("loot claim (R-20261031-203155-cea0): Boost Nav Priority with no route: no loot work, never in Looting; looted once the flag is off", BoostNavNoRouteLoots); r.Add("loot claim (R-20261031-203155-cea0): Boost Nav Priority with a route, then none: nav has the tick, nothing claimed either way", BoostNavWithRouteYields); r.Add("loot claim (R-20261031-203155-cea0): Looting with nothing claimed is logged with the reason after 3 s, then throttled", LootStallLogged); + r.Add("boost nav (R-20261102-041824-3f7c): a corpse it passes by is said once in chat; nothing claimed; looted once the flag is off", BoostNavCorpseNotice); } // ── Clock and world ─────────────────────────────────────────────────────── @@ -288,4 +289,33 @@ internal static class LootClaimMismatchTests Check.Eq(bot.Claimed, unchecked((int)Corpse), "once the halt ends the corpse is claimed"); Check.True(Logged("the Looting stall is over"), "and the end of the stall is logged"); }); + + // ── 5. Boost Nav Priority says it skipped the corpse (owner, 2026-11-02) ─── + + private static void BoostNavCorpseNotice() => Clocked(() => + { + World(); + var bot = RescuedCorpse(); + bot.S.BoostNavPriority = true; // NavLootPrio turned it on; no route, no monster + int Notices() => FakeHost.Chat.Count(c => c == RynthAiPlugin.BoostNavNotice); + void Note() => bot.Call("NoteBoostNavSkip", bot.S, false); + + for (int i = 0; i < 200; i++) // 5 s of ticks, the notice looked at after each decision + { + Check.True(bot.Tick() != BotActivity.Looting, "never in Looting"); + Note(); + } + Check.Eq(Notices(), 1, "the passed-by corpse is said once in chat"); + Check.True(Logged(RynthAiPlugin.BoostNavNotice + " (skipped a corpse)"), "and in the log, with what was skipped"); + Check.Eq(bot.Claimed, 0, "nothing claimed"); + Check.False(FakeHost.Uses.Contains(Corpse), "nothing opened"); + + bot.S.BoostNavPriority = false; + Note(); + bot.Tick(); + Check.Eq(bot.Claimed, unchecked((int)Corpse), "flag off: the corpse is claimed"); + LootToTheEnd(bot); + Check.True(bot.Completed, "and looted to the end"); + Check.Eq(Notices(), 1, "nothing more said"); + }); } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs index 5318420..1e1d2bf 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/NavEngineTests.cs @@ -57,6 +57,13 @@ internal static class NavEngineTests r.Add("nav engine: a hold is checked again every 3 s, so a wrong answer doesn't hold for good", AreaRecheck); r.Add("nav engine: at the last waypoint before the area change it walks on through for 6 s", AreaGraceWalk); r.Add("nav engine: with recovery off the area is never checked", AreaRecoveryOff); + r.Add("nav area after a portal: a later waypoint in this area (a recall cast here, the loop's start) is carried on from", AreaCarryOnRecallHere); + r.Add("nav area after a portal: a route that walks into the dungeon carries on at its first waypoint inside", AreaCarryOnIntoDungeon); + r.Add("nav area after a portal: a Linear route looks to its end and back, and turns round for a point behind", AreaCarryOnLinearBack); + r.Add("nav area: at the route's own way out it still walks through, it doesn't go back to an earlier point here", AreaBoundaryNotCarried); + r.Add("nav area: nothing of the route here, in a dungeon: says once to load a route or press Patrol, offers Patrol", AreaNoneHereDungeon); + r.Add("nav area: nothing of the route here, on the landscape: says to load a route for here, no Patrol", AreaNoneHereLandscape); + r.Add("nav area: loading the route again over a hold says so again; a route for here (the Patrol) runs at once", AreaReloadAndPatrol); r.Add("nav area: the decision (same dungeon, other dungeon, landscape, off the map)", ClassifyArea); r.Add("nav recovery: a waypoint behind a wall is in the room whose floor holds it, not the nearest centre", ContainingCellByFloor); @@ -114,6 +121,9 @@ internal static class NavEngineTests private sealed class FakePlanner : INavRecoveryPlanner { public NavAreaCheck Area = NavAreaCheck.Match; + /// Per-point answer (nav coordinates); used instead of when set. + public Func? AreaAt; + public string RouteArea = "dungeon 0x01D9", PlayerArea = "on the landscape"; public int AreaCalls; public bool GivePlan; /// Per-target walk length (yd); null = no path. Used instead of GivePlan when set. @@ -134,10 +144,11 @@ internal static class NavEngineTests public NavAreaCheck CheckArea(uint playerCell, double tNs, double tEw, out string routeArea, out string playerArea) { AreaCalls++; - bool mis = Area == NavAreaCheck.Mismatch; - routeArea = mis ? "dungeon 0x01D9" : string.Empty; - playerArea = mis ? "on the landscape" : string.Empty; - return Area; + var a = AreaAt != null ? AreaAt(tNs, tEw) : Area; + bool mis = a == NavAreaCheck.Mismatch; + routeArea = mis ? RouteArea : string.Empty; + playerArea = mis ? PlayerArea : string.Empty; + return a; } } @@ -748,7 +759,8 @@ internal static class NavEngineTests nav.Run(12); Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 1, "still one chat line after 12 s"); - Check.True(p.AreaCalls >= 4 && p.AreaCalls <= 5, $"asked again every 3 s while held ({p.AreaCalls} calls in 12 s)"); + // 1 for the waypoint, 1 for the one look along the route for a waypoint here (not repeated), 4 rechecks. + Check.True(p.AreaCalls >= 5 && p.AreaCalls <= 6, $"asked again every 3 s while held ({p.AreaCalls} calls in 12 s)"); Check.Eq(p.PlanTargets.Count, 0, "no detour is tried"); Check.Eq(FakeHost.Jumps, 0, "no escape jumps"); Check.Eq(nav.Idx, 1, "the waypoint is kept"); @@ -834,6 +846,129 @@ internal static class NavEngineTests Check.True(FakeHost.AutoRun, "walks toward the waypoint"); } + // ── Different area after a portal / a load (2026-11-01) ────────────────── + + /// A planner that says Match where holds (yards north, east of the origin), Mismatch elsewhere. + private static FakePlanner AreaWhere(Func here, string routeArea = "the landscape", string playerArea = "in dungeon 0x5756") + => new() { AreaAt = (ns, ew) => here((ns - NS0) * 240.0, (ew - EW0) * 240.0) ? NavAreaCheck.Match : NavAreaCheck.Mismatch, + RouteArea = routeArea, PlayerArea = playerArea }; + + /// Puts the fake character in an indoor cell of the landblock it stands in. + private static void Indoors() => FakeHost.PlayerPose = ((FakeHost.PlayerPose.Cell & 0xFFFF0000u) | 0x0124, FakeHost.PlayerPose.X, FakeHost.PlayerPose.Y, FakeHost.PlayerPose.Z); + + private static void AreaCarryOnRecallHere() + { + // The logged case: a Circular route that starts with a recall cast in the home dungeon, then walks + // the landscape to a portal. Loaded (or the macro started) in the dungeon, nav was on [2] out on the + // landscape (the "nearest" point by map distance) and held for good. + FakeHost.Reset(); At(-500, -500); Indoors(); + var recall = Pt(-500, -500, T.Recall); recall.SpellId = 4198; + var route = Route(RT.Circular, recall, Pt(100, 0), Pt(110, 0), Pt(120, 0)); + var p = AreaWhere((n, e) => n < -400); + var nav = new Nav(route, idx: 2, planner: p); + nav.Tick(); + Check.Eq(nav.Idx, 0, "carries on from [0], the recall cast here (the loop goes on to it)"); + Check.True(FakeHost.Chat.Exists(c => c.Contains("carrying on from [0]") && c.Contains("Recall")), "says so in chat, naming the step"); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 0, "no hold line"); + Check.False(nav.S.NavIsStuck, "not flagged stuck"); + Check.Eq(nav.Recovery, "none", "no area hold"); + nav.Run(1.0); + Check.Eq(nav.E.GetStateSnapshot().PortalState, "FiringAction", "and casts the recall"); + } + + private static void AreaCarryOnIntoDungeon() + { + // A Once route: landscape [0]-[1], the portal at [2] (used out there), then the dungeon [3]-[4]. + // The character went through (or was put) inside with nav still on [1]: on to [3], not a hold. + FakeHost.Reset(); At(-300, 0); Indoors(); + var portal = Pt(20, 0, T.PortalNPC); portal.TargetName = "Abandoned Experiment"; + var route = Route(RT.Once, Pt(0, 0), Pt(10, 0), portal, Pt(-290, 0), Pt(-280, 0)); + var nav = new Nav(route, idx: 1, planner: AreaWhere((n, e) => n < -200)); + nav.Tick(); + Check.Eq(nav.Idx, 3, "carries on from [3], the first waypoint inside (the portal step out there is passed)"); + nav.Run(0.5); + Check.True(FakeHost.AutoRun, "walks toward [3]"); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 0, "never held"); + + // Nothing is walked out of order on a Once route: points before the current one are never picked. + FakeHost.Reset(); At(-330, 0); Indoors(); // 40 yd from [0]: not standing at the way out + var back = new Nav(Route(RT.Once, Pt(-290, 0), Pt(10, 0), Pt(20, 0)), idx: 1, planner: AreaWhere((n, e) => n < -200)); + back.Tick(); + Check.Eq(back.Idx, 1, "a Once route never goes back to [0]"); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("nothing ahead on it is here")), 1, "it holds and says nothing ahead is here"); + } + + private static void AreaCarryOnLinearBack() + { + FakeHost.Reset(); At(-330, 0); Indoors(); // 40 yd from [0]: not standing at the way out + var nav = new Nav(Route(RT.Linear, Pt(-290, 0), Pt(10, 0), Pt(20, 0)), idx: 1, planner: AreaWhere((n, e) => n < -200)); + nav.Tick(); + Check.Eq(nav.Idx, 0, "nothing ahead to the end: back from it to [0]"); + Check.Eq(nav.E.GetStateSnapshot().LinearDir, -1, "reached heading back"); + } + + private static void AreaBoundaryNotCarried() + { + // The route walks into a portal at [1]; [0] is in this area too. Standing at [1] (the way out), it + // walks on through as before rather than turning back to [0]. + FakeHost.Reset(); At(0.5, 0); + var nav = new Nav(Route(RT.Circular, Pt(-20, 0), Pt(0, 0), Pt(900, 0)), idx: 2, planner: AreaWhere((n, e) => n < 100, "dungeon 0x01D9", "on the landscape")); + nav.Tick(); + Check.Eq(nav.Idx, 2, "keeps the waypoint past the portal"); + Check.True(nav.S.NavStatusLine.Contains("walking on through"), "the grace walk"); + Check.False(FakeHost.Chat.Exists(c => c.Contains("carrying on")), "no carry-on"); + } + + private static void AreaNoneHereDungeon() + { + FakeHost.Reset(); At(-500, -500); Indoors(); + var nav = new Nav(Route(RT.Circular, Pt(100, 0), Pt(110, 0), Pt(120, 0)), idx: 1, planner: AreaWhere((n, e) => false)); + nav.Tick(); + Check.False(FakeHost.AutoRun, "held"); + var lines = FakeHost.Chat.Where(c => c.Contains("different area")).ToList(); + Check.Eq(lines.Count, 1, "one chat line"); + Check.True(lines.Count == 1 && lines[0].Contains("nothing ahead on it is here") && lines[0].Contains("press Patrol"), + $"it says what to do ({(lines.Count > 0 ? lines[0] : "")})"); + Check.True(nav.S.NavStatusLine.Contains("press Patrol") && nav.S.NavStatusLine.Contains("the landscape"), $"status says it too ({nav.S.NavStatusLine})"); + Check.True(nav.S.NavAreaHoldOffersPatrol, "the nav window offers the Patrol button"); + nav.Run(12); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 1, "still one line after 12 s of rechecks"); + Check.Eq(nav.Idx, 1, "the waypoint is kept"); + } + + private static void AreaNoneHereLandscape() + { + FakeHost.Reset(); At(30, 0); + var nav = new Nav(Route(RT.Circular, Pt(0, 0), Pt(50, 0)), idx: 1, planner: new FakePlanner { Area = NavAreaCheck.Mismatch }); + nav.Tick(); + var line = FakeHost.Chat.FirstOrDefault(c => c.Contains("different area")) ?? ""; + Check.True(line.Contains("load a route for here") && !line.Contains("Patrol"), $"load a route, no Patrol on the landscape ({line})"); + Check.False(nav.S.NavAreaHoldOffersPatrol, "no Patrol button"); + } + + private static void AreaReloadAndPatrol() + { + FakeHost.Reset(); At(-500, -500); Indoors(); + var p = AreaWhere((n, e) => n < -400); + var landscape = Route(RT.Circular, Pt(100, 0), Pt(110, 0)); + var nav = new Nav(landscape, idx: 1, planner: p); + nav.Tick(); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 1, "held, said once"); + + // The player loads the same nav file again: a new route object, the same hold - and it says so again. + nav.S.CurrentRoute = Route(RT.Circular, Pt(100, 0), Pt(110, 0)); + nav.Run(0.3); + Check.Eq(FakeHost.Chat.Count(c => c.Contains("different area")), 2, "the load is answered: still nothing here, said again"); + + // Patrol (or a route for this dungeon) replaces it: walks at once, the hold and its button are gone. + nav.S.CurrentRoute = Route(RT.Circular, Pt(-490, -500), Pt(-480, -500)); + nav.S.ActiveNavIndex = 0; + nav.Run(0.5); + Check.True(FakeHost.AutoRun, "walking the route for here"); + Check.Eq(nav.Recovery, "none", "no hold"); + Check.False(nav.S.NavAreaHoldOffersPatrol, "no Patrol button any more"); + } + private static void ContainingCellByFloor() { static RynthCore.Plugin.RynthAi.Raycasting.Vector3[] Sq(float x0, float y0, float x1, float y1, float z) => new[] diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs index 87579f9..3507cf7 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OffhandTests.cs @@ -23,6 +23,8 @@ internal static class OffhandTests private const uint Wcid = 434343; private const uint Sword = 0x80000401, Dagger = 0x80000402, Great = 0x80000403, Shield = 0x80000404, Round = 0x80000405, Bow = 0x80000406, Arrows = 0x80000407, Wand = 0x80000408; + // Two matched pairs of one-handed weapons for dual wield (an element each). + private const uint ColdA = 0x80000411, ColdB = 0x80000412, FireA = 0x80000413, FireB = 0x80000414; private const uint Pack = 0x80000501; private const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000, MissileSlot = 0x00400000, AmmoSlot = 0x00800000, HeldSlot = 0x01000000, TwoHandedSlot = 0x02000000; @@ -37,6 +39,10 @@ internal static class OffhandTests r.Add("swap speed: a weapon in hand -> one use of the wand (the client swaps); the pack move only as the fallback", CasterDirectSwap); r.Add("swap speed: the gate lets the next step go once the server is done, else after 3 s", SwapGateSettles); r.Add("offhand: dual wield with the Dual Wield skill", DualWield); + r.Add("offhand: dual wield pairs, the element changes -> both hands swap to the pair", DualWieldPairSwap); + r.Add("offhand: dual wield pairs, the off hand already right stays (no loop)", DualWieldPairStays); + r.Add("offhand: dual wield pairs, the wanted weapon in the off hand -> its partner goes in the main hand", DualWieldPairPartnerToMain); + r.Add("offhand: element pairs leave shield users and single weapons as they were", PairsLeaveShieldAndSingle); r.Add("offhand: the weapon in hand is the main hand's when the wielded slot reads 0 (the weenie's wielder record)", InHandFromWielderInfo); r.Add("weapons: a weapon refused 'skill too low' is left out of the choice (the off hand stays)", SkillTooLowLeftOut); r.Add("offhand: two weapons wielded and no slot read says which: the one RynthAi put in the off hand is the off hand's", OffhandRemembered); @@ -146,7 +152,7 @@ internal static class OffhandTests private readonly FieldInfo _lastEquip = typeof(CombatManager).GetField("_lastEquipTime", BindingFlags.Instance | BindingFlags.NonPublic)!; public Rig(bool dualWieldSkill = false, bool shieldOn = false, bool wieldCalls = true, bool wielderInfo = false, bool weenieErrors = false, - bool contents = false, bool tracker = false) + bool contents = false, bool tracker = false, bool pairs = false) { FakeHost.Reset(); FakeHost.EquippedCalls = tracker; // v87 GetWieldedItems (answering FakeHost.Equipped) @@ -166,6 +172,13 @@ internal static class OffhandTests Item(Arrows, "Arrow", 0x100, AmmoSlot); FakeHost.Ints[(Arrows, 50)] = 1; FakeHost.Ints[(Arrows, 12)] = 100; FakeHost.Ints[(Arrows, 11)] = 250; Item(Wand, "Wand", 0x8000, HeldSlot); + if (pairs) + { + Item(ColdA, "Cold Sword", 0x1, MeleeSlot, combatUse: 1); + Item(ColdB, "Cold Dagger", 0x1, MeleeSlot, combatUse: 1); + Item(FireA, "Fire Sword", 0x1, MeleeSlot, combatUse: 1); + Item(FireB, "Fire Dagger", 0x1, MeleeSlot, combatUse: 1); + } Wield(Sword, MeleeSlot); if (shieldOn) Wield(Shield, ShieldSlot); FakeHost.Wcids[Monster] = Wcid; @@ -174,7 +187,9 @@ internal static class OffhandTests // ownership read (GetObjectOwnershipInfo: the item's own container field). if (contents) { FakeHost.Names[Pack] = "Pack"; FakeHost.ItemTypes[Pack] = 0x200; FakeHost.Containers[Pack] = Player; } var host = FakeHost.Create(wielderInfo ? Player : 0); - var cache = FakeHost.MakeCache(host, Player, new[] { Sword, Dagger, Great, Shield, Round, Bow, Arrows, Wand }); + var ids = new List { Sword, Dagger, Great, Shield, Round, Bow, Arrows, Wand }; + if (pairs) ids.AddRange(new[] { ColdA, ColdB, FireA, FireB }); + var cache = FakeHost.MakeCache(host, Player, ids.ToArray()); C = new CombatManager(host, S, cache); C.SetPlayerId(Player); C.SetDamageStores(null, Store); @@ -197,6 +212,17 @@ internal static class OffhandTests Action = i == Shield || i == Round ? WeaponList.ShieldAction : "Weapon", }).ToList(); + /// The Items list with an element set on each entry. + public void ListWith(params (uint Id, string Element)[] items) + { + List(items.Select(i => i.Id).ToArray()); + foreach (var (id, elem) in items) S.ItemRules.First(r => r.Id == unchecked((int)id)).Element = elem; + } + + /// This monster's Monsters rule fights with (its DamageType). + public void Element(string element, int offhandId = 0) => + S.MonsterRules = new List { new() { Name = "Default" }, new() { Name = "Test Dummy", DamageType = element, OffhandId = offhandId } }; + public void Rule(int offhandId) => S.MonsterRules = new List { new() { Name = "Default" }, new() { Name = "Test Dummy", OffhandId = offhandId } }; @@ -462,6 +488,174 @@ internal static class OffhandTests Check.Eq(rig2.ShieldWields(Dagger), 1, "Monsters rule 'Offhand weapon': the dagger"); } + // ── Dual wield pairs ────────────────────────────────────────────────────── + + // 2026-11-02 report: a dual-wield character with a matched pair per element (a Cold pair, a + // Fire pair). When the element changed only the main hand swapped; the off hand kept whatever + // it held, because the off-hand pick was "the one already in the off hand, else list order" + // and never looked at the element. + private static (uint, string)[] Pairs => new[] { (ColdA, "Cold"), (ColdB, "Cold"), (FireA, "Fire"), (FireB, "Fire") }; + + private static Rig PairRig(uint main, uint off) + { + var rig = new Rig(dualWieldSkill: true, pairs: true); + Rig.Unwield(Sword); + Rig.Wield(main, MeleeSlot); + Rig.Wield(off, ShieldSlot); + rig.InHand = unchecked((int)main); + rig.S.PreferDualWield = true; + rig.ListWith(Pairs); + return rig; + } + + private static void DualWieldPairSwap() + { + // The pure plan: the main weapon's partner (same element) first, whatever is in the off hand. + var coldA = new OffhandCandidate(30, "Cold Sword", false, false, "Cold"); + var coldB = new OffhandCandidate(31, "Cold Dagger", false, false, "Cold"); + var fireA = new OffhandCandidate(40, "Fire Sword", false, false, "Fire"); + var fireB = new OffhandCandidate(41, "Fire Dagger", false, true, "Fire"); // in the off hand + var pairs = new[] { coldA, coldB, fireA, fireB }; + OffhandPlan P(OffhandMode m, int main, string elem, bool pref = true, int pick = 0, bool isDefault = false) + => OffhandPlanner.Choose(m, MainHandKind.OneHandedMelee, main, pairs, true, pref, true, pick, "pick", elem, isDefault); + Check.Eq(P(OffhandMode.Auto, 30, "Cold").Id, 31, "Auto, dual wield preferred, Cold main: the Cold partner, not the Fire one in the off hand"); + Check.Eq(P(OffhandMode.Weapon, 30, "Cold").Id, 31, "Offhand weapon, Cold main: the Cold partner"); + Check.True(P(OffhandMode.Weapon, 30, "Cold").Source.Contains("Cold"), "the log says why: " + P(OffhandMode.Weapon, 30, "Cold").Source); + Check.Eq(P(OffhandMode.Weapon, 40, "Fire").Id, 41, "Fire main, the Fire partner already in the off hand: it stays"); + Check.Eq(P(OffhandMode.Weapon, 30, "").Id, 41, "main element not known: the one in the off hand stays, as before"); + Check.Eq(P(OffhandMode.Auto, 30, "Cold", pref: false).Id, 0, "Auto, dual wield not preferred, no shield: nothing, as before"); + Check.Eq(P(OffhandMode.Weapon, 30, "Cold", pick: 41).Id, 41, "a pick for this monster wins over the partner"); + Check.Eq(P(OffhandMode.Weapon, 30, "Cold", pick: 41, isDefault: true).Id, 31, "the Default row's pick gives way to the main weapon's partner"); + Check.Eq(P(OffhandMode.Weapon, 30, "Cold", pick: 31, isDefault: true).Id, 31, "the Default row's pick that is the partner: kept"); + Check.Eq(P(OffhandMode.Weapon, 31, "Cold", pick: 31, isDefault: true).Id, 30, "the Default row's pick is the main weapon: the other of its pair"); + + // In combat: the Fire pair in hand, the monster wants Cold. + var rig = PairRig(FireA, FireB); + rig.Element("Cold"); + Check.False(rig.Tick(), "Cold wanted: the main hand swaps"); + Check.Eq(FakeHost.Uses.LastOrDefault(), ColdA, "the main hand: the Cold sword"); + rig.Landed(ColdA, FireA, MeleeSlot); + Check.False(rig.Tick(), "Cold sword in hand: the off hand goes next"); + Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0] == (FireB, Pack, 1), "the Fire dagger into the pack first"); + Rig.Unwield(FireB); + Check.False(rig.Tick(), "off hand empty: the partner goes on"); + Check.Eq(rig.ShieldWields(ColdB), 1, "WieldItem(Cold dagger, Shield slot)"); + Rig.Wield(ColdB, ShieldSlot); + Check.True(rig.Tick(), "the Cold pair in both hands: ready"); + Check.True(FakeHost.Logs.Any(l => l.Contains("off hand for") && l.Contains("Cold Dagger")), "the off-hand choice is logged"); + + // And back to Fire (another fight): both hands again. + rig.C.SwapTracker.MinDwellMs = 0; + rig.C.OffhandTracker.MinDwellMs = 0; + rig.Element("Fire"); + rig.Tick(); + Check.Eq(FakeHost.Uses.LastOrDefault(), FireA, "Fire wanted: the Fire sword"); + rig.Landed(FireA, ColdA, MeleeSlot); + rig.Tick(); + Check.True(FakeHost.Moves.Any(m => m.Id == ColdB), "the Cold dagger comes off"); + Rig.Unwield(ColdB); + rig.Tick(); + Check.Eq(rig.ShieldWields(FireB), 1, "the Fire dagger goes on"); + Rig.Wield(FireB, ShieldSlot); + Check.True(rig.Tick(), "the Fire pair: ready"); + } + + private static void DualWieldPairStays() + { + var rig = PairRig(ColdA, ColdB); + rig.Element("Cold"); + for (int i = 0; i < 10; i++) Check.True(rig.Tick(), $"the Cold pair for a Cold monster: ready (tick {i + 1})"); + Check.Eq(FakeHost.Uses.Count, 0, "no main-hand wield"); + Check.Eq(FakeHost.Wields.Count, 0, "no off-hand wield"); + Check.Eq(FakeHost.Moves.Count, 0, "nothing moved"); + + // The pair in hand the other way round (the B weapon in the main hand): still the pair, left alone. + var rig2 = PairRig(FireB, FireA); + rig2.Element("Fire"); + for (int i = 0; i < 10; i++) rig2.Tick(); + Check.True(rig2.Tick(), "the Fire pair, either way round: ready"); + Check.Eq(FakeHost.Uses.Count + FakeHost.Wields.Count + FakeHost.Moves.Count, 0, "no swap, no loop"); + + // After a swap to the pair, ticks on do nothing more (each swap pays a stance change). + var rig3 = PairRig(FireA, FireB); + rig3.Element("Cold"); + rig3.Tick(); + rig3.Landed(ColdA, FireA, MeleeSlot); + rig3.Tick(); + Rig.Unwield(FireB); + rig3.Tick(); + Rig.Wield(ColdB, ShieldSlot); + int uses = FakeHost.Uses.Count, wields = FakeHost.Wields.Count, moves = FakeHost.Moves.Count; + for (int i = 0; i < 20; i++) Check.True(rig3.Tick(), $"converged: ready (tick {i + 1})"); + Check.Eq(FakeHost.Uses.Count, uses, "no further main-hand wields"); + Check.Eq(FakeHost.Wields.Count, wields, "no further off-hand wields"); + Check.Eq(FakeHost.Moves.Count, moves, "no further moves"); + } + + private static void DualWieldPairPartnerToMain() + { + // The Cold sword with the Fire dagger (half a swap, say), the Fire dagger listed first: the + // weapon choice wants it, and it already swings in the off hand. Its partner, the Fire sword, + // goes in the main hand; the off hand stays. Before, combat fought on with Cold + Fire. + var rig = new Rig(dualWieldSkill: true, pairs: true); + Rig.Unwield(Sword); + Rig.Wield(ColdA, MeleeSlot); + Rig.Wield(FireB, ShieldSlot); + rig.InHand = unchecked((int)ColdA); + rig.S.PreferDualWield = true; + rig.ListWith((FireB, "Fire"), (FireA, "Fire"), (ColdA, "Cold"), (ColdB, "Cold")); + rig.Element("Fire"); + Check.Eq(unchecked((uint)rig.C.PlanFor(rig.Target, rig.S.MonsterRules[1]).WeaponId), FireB, "the plan: the Fire dagger (listed first)"); + Check.False(rig.Tick(), "not ready: the main hand swaps"); + Check.Eq(FakeHost.Uses.LastOrDefault(), FireA, "the main hand: the Fire dagger's partner, the Fire sword"); + Check.Eq(FakeHost.Moves.Count, 0, "the Fire dagger isn't moved out of the off hand"); + Check.True(FakeHost.Logs.Any(l => l.Contains("its partner") && l.Contains("Fire Sword")), "logged"); + rig.Landed(FireA, ColdA, MeleeSlot); + for (int i = 0; i < 5; i++) Check.True(rig.Tick(), $"the Fire pair: ready (tick {i + 1})"); + Check.Eq(FakeHost.Wields.Count, 0, "the off hand was right: no off-hand wield"); + Check.Eq(FakeHost.Moves.Count, 0, "nothing moved"); + } + + private static void PairsLeaveShieldAndSingle() + { + // A shield user with a Cold and a Fire sword (dual wield skill, not preferred): the shield + // stays through element changes; only the main hand swaps. + var rig = new Rig(dualWieldSkill: true, shieldOn: true, pairs: true); + Rig.Unwield(Sword); + Rig.Wield(FireA, MeleeSlot); + rig.InHand = unchecked((int)FireA); + rig.ListWith((ColdA, "Cold"), (FireA, "Fire"), (Shield, "")); + rig.Element("Cold"); + rig.Tick(); + Check.Eq(FakeHost.Uses.LastOrDefault(), ColdA, "the main hand: the Cold sword"); + rig.Landed(ColdA, FireA, MeleeSlot); + for (int i = 0; i < 5; i++) Check.True(rig.Tick(), $"Cold sword and shield: ready (tick {i + 1})"); + Check.Eq(FakeHost.Wields.Count, 0, "the shield stays: no off-hand wield"); + Check.Eq(FakeHost.Moves.Count, 0, "nothing moved"); + + // Offhand Shield with dual wield preferred and a Cold pair listed: still the shield. + var rig2 = new Rig(dualWieldSkill: true, shieldOn: true, pairs: true); + Rig.Unwield(Sword); + Rig.Wield(ColdA, MeleeSlot); + rig2.InHand = unchecked((int)ColdA); + rig2.S.PreferDualWield = true; + rig2.ListWith((ColdA, "Cold"), (ColdB, "Cold"), (Shield, "")); + rig2.Element("Cold", OffhandRules.RuleShield); + for (int i = 0; i < 5; i++) Check.True(rig2.Tick(), $"Offhand Shield: sword and shield, ready (tick {i + 1})"); + Check.Eq(FakeHost.Wields.Count + FakeHost.Moves.Count, 0, "the Cold dagger never goes on"); + + // One weapon listed: it stays, nothing goes in the off hand. + var rig3 = new Rig(dualWieldSkill: true, pairs: true); + Rig.Unwield(Sword); + Rig.Wield(ColdA, MeleeSlot); + rig3.InHand = unchecked((int)ColdA); + rig3.S.PreferDualWield = true; + rig3.ListWith((ColdA, "Cold")); + rig3.Element("Fire"); + for (int i = 0; i < 5; i++) Check.True(rig3.Tick(), $"a single weapon: ready (tick {i + 1})"); + Check.Eq(FakeHost.Uses.Count + FakeHost.Wields.Count + FakeHost.Moves.Count, 0, "nothing wielded or moved"); + } + // 2026-10-16: Drakkon dual wielding two Hand Wraps; CurrentWieldedLocation read 0, so both // counted as in hand and the later listed one (the off hand's) was taken for the main weapon. private static void InHandFromWielderInfo() diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs new file mode 100644 index 0000000..347af23 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/OutdoorHuntTests.cs @@ -0,0 +1,358 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// Outdoor hunting (2026-10-23): walk from monster to monster around obstacles on RynthNav's map. +// The path function here plays RynthNav: by default a straight walk, with per-monster overrides (a +// building in the way makes the walk long; a cliff makes it impossible). +internal static class OutdoorHuntTests +{ + public static void Register(Runner r) + { + r.Add("hunt: the next monster is the shortest walk, not the nearest in a straight line (one behind a building)", ShortestWalk); + r.Add("hunt: a higher Priority comes first, whatever the walk", PriorityFirst); + r.Add("hunt: no way to a monster (a cliff, water): left out for a while; a walk ending close enough still counts", Unreachable); + r.Add("hunt: it stays within Hunt Radius of where it started (0 = anywhere)", Radius); + r.Add("hunt: plans again when the monster moves, the walk runs out, or a while passes; not every tick", Replan); + r.Add("hunt: nothing in range: it waits where it is (no walk back to the start); Hunt Radius defaults to anywhere", WaitsWhereItIs); + r.Add("hunt: /ra hunt range|radius answer and cap; status and stop don't toggle it; panel opens the window", Commands); + r.Add("hunt: the target dies: the next one; no pathfinder: it stands", NextAndNoPathfinder); + r.Add("hunt: the settings round-trip with the rest (saved, copied, engine payload)", Settings); + r.Add("hunt (test 10-23): a monster 12 yd away but a 143 yd walk is too far round; the one being walked to is kept past Hunt Range", FarRound); + r.Add("hunt (test 10-23): at a wall with the monster on its far side: no 1 yd walks every half second; left out after NoFightSec", WallBetween); + r.Add("hunt: a monster right beside it that combat doesn't take: stands, then leaves it out", RightHere); + r.Add("hunt (test 10-23): in a building it walks back out the way it went in (the loops it made cut out)", WayBackOut); + r.Add("hunt: in a building with no way in known, or the walks out ending still inside: it waits", IndoorsWaits); + } + + private static void WallBetween() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + nav.Walls[(1010, 1000)] = (V(1008.7, 1000), 1.3); // behind a wall: the walk ends 1.3 yd short, on this side + var list = Sorted(C(1, 1010, 1000, me), C(2, 1000, 1030, me)); + var d = h.Tick(T0, me, true, list, nav.Path); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 1, "walks to the nearer one (its walk ends close enough to count)"); + // At the wall: combat can't see through it, so the hunt is asked again and again. + var atWall = V(1008.7, 1000); + var walks = 0; + for (double t = 3; t < 3 + h.NoFightSec - 0.1; t += 0.25) + { + d = h.Tick(T0.AddSeconds(t), atWall, true, Sorted(C(1, 1010, 1000, atWall), C(2, 1000, 1030, atWall)), nav.Path); + if (d.Act == OutdoorHunt.Act.Walk) walks++; + } + Check.Eq(walks, 0, "no 1 yd walks at the wall"); + Check.Eq(h.TargetId, 1, "still its target while combat has the time to take it"); + h.ClearNotes(); + d = h.Tick(T0.AddSeconds(3.5 + h.NoFightSec), atWall, true, Sorted(C(1, 1010, 1000, atWall), C(2, 1000, 1030, atWall)), nav.Path); + Check.True(h.IsSkipped(1, T0.AddSeconds(30)), "left out after NoFightSec"); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 2, $"and on to the other one at once: {d.Act} {d.TargetId}"); + var notes = string.Join(" | ", h.PendingNotes); + Check.True(h.PendingNotes.Count == 2 && h.PendingNotes[0].Contains("wall") && h.PendingNotes[1].StartsWith("next: 'Monster 2'"), + "both logged, the why first: " + notes); + } + + private static void RightHere() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + var d = h.Tick(T0, me, true, Sorted(C(1, 1001.5, 1000, me)), nav.Path); + Check.True(d.Act == OutdoorHunt.Act.Idle && d.TargetId == 1, $"1.5 yd away: no walk, it stands with it as the target ({d.Act} {d.TargetId})"); + d = h.Tick(T0.AddSeconds(1), me, true, Sorted(C(1, 1001.5, 1000, me)), nav.Path); + Check.True(d.Act != OutdoorHunt.Act.Walk && !h.IsSkipped(1, T0.AddSeconds(1)), "a second: still waiting for combat"); + h.Tick(T0.AddSeconds(h.NoFightSec + 0.6), me, true, Sorted(C(1, 1001.5, 1000, me)), nav.Path); + Check.True(h.IsSkipped(1, T0.AddSeconds(h.NoFightSec + 1)), "combat never took it: left out"); + } + + private static void WayBackOut() + { + var h = new OutdoorHunt(); + h.Start(T0, V(990, 1000)); + h.Track(V(1000, 1000), indoors: false); // the last spot outdoors, at the doorway + for (int x = 1001; x <= 1010; x++) h.Track(V(x, 1000), indoors: true); + h.Track(V(1010, 1002), indoors: true); // a fight took it up a side room... + h.Track(V(1010, 1004), indoors: true); + h.Track(V(1010, 1000.5), indoors: true); // ...and back + Check.Eq(h.WayInSteps, 6, "the side room is cut out of the way in (the door and 5 steps)"); + var me = V(1010, 1000.5); + var d = h.Indoors(T0, me, routeDone: true); + Check.Eq(d.Act, OutdoorHunt.Act.Walk, "walks out"); + var want = new[] { V(1008, 1000), V(1006, 1000), V(1004, 1000), V(1002, 1000), V(1000, 1000), V(1000 - h.OutPastYd, 1000) }; + Check.True(d.Corners!.SequenceEqual(want), "the way in backwards, then out past the doorway: " + string.Join(" ", d.Corners!.Select(c => $"{c.X:0.#},{c.Y:0.#}"))); + Check.True(h.WalkingOut && h.Note.Contains("back out"), "walking out: " + h.Note); + Check.Eq(h.Indoors(T0.AddSeconds(2), V(1005, 1000), routeDone: false).Act, OutdoorHunt.Act.None, "on the way: keeps walking"); + h.Track(V(996, 1000), indoors: false); + Check.False(h.WalkingOut, "outdoors again: done"); + Check.Eq(h.WayInSteps, 0, "and the way in forgotten"); + } + + private static void IndoorsWaits() + { + var never = new OutdoorHunt(); + never.Start(T0, V(1000, 1000)); + never.Track(V(1005, 1000), indoors: true); // never seen outdoors (a reload inside, say) + var d = never.Indoors(T0, V(1005, 1000), routeDone: true); + Check.Eq(d.Act, OutdoorHunt.Act.Idle, "no way in known: waits"); + Check.True(never.Note.Contains("no way out known"), never.Note); + + var h = new OutdoorHunt(); + h.Start(T0, V(990, 1000)); + h.Track(V(1000, 1000), indoors: false); + h.Track(V(1003, 1000), indoors: true); + var t = T0; + for (int i = 0; i < h.OutTriesMax; i++) + { + d = h.Indoors(t, V(1003, 1000), routeDone: true); + Check.Eq(d.Act, OutdoorHunt.Act.Walk, $"walk out {i + 1}"); + t = t.AddSeconds(5); + // It got to the end of the walk and the cell still says indoors. + d = h.Indoors(t, d.Corners![^1], routeDone: true); + if (i < h.OutTriesMax - 1) Check.Eq(d.Act, OutdoorHunt.Act.Walk, $"ended still inside: again ({i + 2})"); + t = t.AddSeconds(5); + if (d.Act != OutdoorHunt.Act.Walk) break; + } + Check.Eq(d.Act, OutdoorHunt.Act.Idle, $"after {h.OutTriesMax} walks out ending inside: waits"); + Check.True(h.Note.Contains("ended still inside"), h.Note); + } + + private static readonly DateTime T0 = new(2026, 10, 23, 16, 0, 0); + private static OutdoorHunt.Vec V(double x, double y) => new(x, y, 0); + + private static OutdoorHunt.Candidate C(int id, double x, double y, OutdoorHunt.Vec me, int priority = 1, string? name = null) + => new(id, name ?? $"Monster {id}", V(x, y), V(x, y).DistanceTo(me), priority); + + private sealed class Nav + { + public readonly Dictionary<(double, double), OutdoorHunt.PathResult> Overrides = new(); + /// A wall just in front of a monster: every walk to it ends at end, gap short. + public readonly Dictionary<(double, double), (OutdoorHunt.Vec End, double Gap)> Walls = new(); + public int Calls; + public bool Unavailable; + + public OutdoorHunt.PathResult Path(OutdoorHunt.Vec a, OutdoorHunt.Vec b) + { + Calls++; + if (Unavailable) return new(OutdoorHunt.PathStatus.Unavailable, Array.Empty(), 0, 0); + if (Overrides.TryGetValue((b.X, b.Y), out var o)) return o; + if (Walls.TryGetValue((b.X, b.Y), out var w)) return new(OutdoorHunt.PathStatus.Partial, new[] { w.End }, a.DistanceTo(w.End), w.Gap); + return new(OutdoorHunt.PathStatus.Ok, new[] { b }, a.DistanceTo(b), 0); + } + + public void Around(double x, double y, double length) => + Overrides[(x, y)] = new(OutdoorHunt.PathStatus.Ok, new[] { V(x + 5, y + 5), V(x, y) }, length, 0); + } + + private static List Sorted(params OutdoorHunt.Candidate[] c) => c.OrderBy(x => x.Distance).ToList(); + + private static void ShortestWalk() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + nav.Around(1010, 1000, 45); // 10 yd away, a building between: a 45 yd walk + var list = Sorted(C(1, 1010, 1000, me), C(2, 1000, 1018, me)); + var d = h.Tick(T0, me, true, list, nav.Path); + Check.Eq(d.Act, OutdoorHunt.Act.Walk, "walks"); + Check.Eq(d.TargetId, 2, "to the one 18 yd away in the open, not the one 10 yd away behind the building"); + Check.True(h.Note.Contains("18 yd walk"), "logged: " + h.Note); + Check.Eq(d.Corners!.Last(), V(1000, 1018), "the walk ends at the monster"); + } + + private static void PriorityFirst() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + var d = h.Tick(T0, me, true, Sorted(C(1, 1005, 1000, me, priority: 1), C(2, 1030, 1000, me, priority: 5)), nav.Path); + Check.Eq(d.TargetId, 2, "Priority 5 at 30 yd before Priority 1 at 5 yd"); + } + + private static void Unreachable() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + nav.Overrides[(1008, 1000)] = new(OutdoorHunt.PathStatus.NoPath, Array.Empty(), 0, 0); // up a cliff + nav.Overrides[(1012, 1000)] = new(OutdoorHunt.PathStatus.Partial, new[] { V(1004, 1000) }, 4, 8); // in water: the walk ends 8 yd short + nav.Overrides[(1020, 1000)] = new(OutdoorHunt.PathStatus.Partial, new[] { V(1018, 1000) }, 18, 2); // on a rock: 2 yd short is close enough + var list = Sorted(C(1, 1008, 1000, me), C(2, 1012, 1000, me), C(3, 1020, 1000, me)); + var d = h.Tick(T0, me, true, list, nav.Path); + Check.Eq(d.TargetId, 3, "the one whose walk ends 2 yd short; the cliff and the water ones are left out"); + Check.True(h.IsSkipped(1, T0.AddSeconds(60)) && h.IsSkipped(2, T0.AddSeconds(60)), "left out for a while"); + Check.False(h.IsSkipped(1, T0.AddSeconds(h.SkipSec + 1)), "and tried again after SkipSec"); + } + + private static void Radius() + { + var start = V(1000, 1000); + var h = new OutdoorHunt { RadiusYd = 50, RangeYd = 100 }; + h.Start(T0, start); + var nav = new Nav(); + var me = V(1040, 1000); // hunted out to 40 yd east + var d = h.Tick(T0, me, true, Sorted(C(1, 1070, 1000, me), C(2, 1000, 1030, me)), nav.Path); + Check.Eq(d.TargetId, 2, "the one 70 yd from the start is outside the 50 yd radius, even though it is closer"); + var any = new OutdoorHunt { RadiusYd = 0, RangeYd = 100 }; + any.Start(T0, start); + Check.Eq(any.Tick(T0, me, true, Sorted(C(1, 1070, 1000, me), C(2, 1000, 1030, me)), nav.Path).TargetId, 1, "radius 0: anywhere, the nearest walk"); + } + + private static void Replan() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + Check.Eq(h.Tick(T0, me, true, Sorted(C(1, 1030, 1000, me)), nav.Path).Act, OutdoorHunt.Act.Walk, "walks to it"); + int calls = nav.Calls; + // Walking; it moved 2 yd: not worth a new plan. + var d = h.Tick(T0.AddSeconds(2), V(1005, 1000), false, Sorted(C(1, 1032, 1000, me)), nav.Path); + Check.Eq(d.Act, OutdoorHunt.Act.None, "it moved 2 yd: keep walking"); + Check.Eq(nav.Calls, calls, "no path asked for"); + // It moved 6 yd: plan again. + d = h.Tick(T0.AddSeconds(3), V(1008, 1000), false, Sorted(C(1, 1036, 1000, me)), nav.Path); + Check.Eq(d.Act, OutdoorHunt.Act.Walk, "it moved 6 yd: a new walk"); + Check.Eq(d.Corners!.Last(), V(1036, 1000), "to where it is now"); + // Within a second: not again, even if it moves. + d = h.Tick(T0.AddSeconds(3.5), V(1009, 1000), false, Sorted(C(1, 1045, 1000, me)), nav.Path); + Check.Eq(d.Act, OutdoorHunt.Act.None, "not twice in a second"); + // The walk ran out short of it (the monster still out of combat's reach): plan again. + d = h.Tick(T0.AddSeconds(4.2), V(1030, 1000), true, Sorted(C(1, 1036, 1000, me)), nav.Path); + Check.Eq(d.Act, OutdoorHunt.Act.Walk, "the walk ran out: again"); + // Nothing changed for ReplanMaxSec: again anyway. + d = h.Tick(T0.AddSeconds(4.2 + h.ReplanMaxSec + 0.1), V(1030, 1000), false, Sorted(C(1, 1036, 1000, me)), nav.Path); + Check.Eq(d.Act, OutdoorHunt.Act.Walk, "a while with no change: again"); + } + + // Tom 10-23: no walk back to the start ("it shouldn't bother"). + private static void WaitsWhereItIs() + { + var start = V(1000, 1000); + var h = new OutdoorHunt { RadiusYd = 100 }; + h.Start(T0, start); + var nav = new Nav(); + var me = V(1060, 1000); + h.ClearNotes(); + var d = h.Tick(T0, me, true, new List(), nav.Path); + Check.Eq(d.Act, OutdoorHunt.Act.Idle, "nothing to hunt, 60 yd from the start: waits there, no walk back"); + Check.Eq(nav.Calls, 0, "no path asked for"); + Check.True(h.Note.Contains("waiting here") && h.Note.Contains($"({h.RangeYd:0} yd)"), "says why, with Hunt Range: " + h.Note); + h.Tick(T0.AddSeconds(2), me, true, new List(), nav.Path); + Check.Eq(h.PendingNotes.Count, 1, "said once, not every second"); + // A monster comes into range: hunted from there. + d = h.Tick(T0.AddSeconds(4), me, true, Sorted(C(7, 1060, 1025, me)), nav.Path); + Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId == 7, $"a monster turns up: hunted ({d.Act} {d.TargetId})"); + Check.Eq(new OutdoorHunt().RadiusYd, 0.0, "Hunt Radius defaults to 0 (anywhere)"); + } + + // Tom 10-23: "/mt opt set" gave no answer, and "/ra hunt status" toggled the hunt (the command read + // the word "hunt" as its argument). The /ra hunt settings answer, and status/stop don't start it. + private static void Commands() + { + const System.Reflection.BindingFlags Any = System.Reflection.BindingFlags.Instance + | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public; + RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset(); + var host = RynthCore.RynthAiHostTests.Fakes.FakeHost.Create(); + var p = new RynthAiPlugin(); + typeof(RynthCore.PluginCore.RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { RynthCore.RynthAiHostTests.Fakes.FakeHost.LastApi }); + var dash = new LegacyDashboardRenderer(host); + typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash); + var chat = RynthCore.RynthAiHostTests.Fakes.FakeHost.Chat; + void Ra(string line) + { + chat.Clear(); + string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, new object[] { parts[1].ToLowerInvariant(), parts, 0 }); + } + string All() => string.Join(" | ", chat); + + Ra("/ra hunt range 150"); + Check.Eq(dash.Settings.OutdoorHuntRange, 150f, "range set"); + Check.True(All().Contains("Outdoor hunt set") && All().Contains("150 yd (Hunt Range)"), "and said: " + All()); + Ra("/ra hunt range 2000"); + Check.Eq(dash.Settings.OutdoorHuntRange, 2000f, "2000 is allowed (Tom 10-23)"); + Ra("/ra hunt range 5000"); + Check.Eq(dash.Settings.OutdoorHuntRange, (float)RynthAiPlugin.OutdoorHuntRangeMax, "capped at the most"); + Check.True(All().Contains("outside"), "and says it was capped: " + All()); + Ra("/ra hunt radius 0"); + Check.True(dash.Settings.OutdoorHuntRadius == 0 && All().Contains("anywhere"), "radius 0 = anywhere: " + All()); + Ra("/ra hunt range"); + Check.True(All().Contains("Hunt Range") && All().Contains("/ra hunt range "), "no number: shows the setting: " + All()); + Ra("/ra hunt status"); + Check.False(p.HuntActive, "status doesn't start it"); + Check.True(All().Contains("Outdoor hunt: off") && All().Contains("Hunt Range"), "status says off, with the distances: " + All()); + Ra("/ra hunt stop"); + Check.False(p.HuntActive, "stop doesn't start it"); + Ra("/ra hunt nonsense"); + Check.True(All().Contains("/ra hunt range "), "anything else: the usage: " + All()); + Ra("/ra hunt panel"); + Check.True((bool)typeof(RynthAiPlugin).GetField("_huntPanelOpen", Any)!.GetValue(p)!, "panel opens the window"); + } + + private static void NextAndNoPathfinder() + { + var me = V(1000, 1000); + var h = new OutdoorHunt(); + h.Start(T0, me); + var nav = new Nav(); + Check.Eq(h.Tick(T0, me, true, Sorted(C(1, 1010, 1000, me), C(2, 1030, 1000, me)), nav.Path).TargetId, 1, "the nearer first"); + // It died (combat killed it; it is gone from the list): the next one. + var d = h.Tick(T0.AddSeconds(10), V(1009, 1000), true, Sorted(C(2, 1030, 1000, V(1009, 1000))), nav.Path); + Check.Eq(d.TargetId, 2, "killed: on to the next"); + var none = new OutdoorHunt(); + none.Start(T0, me); + var gone = new Nav { Unavailable = true }; + d = none.Tick(T0, me, true, Sorted(C(1, 1010, 1000, me)), gone.Path); + Check.Eq(d.Act, OutdoorHunt.Act.Idle, "RynthNav missing: stands"); + Check.Eq(d.Why, "no pathfinder", "and says why"); + } + + private static void FarRound() + { + var me = V(1000, 1000); + var h = new OutdoorHunt { RangeYd = 60 }; + h.Start(T0, me); + var nav = new Nav(); + nav.Around(1012, 1000, 143); // a buff bot inside a building: 12 yd away, a 143 yd walk + var d = h.Tick(T0, me, true, Sorted(C(1, 1012, 1000, me), C(2, 1040, 1000, me)), nav.Path); + Check.Eq(d.TargetId, 2, "the 143 yd walk (over twice Hunt Range) is too far round: the one 40 yd away instead"); + Check.True(h.IsSkipped(1, T0.AddSeconds(30)), "and it is left out for a while (no choosing it again every second)"); + Check.True(h.Note.Contains("40 yd walk"), "logged: " + h.Note); + // Walking round to the 40 yd one took the character 70 yd from it (past Hunt Range): still its target. + var far = V(970, 1000); + var c2 = new OutdoorHunt.Candidate(2, "Monster 2", V(1040, 1000), 70, 1); + d = h.Tick(T0.AddSeconds(2), far, false, new List { c2 }, nav.Path); + Check.True(d.Act != OutdoorHunt.Act.Idle && h.TargetId == 2, $"kept at 70 yd (Hunt Range 60): {d.Act}, target {h.TargetId}"); + } + + private static void Settings() + { + var s = new LegacyUiSettings(); + // 2026-10-25 (Tom: "the entire radar range"): 192, the radar's default range (was 60). + Check.Eq(s.OutdoorHuntRange, 192f, "Hunt Range defaults to 192 yd, the radar's range"); + Check.Eq(new OutdoorHunt().RangeYd, 192.0, "and the hunt's own default too"); + Check.Eq(s.OutdoorHuntRadius, 0f, "Hunt Radius defaults to 0 (anywhere)"); + var ctx = RynthAiJsonContext.Default.LegacyUiSettings; + var saved = System.Text.Json.JsonSerializer.Deserialize( + System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { OutdoorHuntRange = 90, OutdoorHuntRadius = 250 }, ctx), ctx)!; + var live = new LegacyUiSettings(); + typeof(LegacyDashboardRenderer).GetMethod("CopySettings", + System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)! + .Invoke(null, new object[] { saved, live }); + Check.True(live.OutdoorHuntRange == 90 && live.OutdoorHuntRadius == 250, "saved and copied"); + // A file saved before 10-23 evening still has "OutdoorHuntReturn": it loads (the setting is gone). + var old = System.Text.Json.JsonSerializer.Deserialize("{\"OutdoorHuntRange\":70,\"OutdoorHuntRadius\":2000,\"OutdoorHuntReturn\":true}", ctx); + Check.True(old != null && old.OutdoorHuntRange == 70 && old.OutdoorHuntRadius == 2000, "an old file with Back To Start loads"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PatrolModeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolModeTests.cs new file mode 100644 index 0000000..63d5992 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PatrolModeTests.cs @@ -0,0 +1,138 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.PluginCore; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The Dungeon Patrol as the chosen mode (2026-11-01): it stays the route through a macro stop and +// start, ends (said in chat) only when another route is loaded in its place, and follows the +// character through a portal into another dungeon (not after a death). The patrol tick +// (TickDunPatrolHazardReroute) is driven directly, as ServerPolicyTests does. +internal static class PatrolModeTests +{ + private const uint Player = 0x50000D01; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public; + private const uint PatrolCell = 0x57560124, OtherDungeonCell = 0x00830188, OutdoorCell = 0xC4B60002; + + public static void Register(Runner r) + { + r.Add("patrol mode: a macro stop and start keeps the patrol as the route and as the mode", StopStartKeepsPatrol); + r.Add("patrol mode: a nav file loaded in its place ends it, said in chat with the file's name", ReplacedSaysSo); + r.Add("patrol mode: through a portal taken while it runs it follows into another dungeon; not after a death or with the macro off, not into a building, once per dungeon", FollowDecision); + } + + private sealed class Rig + { + public readonly RynthAiPlugin P = new(); + public readonly LegacyUiSettings S = new() { IsMacroRunning = true, EnableNavigation = true }; + + public Rig() + { + FakeHost.Reset(); + ServerPolicy.Forget(); + FakeHost.WorldName = "Conquest"; + FakeHost.Names[Player] = "Mage"; + FakeHost.PlayerPose = (PatrolCell, 70f, -80f, 0f); + FakeHost.Create(Player); + typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi }); + var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer)); + typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S); + typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(P, dash); + } + + private object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P); + private void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v); + + public bool Active => (bool)Get("_dunPatrolActive")!; + public void Tick() => typeof(RynthAiPlugin).GetMethod("TickDunPatrolHazardReroute", Any)!.Invoke(P, null); + + /// A patrol as BuildDunPatrol leaves it: the route, its object remembered, nav on, this dungeon. + public NavRouteParser RunningPatrol() + { + var route = new NavRouteParser { RouteType = NavRouteType.Circular }; + route.Points.Add(new NavPoint { NS = -33.3, EW = -32.3 }); + route.Points.Add(new NavPoint { NS = -33.2, EW = -32.3 }); + S.CurrentNavPath = string.Empty; + S.CurrentRoute = route; + Set("_dunPatrolActive", true); + Set("_dunPatrolRoute", route); + Set("_dunPatrolLandblock", PatrolCell >> 16); + return route; + } + } + + private static bool Said(string text) => FakeHost.Chat.Exists(l => l.Contains(text, StringComparison.Ordinal)); + + private static void StopStartKeepsPatrol() + { + var b = new Rig(); + var patrol = b.RunningPatrol(); + b.Tick(); + Check.True(b.Active, "running: the patrol is the mode"); + + b.S.IsMacroRunning = false; // the player stops the macro + b.Tick(); + Check.True(b.Active, "stopped: still the mode (it used to be stood down here)"); + Check.True(ReferenceEquals(b.S.CurrentRoute, patrol), "and still the route"); + + b.S.IsMacroRunning = true; // ... and starts it again + b.Tick(); + Check.True(b.Active, "started again: the patrol carries on"); + Check.True(ReferenceEquals(b.S.CurrentRoute, patrol), "the same route, not the nav file loaded before it"); + + b.S.EnableNavigation = false; b.Tick(); b.S.EnableNavigation = true; b.Tick(); + Check.True(b.Active, "nav switched off and on: the same"); + Check.False(Said("Dungeon Patrol ended"), "nothing said"); + } + + private static void ReplacedSaysSo() + { + var b = new Rig(); + b.RunningPatrol(); + b.Tick(); + // The player picks a nav file (LoadSelectedNav: the path and a new route). + var file = new NavRouteParser { RouteType = NavRouteType.Circular }; + file.Points.Add(new NavPoint { NS = 42.4, EW = 54.9 }); + b.S.CurrentNavPath = @"C:\Games\RynthSuite\RynthAi\NavProfiles\ToSomewhere.nav"; + b.S.CurrentRoute = file; + b.Tick(); + Check.False(b.Active, "the patrol ended"); + Check.True(Said("Dungeon Patrol ended: nav route 'ToSomewhere' is the route now"), "said in chat, naming the file"); + Check.True(FakeHost.Logs.Exists(l => l.Contains("DunNav-Patrol: ended")), "and logged"); + Check.True(ReferenceEquals(b.S.CurrentRoute, file), "the loaded route is left alone"); + + // A meta's route in its place is named as the meta's. + var m = new Rig(); + m.RunningPatrol(); + var emb = new NavRouteParser { RouteType = NavRouteType.Linear }; + emb.Points.Add(new NavPoint { NS = 1, EW = 1 }); + m.S.CurrentNavPath = ""; + m.S.CurrentRoute = emb; + m.Tick(); + Check.True(Said("the meta's route 'Hunt'"), "a meta's route is named as the meta's"); + } + + private static void FollowDecision() + { + uint patrolLb = PatrolCell >> 16; + var F = RynthAiPlugin.PatrolFollow.Follow; + var N = RynthAiPlugin.PatrolFollow.None; + var D = RynthAiPlugin.PatrolFollow.AfterDeath; + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, uint.MaxValue, -1, true), F, "portalled into another dungeon while running: follow"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, uint.MaxValue, -1, false), RynthAiPlugin.PatrolFollow.CameWhileStopped, "got there with the macro off (a failsafe recall, by hand): says so, doesn't follow"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, PatrolCell + 5, true, false, uint.MaxValue, -1, true), N, "same dungeon: nothing"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OutdoorCell, false, false, uint.MaxValue, -1, true), N, "the landscape: nothing (nav holds and says so)"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, 0xC4B60105, false, false, uint.MaxValue, -1, true), N, "a building on the landscape: not a dungeon"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, true, uint.MaxValue, -1, true), N, "mid-portal: wait"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, OtherDungeonCell >> 16, -1, true), N, "tried there already: once per dungeon"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, uint.MaxValue, 30_000, true), D, "30 s after a death: says so, doesn't follow"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, OtherDungeonCell, true, false, uint.MaxValue, RynthAiPlugin.PatrolFollowDeathMs + 1, true), F, "long after a death: follows"); + Check.Eq(RynthAiPlugin.DecidePatrolFollow(patrolLb, 0, true, false, uint.MaxValue, -1, true), N, "no pose: nothing"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs index d0e3650..3e30d9f 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs @@ -41,6 +41,19 @@ internal static class PetRefillTests r.Add("pets: the server's 'full' trust expires after 30 min", TrustExpires); r.Add("pets: a landed summon whose pet is not in the cache yet holds a second essence back for the 10 s window", LandedSummonHoldsWindow); r.Add("pets: failed summon (no charge drop) does not assume a pet; waits the 45 s essence cooldown", FailedSummonRespectsCooldown); + r.Add("pets: Boost Nav Priority on (RynthAi only navigates): no summon with a monster near; off: it summons", BoostNavNoSummon); + } + + // Owner's rule (2026-11-02): with Boost Nav Priority on there is no fight, so no pet is called for one. + private static void BoostNavNoSummon() + { + using var rig = new Rig(charges: 50); + rig.S.BoostNavPriority = true; + rig.Run(5000); + Check.Eq(rig.AllSummons, 0, "flag on: no summon in 5 s with the monster 3 m away"); + rig.S.BoostNavPriority = false; + rig.Run(1500); + Check.Eq(rig.Summons, 1, "flag off: it summons"); } // ── Rig ─────────────────────────────────────────────────────────────── diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/VTankHotkeyTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/VTankHotkeyTests.cs index 881d261..9e87955 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/VTankHotkeyTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/VTankHotkeyTests.cs @@ -388,6 +388,7 @@ internal static class VTankHotkeyTests bot.UseGemProfile(); bot.S.IsMacroRunning = false; bot.S.EnableLooting = false; + bot.S.LootChestsMacroOff = false; // the chest waits for LootThisCont (Pickup with macro off would take it) bot.Create(Chest, Gem, Spoon); FakeHost.GroundContainer = Chest; bot.P.OnViewObjectContents(Chest); diff --git a/Tools/RynthNav.GraphTests/Program.cs b/Tools/RynthNav.GraphTests/Program.cs index 2dc9560..1b2b04e 100644 --- a/Tools/RynthNav.GraphTests/Program.cs +++ b/Tools/RynthNav.GraphTests/Program.cs @@ -8,6 +8,7 @@ using DotRecast.Recast.Toolset; using DotRecast.Recast.Toolset.Builder; using RynthNav.Baker; using RynthNav.Routing; +using RynthCore.Plugin.Shared; internal static class Program { @@ -36,8 +37,20 @@ internal static class Program Run(nameof(RouteFollower), RouteFollower); Run(nameof(EndToEndAroundAWall), EndToEndAroundAWall); Run(nameof(LandmassesAndSameLand), LandmassesAndSameLand); + Run(nameof(FencedInGoalMovesToReachableGround), FencedInGoalMovesToReachableGround); + Run(nameof(RealFencedInGoal), RealFencedInGoal); Run(nameof(PathGoesRoundAPortal), PathGoesRoundAPortal); Run(nameof(TripWalkFromTileFiles), TripWalkFromTileFiles); + Run(nameof(PathInterfaceVersions), PathInterfaceVersions); + Run(nameof(PathTileBox), PathTileBox); + Run(nameof(PathExOpenFloorAndInfo), PathExOpenFloorAndInfo); + Run(nameof(PathExRoundAPortal), PathExRoundAPortal); + Run(nameof(PathExPartial), PathExPartial); + Run(nameof(PathExNoMeshAndStartSnap), PathExNoMeshAndStartSnap); + Run(nameof(PathExWallsAndBuffer), PathExWallsAndBuffer); + Run(nameof(RaycastOnTheMesh), RaycastOnTheMesh); + Run(nameof(RealPathEx), RealPathEx); + Run(nameof(RealDoorsteps), RealDoorsteps); Run(nameof(RealTripWalk), RealTripWalk); Run(nameof(MeshViewFloorAndWalls), MeshViewFloorAndWalls); Run(nameof(MeshViewEmitBudgetAndFrame), MeshViewEmitBudgetAndFrame); @@ -63,6 +76,10 @@ internal static class Program /// Flat rectangles (x0, z0, x1, z1) at height 0, plus a corner marker so the grid starts at (0,0). private static string Bake(string name, params (float x0, float z0, float x1, float z1)[] floors) + => BakeLayers(name, floors.Select(f => (f.x0, f.z0, f.x1, f.z1, 0f)).ToArray()); + + /// Flat rectangles (x0, z0, x1, z1) each at its own height y: a floor with a roof over part of it. + private static string BakeLayers(string name, params (float x0, float z0, float x1, float z1, float y)[] floors) { var verts = new List(); var faces = new List(); void Quad(float x0, float z0, float x1, float z1, float y) @@ -72,7 +89,7 @@ internal static class Program // Both windings: Recast keeps the upward-facing one as walkable. faces.AddRange(new[] { b, b + 1, b + 2, b, b + 2, b + 3, b, b + 2, b + 1, b, b + 3, b + 2 }); } - foreach (var f in floors) Quad(f.x0, f.z0, f.x1, f.z1, 0); + foreach (var f in floors) Quad(f.x0, f.z0, f.x1, f.z1, f.y); // Pin the bounds to the landblock grid (unused vertices, as the baker does). float maxX = floors.Max(f => f.x1), maxZ = floors.Max(f => f.z1); verts.AddRange(new[] { 0f, -1f, 0f, (float)Math.Ceiling(maxX / 192) * 192f, 1f, (float)Math.Ceiling(maxZ / 192) * 192f }); @@ -311,6 +328,78 @@ internal static class Program Check(m != null && m.Count == 2 && m.Cost >= c.Cost - 1, $"with walked end legs too ({m?.Cost:F0})"); } + private static void FencedInGoalMovesToReachableGround() + { + // 11-01: a /loc on ground fenced in by a building's walls. Two tiles of open ground; in tile 1 + // a small floor (300..320, 80..100) with a 10 m moat round it: a pocket region of its own, + // with no border links. Every route search to it found nothing (0 expanded), and the walk + // headed straight for the spot instead. The goal end now moves to the nearest ground a + // walk can end on. + string dir = Bake("pocket", (0, 10, 384, 70), (0, 110, 384, 180), (0, 70, 290, 110), (330, 70, 384, 110), (300, 80, 320, 100)); + BuildGraph(dir, out NavGraph g); + g.BuildComponents(); + var nav = new DtNavMesh(); + var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 4, maxPolys = 1 << 16 }; + nav.Init(prm, 6); + var regions = new Dictionary(); + foreach (uint lb in new uint[] { 0x0000, 0x0100 }) + { + DtMeshData md = ReadTile(dir, lb); + nav.AddTile(md, 0, 0, out _); + regions[lb] = NavRegions.Build(md, out _); + } + var q = new DtNavMeshQuery(nav); + NavCoarse.Probe? start = NavCoarse.ProbeNear(g, nav, q, 40, 0, 40, 12, regions); + Check(start != null && g.RegionPortals(start.Region).Length > 0, "the start is on open ground with border links"); + + NavCoarse.Probe? pocket = NavCoarse.ProbeNear(g, nav, q, 310, 0, 90, 40, regions); + Check(pocket != null && g.RegionPortals(pocket.Region).Length == 0, "the spot's own polygon is a pocket with no border links"); + var none = g.FindRoute(start!.Region, 40, 40, pocket!.Region, 310, 90, out _, out int expanded); + Check(none == null && expanded == 0, $"to the pocket: no route, nothing expanded (the 11-01 log: '0 expanded') (expanded {expanded})"); + Check(!NavCoarse.Reachable(g, start.Region, pocket.Region) && NavCoarse.Reachable(g, start.Region, start.Region), "a pocket isn't reachable; the start's own region is"); + + NavCoarse.Probe? goal = NavCoarse.ProbeReachable(g, nav, q, 310, 0, 90, 40, regions, start.Region, out bool moved); + double off = goal == null ? double.NaN : Math.Sqrt((goal.Pt.X - 310) * (goal.Pt.X - 310) + (goal.Pt.Z - 90) * (goal.Pt.Z - 90)); + Check(goal != null && moved && goal.Region != pocket.Region && NavCoarse.Reachable(g, start.Region, goal.Region), + $"the goal moves to linked ground (region {goal?.Region}, moved {moved})"); + Check(off < 25, $"...the nearest such ground, beside the moat ({off:F1} u from the spot)"); + NavCoarse? c = NavCoarse.Plan(g, start, goal!, out _); + Check(c != null && c.Count >= 1 && Math.Abs(c.GoalEw - goal!.Pt.X) < 0.01 && !double.IsNaN(c.GoalUp), "a route to it, ending on that ground (with its height)"); + + NavCoarse.Probe? fromFile = NavCoarse.ProbeFile(g, dir, 310, 0, 90, 40, start.Region, out bool movedFile); + Check(fromFile != null && movedFile && fromFile.Region == goal!.Region, "the same from the tile file (the target's tile not loaded)"); + + NavCoarse.Probe? open = NavCoarse.ProbeReachable(g, nav, q, 250, 0, 150, 40, regions, start.Region, out bool movedOpen); + Check(open != null && !movedOpen && Math.Abs(open.Pt.X - 250) < 0.5 && Math.Abs(open.Pt.Z - 150) < 0.5, "a spot on open ground stays where it is"); + } + + private static void RealFencedInGoal() + { + // The 11-01 goto to 43.6N, 85.4W on the real navmesh: the spot probes onto a fenced-in + // polygon (a region of its own, no border links); every search from 41.8N, 82.2W (and from + // everywhere else on the way) found no route. + string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData"; + string graphFile = Path.Combine(dir, NavGraph.FileName); + if (!File.Exists(graphFile)) { Console.WriteLine(" (no real NavData here: skipped)"); return; } + NavGraph g = NavGraph.Load(graphFile); + g.BuildComponents(); + static double W(double map) => (map * 10.0 + 1019.5) * 24.0; + double sx = W(-82.2), sy = W(41.8), tx = W(-85.4), ty = W(43.6); + NavCoarse.Probe? start = NavCoarse.ProbeFile(g, dir, sx, 22, sy, 12); + if (start == null) { Console.WriteLine(" (these tiles aren't the ones this test was written for: skipped)"); return; } + NavCoarse.Probe? old = NavCoarse.ProbeFile(g, dir, tx, 22, ty, 40); + NavCoarse.Probe? goal = NavCoarse.ProbeFile(g, dir, tx, 22, ty, 40, start.Region, out bool moved); + Check(old != null && goal != null, "both probes find ground"); + if (old == null || goal == null) return; + bool oldRoute = NavCoarse.Plan(g, start, old, out int oldExpanded) != null; + NavCoarse? c = NavCoarse.Plan(g, start, goal, out int expanded); + double off = Math.Sqrt((goal.Pt.X - tx) * (goal.Pt.X - tx) + (goal.Pt.Z - ty) * (goal.Pt.Z - ty)); + Console.WriteLine($" 43.6N 85.4W: the spot's own region {old.Region} ({g.RegionPortals(old.Region).Length} border links, route {(oldRoute ? "yes" : "none")}, {oldExpanded} expanded); " + + $"moved {moved} to region {goal.Region}, {off:F1} u off; route {(c == null ? "none" : $"{c.Count} crossings, ~{c.Cost:F0} u")} ({expanded} expanded)"); + Check(c != null, "a route to the ground beside the fenced-in spot"); + Check(off < 12, $"that ground is beside the spot ({off:F1} u)"); + } + private static void LandmassesAndSameLand() { // Two joined tiles (the mainland) and a tile two landblocks away (an island). @@ -431,6 +520,407 @@ internal static class Program Check(own != null && Math.Abs(own[^1].X - 95) < 3, "walking into that portal: it's the goal, not avoided"); } + // ── "RynthNav.Path" v2: FindPathEx and Raycast (NavPathQuery, the plugin's interface) ── + + /// Every tile file of a bake in one navmesh, as the plugin has its loaded tiles. + private static DtNavMeshQuery QueryOn(string dir) + { + var nav = new DtNavMesh(); + var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 64, maxPolys = 1 << 16 }; + nav.Init(prm, 6); + foreach (string f in Directory.GetFiles(dir, "nav_*.tile")) + { + uint lb = Convert.ToUInt32(Path.GetFileNameWithoutExtension(f).Substring(4), 16); + nav.AddTile(ReadTile(dir, lb), 0, 0, out _); + } + return new DtNavMeshQuery(nav); + } + + private static PathExResult Ex(DtNavMeshQuery q, double sx, double sy, double gx, double gy, int flags, + AvoidFilter? portals = null, double clearance = 1.0, int maxCorners = 64, double sz = 0, double gz = 0) + { + var r = new PathExResult(); + int code = NavPathQuery.FindPathEx(q, sx, sy, sz, gx, gy, gz, flags, maxCorners, portals, clearance, r); + if (code != r.Code) throw new InvalidOperationException("the returned code and the result's differ"); + return r; + } + + /// The path's closest pass to (x, y), flat. + private static double Closest(PathExResult r, double x, double y) + { + double best = double.MaxValue; + for (int i = 1; i < r.Corners.Count; i++) + best = Math.Min(best, PortalAvoid.SegmentDistance(x, y, r.Corners[i - 1].X, r.Corners[i - 1].Y, r.Corners[i].X, r.Corners[i].Y)); + return best; + } + + private static double Flat((double X, double Y, double Z) a, double x, double y) => Math.Sqrt((a.X - x) * (a.X - x) + (a.Y - y) * (a.Y - y)); + + private static double Legs(PathExResult r) + { + double len = 0; + for (int i = 1; i < r.Corners.Count; i++) + { + var a = r.Corners[i - 1]; var b = r.Corners[i]; + len += Math.Sqrt((b.X - a.X) * (b.X - a.X) + (b.Y - a.Y) * (b.Y - a.Y) + (b.Z - a.Z) * (b.Z - a.Z)); + } + return len; + } + + /// + /// The table is handed to v1 callers too (older RynthAi's stuck recovery asks for 1) and to v2 and + /// v3 callers, never for 0 or a newer version; and the layout only ever grew at its end. v3 + /// (2026-10-25) added no field, only the PathStartOutdoors flag (RynthAi's hunt plans from a + /// building's doorstep while the player is inside). + /// + private static unsafe void PathInterfaceVersions() + { + const string name = RynthNavPathApiV1.InterfaceName; + Check(RynthNavPathApiV1.InterfaceVersion == 3, "the contract is version 3"); + Check(!NavPathQuery.ServesInterface(name, 0), "version 0: refused"); + Check(NavPathQuery.ServesInterface(name, 1), "version 1 (FindPath callers): served the same table"); + Check(NavPathQuery.ServesInterface(name, 2), "version 2: served"); + Check(NavPathQuery.ServesInterface(name, 3), "version 3: served"); + Check(!NavPathQuery.ServesInterface(name, 4) && !NavPathQuery.ServesInterface(name, uint.MaxValue), "a version newer than the one built: refused"); + Check(RynthNavPathApiV1.PathStartOutdoors == 16 + && (RynthNavPathApiV1.PathStartOutdoors & (RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance + | RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet)) == 0, + "the v3 flag is a bit of its own"); + Check(!NavPathQuery.ServesInterface("RynthNav.path", 1) && !NavPathQuery.ServesInterface("", 2) && !NavPathQuery.ServesInterface(null, 2) + && !NavPathQuery.ServesInterface("RynthAi.Script", 1), "another interface's name: refused"); + + RynthNavPathApiV1 t = default; + byte* b = (byte*)&t; + int p = IntPtr.Size; + Check((byte*)&t.Version - b == 0 && (byte*)&t.StructSize - b == 4 && (byte*)&t.FindPath - b == 8, "v1's fields where v1 callers read them"); + Check((byte*)&t.FindPathEx - b == 8 + p && (byte*)&t.Raycast - b == 8 + 2 * p && sizeof(RynthNavPathApiV1) == 8 + 3 * p, + $"v2 appended after FindPath (size {sizeof(RynthNavPathApiV1)} with {p}-byte pointers)"); + Check(RynthNavPathApiV1.InfoLength == 6 && RynthNavPathApiV1.ResultPartial == 2 && RynthNavPathApiV1.RayClear == 1 && RynthNavPathApiV1.RayBlocked == 0, + "the v2 constants"); + } + + private static void PathTileBox() + { + Check(NavPathQuery.ClampMaxTiles(0) == 25 && NavPathQuery.ClampMaxTiles(-4) == 25, "maxTiles 0: the default 25"); + Check(NavPathQuery.ClampMaxTiles(9) == 9 && NavPathQuery.ClampMaxTiles(49) == 49 && NavPathQuery.ClampMaxTiles(1000) == 49, "else as asked, at most 49"); + double hx = 0xA9 * 192 + 96, hy = 0xB4 * 192 + 96; // the middle of Holtburg's landblock + Check(NavPathQuery.TileBox(hx, hy, hx + 50, hy + 50, 25, false, out int x0, out int y0, out int x1, out int y1) + && x0 == 0xA8 && x1 == 0xAA && y0 == 0xB3 && y1 == 0xB5, "both ends in one landblock: it and the ring round it"); + Check(!NavPathQuery.TileBox(hx, hy, hx + 192, hy, 9, false, out _, out _, out _, out _), "FindPath (v1): 4x3 with the margin doesn't fit 9, no smaller box"); + Check(NavPathQuery.TileBox(hx, hy, hx + 192, hy, 9, true, out x0, out y0, out x1, out y1) && x0 == 0xA9 && x1 == 0xAA && y0 == 0xB4 && y1 == 0xB4, + "FindPathEx: then the two landblocks alone"); + Check(NavPathQuery.TileBox(hx, hy, hx + 192, hy, 12, true, out x0, out _, out x1, out _) && x0 == 0xA8 && x1 == 0xAB, "with room for it, the margin stays"); + Check(NavPathQuery.TileBox(hx, hy, hx + 192 * 8, hy, 49, true, out _, out _, out _, out _), "nine landblocks in a row fit 49 without the margin (9 tiles)"); + Check(!NavPathQuery.TileBox(hx, hy, hx + 192 * 8, hy + 192 * 8, 49, true, out _, out _, out _, out _), "nine apart both ways (81 tiles): too far even for 49"); + Check(NavPathQuery.TileBox(10, 10, 20, 20, 25, false, out x0, out y0, out x1, out y1) && x0 == 0 && y0 == 0 && x1 == 1 && y1 == 1, "the box stops at the map's edge"); + Check(!NavPathQuery.TileBox(1e12, 0, 0, 0, 49, true, out _, out _, out _, out _), "a position far off the map: no box (and no overflow)"); + } + + private static void PathExOpenFloorAndInfo() + { + var q = QueryOn(Bake("exfloor", (0, 0, 192, 192))); + var r = Ex(q, 30, 96, 160, 96, 0); + Check(r.Code == RynthNavPathApiV1.ResultOk && !r.Partial, $"open ground: ResultOk ({r.Code}, {r.Note})"); + Check(r.Corners.Count >= 2 && Flat(r.Corners[0], 30, 96) < 0.5 && Flat(r.Corners[^1], 160, 96) < 0.5, "start first, goal last"); + Check(Math.Abs(r.Length - Legs(r)) < 1e-9 && Math.Abs(r.Length - 130) < 1, $"info[0]: the sum of the legs ({r.Length:F2})"); + Check(r.EndDistance < 0.5, $"info[5]: at the goal ({r.EndDistance:F2})"); + Check(r.Corners.TrueForAll(c => Math.Abs(c.Z) < 0.5), "heights from the mesh (the floor's)"); + var up = Ex(q, 30, 96, 160, 96, 0, gz: 5); + Check(up.Code == RynthNavPathApiV1.ResultOk && Math.Abs(up.EndDistance - 5) < 0.6, $"info[5] is 3D: a goal 5 u above the ground is ~5 u away ({up.EndDistance:F2})"); + var same = Ex(q, 50, 50, 50, 50, 0); + Check(same.Code == RynthNavPathApiV1.ResultOk && same.Corners.Count == 2 && same.Length < 1e-6, "start = goal: two corners, length 0"); + var quiet = Ex(q, 30, 96, 160, 96, RynthNavPathApiV1.PathQuiet); + Check(quiet.Code == r.Code && quiet.Corners.Count == r.Corners.Count && Math.Abs(quiet.Length - r.Length) < 1e-9, "PathQuiet changes only the log"); + } + + private static void PathExRoundAPortal() + { + var q = QueryOn(Bake("exportal", (0, 0, 192, 192))); + var spots = new PortalAvoid(); + spots.Set(new[] { new PortalAvoid.Spot(95, 96, PortalAvoid.LiveRadius, "Unwanted Portal") }, Array.Empty()); + var filter = new AvoidFilter(spots); + var over = Ex(q, 30, 96, 160, 96, 0, filter); + Check(over.Code == RynthNavPathApiV1.ResultOk && Closest(over, 95, 96) < 1 && over.Portals == 0, "without PathAvoidPortals it walks over the portal"); + var round = Ex(q, 30, 96, 160, 96, RynthNavPathApiV1.PathAvoidPortals, filter); + double gap = Closest(round, 95, 96); + Console.WriteLine($" portal on the line: {over.Corners.Count} corners {over.Length:F1}u straight; avoided {round.Corners.Count} corners {round.Length:F1}u, closest {gap:F2}u, bent {round.Bent}"); + Check(round.Code == RynthNavPathApiV1.ResultOk && gap >= PortalAvoid.LiveRadius - 0.01, $"PathAvoidPortals: keeps out of the circle ({gap:F2} u)"); + Check(round.Portals == 1 && round.Corners.Count > over.Corners.Count && round.Length > over.Length, "bent round it, a little longer"); + Check(Flat(round.Corners[^1], 160, 96) < 0.5 && Math.Abs(round.Length - Legs(round)) < 1e-9, "still to the goal; the length counts the bend"); + Check(round.Corners.TrueForAll(c => double.IsFinite(c.Z) && Math.Abs(c.Z) < 0.5), "a bend corner gets the mesh's height"); + var into = Ex(q, 30, 96, 95, 96, RynthNavPathApiV1.PathAvoidPortals, filter); + Check(into.Code == RynthNavPathApiV1.ResultOk && Flat(into.Corners[^1], 95, 96) < 1, "a goal inside a circle is still reached (its polygon is allowed)"); + var empty = new AvoidFilter(new PortalAvoid()); + Check(Ex(q, 30, 96, 160, 96, RynthNavPathApiV1.PathAvoidPortals, empty).Corners.Count == over.Corners.Count, "no portals near: the plain path"); + } + + private static void PathExPartial() + { + var q = QueryOn(Bake("exisland", (10, 10, 70, 180), (110, 10, 180, 180))); + var no = Ex(q, 40, 96, 150, 96, 0); + Check(no.Code == RynthNavPathApiV1.ResultNoPath && no.Corners.Count == 0, "the other island without PathAllowPartial: ResultNoPath (as FindPath)"); + var part = Ex(q, 40, 96, 150, 96, RynthNavPathApiV1.PathAllowPartial); + Check(part.Code == RynthNavPathApiV1.ResultPartial && part.Partial, $"with it: ResultPartial ({part.Code}, {part.Note})"); + if (part.Corners.Count == 0) return; + var end = part.Corners[^1]; + Console.WriteLine($" partial: {part.Corners.Count} corners, ends at ({end.X:F1}, {end.Y:F1}), {part.EndDistance:F1}u from the goal"); + Check(end.X > 60 && end.X < 70 && Math.Abs(end.Y - 96) < 8, $"it ends on the near island's edge, facing the goal ({end.X:F1}, {end.Y:F1})"); + Check(Math.Abs(part.EndDistance - Math.Sqrt((150 - end.X) * (150 - end.X) + (96 - end.Y) * (96 - end.Y) + end.Z * end.Z)) < 1e-9 && part.EndDistance > 70, + $"info[5]: what's left to the goal ({part.EndDistance:F1})"); + var all = Ex(q, 40, 96, 150, 96, RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance | RynthNavPathApiV1.PathQuiet, + new AvoidFilter(new PortalAvoid())); + Check(all.Code == RynthNavPathApiV1.ResultPartial, "with every flag at once too"); + var reach = Ex(q, 40, 96, 60, 150, RynthNavPathApiV1.PathAllowPartial); + Check(reach.Code == RynthNavPathApiV1.ResultOk && !reach.Partial, "a goal it can reach is ResultOk, flag or not"); + } + + private static void PathExNoMeshAndStartSnap() + { + var q = QueryOn(Bake("exsnap", (10, 10, 70, 180), (110, 10, 180, 180))); + var far = Ex(q, 40, 96, 2000, 2000, 0); + Check(far.Code == RynthNavPathApiV1.ResultNoMesh && far.Note.Contains("goal"), $"no tile at the goal: ResultNoMesh ({far.Note})"); + var gap = Ex(q, 90, 96, 40, 96, 0); + Check(gap.Code == RynthNavPathApiV1.ResultNoMesh && gap.Note.Contains("start"), $"a start 20 u from any ground: ResultNoMesh ({gap.Note})"); + var off = Ex(q, 73, 96, 40, 96, 0); + Check(off.Code == RynthNavPathApiV1.ResultOk && off.Corners[0].X < 69 && off.Corners[0].X > 60, $"a start a few yards off the mesh: the wide search finds the ground beside it ({(off.Corners.Count > 0 ? off.Corners[0].X : 0):F1})"); + + // A roof over part of a floor (3.5 u up: room to walk under it). + var rq = QueryOn(BakeLayers("exroof", (0, 0, 192, 192, 0f), (60, 60, 130, 130, 3.5f))); + var under = Ex(rq, 95, 95, 20, 95, 0, sz: 0.1); + Check(under.Code == RynthNavPathApiV1.ResultOk && Math.Abs(under.Corners[0].Z) < 1, $"a start under a roof starts on the floor ({(under.Corners.Count > 0 ? under.Corners[0].Z : double.NaN):F2})"); + var onTop = Ex(rq, 95, 95, 100, 100, 0, sz: 3.6, gz: 3.6); + Check(onTop.Code == RynthNavPathApiV1.ResultOk && Math.Abs(onTop.Corners[0].Z - 3.5) < 1, "one standing on the roof starts on the roof"); + var down = Ex(rq, 95, 95, 20, 95, RynthNavPathApiV1.PathAllowPartial, sz: 3.6, gz: 0); + Check(down.Code == RynthNavPathApiV1.ResultPartial, "and the roof has no way down: partial"); + } + + private static void PathExWallsAndBuffer() + { + // The wall: from the south of tile 0 to the south of tile 2, the only way is round the north. + var q = QueryOn(Bake("exwall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192))); + var bare = Ex(q, 100, 20, 480, 20, 0); + Check(bare.Code == RynthNavPathApiV1.ResultOk && bare.Corners.Count >= 4 && bare.Corners.Exists(c => c.Y > 150), $"round the wall through the north passage ({bare.Corners.Count} corners)"); + Check(bare.Length > 380 * 1.3 && bare.Length < 380 * 1.5, $"the length goes north and back ({bare.Length:F0}u, 380u straight)"); + var walls = Ex(q, 100, 20, 480, 20, RynthNavPathApiV1.PathWallClearance, clearance: 1.0); + Check(walls.Code == RynthNavPathApiV1.ResultOk && walls.Pushed > 0 && walls.Corners.Count == bare.Corners.Count, $"PathWallClearance: corners pushed off the walls ({walls.Pushed})"); + int moved = 0; bool byClearance = true, away = true, onMesh = true; + var plain = new DtQueryDefaultFilter(); + for (int i = 1; i + 1 < walls.Corners.Count && i < bare.Corners.Count; i++) + { + var a = bare.Corners[i]; var b = walls.Corners[i]; + double d = Flat(a, b.X, b.Y); + onMesh &= NavPathQuery.OnMesh(q, plain, b.X, b.Y, (float)b.Z); + if (d < 0.01) continue; + moved++; + byClearance &= Math.Abs(d - 1.0) < 0.01; + // Away from the wall's own corner (the void is x 192..384, y 0..150). + double ca = Math.Min(Flat(a, 192, 150), Flat(a, 384, 150)), cb = Math.Min(Flat(b, 192, 150), Flat(b, 384, 150)); + away &= cb > ca + 0.5; + } + Check(moved == walls.Pushed && byClearance, $"each moved corner moved the clearance, 1 u ({moved} moved)"); + Check(away, "out from the wall it turns round, not into it"); + Check(onMesh, "every corner on walkable ground"); + var zero = Ex(q, 100, 20, 480, 20, RynthNavPathApiV1.PathWallClearance, clearance: 0); + Check(zero.Pushed == 0 && Math.Abs(zero.Length - bare.Length) < 1e-9, "a clearance of 0: nothing moves"); + + // More corners than the caller has room for. + Check(Ex(q, 100, 20, 480, 20, 0, maxCorners: 2).Code == RynthNavPathApiV1.ResultNoPath, "no room for the corners: ResultNoPath (FindPath's rule)"); + var cut = Ex(q, 100, 20, 480, 20, RynthNavPathApiV1.PathAllowPartial, maxCorners: 3); + Check(cut.Code == RynthNavPathApiV1.ResultPartial && cut.Corners.Count == 3 && cut.Truncated && cut.EndDistance > 6, + $"with PathAllowPartial: the first stretch, partial ({cut.Corners.Count} corners, {cut.EndDistance:F0}u left)"); + } + + private static void RaycastOnTheMesh() + { + var open = QueryOn(Bake("rayfloor", (0, 0, 192, 192))); + Check(NavPathQuery.Raycast(open, 30, 96, 0, 160, 96, 0, out float t1) == RynthNavPathApiV1.RayClear && t1 >= 1, "open ground: clear"); + Check(NavPathQuery.Raycast(open, 30, 96, 0, 30, 96, 0, out _) == RynthNavPathApiV1.RayClear, "no distance at all: clear"); + var isl = QueryOn(Bake("rayisland", (10, 10, 70, 180), (110, 10, 180, 180))); + Check(NavPathQuery.Raycast(isl, 40, 96, 0, 150, 96, 0, out float t2) == RynthNavPathApiV1.RayBlocked && t2 > 0.2f && t2 < 0.4f, + $"across the gap: blocked at the island's edge (t {t2:F2})"); + Check(NavPathQuery.Raycast(isl, 90, 96, 0, 40, 96, 0, out _) == RynthNavPathApiV1.ResultNoMesh, "a start off the mesh: ResultNoMesh"); + Check(NavPathQuery.Raycast(isl, 40, 96, 0, 2000, 2000, 0, out _) == RynthNavPathApiV1.ResultNoMesh, "no mesh at the goal: ResultNoMesh"); + var wall = QueryOn(Bake("raywall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192))); + Check(NavPathQuery.Raycast(wall, 100, 20, 0, 480, 20, 0, out _) == RynthNavPathApiV1.RayBlocked, "straight through the wall: blocked"); + Check(NavPathQuery.Raycast(wall, 100, 20, 0, 100, 170, 0, out _) == RynthNavPathApiV1.RayClear, "north on open ground: clear"); + Check(NavPathQuery.Raycast(wall, 100, 170, 0, 480, 170, 0, out _) == RynthNavPathApiV1.RayClear, "along the passage, over two tile seams: clear"); + } + + /// + /// The real map (read only, when it's installed): FindPathEx and Raycast round Holtburg on the tiles + /// a short query loads, a ring of goals at 40/80/150 u; the answers agree, and how long they take. + /// + /// + /// RynthAi's hunt into buildings (2026-10-25) walks to a door's step out (BuildingMap: 1.5 m out of + /// the door, at its foot) and asks RynthNav where the ground is there (a path from the step to + /// itself): within 3 yd across and 1.5 in height it is a door from the ground. The steps of + /// Holtburg's doors (A9B4, as BuildingMap finds them on the real dats) on the real tiles. + /// + private static void RealDoorsteps() + { + string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData"; + if (!File.Exists(Path.Combine(dir, "nav_A9B4.tile"))) { Console.WriteLine(" (no real NavData here: skipped)"); return; } + var nav = new DtNavMesh(); + nav.Init(new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 64, maxPolys = 1 << 16 }, 6); + Check(NavPathQuery.TileBox(0xA9 * 192 + 96, 0xB4 * 192 + 96, 0xA9 * 192 + 96, 0xB4 * 192 + 96, NavPathQuery.DefaultMaxTiles, true, out int x0, out int y0, out int x1, out int y1), "A9B4's box"); + for (int x = x0; x <= x1; x++) + for (int y = y0; y <= y1; y++) + { + uint lb = (uint)((x << 8) | y); + if (File.Exists(Path.Combine(dir, $"nav_{lb:X4}.tile"))) nav.AddTile(ReadTile(dir, lb), 0, 0, out _); + } + var q = new DtNavMeshQuery(nav); + // (door cell, step out x, y, z): every A9B4 door BuildingMap offers (its log, 2026-10-25). + var steps = new (string Cell, double X, double Y, double Z)[] + { + ("A9B40102", 32537.1, 34698.0, 67.0), ("A9B40107", 32527.6, 34700.5, 66.8), ("A9B4010B", 32519.6, 34691.5, 66.0), + ("A9B40113", 32474.7, 34714.7, 66.0), ("A9B40114", 32473.7, 34721.9, 67.0), ("A9B40115", 32482.7, 34714.6, 66.0), + ("A9B40116", 32598.0, 34688.1, 67.0), ("A9B40118", 32595.5, 34690.6, 66.0), ("A9B40119", 32608.8, 34695.0, 66.0), + ("A9B4011F", 32560.2, 34695.8, 70.0), ("A9B40120", 32555.4, 34702.6, 67.0), ("A9B40122", 32549.0, 34702.6, 67.0), + ("A9B40124", 32560.2, 34693.4, 66.0), ("A9B40125", 32552.2, 34702.6, 66.0), ("A9B4012B", 32499.3, 34694.9, 66.0), + ("A9B4012C", 32505.3, 34701.4, 66.0), ("A9B40133", 32506.9, 34701.4, 70.0), ("A9B40139", 32575.2, 34719.3, 66.0), + ("A9B4013D", 32585.8, 34708.7, 66.0), ("A9B4014C", 32577.6, 34578.6, 95.0), ("A9B4014F", 32587.4, 34581.0, 94.8), + ("A9B40150", 32580.5, 34578.6, 94.0), ("A9B40164", 32568.0, 34596.0, 94.0), ("A9B40165", 32544.0, 34596.0, 94.0), + ("A9B4016C", 32522.7, 34592.7, 94.0), ("A9B4016D", 32521.7, 34599.9, 95.0), ("A9B4016E", 32530.7, 34592.6, 94.0), + ("A9B40170", 32603.4, 34577.5, 94.0), ("A9B40177", 32508.8, 34716.5, 66.2), ("A9B40179", 32603.9, 34595.0, 96.0), + ("A9B4017F", 32605.3, 34667.5, 66.0), ("A9B40184", 32478.7, 34614.6, 78.0), ("A9B40189", 32556.1, 34649.0, 80.0), + }; + int flags = RynthNavPathApiV1.PathWallClearance | RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet; + var r = new PathExResult(); + int ground = 0; + var off = new List(); + foreach (var (cell, x, y, z) in steps) + { + int code = NavPathQuery.FindPathEx(q, x, y, z, x, y, z, flags, 64, null, 1.0, r); + bool ok = code is RynthNavPathApiV1.ResultOk or RynthNavPathApiV1.ResultPartial && r.Corners.Count > 0; + double flat = 99, dz = 99; + if (ok) + { + var c = r.Corners[^1]; + flat = Math.Sqrt((c.X - x) * (c.X - x) + (c.Y - y) * (c.Y - y)); + dz = c.Z - z; + } + if (ok && flat <= 3 && Math.Abs(dz) <= 1.5) ground++; + else off.Add($"{cell} ({(ok ? $"{flat:F1} across, {dz:+0.0;-0.0} high" : $"code {code}")})"); + } + Console.WriteLine($" A9B4 doorsteps on RynthNav's ground: {ground} of {steps.Length}; not: {string.Join(", ", off)}"); + // 2026-10-25: 32 of 33; A9B4011F's step is 3.8 above the ground (an upper door with no floor under its step). + Check(ground >= 30, $"Holtburg's door steps are on the ground ({ground} of {steps.Length})"); + Check(off.Any(o => o.StartsWith("A9B4011F")), "the upper door A9B4011F's isn't (the hunt leaves it alone)"); + } + + private static void RealPathEx() + { + string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData"; + if (!File.Exists(Path.Combine(dir, "nav_A9B4.tile"))) { Console.WriteLine(" (no real NavData here: skipped)"); return; } + var centre = RynthCore.Plugin.RynthNav.WorldPt.FromMap(42.08, 33.6); + var sw = System.Diagnostics.Stopwatch.StartNew(); + var nav = new DtNavMesh(); + var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 64, maxPolys = 1 << 16 }; + nav.Init(prm, 6); + int loaded = 0; + Check(NavPathQuery.TileBox(centre.X, centre.Y, centre.X, centre.Y, NavPathQuery.DefaultMaxTiles, true, out int x0, out int y0, out int x1, out int y1), "Holtburg's box"); + for (int x = x0; x <= x1; x++) + for (int y = y0; y <= y1; y++) + { + uint lb = (uint)((x << 8) | y); + if (!File.Exists(Path.Combine(dir, $"nav_{lb:X4}.tile"))) continue; + if (nav.AddTile(ReadTile(dir, lb), 0, 0, out _).Succeeded()) loaded++; + } + long loadMs = sw.ElapsedMilliseconds; + var q = new DtNavMeshQuery(nav); + + // The start: walkable ground at the town's centre (it's under a roof in places; the snap finds the ground). + var plain = new DtQueryDefaultFilter(); + q.FindNearestPoly(new RcVec3f((float)centre.X, 0, (float)centre.Y), new RcVec3f(30, 600, 30), plain, out long sRef, out RcVec3f s0, out _); + Check(sRef != 0, "ground at Holtburg's centre"); + if (sRef == 0) return; + double sx = s0.X, sy = s0.Z, sz = s0.Y; + + int flags = RynthNavPathApiV1.PathWallClearance | RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet; + var counts = new Dictionary(); + int rays = 0, clear = 0, agree = 0, compared = 0, queries = 0; + double worst = 1, pathMs = 0, rayMs = 0; + bool infoOk = true; + var r = new PathExResult(); + var paths = new List<(double gx, double gy, double gz, double len)>(); + foreach (double dist in new[] { 40.0, 80.0, 150.0 }) + for (int k = 0; k < 8; k++) + { + double a = k * Math.PI / 4; + double gx = sx + Math.Cos(a) * dist, gy = sy + Math.Sin(a) * dist; + // A goal on the ground there (a monster stands on it), else the raw spot. + q.FindNearestPoly(new RcVec3f((float)gx, (float)sz, (float)gy), new RcVec3f(2, 64, 2), plain, out long gr, out RcVec3f gp, out _); + double gz = gr != 0 ? gp.Y : sz; + long t0 = System.Diagnostics.Stopwatch.GetTimestamp(); + int code = NavPathQuery.FindPathEx(q, sx, sy, sz, gx, gy, gz, flags, 64, null, 1.0, r); + pathMs += System.Diagnostics.Stopwatch.GetElapsedTime(t0).TotalMilliseconds; queries++; + counts[code] = counts.GetValueOrDefault(code) + 1; + if (code is RynthNavPathApiV1.ResultOk or RynthNavPathApiV1.ResultPartial) + { + infoOk &= Math.Abs(r.Length - Legs(r)) < 1e-6 && r.Corners.Count >= 2 && r.Corners.Count <= 64 + && (code == RynthNavPathApiV1.ResultPartial) == r.Partial; + if (code == RynthNavPathApiV1.ResultOk) paths.Add((gx, gy, gz, r.Length)); + } + t0 = System.Diagnostics.Stopwatch.GetTimestamp(); + int ray = NavPathQuery.Raycast(q, sx, sy, sz, gx, gy, gz, out _); + rayMs += System.Diagnostics.Stopwatch.GetElapsedTime(t0).TotalMilliseconds; rays++; + if (ray == RynthNavPathApiV1.RayClear) + { + clear++; + // A clear straight walk: the planned path is (about) the straight line. + if (code == RynthNavPathApiV1.ResultOk) + { + compared++; + double straight = Math.Sqrt((r.Corners[^1].X - sx) * (r.Corners[^1].X - sx) + (r.Corners[^1].Y - sy) * (r.Corners[^1].Y - sy)); + double ratio = straight < 1 ? 1 : r.Length / straight; + worst = Math.Max(worst, ratio); + if (ratio < 1.25) agree++; + else Console.WriteLine($" clear ray, path x{ratio:F2}: goal ({gx - sx:F0},{gy - sy:F0}) from the start, {r.Corners.Count} corners, {r.Polys} polys, pushed {r.Pushed}: " + string.Join(" ", r.Corners.Select(c => $"({c.X - sx:F1},{c.Y - sy:F1},{c.Z - sz:F1})"))); + } + } + } + + // Portals: one on the way of each of the longer paths, kept out of (or the plain path when there's no way round). + int portalTried = 0, keptOut = 0, fellBack = 0; + foreach (var p in paths) + { + if (p.len < 30) continue; + NavPathQuery.FindPathEx(q, sx, sy, sz, p.gx, p.gy, p.gz, 0, 64, null, 1.0, r); + if (r.Corners.Count < 2) continue; + var mid = (X: (r.Corners[0].X + r.Corners[1].X) / 2, Y: (r.Corners[0].Y + r.Corners[1].Y) / 2); + if (Flat(r.Corners[0], mid.X, mid.Y) < PortalAvoid.LiveRadius + 3) continue; // the start would be inside it + var spots = new PortalAvoid(); + spots.Set(new[] { new PortalAvoid.Spot(mid.X, mid.Y, PortalAvoid.LiveRadius, "test portal") }, Array.Empty()); + int code = NavPathQuery.FindPathEx(q, sx, sy, sz, p.gx, p.gy, p.gz, flags | RynthNavPathApiV1.PathAvoidPortals, 64, new AvoidFilter(spots), 1.0, r); + if (code is not (RynthNavPathApiV1.ResultOk or RynthNavPathApiV1.ResultPartial)) continue; + portalTried++; + if (Closest(r, mid.X, mid.Y) >= PortalAvoid.LiveRadius - 0.01) keptOut++; + if (r.FellBack) fellBack++; + } + + // A typical short query, many times (the tiles already loaded, as in a hunt). + var pick = paths.Count > 0 ? paths[0] : (sx + 40, sy, sz, 0.0); + int reps = 500; + long tr = System.Diagnostics.Stopwatch.GetTimestamp(); + for (int i = 0; i < reps; i++) NavPathQuery.FindPathEx(q, sx, sy, sz, pick.Item1, pick.Item2, pick.Item3, flags | RynthNavPathApiV1.PathAvoidPortals, 64, null, 1.0, r); + double perPath = System.Diagnostics.Stopwatch.GetElapsedTime(tr).TotalMilliseconds / reps; + tr = System.Diagnostics.Stopwatch.GetTimestamp(); + for (int i = 0; i < reps; i++) NavPathQuery.Raycast(q, sx, sy, sz, pick.Item1, pick.Item2, pick.Item3, out _); + double perRay = System.Diagnostics.Stopwatch.GetElapsedTime(tr).TotalMilliseconds / reps; + + string tally = string.Join(", ", counts.OrderBy(kv => -kv.Key).Select(kv => $"{(kv.Key switch { 1 => "ok", 2 => "partial", 0 => "no path", _ => "no mesh" })} {kv.Value}")); + Console.WriteLine($" Holtburg: {loaded} tiles read in {loadMs} ms; {queries} FindPathEx ({tally}), {pathMs / queries:F2} ms each cold; " + + $"Raycast {clear}/{rays} clear, {rayMs / rays:F3} ms each; clear rays vs paths {agree}/{compared} near-straight (worst x{worst:F2}); " + + $"portal on the way: kept out {keptOut}/{portalTried} ({fellBack} plain fallback); a short query {perPath:F3} ms, its ray {perRay:F3} ms"); + Check(loaded >= 9, $"Holtburg's 3x3 tiles ({loaded})"); + Check(counts.GetValueOrDefault(RynthNavPathApiV1.ResultOk) >= 12, "most of the ring is reached"); + Check(infoOk, "info consistent with the corners on every path"); + Check(compared == 0 || agree >= compared - 1, $"a clear ray's path is the straight line (or near it): {agree}/{compared}"); + Check(portalTried == 0 || keptOut + fellBack >= portalTried, $"a portal on the way is kept out of, or the plain path is taken ({keptOut}+{fellBack}/{portalTried})"); + Check(perPath < 20 && perRay < 5, $"fast enough to ask several times a second ({perPath:F3} / {perRay:F3} ms)"); + } + // ── The navmesh view (NavMeshView) ─────────────────────────────────────────── private sealed class TriSink : RynthCore.Plugin.Shared.INav3DSink diff --git a/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj b/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj index 6029bc6..922c46b 100644 --- a/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj +++ b/Tools/RynthNav.GraphTests/RynthNav.GraphTests.csproj @@ -3,7 +3,8 @@ @@ -13,6 +14,8 @@ enable enable RynthNav.GraphTests + + true @@ -33,6 +36,9 @@ + + + diff --git a/Tools/RynthNav.RouteTests/Program.cs b/Tools/RynthNav.RouteTests/Program.cs index daf0a44..36d6958 100644 --- a/Tools/RynthNav.RouteTests/Program.cs +++ b/Tools/RynthNav.RouteTests/Program.cs @@ -61,6 +61,7 @@ internal static partial class Program RunTravelPlan(); RunTripExport(); RunAutoRunGate(); + RunSteering(); Console.WriteLine(); Console.WriteLine(_fails == 0 && _asserts > 0 diff --git a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj index 0bd3a2e..ff1a946 100644 --- a/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj +++ b/Tools/RynthNav.RouteTests/RynthNav.RouteTests.csproj @@ -31,6 +31,8 @@ + + diff --git a/Tools/RynthNav.RouteTests/SteeringTests.cs b/Tools/RynthNav.RouteTests/SteeringTests.cs new file mode 100644 index 0000000..cedd80d --- /dev/null +++ b/Tools/RynthNav.RouteTests/SteeringTests.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using RynthNav.Routing; + +namespace RynthNav.RouteTests; + +// The goto's steering (WalkSteer, PathFollow). 11-01: "whenever I use auto navigation mode (Select +// coordinates) it bounces left and right a lot with a lot of stopping": 862 turns and 21 stops in +// 107 s of one goto. The old servo stopped the run for anything over 20 degrees and each path corner +// was run to within 1.5 m, overshot and turned back to. A simulated character walks made-up paths +// round buildings with the old and the new settings. +internal static partial class Program +{ + private static void RunSteering() + { + Run(nameof(ServoSmallCorrectionsOnTheRun), ServoSmallCorrectionsOnTheRun); + Run(nameof(ServoBigTurnStandsAndResumes), ServoBigTurnStandsAndResumes); + Run(nameof(ServoTurnRateLimited), ServoTurnRateLimited); + Run(nameof(PathFollowCutsOnlyInPlainView), PathFollowCutsOnlyInPlainView); + Run(nameof(UnstickPicksOpenGround), UnstickPicksOpenGround); + Run(nameof(SimulatedWalkRoundBuildings), SimulatedWalkRoundBuildings); + } + + private static void ServoSmallCorrectionsOnTheRun() + { + var s = new WalkSteer(); + double t = s.Step(5, 0, 1000, out bool run); + Check(run && double.IsNaN(t), "5 degrees off while running: no turn (dead zone), still running"); + t = s.Step(35, 0, 1100, out run); + Check(run && !double.IsNaN(t) && t > 0 && t <= 35, $"35 degrees off: turns on the run ({t:F1})"); + var old = WalkSteer.Legacy(); + old.Step(35, 0, 1000, out bool oldRun); + Check(!oldRun, "the old servo stopped the run for 35 degrees"); + Check(Math.Abs(WalkSteer.Diff(350, 10) + 20) < 1e-9 && Math.Abs(WalkSteer.Diff(10, 350) - 20) < 1e-9, "the shortest way round north"); + t = s.Step(345, 5, 1300, out _); + Check(!double.IsNaN(t) && (t < 5 || t > 340), $"from 5 to 345 it turns left across north ({t:F1})"); + } + + private static void ServoBigTurnStandsAndResumes() + { + var s = new WalkSteer(); + long now = 1000; + double h = 0; + s.Step(120, h, now, out bool run); + Check(!run && s.TurnInPlace, "120 degrees off: stops to turn"); + int ticks = 0; + while (!run && ticks++ < 200) + { + now += 18; + double t = s.Step(120, h, now, out run); + if (!double.IsNaN(t)) h = t; + } + Check(run && Math.Abs(WalkSteer.Diff(120, h)) <= 20.0 + 1e-9, $"runs again once within 20 degrees ({h:F1} after {ticks} ticks)"); + Check(ticks * 18 < 600, $"a 120 degree turn takes under 0.6 s ({ticks * 18} ms)"); + } + + private static void ServoTurnRateLimited() + { + var s = new WalkSteer(); + int sent = 0; + double h = 0; + for (long now = 1000; now < 2000; now += 18) + { + double t = s.Step(h + 30, h, now, out _); // a target that keeps moving away + if (!double.IsNaN(t)) { sent++; h = t; } + } + Check(sent <= 21, $"at most 20 turns a second (sent {sent} in 1 s; the old servo: one every tick, 56)"); + var old = WalkSteer.Legacy(); + int oldSent = 0; h = 0; + for (long now = 1000; now < 2000; now += 18) + { + double t = old.Step(h + 30, h, now, out _); + if (!double.IsNaN(t)) { oldSent++; h = t; } + } + Check(oldSent >= 50, $"(the old one sent {oldSent})"); + } + + private static void PathFollowCutsOnlyInPlainView() + { + var path = new List<(double X, double Y)> { (0, 0), (10, 0), (10, 10), (20, 10) }; + Check(PathFollow.Advance(path, 1, 6, 0, 1.5, 7, 6, null) == 1, "without a view check: the corner is run to"); + Check(PathFollow.Advance(path, 1, 6, 0, 1.5, 7, 6, (ax, ay, bx, by) => true) == 2, "4 m from it with the next corner in view: on to the next"); + Check(PathFollow.Advance(path, 1, 6, 0, 1.5, 7, 6, (ax, ay, bx, by) => false) == 1, "...not when something is between"); + Check(PathFollow.Advance(path, 1, 2, 0, 1.5, 7, 6, (ax, ay, bx, by) => true) == 1, "not from farther than the look-ahead"); + Check(PathFollow.Advance(path, 1, 9, 0, 1.5, 7, 6, null) == 2, "within the corner reach: passed"); + Check(PathFollow.Advance(path, 3, 15, 10, 1.5, 7, 6, (ax, ay, bx, by) => true) == 4, "the end is reached at the arrival distance"); + } + + private static void UnstickPicksOpenGround() + { + Check(Math.Abs(WalkSteer.UnstickHeading(0, 1, null) - 100) < 1e-9, "no view check: 100 degrees off on the given side"); + Check(Math.Abs(WalkSteer.UnstickHeading(0, -1, h => true) - 260) < 1e-9, "the other side when asked"); + // A river bank on the right (every heading from 30 to 180 blocked): the left. + double left = WalkSteer.UnstickHeading(0, 1, h => !(h >= 30 && h <= 180)); + Check(Math.Abs(left - 260) < 1e-9, $"open ground on the other side ({left:F0})"); + Check(Math.Abs(WalkSteer.UnstickHeading(90, 1, h => false) - 270) < 1e-9, "nothing open: straight back"); + } + + // ── A simulated walk ─────────────────────────────────────────────────────────── + + private sealed record Building(double X, double Y, double R); + + private sealed class WalkResult + { + public bool Arrived; + public double Seconds, Travelled, MinClearance = double.MaxValue; + public int Turns, Stops; + } + + /// + /// A path like Detour's: every other corner turns 25..45 degrees round a round building, both + /// legs tangent to its eroded edge (building radius + the 2 m agent radius); the corners + /// between are 5..15 degree bends on open ground (polygon edges), nothing near. + /// + private static (List<(double X, double Y)> Path, List Buildings) WeavingPath() + { + var path = new List<(double X, double Y)> { (0, 0) }; + var buildings = new List(); + var rng = new Random(11_01); + double x = 0, y = 0, heading = 45; + for (int i = 0; i < 30; i++) + { + double leg = 6 + rng.NextDouble() * 8; + x += Math.Sin(heading * Math.PI / 180) * leg; y += Math.Cos(heading * Math.PI / 180) * leg; + path.Add((x, y)); + int sign = (i / 2) % 2 == 0 ? 1 : -1; + bool round = i % 2 == 0; + double turn = sign * (round ? 25 + rng.NextDouble() * 20 : 5 + rng.NextDouble() * 10); + if (round) + { + // The building on the inside of the turn, tangent to both legs at the agent radius. + double inner = heading + (turn > 0 ? 90 : -90) + turn / 2; + double r = 3 + rng.NextDouble() * 3; + double d = (r + 2) / Math.Cos(Math.Abs(turn) / 2 * Math.PI / 180); + buildings.Add(new Building(x + Math.Sin(inner * Math.PI / 180) * d, y + Math.Cos(inner * Math.PI / 180) * d, r)); + } + heading += turn; + } + x += Math.Sin(heading * Math.PI / 180) * 20; y += Math.Cos(heading * Math.PI / 180) * 20; + path.Add((x, y)); + return (path, buildings); + } + + private static double SegDist(double px, double py, double ax, double ay, double bx, double by) + { + double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy; + double t = l2 < 1e-12 ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / l2, 0, 1); + double cx = ax + dx * t, cy = ay + dy * t; + return Math.Sqrt((px - cx) * (px - cx) + (py - cy) * (py - cy)); + } + + /// + /// Walks the path at 30 ticks a second: the heading is what the last turn set (TurnToHeading is + /// instant), a run covers 10 u/s, a stop halts at once, and a run takes 0.4 s to get going again + /// (in the 11-01 log a stop and the run after it are 0.3..0.6 s apart). + /// + private static WalkResult Walk(List<(double X, double Y)> path, List buildings, WalkSteer servo, bool lookahead) + { + const long TickMs = 33; + const double RunSpeed = 10.0, AgentRadius = 2.0; + const long StartUpMs = 400; + bool Clear(double ax, double ay, double bx, double by) + { + foreach (Building b in buildings) if (SegDist(b.X, b.Y, ax, ay, bx, by) < b.R + AgentRadius - 1e-6) return false; + return true; + } + var res = new WalkResult(); + double x = path[0].X, y = path[0].Y; + double h = Math.Atan2(path[1].X - x, path[1].Y - y) * 180 / Math.PI; + int idx = 0; + bool running = false; + long runSince = 0; + long now = 1_000_000; + for (int tick = 0; tick < 30 * 180; tick++) + { + now += TickMs; + idx = PathFollow.Advance(path, idx, x, y, 1.5, 7.0, 6.0, lookahead ? Clear : null); + if (idx >= path.Count) { res.Arrived = true; break; } + double desired = WalkSteer.Norm(Math.Atan2(path[idx].X - x, path[idx].Y - y) * 180 / Math.PI); + double t = servo.Step(desired, h, now, out bool run); + if (!double.IsNaN(t)) { res.Turns++; h = t; } + if (running && !run) res.Stops++; + if (!running && run) runSince = now; + running = run; + double step = running && now - runSince >= StartUpMs ? RunSpeed * TickMs / 1000.0 : 0; + x += Math.Sin(h * Math.PI / 180) * step; y += Math.Cos(h * Math.PI / 180) * step; + res.Travelled += step; + foreach (Building b in buildings) + res.MinClearance = Math.Min(res.MinClearance, Math.Sqrt((x - b.X) * (x - b.X) + (y - b.Y) * (y - b.Y)) - b.R); + res.Seconds += TickMs / 1000.0; + } + return res; + } + + private static void SimulatedWalkRoundBuildings() + { + var (path, buildings) = WeavingPath(); + double len = 0; + for (int i = 1; i < path.Count; i++) len += Math.Sqrt((path[i].X - path[i - 1].X) * (path[i].X - path[i - 1].X) + (path[i].Y - path[i - 1].Y) * (path[i].Y - path[i - 1].Y)); + WalkResult old = Walk(path, buildings, WalkSteer.Legacy(), lookahead: false); + WalkResult now = Walk(path, buildings, new WalkSteer(), lookahead: true); + Console.WriteLine($" {path.Count} corners, {buildings.Count} buildings, {len:F0} u: old {old.Seconds:F1} s, {old.Stops} stops, {old.Turns} turns, clearance {old.MinClearance:F1} u; " + + $"new {now.Seconds:F1} s, {now.Stops} stops, {now.Turns} turns, clearance {now.MinClearance:F1} u"); + Check(old.Arrived && now.Arrived, "both walks arrive"); + Check(old.Stops >= 10, $"the old servo stops at the corners ({old.Stops} stops)"); + Check(now.Stops <= old.Stops / 4, $"far fewer stops ({now.Stops} vs {old.Stops})"); + Check(now.Turns * 4 <= old.Turns * 3, $"a quarter fewer turn commands or better ({now.Turns} vs {old.Turns})"); + Check(now.Seconds < old.Seconds * 0.85, $"quicker ({now.Seconds:F1} s vs {old.Seconds:F1} s)"); + Check(now.MinClearance >= 1.0, $"never closer than 1 m to a building ({now.MinClearance:F2} u)"); + Check(now.Travelled < len * 1.05, $"no wandering: walked {now.Travelled:F0} u of a {len:F0} u path"); + } +} diff --git a/Tools/RynthSort.Tests/PackColumnTests.cs b/Tools/RynthSort.Tests/PackColumnTests.cs new file mode 100644 index 0000000..2e4bb05 --- /dev/null +++ b/Tools/RynthSort.Tests/PackColumnTests.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using RynthCore.Plugin.RynthSort.Sorting; +using RynthCore.Plugin.RynthSort.Ui; +using RynthCore.Plugin.RynthSort.Views; + +namespace RynthSort.Tests +{ + // Pack numbers against the game's pack column: which containers are packs, the column's order + // with foci, wielded and unloaded containers in it, why an order isn't known, and what each + // pack's header says and does (icon, Select in game, its place in the column). + internal static partial class Program + { + private static void PackColumnKinds() + { + Check(InventoryReader.IsSidePack(false, true, 24, 0), "a pack whose capacity reads (empty): a pack"); + Check(!InventoryReader.IsSidePack(false, true, 0, 0), "a focus (capacity 0): not a pack"); + Check(!InventoryReader.IsSidePack(true, true, 24, 3), "a wielded container: not a pack"); + Check(InventoryReader.IsSidePack(false, false, 0, 5), "capacity not read yet but items inside: a pack (else every pack below it is numbered one too high)"); + Check(!InventoryReader.IsSidePack(false, false, 0, 0), "capacity not read and nothing inside: not guessed"); + } + + private static void PackColumnOrder() + { + // Column, top first: pack 3, a focus, pack 1, pack 2. The main pack itself in the list changes nothing. + SortInventory inv = Inv(3); + Check(inv.ApplyPackOrder(new uint[] { 0x40000003, 0x40000F01, 0x40000001, Me, 0x40000002 }, 5), "foci and the main pack's own id in the list"); + Check(inv.PackOrderKnown && inv.OrderSource == PackOrderSource.Known, "known"); + Eq(string.Join(",", inv.Packs.Select(p => p.Id & 0xF)), "3,1,2", "pack 1 is the top pack"); + Eq(string.Join(",", inv.Packs.Select(p => p.ColumnSlot)), "1,3,5", "each pack's slot in the column, foci counted"); + Eq(inv.ColumnEntries, 5, "the column's entries"); + + // A wielded container is never read as a pack, so the column (main pack only) needn't have it. + SortInventory worn = Inv(2); + Check(worn.ApplyPackOrder(new uint[] { 0x40000002, 0x40000001 }, 2), "only carried packs need be in the column"); + + // An unloaded pack (read through its items) that the engine's list lacks. + SortInventory miss = Inv(3); + Check(!miss.ApplyPackOrder(new uint[] { 0x40000003, 0x40000001 }, 2), "a pack the list lacks: not known"); + Check(miss.OrderSource == PackOrderSource.Mismatch && miss.MissingFromColumn == 1, "says it is a mismatch, one pack short"); + Check(miss.Packs.All(p => p.ColumnSlot == 0), "no column slots claimed"); + Eq(string.Join(",", miss.Packs.Select(p => p.Id & 0xF)), "1,2,3", "object-id order kept (as the engine's Inventory panel falls back to)"); + + // A later good read clears the mismatch. + Check(miss.ApplyPackOrder(new uint[] { 0x40000002, 0x40000003, 0x40000001 }, 3) && miss.MissingFromColumn == 0, "a full list again: known"); + + // The log lines (one when the source changes). + Check(InventoryReader.OrderSourceLine(inv).Contains("follow the pack column"), "log: known"); + SortInventory notSeen = Inv(2); + notSeen.OrderSource = PackOrderSource.NotSeen; + Check(InventoryReader.OrderSourceLine(notSeen).Contains("no pack column list"), "log: not seen"); + Check(InventoryReader.OrderSourceLine(new SortInventory()).Contains("API 80"), "log: no engine support"); + Check(InventoryReader.OrderSourceLine(Inv(3).With(i => i.ApplyPackOrder(new uint[] { 0x40000001 }, 1))).Contains("lacks 2 of 3"), "log: a mismatch, counted"); + } + + private static SortInventory With(this SortInventory inv, Action a) + { + a(inv); + return inv; + } + + private static SortView ViewOf(SortInventory inv) + { + var p = new SortPlanner(); + p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0); + return p.View; + } + + private static void PackColumnLabels() + { + Eq(string.Join(",", new[] { 1, 2, 3, 4, 11, 12, 13, 21, 22, 23, 101, 111 }.Select(SortPanel.Ordinal)), + "1st,2nd,3rd,4th,11th,12th,13th,21st,22nd,23rd,101st,111th", "ordinals"); + + SortInventory inv = Inv(3); + for (uint i = 0; i < 14; i++) inv.Packs[2].Items.Add(It(500 + i, "Salvaged Iron", ObjectClasses.Salvage)); + inv.ApplyPackOrder(new uint[] { 0x40000003, 0x40000F01, 0x40000001, 0x40000002 }, 4); + SortView v = ViewOf(inv); + Check(v.PackOrderKnown && v.OrderSource == PackOrderSource.Known, "the view carries the order"); + Eq(v.Packs[0].ColumnSlot, 1, "the view carries each pack's slot"); + Eq(SortPanel.WhereText(v, v.Packs[0], 1), "1st pack from the top of the pack column - 14/24 items", "the top pack"); + Eq(SortPanel.WhereText(v, v.Packs[1], 2), "2nd pack from the top of the pack column - 0/24 items", "a pack below a focus: its pack number"); + Check(SortPanel.PackHeaderTooltip(v, 2).Contains("also shows the focus above it, so there it is the 3rd entry"), "and the tooltip says where the retail window has it"); + Check(!SortPanel.PackHeaderTooltip(v, 1).Contains("also shows"), "no focus above: nothing extra"); + string tip = SortPanel.PackHeaderTooltip(v, 1); + Check(tip.StartsWith("Your Pack 3: 14 of 24 items (Salvage).", StringComparison.Ordinal), "header tooltip: which pack, its count and contents"); + Check(tip.Contains("It is the 1st pack from the top of your inventory's pack column."), "header tooltip: where it is"); + Check(tip.Contains("Select in game"), "header tooltip: how to see it in the game"); + Eq(SortPanel.NumberingNote(v), "", "known: no note above the packs"); + + SortInventory unknown = Inv(2); + unknown.OrderSource = PackOrderSource.NotSeen; + SortView u = ViewOf(unknown); + Eq(SortPanel.WhereText(u, u.Packs[1], 2), "Place in the pack column not known - 0/24 items", "unknown: says so"); + Check(SortPanel.PackHeaderTooltip(u, 2).Contains("isn't known right now") && !SortPanel.PackHeaderTooltip(u, 2).Contains("from the top"), "unknown: the tooltip claims no place"); + Check(SortPanel.NumberingNote(u).Contains("hasn't seen your pack list") && SortPanel.NumberingNote(u).Contains("Log out and back in"), "not seen: why and the fix"); + unknown.ApplyPackOrder(new uint[] { 0x40000002 }, 1); + Check(SortPanel.NumberingNote(ViewOf(unknown)).Contains("missing a pack"), "mismatch: why"); + Check(SortPanel.NumberingNote(ViewOf(Inv(2))).Contains("plugin API 80"), "no engine support: why"); + Eq(SortPanel.NumberingNote(ViewOf(Inv(0))), "", "no side packs: no note"); + } + + private static void PackColumnWindow() + { + var c = new SortController(); + var selected = new List(); + var panel = new SortPanel(c, () => { }) + { + Character = () => "Someone", + Icons = () => true, + CanSelect = () => true, + SelectInGame = id => { selected.Add(id); return true; }, + }; + var host = new UiHost(); + UiWindow w = host.Add(new UiWindow("RynthSort/Main", "RynthSort") { Visible = true }); + SortInventory inv = Inv(3); + Fill(inv.Packs[1], 5, 1000); + inv.ApplyPackOrder(new uint[] { 0x40000002, 0x40000F01, 0x40000003, 0x40000001 }, 4); + c.Planner.Plan(inv, c.Data.Rules, SortScope.Main, true, 0, 0); + + Draw(w, panel); + ParseAll(host, "pack headers with icons and Select", out int ops); + Check(ops > 10 && ops < 1500, $"ops in range ({ops})"); + string body = BodyText(w); + Check(body.Contains("Pack 1: Pack 2 (5/24)"), "the top pack (id 2) is pack 1"); + Check(body.Contains("Select in game###select.40000002") && body.Contains("Select in game###select.40000001"), "a Select in game button per pack"); + Check(body.Contains("1st pack from the top of the pack column - 5/24 items"), "where it is, with its item count"); + Check(body.Contains("2nd pack from the top of the pack column - 0/24 items"), "the next pack, below a focus"); + Check(body.Contains("so there it is the 3rd entry"), "the focus above it: said in its tooltip"); + Check(body.Contains("Selects this pack in the game"), "the button says what it does"); + Check(!body.Contains("oldest pack first, not"), "known: no numbering note"); + Check(ContainsOp(w.Body, UiFormat.OpImage), "the pack's icon drawn"); + w.MarkSubmitted(true); + + Apply(host, Event(1, 1, w.Hash, w.KeyOf("select.40000003"), Click)); + Eq(string.Join(",", selected.Select(x => x.ToString("X8"))), "40000003", "Select in game selects that pack's object"); + Draw(w, panel); + ParseAll(host, "after Select", out _); + Check(BodyText(w).Contains("the game has your Pack 3 selected now"), "and says so under it"); + + // Without icon support or selection, neither is drawn (the layout doesn't shift on old engines). + panel.Icons = () => false; + panel.CanSelect = () => false; + Draw(w, panel); + ParseAll(host, "old engine", out _); + Check(!BodyText(w).Contains("Select in game###") && !ContainsOp(w.Body, UiFormat.OpImage), "no icon or Select button when the engine can't"); + Check(BodyText(w).Contains("pack from the top of the pack column"), "the place is still said"); + + // Order unknown: the note above the packs, and no place claimed. + SortInventory lost = Inv(2); + lost.OrderSource = PackOrderSource.NotSeen; + c.Planner.Plan(lost, c.Data.Rules, SortScope.Main, true, 0, 0); + Draw(w, panel); + ParseAll(host, "order unknown", out _); + body = BodyText(w); + Check(body.Contains("Pack numbers here go oldest pack first") && body.Contains("Log out and back in"), "the note says why and the fix"); + Check(body.Contains("Place in the pack column not known"), "each pack says its place isn't known"); + } + + /// Whether the display list has an op of this kind (each op: u8 code, u8 flags, u16 payload length, payload). + private static bool ContainsOp(ReadOnlySpan body, byte op) + { + int at = 0; + while (at + 4 <= body.Length) + { + if (body[at] == op) return true; + at += 4 + System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(body[(at + 2)..]); + } + return false; + } + } +} diff --git a/Tools/RynthSort.Tests/PackTests.cs b/Tools/RynthSort.Tests/PackTests.cs index 0da6d93..ee5b534 100644 --- a/Tools/RynthSort.Tests/PackTests.cs +++ b/Tools/RynthSort.Tests/PackTests.cs @@ -272,11 +272,11 @@ namespace RynthSort.Tests Eq(SortPanel.ShownPack(p.View, rule), 2, "the rule is listed under pack 2"); SortPanel.SetPack(rule, p.View, 6); Check(rule.Pack == 6 && rule.PackId == 0 && rule.PackNote == "", "a number you don't have: no id"); - Check(!p.View.PackOrderKnown && SortPanel.PackTooltip(p.View).Contains("list order") && !SortPanel.PackTooltip(p.View).Contains("top of the pack column"), + Check(!p.View.PackOrderKnown && SortPanel.PackTooltip(p.View).Contains("may not match") && !SortPanel.PackTooltip(p.View).Contains("top pack"), "pack order unknown: the tooltip doesn't claim screen order"); inv.PackOrderKnown = true; p.Plan(inv, SortRules.Defaults(), SortScope.Main, true, 0, 0); - Check(SortPanel.PackTooltip(p.View).Contains("top of the pack column"), "pack order known: numbered from the top"); + Check(SortPanel.PackTooltip(p.View).Contains("Pack 1 is the top pack in your inventory's pack column"), "pack order known: numbered from the top"); // Warnings sit with their pack: a rule that fell back to a number is listed (and warned // about) under the pack it uses; rules whose pack isn't carried are grouped by that pack. diff --git a/Tools/RynthSort.Tests/Program.cs b/Tools/RynthSort.Tests/Program.cs index e3f1b25..4c7a856 100644 --- a/Tools/RynthSort.Tests/Program.cs +++ b/Tools/RynthSort.Tests/Program.cs @@ -82,6 +82,10 @@ namespace RynthSort.Tests Run("store: old rules migrate to version 3", RuleMigration); Run("order: inside a pack (A-Z, fewest moves, every order of up to 7)", InPackOrder); Run("order: slot orders and the pack column", SlotOrders); + Run("pack column: which containers are packs (foci, wielded, unloaded)", PackColumnKinds); + Run("pack column: order with foci, wielded and unloaded packs, and why it isn't known", PackColumnOrder); + Run("pack column: what a pack header says (place, count, why not known)", PackColumnLabels); + Run("pack column: icons and Select in game in the window", PackColumnWindow); Run("plan: stacks and order inside packs", PlanInPack); Run("moves: answers for moves within a pack", MoveAnswersInPlace); Run("replies: every /rsort word answers", Replies);