diff --git a/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs b/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs
index 8104495..5ab4727 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/BuildingMap.cs
@@ -11,7 +11,9 @@
// - 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.
+// rooms as the patrol lays them), kept out of the circles of portal objects standing inside;
+// - what its cells place (tables, chairs, beds, cabinets: GeometryLoader's statics), as the dungeon
+// map's placed objects, less the stairs (see "Placed objects" below).
// Cached per landblock (the last MaxBlocks). Tick thread.
using System;
@@ -35,6 +37,13 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
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;
+ /// An opening under this tall can be a window with a deep sill (see TryDoor); no door this tall or taller is
+ /// judged one.
+ internal const double WindowTallMax = 2.4;
+ /// The highest step a body walks up (AC's step-up height).
+ internal const double StepUpMeters = 0.6;
+ /// The floor a body stands on inside, for the window test: this far in and more (past a sill's depth).
+ internal const double WindowRoomFrom = 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).
@@ -47,6 +56,8 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
/// A bend round a portal keeps this much more than its circle.
internal const double PortalBendMargin = 0.4;
internal const int MaxBlocks = 25;
+ /// A cell's floor centre in furniture moves at most this far to be out of it.
+ internal const double CentreOutOfPlaced = 3.0;
/// 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);
@@ -74,11 +85,46 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
public int ExitRecords;
/// Openings to the outside shared by two cells, joined (JoinSharedOpenings).
public int SharedOpenings;
+ /// What the cells place: pieces given, how many went on the map (furniture), how many were left out as stairs.
+ public int PlacedGiven, Furniture, Stairs;
+
+ private Dictionary? _pointGraph;
+ /// with each cell that has a floor at its floor's centre (), for laying a walk's points.
+ public Dictionary PointGraph => _pointGraph ??= AtFloorCentres(Graph, Geo);
+ }
+
+ ///
+ /// A copy of with each cell that has a floor moved to its floor's centre. Every
+ /// cell of a building sits at the building's own origin, so where a step has no doorway (the top of a
+ /// stair is a floor opening, not a doorway) the walk's points fell back to the origin, on the ground
+ /// floor: DreamWeave Thread E74E#14 (2026-11-17), every walk up its stairs went from the stair's foot
+ /// back to the middle of the ground floor, then straight at the monster above, and ended under it.
+ ///
+ internal static Dictionary AtFloorCentres(Dictionary graph, DungeonGeometry? geo)
+ {
+ var g = new Dictionary(graph.Count);
+ foreach (var (id, n) in graph)
+ {
+ var m = new DungeonNavNode { CellId = n.CellId, NS = n.NS, EW = n.EW, Z = n.Z, Neighbors = n.Neighbors };
+ if (geo != null && geo.TryCellFloorCentre(id, out double x, out double y, out double z))
+ {
+ // A centre in furniture (E74E#0's 0103: on a 0.45 m dais): the nearest spot of the cell's floor out of it.
+ if (geo.PlacedCount > 0 && DungeonPathfinder.InsidePlacedAt(geo, x, y, z))
+ DungeonPathfinder.NearestOutOfPlaced(geo, ref x, ref y, z, CentreOutOfPlaced, new[] { id });
+ m.NS = DungeonGeometry.WorldToNav(y);
+ m.EW = DungeonGeometry.WorldToNav(x);
+ m.Z = (float)z;
+ }
+ g[id] = m;
+ }
+ return g;
}
private readonly DatDatabase? _cellDat;
private readonly Func? _los;
private readonly Func? _isDungeon;
+ private readonly Func?>? _statics;
+ private readonly Func? _terrain;
private readonly Dictionary _blocks = new();
private readonly Queue _order = new();
@@ -107,12 +153,18 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
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)
+ /// On the real dats: says which landblocks are dungeons (their cells are no building's);
+ /// gives what a landblock's cells place (GeometryLoader.GetDungeonStaticMeshes; null: no furniture);
+ /// the ground's height at a world spot (GeometryLoader.GetTerrainZWorld; NaN unknown; null: no window test).
+ public BuildingMap(DatDatabase? cellDat, Func? los, Func? isDungeon = null,
+ Func?>? statics = null,
+ Func? terrain = null)
{
_cellDat = cellDat;
_los = los;
_isDungeon = isDungeon;
+ _statics = statics;
+ _terrain = terrain;
}
internal DatDatabase? CellDat => _cellDat;
@@ -133,7 +185,7 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
if (_isDungeon != null && _isDungeon(landblock)) b = null;
else
{
- try { b = Load(landblock, _cellDat, _los?.Invoke()); }
+ try { b = Load(landblock, _cellDat, _los?.Invoke(), _statics, _terrain); }
catch { b = null; }
}
while (_order.Count >= MaxBlocks) _blocks.Remove(_order.Dequeue());
@@ -190,6 +242,124 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
return p;
}
+ ///
+ /// The rooms walked through from to , the shortest
+ /// by the walk itself: from where it stands to each doorway in turn, then to the goal (Dijkstra, a cell
+ /// entered at its doorway). A building's cells all sit at the building's own origin, so the dungeon A*
+ /// (cell centre to cell centre) saw every step as 0 m and took whichever path came first: DreamWeave
+ /// Thread BA17#4 (2026-11-17), from 012C to the door in 0122 it went five rooms round (west, north, east
+ /// through the raised 012D) instead of two, and its last leg, 012D's doorway to the door, ran into the
+ /// wall; the character ran at it for two minutes ("He's also still running into walls").
+ ///
+ internal static List WalkCells(Block blk, uint fromCell, Vec from, uint toCell, Vec to)
+ {
+ var g = blk.Graph;
+ if (!g.ContainsKey(fromCell) || !g.ContainsKey(toCell)) return new List();
+ if (fromCell == toCell) return new List { fromCell };
+ var at = new Dictionary { [fromCell] = from }; // where each cell is entered
+ var cost = new Dictionary { [fromCell] = 0 };
+ var came = new Dictionary();
+ var open = new PriorityQueue();
+ var done = new HashSet();
+ open.Enqueue(fromCell, 0);
+ double best = double.MaxValue;
+ while (open.Count > 0)
+ {
+ uint c = open.Dequeue();
+ if (!done.Add(c)) continue;
+ if (cost[c] >= best) break;
+ var p = at[c];
+ if (c == toCell) { best = Math.Min(best, cost[c] + p.DistanceTo(to)); continue; }
+ var n = g[c];
+ foreach (uint nb in n.Neighbors)
+ {
+ if (done.Contains(nb) || !g.TryGetValue(nb, out var o) || DungeonPathfinder.IsDropEdge(n, o)) continue;
+ // No doorway known (a floor or ceiling opening: a stair's top, a stairwell, a hole): the next
+ // room's floor centre (PointGraph), not no distance. At no cost, E74E#14 (2026-11-17) went from
+ // the ground floor up through the air under its platform and down to the far end of the second
+ // floor, rather than up the stairs beside it.
+ Vec d = blk.Geo != null && blk.Geo.TryGetDoorway(c, nb, out var door)
+ ? new Vec(door.X, door.Y, door.Z)
+ : blk.PointGraph.TryGetValue(nb, out var m)
+ ? new Vec(DungeonGeometry.NavToWorld(m.EW), DungeonGeometry.NavToWorld(m.NS), m.Z)
+ : p;
+ double step = cost[c] + p.DistanceTo(d) + 0.1; // a little for each doorway: fewer rooms when equal
+ if (step >= cost.GetValueOrDefault(nb, double.MaxValue)) continue;
+ cost[nb] = step;
+ at[nb] = d;
+ came[nb] = c;
+ open.Enqueue(nb, step);
+ }
+ }
+ if (!came.ContainsKey(toCell)) return new List();
+ var path = new List();
+ for (uint c = toCell; ; c = came[c])
+ {
+ path.Add(c);
+ if (c == fromCell) break;
+ }
+ path.Reverse();
+ return path;
+ }
+
+ ///
+ /// A leg of the walk that crosses a wall (SegmentClear says no) is bent through one point it can go by
+ /// with both halves clear: a room's middle or a doorway on the way (the walk's own cells), the one
+ /// adding the least. BA17#4 (2026-11-17): from the raised 012D the walk went from its doorway straight
+ /// at the front door across 012B, into the wall; by 012B's middle both halves are clear. A leg with
+ /// no such point is left as it was.
+ ///
+ internal static int MendBlockedLegs(List way, IReadOnlyList cells, DungeonGeometry geo, Func clear)
+ {
+ var vias = new List();
+ foreach (uint c in cells)
+ if (geo.TryCellFloorCentre(c, out double x, out double y, out double z)) vias.Add(new Vec(x, y, z));
+ for (int i = 0; i + 1 < cells.Count; i++)
+ if (geo.TryGetDoorway(cells[i], cells[i + 1], out var d)) vias.Add(new Vec(d.X, d.Y, d.Z, true));
+ int mended = 0;
+ for (int i = 0; i + 1 < way.Count && mended < 8; i++)
+ {
+ Vec a = way[i], b = way[i + 1];
+ if (clear(a, b)) continue;
+ Vec? best = null;
+ double bestLen = double.MaxValue;
+ foreach (var v in vias)
+ {
+ if (v.DistanceTo(a) < 0.3 || v.DistanceTo(b) < 0.3) continue;
+ double len = a.DistanceTo(v) + v.DistanceTo(b);
+ if (len >= bestLen || !clear(a, v) || !clear(v, b)) continue;
+ best = v;
+ bestLen = len;
+ }
+ if (best is Vec via)
+ {
+ way.Insert(i + 1, via);
+ mended++;
+ i++; // the second half is clear: on past it
+ continue;
+ }
+ // No one point: two (a room's middle, then a doorway, say), all three parts clear.
+ Vec? b1 = null, b2 = null;
+ foreach (var v in vias)
+ {
+ if (v.DistanceTo(a) < 0.3 || !clear(a, v)) continue;
+ foreach (var w in vias)
+ {
+ if (w.Equals(v) || w.DistanceTo(b) < 0.3) continue;
+ double len = a.DistanceTo(v) + v.DistanceTo(w) + w.DistanceTo(b);
+ if (len >= bestLen || !clear(v, w) || !clear(w, b)) continue;
+ b1 = v; b2 = w; bestLen = len;
+ }
+ }
+ if (b1 is not Vec v1 || b2 is not Vec v2) continue;
+ way.Insert(i + 1, v1);
+ way.Insert(i + 2, v2);
+ mended++;
+ i += 2;
+ }
+ return mended;
+ }
+
private PathResult WorkOutInside(uint fromCell, Vec from, uint toCell, Vec to)
{
var none = new PathResult(PathStatus.NoPath, Array.Empty(), 0, 0);
@@ -197,10 +367,18 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
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);
+ // Each end in the cell whose floor holds it. A door is mostly a thin cell of its own, and its step in, 1.5 m
+ // in, is on the next cell's floor (BA17#4's front door 0122: 012B's; Holtburg A9B4's 010B: 0104's): a walk
+ // from it in the door's cell went back out to the doorway between the two first, then in again.
+ if (blk.Geo != null)
+ {
+ fromCell = CellHolding(blk.Geo, fromCell, bf.Cells, from.X, from.Y, from.Z);
+ toCell = CellHolding(blk.Geo, toCell, bt.Cells, to.X, to.Y, to.Z);
+ }
+ var cells = WalkCells(blk, fromCell, from, toCell, to);
if (cells.Count == 0) return none;
- var pts = DungeonPathfinder.BuildPathPoints(cells, blk.Graph, blk.Geo, null,
+ var pts = DungeonPathfinder.BuildPathPoints(cells, blk.PointGraph, blk.Geo, null,
DungeonGeometry.WorldToNav(from.Y), DungeonGeometry.WorldToNav(from.X), from.Z,
DungeonGeometry.WorldToNav(to.Y), DungeonGeometry.WorldToNav(to.X), to.Z, out _, mergeSamePieces: false);
var way = new List(pts.Count + 2) { from };
@@ -212,6 +390,7 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
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);
+ if (geo != null && clear != null) MendBlockedLegs(way, cells, geo, clear);
var status = KeepOutOfPortals(way, Portals, onFloor, clear, out double gap);
if (status == PathStatus.NoPath) return none;
@@ -388,8 +567,11 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
/// 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).
+ /// : what the cells place, for the furniture (none: the rooms bare, as before).
///
- internal static Block Load(uint landblock, DatDatabase cellDat, DungeonLOS? los)
+ internal static Block Load(uint landblock, DatDatabase cellDat, DungeonLOS? los,
+ Func?>? statics = null,
+ Func? terrain = null)
{
// A graph of its own (never DungeonPathfinder's cached one): shared openings add edges to it.
var graph = DungeonPathfinder.BuildGraph(landblock, cellDat);
@@ -417,7 +599,10 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
}
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);
+ IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)>? placed = null;
+ try { placed = statics?.Invoke(landblock); }
+ catch { placed = null; } // no statics: the rooms bare, the doors and walks as before
+ var block = Build(landblock, graph, portals, floors, walls, exitPolys, placed, terrain);
block.ExitRecords = exits.Count;
return block;
}
@@ -503,15 +688,27 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
/// 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).
+ /// (what the cells place) go on the geometry as furniture before the doors
+ /// are looked for, so no door's step in is inside one (AddFurniture).
///
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)
+ IReadOnlyList<(uint, Vector3[])>? walls, IReadOnlyList<(uint Cell, Vector3[] Poly)> exitPolys,
+ IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)>? statics = null,
+ Func? terrain = null)
{
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 };
+ if (geo != null) DungeonPathfinder.MarkBuildingMap(geo);
+ if (geo != null && statics is { Count: > 0 })
+ {
+ var f = AddFurniture(geo, statics);
+ block.PlacedGiven = statics.Count;
+ block.Furniture = f.Kept;
+ block.Stairs = f.Stairs.Count;
+ }
// Buildings: the cells joined to each other (union-find over the portal records, either way).
var parent = new Dictionary(graph.Count);
@@ -548,7 +745,7 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
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))
+ if (TryDoor(cell, node, poly, geo, b.Cells, out var door, out string why, terrain))
{
bool same = false;
foreach (var d in b.Doors)
@@ -564,10 +761,12 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
/// 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).
+ /// foot off the floor inside (a window). The inner point is never inside furniture, nor the leg in to
+ /// it through one (InnerPoint). It can be past a doorway, in the next cell: a walk from it starts there
+ /// (WorkOutInside, CellHolding).
///
internal static bool TryDoor(uint cell, DungeonNavNode node, Vector3[] poly, DungeonGeometry? geo, IReadOnlyCollection buildingCells,
- out OutdoorHunt.Door door, out string why)
+ out OutdoorHunt.Door door, out string why, Func? terrain = null)
{
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))
@@ -599,6 +798,30 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
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; }
+
+ // A window with a deep sill: the floor just inside is the sill's own top, level with the foot, and the
+ // room's floor is a metre below (DreamWeave Thread B470#25, 2026-11-19: the hunt walked at its two 1.5 m
+ // tall windows, 1.0 m over the room's floor and the ground, as doors). Under WindowTallMax, a foot more than a
+ // step over both the ground outside and the floor a body stands on inside (WindowRoomFrom to InnerLongest in;
+ // none there: no floor to step down to) is a window. Over the 1,633 landblocks with buildings this took 416
+ // of 6,322 doors, every one 1.5 to 2.0 m tall; 9 buildings were left without a door, each an opening 5.7 m
+ // up a tower or a wide window.
+ if (terrain != null && top - z < WindowTallMax)
+ {
+ double ground = terrain(x + nx * OutsideMeters, y + ny * OutsideMeters);
+ if (!double.IsNaN(ground) && z - ground > StepUpMeters)
+ {
+ double room = double.NaN;
+ for (double s = InnerLongest; s >= WindowRoomFrom - 1e-9 && double.IsNaN(room); s -= 0.25)
+ if (geo.TryFloorHeight(x - nx * s, y - ny * s, z, 2.5, out double f)) room = f;
+ if (double.IsNaN(room) || z - room > StepUpMeters)
+ {
+ why = string.Format(inv, "a window: {0:F1} m tall, its foot {1:F1} m over the ground outside and {2}", top - z, z - ground,
+ double.IsNaN(room) ? "no floor a step past it inside" : string.Format(inv, "{0:F1} m over the floor inside", z - room));
+ return false;
+ }
+ }
+ }
}
// The step out is onto the ground: no floor of the landblock under it, from 8 m below to just
@@ -610,21 +833,237 @@ internal sealed class BuildingMap : OutdoorHunt.IBuildings
return false;
}
- // The inner point: as far in as InnerLongest that is on the building's floor.
- double inS = -1;
- if (geo != null)
+ // The inner point: as far in as InnerLongest that is on the building's floor (and clear of furniture).
+ double ix = x - nx, iy = y - ny;
+ if (geo != null && !InnerPoint(geo, buildingCells, x, y, nx, ny, floor, out ix, out iy, out bool furniture))
{
- 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; }
+ why = furniture ? "furniture stands a step inside it" : "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),
+ Inner: new Vec(ix, iy, floor, true),
At: new Vec(x, y, z, true),
Outside: new Vec(x + nx * OutsideMeters, y + ny * OutsideMeters, z, true));
why = "";
return true;
}
+
+ /// How far a door's step in goes to either side of its centre line when furniture is on the line.
+ internal const double InnerSideways = 0.5;
+
+ ///
+ /// The door's inner point: on its centre line as far in as InnerLongest (shortened in 0.25 m steps to
+ /// InnerShortest) on the building's floor, not inside furniture, the leg in to it from the door crossing
+ /// none; else the same InnerSideways either side of the line. False when none is (:
+ /// one had a floor, furniture was in the way).
+ ///
+ private static bool InnerPoint(DungeonGeometry geo, IReadOnlyCollection buildingCells, double x, double y, double nx, double ny,
+ double floor, out double ix, out double iy, out bool furniture)
+ {
+ furniture = false;
+ bool objects = geo.PlacedCount > 0;
+ foreach (double side in objects ? new[] { 0.0, InnerSideways, -InnerSideways } : new[] { 0.0 })
+ {
+ double ox = -ny * side, oy = nx * side;
+ for (double s = InnerLongest; s >= InnerShortest - 1e-9; s -= 0.25)
+ {
+ ix = x - nx * s + ox; iy = y - ny * s + oy;
+ if (!geo.OnFloorOfAny(buildingCells, ix, iy, floor)) continue;
+ if (objects && !LegClearOfPlaced(geo, x, y, ix, iy, floor)) { furniture = true; continue; }
+ return true;
+ }
+ }
+ ix = iy = 0;
+ return false;
+ }
+
+ /// The straight walk from (x0, y0) to (x1, y1), on the floor under it (the nearest within a metre of
+ /// , then of the last sample's), is inside no placed object anywhere along it (every 0.1 m,
+ /// the far end included). The floor under a door's step in can be a step below its sill (Holtburg A9B4#0's door
+ /// 0102: the sill at 67.0, the room at 66.0, a bench there whose top is the sill's height).
+ internal static bool LegClearOfPlaced(DungeonGeometry geo, double x0, double y0, double x1, double y1, double floor)
+ {
+ double len = Math.Sqrt(Sq(x1 - x0) + Sq(y1 - y0));
+ int n = Math.Max(1, (int)Math.Ceiling(len / 0.1));
+ double h = floor;
+ for (int k = 1; k <= n; k++)
+ {
+ double t = (double)k / n, px = x0 + (x1 - x0) * t, py = y0 + (y1 - y0) * t;
+ if (geo.TryFloorHeight(px, py, h, 1.0, out double fh)) h = fh;
+ if (geo.InsidePlaced(px, py, h)) return false;
+ }
+ return true;
+ }
+
+ /// The building's cell whose floor (the nearest in height to , within 0.6 m) holds (x, y):
+ /// itself when its floor does; too when none does.
+ private static uint CellHolding(DungeonGeometry geo, uint cell, IReadOnlyCollection buildingCells, double x, double y, double floor)
+ {
+ if (geo.TryCellFloorHeight(cell, x, y, floor, out double h0) && Math.Abs(h0 - floor) <= 0.6) return cell;
+ uint best = cell;
+ double bestDz = 0.6;
+ foreach (uint c in buildingCells)
+ if (c != cell && geo.TryCellFloorHeight(c, x, y, floor, out double h) && Math.Abs(h - floor) <= bestDz) { best = c; bestDz = Math.Abs(h - floor); }
+ return best;
+ }
+
+ // ── Placed objects (2026-11-18) ─────────────────────────────────────────────────────────────
+ //
+ // A building's cells place its furniture (tables, chairs, beds, stools, benches, cabinets) and, in most
+ // buildings, its stairs too: 6,350 of the 6,571 placed stairs world-wide stand on a flat cell floor, the
+ // object the only thing to walk up. Without them every walk went through the furniture (the survey's six
+ // landblocks 7D64, E74E, BA17, A9B4, A9B3 and DF61: 194 of 1,110 walks, 88 of their corners inside a piece).
+ // The furniture goes on the map as the dungeon map's placed objects (DungeonGeometry.AddPlacedObjects: walls
+ // round what is in a body's way at its floor), the stairs stay off it: as walls the ground floor would meet a
+ // stair's sides on every walk up (stairs as floors is a later step).
+ //
+ // A stair is a CONNECTOR that also climbs by itself. The map's own class alone is not enough here: its chain
+ // of walkable faces runs across objects, so a chair (its seat, then the top of its back at 1.02 m), a cup on a
+ // table and a cabinet beside one are connectors too (in the six landblocks 107 of the 184 connectors are such
+ // furniture). What climbs by itself: a sloped walkable face of some size (a ramp, a stair's stringer: furniture
+ // tops are flat), walkable faces at three heights or more over 0.9 m, or a slab raised a metre or more (the landing
+ // between DF61 010C's two ramps). A sphere's cap is sloped too, but in triangles too small to count; its rings are
+ // walkable faces at many heights though, so the loader's round solids (its cylinders and spheres) are never stairs: a
+ // 1 m ball the chain ran to from a dais beside it was taken for steps and left off (8090012A's 0x0200035E, review of
+ // wf/obst-int). Besides those
+ // 77, a piece the map doesn't take for a connector is still a stair when it is a ramp up from its own floor (the
+ // bottom step of a stair whose chain doesn't reach the next: 7 in the six). Measured: every stair of the six the
+ // survey's own rule found is one of these 84, but for 7 spheres and platforms that rule counted by their caps.
+ // Dungeons are not touched: there every object the map takes stays a wall (DungeonPathfinder.AddPlacedObjectsTo).
+
+ /// A walkable face less flat than this (nz) is a slope: a ramp, a stair's stringer.
+ internal const double StairSlopeNz = 0.95;
+ /// A sloped face at least this big (m2, one triangle) makes a connector a stair; a sphere's cap rings are smaller.
+ internal const double StairSlopeTriangle = 0.3;
+ /// Stepped: walkable faces at StairSteps heights or more, StairStepGap apart, spanning StairStepSpan.
+ internal const double StairStepGap = 0.15, StairStepSpan = 0.9;
+ internal const int StairSteps = 3;
+ /// A raised slab: its bottom this far over its floor, its flat walkable area (m2) this big.
+ internal const double StairSlabRaised = 1.0, StairSlabArea = 1.0;
+
+ /// Which of a landblock's placed objects a building map takes: what the dungeon map would (in the body band at its
+ /// floor) less the stairs, whose keys it keeps.
+ internal sealed class FurnitureFilter
+ {
+ private readonly Dictionary _tris = new();
+ private readonly HashSet _round = new();
+ /// The pieces left out as stairs.
+ public readonly HashSet Stairs = new();
+ /// How many went on the map.
+ public int Kept;
+
+ /// : the pieces that are the loader's cylinders and spheres (BoundingVolume.Round), never stairs.
+ public FurnitureFilter(IEnumerable<(uint SetupId, uint CellId, Vector3[] Triangles)> pieces, IEnumerable? round = null)
+ {
+ foreach (var (setup, cell, tris) in pieces)
+ if (KeyOf(setup, cell, tris) is PieceKey k) _tris.TryAdd(k, tris);
+ if (round != null) _round.UnionWith(round);
+ }
+
+ public PlacedObjectOptions Options => new() { Keep = Keep };
+
+ private bool Keep(PlacedInfo p)
+ {
+ if (p.Class is not (PlacedClass.Obstacle or PlacedClass.StepOver or PlacedClass.Connector)) return false;
+ var k = new PieceKey(p.Setup, p.Cell, p.MinX, p.MinY, p.MinZ, p.MaxX, p.MaxY, p.MaxZ);
+ if (!_round.Contains(k) && _tris.TryGetValue(k, out var t)
+ && (p.Class == PlacedClass.Connector ? ClimbsByItself(t, p.Floor) : RampFromFloor(t, p.Floor)))
+ {
+ Stairs.Add(k);
+ return false;
+ }
+ Kept++;
+ return true;
+ }
+ }
+
+ /// A placed piece by its model, cell and box (the box PlacedSolid gives it: its vertices' own).
+ internal readonly record struct PieceKey(uint Setup, uint Cell, double MinX, double MinY, double MinZ, double MaxX, double MaxY, double MaxZ);
+
+ internal static PieceKey? KeyOf(uint setup, uint cell, Vector3[]? tris)
+ {
+ if (tris == null || tris.Length < 3) return null;
+ int n = tris.Length - tris.Length % 3;
+ double minX = double.MaxValue, minY = double.MaxValue, minZ = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue, maxZ = double.MinValue;
+ for (int k = 0; k < n; k++)
+ {
+ var p = tris[k];
+ if (p.X < minX) minX = p.X; if (p.X > maxX) maxX = p.X;
+ if (p.Y < minY) minY = p.Y; if (p.Y > maxY) maxY = p.Y;
+ if (p.Z < minZ) minZ = p.Z; if (p.Z > maxZ) maxZ = p.Z;
+ }
+ return new PieceKey(setup, cell, minX, minY, minZ, maxX, maxY, maxZ);
+ }
+
+ ///
+ /// A piece standing on climbs by itself (see the section's comment): a sloped walkable
+ /// triangle of StairSlopeTriangle or more, walkable faces at StairSteps heights over StairStepSpan, or a raised slab.
+ /// Either winding counts: the dats list some stairs' faces both ways round (Holtburg A9B3's 020001B4).
+ ///
+ internal static bool ClimbsByItself(Vector3[] t, double floor)
+ {
+ double bottom = double.MaxValue, flat = 0;
+ int lo = int.MaxValue, hi = int.MinValue;
+ var heights = new HashSet();
+ bool slope = false;
+ for (int i = 0; i + 2 < t.Length; i += 3)
+ {
+ var p0 = t[i]; var p1 = t[i + 1]; var p2 = t[i + 2];
+ bottom = Math.Min(bottom, Math.Min(p0.Z, Math.Min(p1.Z, p2.Z)));
+ double ux = p1.X - p0.X, uy = p1.Y - p0.Y, uz = p1.Z - p0.Z, vx = p2.X - p0.X, vy = p2.Y - p0.Y, vz = p2.Z - p0.Z;
+ double cx = uy * vz - uz * vy, cy = uz * vx - ux * vz, cz = ux * vy - uy * vx, len = Math.Sqrt(cx * cx + cy * cy + cz * cz);
+ if (len < 1e-9) continue;
+ double nz = Math.Abs(cz) / len;
+ if (nz < DungeonGeometry.WalkableNz) continue;
+ double area = len / 2;
+ if (nz < StairSlopeNz) { if (area >= StairSlopeTriangle) slope = true; }
+ else flat += area;
+ double h = (p0.Z + p1.Z + p2.Z) / 3.0 - floor;
+ if (h < StairStepGap || h > 6.0) continue;
+ int step = (int)Math.Round(h / StairStepGap);
+ if (heights.Add(step)) { lo = Math.Min(lo, step); hi = Math.Max(hi, step); }
+ }
+ if (slope) return true;
+ if (heights.Count >= StairSteps && (hi - lo) * StairStepGap >= StairStepSpan - 1e-9) return true;
+ // A slab's top and bottom are both flat walkable faces: half the area is its top.
+ return bottom - floor >= StairSlabRaised && flat / 2 >= StairSlabArea;
+ }
+
+ ///
+ /// A piece the map doesn't take for a connector that is still a ramp up from its floor: a sloped walkable triangle of
+ /// StairSlopeTriangle or more whose foot is on the floor (within StairStepGap). The bottom step of a stair whose next
+ /// one the chain doesn't reach (E74E's door steps: 01000ACA, 0 to 0.6 m, under 01000AC5 and 01000ACD up to the sill
+ /// at 32.0), a dais with sloped sides (7D64's 0200033D). A desk's or a lectern's top is no ramp: its foot is off the floor.
+ ///
+ internal static bool RampFromFloor(Vector3[] t, double floor)
+ {
+ for (int i = 0; i + 2 < t.Length; i += 3)
+ {
+ var p0 = t[i]; var p1 = t[i + 1]; var p2 = t[i + 2];
+ double ux = p1.X - p0.X, uy = p1.Y - p0.Y, uz = p1.Z - p0.Z, vx = p2.X - p0.X, vy = p2.Y - p0.Y, vz = p2.Z - p0.Z;
+ double cx = uy * vz - uz * vy, cy = uz * vx - ux * vz, cz = ux * vy - uy * vx, len = Math.Sqrt(cx * cx + cy * cy + cz * cz);
+ if (len < 1e-9) continue;
+ double nz = Math.Abs(cz) / len;
+ if (nz < DungeonGeometry.WalkableNz || nz >= StairSlopeNz || len / 2 < StairSlopeTriangle) continue;
+ if (Math.Min(p0.Z, Math.Min(p1.Z, p2.Z)) - floor <= StairStepGap) return true;
+ }
+ return false;
+ }
+
+ /// The furniture onto (DungeonGeometry.AddPlacedObjects, the stairs left out).
+ internal static FurnitureFilter AddFurniture(DungeonGeometry geo, IReadOnlyList<(uint SetupId, uint CellId, BoundingVolume Mesh)> statics)
+ {
+ var pieces = new List<(uint, uint, Vector3[])>(statics.Count);
+ var round = new List();
+ foreach (var s in statics)
+ if (s.Mesh?.MeshTriangles is { Length: >= 3 } t)
+ {
+ pieces.Add((s.SetupId, s.CellId, t));
+ if (s.Mesh.Round && KeyOf(s.SetupId, s.CellId, t) is PieceKey k) round.Add(k);
+ }
+ var filter = new FurnitureFilter(pieces, round);
+ geo.AddPlacedObjects(pieces, filter.Options);
+ return filter;
+ }
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffCastChain.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffCastChain.cs
index d245173..e4bef37 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffCastChain.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffCastChain.cs
@@ -36,6 +36,18 @@
// returning false, a "too busy" line for it, or an error in its UseDone) turns the fast
// path off for the rest of the pass, logged. Every refusal during buffing is counted for
// as a running total since load, logged one line each, and each pass ends with a summary line.
+//
+// Vital casts in the between-fights top-off (2026-11-20): Heal Self, Revitalize and Stamina to
+// Mana after one another waited on the same animation gate after each UseDone (200-750 ms in the
+// logs: Revitalize UseDone 20:52:40.784, the next one sent 40.996; Executor's Blessing UseDone
+// 11:55:01.293, Stamina to Mana sent 02.049), on top of the server's 2.2 s cast and 1.0 s recoil.
+// The same ACE rule holds for them (one Player_Magic path). SentVital records a vital cast;
+// EligibleVital lets the NEXT vital cast skip the animation gate when the last action was our
+// own vital cast answered UseDone(0), with every condition above. BuffManager asks only with no
+// monster within Monster Range (in a fight nothing changes), in Magic stance, and lets only a
+// vital cast ride it (no kit, potion, stance change or buff). A refusal of a fast vital cast
+// turns the vital fast path off for VitalOffMs. A buff never chains on a vital's UseDone, and a
+// vital never on a buff's (Eligible / EligibleVital check which kind went last).
// ============================================================================
using System;
@@ -56,6 +68,8 @@ internal sealed class BuffCastChain
private long _movesAfter;
private bool _moveCounted; // MovementWaits counted for this send
private bool _wasFast;
+ private bool _wasVital; // the last cast recorded was a vital (SentVital), not a buff
+ private DateTime _vitalOffUntil = DateTime.MinValue; // a refused fast vital cast: no vital fast path until then
private bool _heldForAnimation; // the next buff goes through the animation gate (HoldForAnimation)
private bool _answerSeen; // the first UseDone after it was read
private bool _answerOk; // ... and it was UseDone(0), the next UseDone after the send
@@ -75,6 +89,13 @@ internal sealed class BuffCastChain
public int PassesSwitchedOff { get; private set; }
/// Times the fast path was refused because a movement call went out after the last buff.
public int MovementWaits { get; private set; }
+ /// Vital casts recorded (SentVital), and those that went on the vital fast path.
+ public int VitalCasts { get; private set; }
+ public int VitalFastCasts { get; private set; }
+ /// Times a refusal turned the vital fast path off for VitalOffMs.
+ public int VitalSwitchOffs { get; private set; }
+ /// How long a refused fast vital cast keeps the vital fast path off.
+ public const double VitalOffMs = 60_000;
/// True when a refusal turned the fast path off for the rest of this pass.
public bool OffThisPass => _offThisPass;
@@ -113,6 +134,7 @@ internal sealed class BuffCastChain
_movesAfter = moves;
_moveCounted = false;
_wasFast = fast;
+ _wasVital = false;
_heldForAnimation = false;
_answerSeen = false;
_answerOk = false;
@@ -122,6 +144,54 @@ internal sealed class BuffCastChain
if (fast) { FastCasts++; _passFast++; }
}
+ /// A vital cast went out (Heal Self, Revitalize, Stamina to Mana ... out of a fight): the
+ /// same tracking as , counted as a vital, not a buff of the pass.
+ public void SentVital(int spellId, string name, int seqAtSend, long started, long attacks, long moves, bool fast)
+ {
+ _spellId = spellId;
+ _name = name;
+ _seqAtSend = seqAtSend;
+ _startedAfter = started;
+ _attacksAfter = attacks;
+ _movesAfter = moves;
+ _moveCounted = false;
+ _wasFast = fast;
+ _wasVital = true;
+ _heldForAnimation = false;
+ _answerSeen = false;
+ _answerOk = false;
+ _answerSeenAt = DateTime.MinValue;
+ VitalCasts++;
+ if (fast) VitalFastCasts++;
+ }
+
+ /// The client refused a vital cast (nothing went out). On the vital fast path: off for VitalOffMs.
+ public void VitalClientRefused(int spellId, string name, bool fast, DateTime now, Action log)
+ {
+ ClientRefusals++;
+ log($"[BuffChain] refusal (client): CastSpell refused vital '{name}' (id {spellId}){(fast ? " on the fast path" : "")}" +
+ $" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
+ if (fast) VitalOff("the client refused a fast-path vital cast", now, log);
+ _spellId = 0;
+ }
+
+ /// A "You're too busy!" line while (a vital of ours) waited for its result.
+ public void TooBusyLineVital(int pendingSpellId, DateTime now, Action log)
+ {
+ if (pendingSpellId == 0 || pendingSpellId != _spellId || !_wasVital) return;
+ TooBusyLines++;
+ log($"[BuffChain] refusal (too-busy line) while vital '{_name}' was pending{(_wasFast ? " (sent on the fast path)" : "")}" +
+ $" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
+ if (_wasFast) VitalOff("a fast-path vital cast drew 'You're too busy!'", now, log);
+ }
+
+ private void VitalOff(string why, DateTime now, Action log)
+ {
+ _vitalOffUntil = now.AddMilliseconds(VitalOffMs);
+ VitalSwitchOffs++;
+ log($"[BuffChain] {why}: vital casts wait for the animation again for {VitalOffMs / 1000:0} s");
+ }
+
/// The client refused a buff cast (CastSpell returned false: nothing went out).
public void ClientRefused(int spellId, string name, bool fast, Action log)
{
@@ -148,10 +218,14 @@ internal sealed class BuffCastChain
if (next && lastErr != 0)
{
ServerRefusals++;
- _passServer++;
- log($"[BuffChain] refusal (server): UseDone error 0x{lastErr:X} for '{_name}'{(_wasFast ? " on the fast path" : "")}" +
+ if (!_wasVital) _passServer++;
+ log($"[BuffChain] refusal (server): UseDone error 0x{lastErr:X} for {(_wasVital ? "vital " : "")}'{_name}'{(_wasFast ? " on the fast path" : "")}" +
$" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
- if (_wasFast) SwitchOff($"the server refused a fast-path cast (0x{lastErr:X})", log);
+ if (_wasFast)
+ {
+ if (_wasVital) VitalOff($"the server refused a fast-path vital cast (0x{lastErr:X})", now, log);
+ else SwitchOff($"the server refused a fast-path cast (0x{lastErr:X})", log);
+ }
}
}
@@ -184,6 +258,25 @@ internal sealed class BuffCastChain
/// The caller has checked the setting, the pacing and the vitals.
///
public bool Eligible(long started, long attacks, long moves, bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, out string why)
+ {
+ why = "";
+ if (_wasVital) return false; // a buff never chains on a vital's UseDone (unchanged buff behaviour)
+ return EligibleCore(started, attacks, moves, hasLast, lastSeq, lastErr, seqNow, now, out why);
+ }
+
+ ///
+ /// May the next VITAL cast skip the animation gate? Only right after our own vital cast's UseDone(0),
+ /// with every condition of , and not within VitalOffMs of a refused fast vital.
+ /// The caller has checked the setting, the pacing, the stance and that no monster is within range.
+ ///
+ public bool EligibleVital(long started, long attacks, long moves, bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, out string why)
+ {
+ why = "";
+ if (!_wasVital || now < _vitalOffUntil) return false;
+ return EligibleCore(started, attacks, moves, hasLast, lastSeq, lastErr, seqNow, now, out why);
+ }
+
+ private bool EligibleCore(long started, long attacks, long moves, bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, out string why)
{
why = "";
if (_offThisPass || _heldForAnimation || _spellId == 0 || !_answerSeen || !_answerOk) return false;
@@ -202,5 +295,6 @@ internal sealed class BuffCastChain
public string Describe() =>
$"Buff chain: {FastCasts} of {BuffCasts} buff casts on the fast path; refusals client {ClientRefusals}, " +
- $"server {ServerRefusals}, too-busy lines {TooBusyLines}; passes switched off {PassesSwitchedOff}; movement waits {MovementWaits}";
+ $"server {ServerRefusals}, too-busy lines {TooBusyLines}; passes switched off {PassesSwitchedOff}; movement waits {MovementWaits}; " +
+ $"vital casts {VitalFastCasts} of {VitalCasts} on the fast path, vital switch-offs {VitalSwitchOffs}";
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealAnimationCap.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealAnimationCap.cs
new file mode 100644
index 0000000..3681e5a
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealAnimationCap.cs
@@ -0,0 +1,71 @@
+// ============================================================================
+// RynthSuite - Combat/BuffManager.HealAnimationCap.cs
+// A heal under a heal line waits on the character's animation for HealAnimationCapMs at most.
+//
+// The vitals step waits while the client's motion queue reads busy (ActionPacer.GestureHolds) and
+// while the engine's cast gate is closed (CastGateWatchdog). Both limits (4 s, 1.5 s at Emergency
+// Heal At) count one unbroken busy spell. A monster hitting the character plays a recoil on every
+// hit, so the queue reads busy, clear for a moment, busy again: every spell starts the count from
+// 0 and the limit never comes, while a tick that happens to read busy holds the heal each time.
+//
+// Here the time a heal is held by the animation counts all told, across those clear moments, from
+// the first such hold until the vitals step is reached (a gate let it through) or health is over
+// every heal line. Past HealAnimationCapMs the heal skips both animation gates (logged once per
+// hold). Every other gate keeps its rules: an unanswered action of ours, the busy count, a cast in
+// flight, the player's turn.
+// ============================================================================
+
+using System;
+using RynthCore.Plugin.Shared;
+
+namespace RynthCore.Plugin.RynthAi;
+
+public partial class BuffManager
+{
+ /// The longest a heal under a heal line waits on the character's animation, all told.
+ internal const double HealAnimationCapMs = 1000;
+
+ private DateTime _healAnimHeldSince = DateTime.MinValue;
+ private bool _healAnimCapLogged;
+
+ /// Times a heal went on without the animation gates (tests, status).
+ internal int HealAnimationCaps { get; private set; }
+
+ /// The pacer's hold reasons that are the character's animation (ActionPacer.GestureHolds / SwingHolds).
+ internal static bool IsAnimationHold(string why) =>
+ why.StartsWith("the character is still animating", StringComparison.Ordinal)
+ || why.StartsWith("a swing sent", StringComparison.Ordinal);
+
+ /// True when a heal is due and the animation has held it HealAnimationCapMs or more.
+ private bool HealAnimationCapReached()
+ {
+ if (HealNeedNow() == HealNeed.None) { EndHealAnimationHold(); return false; }
+ if (_healAnimHeldSince == DateTime.MinValue) return false;
+ double ms = (RynthClock.Now - _healAnimHeldSince).TotalMilliseconds;
+ if (ms < HealAnimationCapMs) return false;
+ if (!_healAnimCapLogged)
+ {
+ _healAnimCapLogged = true;
+ HealAnimationCaps++;
+ string line = ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out int value, out _);
+ _host.Log($"[RynthAi] Vitals: the heal has waited {ms:0} ms on the character's animation " +
+ $"(health {_vitals.HealthPct}% under {line} {value}%): it goes on without the animation gate.");
+ }
+ return true;
+ }
+
+ /// The vitals step was held this tick; : by the character's animation.
+ private void NoteHealAnimationHold(bool animation)
+ {
+ if (!animation || _healAnimHeldSince != DateTime.MinValue) return;
+ if (HealNeedNow() == HealNeed.None) return;
+ _healAnimHeldSince = RynthClock.Now;
+ }
+
+ /// The vitals step was reached, or no heal is due: the count starts again at the next hold.
+ private void EndHealAnimationHold()
+ {
+ _healAnimHeldSince = DateTime.MinValue;
+ _healAnimCapLogged = false;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs
index 2c15821..a877772 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HpFailsafe.cs
@@ -260,7 +260,7 @@ public partial class BuffManager
private void StartFailsafeRecall(DateTime now, int hp, double failedSec)
{
HpFailsafeRecalls++;
- _settings.IsMacroRunning = false;
+ _settings.SetMacroRunning(false, "the HP failsafe (heals failing at Emergency Heal At: a recall)");
_macroStoppedByFailsafe = true;
MacroStopForRecall?.Invoke();
// The heal the jump broke is not waited on, here or by the pacer: a stuck cast may never be
@@ -319,7 +319,7 @@ public partial class BuffManager
else if (MayRestartMacro != null && !MayRestartMacro()) what = "the macro stays off (VTank yield)";
else
{
- _settings.IsMacroRunning = true; // the heals and kits run again; the failsafe re-arms
+ _settings.SetMacroRunning(true, "the HP failsafe after its recall"); // the heals and kits run again; the failsafe re-arms
what = "macro back on to keep healing";
}
_macroStoppedByFailsafe = false;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.KitUsedUp.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.KitUsedUp.cs
index c707ea9..d502ae4 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.KitUsedUp.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.KitUsedUp.cs
@@ -8,8 +8,8 @@
//
// Kit picks read the client's live pack walk (ConsumableLookup.Resolve, BestPackHealingKit,
// BestPackStaminaKit: WorldObjectCache.GetDirectInventory), which drops a removed kit, but a walk is
-// reused for up to a second (DirectInventoryCooldownMs) and the next kit goes out KitLandGraceMs
-// (700 ms) after the line, inside that reuse. An engine without GetContainerContents has no walk at
+// reused for up to a second (DirectInventoryCooldownMs) and the next kit goes out at most
+// KitVitalsCatchUpMs (300 ms; 700 ms before 2026-11-20) after the line, inside that reuse. An engine without GetContainerContents has no walk at
// all: its inventory view is the object cache, which can keep a removed kit for good.
//
// So: the line names the kit in flight -> every kit pick skips that kit. With the live walk the skip
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.LegacySwap.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.LegacySwap.cs
index 6aaa5a0..f150048 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.LegacySwap.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.LegacySwap.cs
@@ -108,7 +108,7 @@ public partial class BuffManager
if (IsWieldedLive(bowId))
{
- int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
+ int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1, new[] { bowId });
if (openPack == 0 || _bowDequipAttempts >= BowDequipMaxAttempts)
{
// No verified-open pack to receive the bow, or repeated dequip
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs
index 665273c..5726983 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.VitalWandGate.cs
@@ -19,6 +19,9 @@
// chance, and refusing the spell there killed Drakkon; the surest heal goes;
// - Stamina to Mana never swaps in a fight (InCombatNow), potion or not; out of a fight it may, even
// with a mana potion carried (buffing is about to swap to the wand anyway).
+// - out of a fight (2026-11-20), a healing kit under Kit Min Success % (KitChanceOk, the weapon-out
+// bar included) doesn't refuse Heal Self's swap: the between-fights top-off otherwise sent a 3-19%
+// kit again and again (3.1 s a try) as the last resort.
// Buffing (EnsureMagicMode forBuff) is not gated and still swaps, and so does the HP failsafe's
// Lifestone Recall (it calls EnsureMagicMode itself, with the macro off).
//
@@ -90,6 +93,15 @@ public partial class BuffManager
// means "this is my emergency heal", kit or no kit.
allowed = $"health {_vitals.HealthPct}% at or under Stamina To Health At {_settings.StaminaToHealthAt}%";
}
+ else if (label == LabelHealing && !InCombatNow() && HealthKitUnderMinSuccess(out string kitName))
+ {
+ // The between-fights top-off (2026-11-20): with no monster within Monster Range the shield
+ // argument is gone, and a kit under Kit Min Success % (the weapon-out bar, 30%, from melee)
+ // fails most uses: an Eternal Health Kit at 3-19% on 317-346 missing, each try 3.1 s,
+ // was the "kit despite Kit Min Success" last resort until health crept up. As for stamina
+ // kits (2026-11-13), the % is respected: the wand comes out for Heal Self. In a fight, unchanged.
+ allowed = $"out of a fight, {kitName} is under Kit Min Success %";
+ }
else
{
bool stamina = label == LabelStamina;
@@ -192,6 +204,30 @@ public partial class BuffManager
return HasPackKit("Healing Kit");
}
+ ///
+ /// The healing kit AttemptHealthKitUse would pick (the first listed one, else the pack's best) is under
+ /// Kit Min Success % for what is missing now (KitChanceOk, the weapon-out bar included). No kit: false.
+ ///
+ private bool HealthKitUnderMinSuccess(out string kitName)
+ {
+ kitName = "";
+ if (_worldObjectCache == null) return false;
+ WorldObject? kit = null;
+ foreach (var r in _settings.ConsumableRules)
+ if (r.Type.Equals("HealthKit", StringComparison.OrdinalIgnoreCase)
+ && !(r.Name ?? "").Contains("Stamina Kit", StringComparison.OrdinalIgnoreCase)
+ && ConsumableLookup.Resolve(_worldObjectCache, r, KitOutForGate) is WorldObject wo
+ && IsUseOnSelfKit(wo)) { kit = wo; break; }
+ kit ??= BestPackHealingKit();
+ if (kit == null || KitOutForGate(kit.Id)) return false;
+ uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0;
+ if (KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch,
+ _settings.KitMinSuccessPct, log: false))
+ return false;
+ kitName = kit.Name ?? "the healing kit";
+ return true;
+ }
+
/// A stamina kit AttemptStaminaKitUse could pick.
// Only one Stamina Kit Min Success % lets through (2026-11-13): a kit under it is never used, so it
// must not refuse Revitalize's swap either (that left a melee character with no stamina source, and
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
index 2f1608b..166bb62 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
@@ -293,6 +293,9 @@ public partial class BuffManager : IDisposable
internal BuffCastChain Chain => _chain;
/// This tick skipped the animation gate (the fast path): only a buff cast may go out.
private bool _fastChainTick;
+ /// This tick skipped the animation gate for a vital cast in the between-fights top-off
+ /// (FastVitalChainNow): only a vital spell cast may go out; a kit, potion or buff waits a tick.
+ private bool _fastVitalTick;
private string _fastChainWhy = "";
// Held-cast nudge (2026-10-05): a cast the server holds open (incantation, no result) is
@@ -375,33 +378,68 @@ public partial class BuffManager : IDisposable
return _healthFellAt != DateTime.MinValue && (now - _healthFellAt).TotalMilliseconds < HealthFellCountsMs;
}
- // ── Buffs wait while hurt in a fight (2026-11-07) ──
- // Drakkon cast four weapon auras (2.4 s each) one after another with a golem's Force Bolts hitting him
- // and his health under Heal At; the emergency heal then waited for the last aura's cast and he died.
- // Under Heal At in a fight no new buff cast starts (one already sent finishes) and the arbiter doesn't
- // give Buffing the tick for buffs: the heals (vital recharge keeps its slot) and combat go first. The
- // buffs carry on once health is back over Heal At or the fight is over.
- private bool _buffHurtWaitOn;
+ // ── Buffs wait for the fight (2026-11-07, every buff since 2026-11-20) ──
+ // 2026-11-07: a character cast four weapon auras (2.4 s each) one after another with a golem's Force Bolts
+ // hitting him and his health under Heal At; the emergency heal then waited for the last aura's cast and
+ // he died. Then only health under Heal At held the buffs back.
+ // 2026-11-20, DreamWeave Thread 0x5C47: a Virindi dispelled Robustify and Executor's Blessing in the
+ // middle of a fight. RynthAi put his hand wraps away for the staff and cast them with a Rager on him and
+ // five monsters in range, and he died 4 s later. The owner: "dispel makes sense... but i think we should
+ // clear the mobs nearby before we rebuff". So in a fight (a monster within Monster Range, or health
+ // falling: InCombatNow) no new buff cast starts, whatever the health; one already sent finishes. The
+ // arbiter doesn't give Buffing the tick for buffs, so combat goes first, and the heals (a vital recharge
+ // keeps its slot). A rebuff run under way stops between two casts and carries on once the fight is over.
+ // The same for a dispelled buff and one at Rebuff With. A Force Rebuff the player asked for still goes in a
+ // fight (their own ask), except under Heal At, as before.
+ private bool _buffFightWaitOn; // a wait with buffs to cast was logged
+ private DateTime _buffFightWaitSince = DateTime.MinValue;
+ private DateTime _buffFightNeedCheckedAt = DateTime.MinValue;
- /// True while health is under Heal At in a fight: no new buff cast. Logs the start and end of each wait.
- public bool BuffsWaitForHealth()
+ /// True in a fight: no new buff cast. A Force Rebuff the player asked for waits only while health
+ /// is under Heal At. Logs the start (when there are buffs to cast) and the end of each wait.
+ public bool BuffsWaitForFight()
{
- bool wait = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt && InCombatNow();
- if (wait != _buffHurtWaitOn)
+ bool fight = InCombatNow();
+ bool hurt = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt;
+ bool playersOwn = _isForceRebuffing && !_isAutoBatchRebuff;
+ bool wait = fight && (!playersOwn || hurt);
+ DateTime now = RynthClock.Now;
+ if (!wait)
{
- _host.Log(wait
- ? $"[Buff] buffs wait: health {_vitals.HealthPct}% is under Heal At {_settings.HealAt}% in a fight; heals and combat go first."
- : $"[Buff] buffs go on: health {_vitals.HealthPct}%, {(InCombatNow() ? "back over Heal At" : "the fight is over")}.");
- _buffHurtWaitOn = wait;
+ if (_buffFightWaitOn)
+ _host.Log($"[Buff] buffs go on: {(fight ? $"health {_vitals.HealthPct}%, back over Heal At, for the Force Rebuff you asked for" : "the fight is over")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s).");
+ _buffFightWaitOn = false;
+ return false;
}
- return wait;
+ // Logged only when something is held back (a fight with every buff up isn't a wait); asked once a second.
+ if (!_buffFightWaitOn && (now - _buffFightNeedCheckedAt).TotalMilliseconds >= 1000)
+ {
+ _buffFightNeedCheckedAt = now;
+ if (NeedsAnyBuff())
+ {
+ _buffFightWaitOn = true;
+ _buffFightWaitSince = now;
+ _host.Log($"[Buff] buffs wait: {FightWhy(hurt)}; they go on once the fight is over (combat and the heals first).");
+ }
+ }
+ return true;
+ }
+
+ private string FightWhy(bool hurt)
+ {
+ string why = InCombatOverride != null ? "a fight"
+ : _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true
+ ? $"a monster within Monster Range ({_settings.MonsterRange} yd)"
+ : "health falling (something is hitting you)";
+ return hurt ? $"{why}, health {_vitals.HealthPct}% under Heal At {_settings.HealAt}%" : why;
}
// ── Rebuff When Idle (RebuffWhenIdle + RebuffIdleMarginMinutes; VTank's "idlebufftopoff") ──
// The checkbox was saved and shown since the first version but nothing read it (a player asked,
// 2026-10-30, whether "buff only when idle" was implemented). What it means (the owner): an earlier
// timer for idle moments. The regular rebuff is unchanged: a buff at or under Rebuff With
- // (RebuffSecondsRemaining), or dispelled, is recast as always, in a fight or not. With the option
+ // (RebuffSecondsRemaining), or dispelled, is recast as always, once a fight is over (BuffsWaitForFight,
+ // since 2026-11-20; before that in a fight too). With the option
// on and the bot idle (IdleForTopOff: no fight target, no monster within Monster Range, no corpse
// to loot, no salvage), a rebuff run also starts once a buff is at or under Rebuff With plus the
// margin (default 2 minutes). Such an early run never starts in a fight, and one under way stops
@@ -1266,11 +1304,29 @@ public partial class BuffManager : IDisposable
value = 0;
if (_settings.EmergencyHealAt > 0 && hp <= _settings.EmergencyHealAt) { value = _settings.EmergencyHealAt; return "Emergency Heal At"; }
if (StaminaToHealthAllowed(_settings, hp, stamPct)) { value = _settings.StaminaToHealthAt; return "Stamina To Health At"; }
- value = inCombat ? _settings.HealAt : _settings.TopOffHP;
- if (hp < value) return inCombat ? "Heal At" : "Top Off HP";
+ bool fightLines = FightHealthLine(inCombat);
+ value = fightLines ? _settings.HealAt : _settings.TopOffHP;
+ if (hp < value) return fightLines ? "Heal At" : "Top Off HP";
return "";
}
+ ///
+ /// The vital lines a fight uses (Heal At, Re-stam At, Get Mana At) apply during a buff run too, not
+ /// only with a monster in range: the Top Off lines are for between fights and buff runs, and the
+ /// top-off follows the run (R-20261120-181322-b31b, 2026.11.19.1). With Top Mana 95 and Get Mana
+ /// At 20 a run cast Stamina to Mana ten times at 77-100% mana, then kits to win the stamina back.
+ ///
+ private bool UseFightVitalLines(bool inCombat) => inCombat || _isForceRebuffing;
+
+ ///
+ /// Heal At (the fight line) or Top Off HP for health. The fight line is for a fight RynthAi is
+ /// fighting (and a buff run, UseFightVitalLines): with Combat off nothing of ours fights back, so a
+ /// monster near or hitting must not lower the line. Top Off HP applies then (2026-11-22: Combat off,
+ /// Heal At 0, a monster hitting; every hit made it "a fight", Heal At 0 healed nothing, and the
+ /// character stood until it died).
+ ///
+ private bool FightHealthLine(bool inCombat) => UseFightVitalLines(inCombat && _settings.EnableCombat);
+
// ── What the activity display says while the arbiter's slot is "Buffing" ──
// BotAction stays "Buffing" for every vitals job: it is a control string (CombatManager's
// canRun and CorpseOpenController read it). The dashboard and the phone showed it as is, so a
@@ -1407,6 +1463,7 @@ public partial class BuffManager : IDisposable
string line = ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out int lineValue, out bool inCombat);
_healLatency.Observe(Now, _vitals.HealthPct, line, lineValue, inCombat, HealInFlight());
}
+ else if (!_settings.IsMacroRunning) _healLatency.MacroOff(Now, _vitals.HealthPct); // no episode spans a stop
try { HeartbeatCore(); }
finally
{
@@ -1464,6 +1521,7 @@ public partial class BuffManager : IDisposable
PollCastTracker();
ObserveBuffChain();
_fastChainTick = false;
+ _fastVitalTick = false;
// Heals failing at Emergency Heal At: break the cast, then recall (BuffManager.HpFailsafe.cs).
TickHpFailsafe();
@@ -1792,8 +1850,14 @@ public partial class BuffManager : IDisposable
// buff, the next buff skips the animation gate only (the pacer's gesture hold and the
// engine's cast gate below). Every other gate stays.
_fastChainTick = FastChainNow();
- if (!PacerAllows(out string paceWhy, gestureGate: !_fastChainTick))
+ // The same for a vital cast after our own vital cast in the between-fights top-off (FastVitalChainNow).
+ _fastVitalTick = !_fastChainTick && FastVitalChainNow();
+ // A heal held by the character's animation past HealAnimationCapMs (all told, across the short
+ // clear moments between hit recoils) skips the animation gates (BuffManager.HealAnimationCap.cs).
+ bool healAnimCap = HealAnimationCapReached();
+ if (!PacerAllows(out string paceWhy, gestureGate: !_fastChainTick && !_fastVitalTick && !healAnimCap))
{
+ NoteHealAnimationHold(IsAnimationHold(paceWhy));
LastBuffSkipReason = "server answering the last action: " + paceWhy;
Hold("server answering the last action", paceWhy);
return;
@@ -1815,23 +1879,33 @@ public partial class BuffManager : IDisposable
// NeedsAnyBuff and is the sole writer of the "Buffing" string.
// A heal goes ahead of a busy count the server has already finished (BusyHoldsHeal);
// everything else still waits for the count to drop.
- bool gateOpen = _fastChainTick || CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
+ bool gateOpen = _fastChainTick || _fastVitalTick || healAnimCap || CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
bool busyHolds = BusyCount > 0
&& !_pacerLetHealAhead // the pacing let this heal go ahead of an unanswered corpse use (its rules)
&& (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal());
if (!gateOpen || busyHolds)
{
+ NoteHealAnimationHold(!gateOpen);
LastBuffSkipReason = busyHolds ? "busy (BusyCount>0)" : "cast gate closed (CanCastNow=false / gesture animating)";
if (!gateOpen) Hold("cast gate (a gesture is animating)");
else Hold("busy count", $"busy {BusyCount}");
return;
}
+ EndHealAnimationHold(); // the vitals step is reached: the heal is not held by the animation
if (CheckVitals())
{
if (_healHold.Length == 0) Hold(_healWaitKind.Length > 0 ? _healWaitKind : "vitals step busy", _vitalWhy);
return;
}
+ // The animation gate was skipped for a vital cast only: nothing else goes this tick, and the
+ // next tick waits for the animation as usual (what goes then is no vital cast of this chain).
+ if (_fastVitalTick)
+ {
+ _chain.HoldForAnimation();
+ Hold("cast gate (a gesture is animating)");
+ return;
+ }
// /ra swaptest: the wand swap and one cast, timed (BuffManager.SwapTest.cs). After the vitals.
if (TickSwapTest())
@@ -1877,8 +1951,9 @@ public partial class BuffManager : IDisposable
if (manaFloor > 0 && _vitals.MaxMana > 0 && _vitals.ManaPct < manaFloor)
{
// The floor refills on its own: Stamina to Mana (or a potion) right here, then buffing
- // carries on. CheckVitals only refills below Top Off Mana out of combat, so a Top Off
- // Mana under Get Mana At left buffing waiting on natural regen - one buff every 1-2
+ // carries on. CheckVitals refilled only below Top Off Mana out of combat (a buff run uses
+ // Get Mana At there too since 2026-11-20), so a Top Off Mana under Get Mana At left
+ // buffing waiting on natural regen - one buff every 1-2
// minutes (tester, 10-01: 85 minutes of "buffing waits", Stamina to Mana never cast).
// A low stamina is topped up first (kit, Revitalize, potion) so Stamina to Mana can run.
// Each source's reason, for the log line below: it used to show only the last one tried
@@ -1986,8 +2061,8 @@ public partial class BuffManager : IDisposable
if (_settings.EnableBuffing)
{
- if (BuffsWaitForHealth())
- return; // hurt in a fight: no new buff cast (a run in progress resumes after)
+ if (BuffsWaitForFight())
+ return; // in a fight: no new buff cast (a run in progress resumes after)
if (CheckAndCastSelfBuffs())
return;
@@ -2161,10 +2236,14 @@ public partial class BuffManager : IDisposable
// Otherwise idle → top up to the HIGH (TopOffHP / TopOffStam /
// TopOffMana) thresholds so we re-engage at full. Thresholds are
// strict "<": set a value to 0 to disable that vital in that mode.
+ // A buff run uses the fight's lines too (UseFightVitalLines); the top-off comes after it.
bool inCombat = InCombatNow();
- int hpThreshold = inCombat ? _settings.HealAt : _settings.TopOffHP;
- int manaThreshold = inCombat ? _settings.GetManaAt : _settings.TopOffMana;
- int stamThreshold = StaminaLine(inCombat, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
+ bool fightLines = UseFightVitalLines(inCombat);
+ bool fightHpLine = FightHealthLine(inCombat); // Combat off: Top Off HP even while hit
+ int hpThreshold = fightHpLine ? _settings.HealAt : _settings.TopOffHP;
+ if (fightHpLine) WarnNoFightHealLine(curHealthPct);
+ int manaThreshold = fightLines ? _settings.GetManaAt : _settings.TopOffMana;
+ int stamThreshold = StaminaLine(fightLines, curStamPct, _settings, ref _restamRun, ref _restamRunCasts);
// A flag is set only when something was actually done about the vital.
// WantsVitalRecharge holds the arbiter on Buffing, above combat and nav, so
@@ -2192,10 +2271,10 @@ public partial class BuffManager : IDisposable
}
_healUnavailableUntil = RynthClock.Now.AddMilliseconds(HealUnavailableMs);
Hold("nothing could heal", $"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}");
- LogNoHeal($"health {curHealthPct}% < {(inCombat ? "Heal At" : "Top Off HP")} {hpThreshold}% but nothing healed: " +
+ LogNoHeal($"health {curHealthPct}% < {(fightHpLine ? "Heal At" : "Top Off HP")} {hpThreshold}% but nothing healed: " +
$"kit: {Why(kitWhy)}; Heal Self: {Why(spellWhy)}; potion: {Why(potionWhy)}");
}
- else if (!inCombat && curHealthPct < _settings.HealAt)
+ else if (!fightLines && curHealthPct < _settings.HealAt)
{
LogNoHeal($"health {curHealthPct}% < Heal At {_settings.HealAt}% but no monster within MonsterRange " +
$"{_settings.MonsterRange} yd, so the idle Top Off HP {hpThreshold}% applies");
@@ -2208,7 +2287,7 @@ public partial class BuffManager : IDisposable
// Mana: under Get Mana At / Top Off Mana, or (a caster) under the reserve kept for Stamina
// to Mana (ManaUnderLine; see "Mana reserve" at the top).
- bool manaLow = curManaPct < manaThreshold || ManaUnderLine(inCombat, out _);
+ bool manaLow = curManaPct < manaThreshold || ManaUnderLine(fightLines, out _);
if (manaLow)
{
// Stamina too low for Stamina to Mana: the refill starts with a stamina use, so a falling
@@ -2285,6 +2364,31 @@ public partial class BuffManager : IDisposable
}
private DateTime _staminaNoSwapLoggedAt = DateTime.MinValue;
+ private DateTime _noFightLineLoggedAt = DateTime.MinValue;
+ private DateTime _noFightLineChatAt = DateTime.MinValue;
+
+ ///
+ /// Heal At 0 switches healing off in a fight; with Emergency Heal At and Stamina To Health At 0 as
+ /// well, nothing heals in a fight at any health (2026-11-22: eight deaths in a row with no heal sent
+ /// in the minutes before each, Heal At and Emergency Heal At both 0). Said in the log (each minute)
+ /// and in chat (each 5 minutes) while health is under Top Off HP in a fight; nothing else changes.
+ ///
+ private void WarnNoFightHealLine(int hp)
+ {
+ if (_settings.HealAt > 0 || _settings.EmergencyHealAt > 0 || _settings.StaminaToHealthAt > 0) return;
+ if (hp <= 0 || hp >= Math.Max(1, _settings.TopOffHP)) return;
+ var now = RynthClock.Now;
+ if ((now - _noFightLineLoggedAt).TotalSeconds < 60) return;
+ _noFightLineLoggedAt = now;
+ string text = $"health {hp}% in a fight and no heal line covers fights (Heal At 0, Emergency Heal At 0, " +
+ $"Stamina To Health At 0): nothing heals until the fight ends. Set Heal At or Emergency Heal At (Advanced settings, Recharge).";
+ _host.Log("[RynthAi] Vitals: " + text);
+ if ((now - _noFightLineChatAt).TotalMinutes >= 5)
+ {
+ _noFightLineChatAt = now;
+ _host.WriteToChat("[RynthAi] " + char.ToUpperInvariant(text[0]) + text[1..], 2);
+ }
+ }
///
/// The heal chain of the vitals step (CheckVitals, and the one-touch heal): a kit, Heal Self and a
@@ -2586,14 +2690,23 @@ public partial class BuffManager : IDisposable
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
_pendingVitalLabel = label;
_pendingVitalBase = what;
- bool castOk = _host.CastSpellFor(targetId, spellId, "Buff",
- SpellTableStub.GetById(spellId)?.Name ?? what);
+ string castName = SpellTableStub.GetById(spellId)?.Name ?? what;
+ bool fast = _fastVitalTick;
+ if (fast)
+ _host.Log($"[BuffChain] vital '{castName}' goes without waiting for the animation: {_fastChainWhy}");
+ // Recorded for the vital fast path only out of a fight: in one, the chain's state stays as it was.
+ bool chainIt = !InCombatNow();
+ int seqAtSend = UseDoneSeqNow();
+ bool castOk = _host.CastSpellFor(targetId, spellId, "Buff", castName);
_lastCastAttempt = RynthClock.Now;
if (!castOk)
{
_pendingSpellId = 0;
+ if (chainIt) _chain.VitalClientRefused(spellId, castName, fast, Now, s => _host.Log(s));
return VitalNo($"the client refused the cast (spell {spellId})");
}
+ if (chainIt)
+ _chain.SentVital(spellId, castName, seqAtSend, ActionPacer.Started, ActionPacer.AttacksSent, MoveAudit.MovementSends, fast);
sent = true;
_vitalActionsSent++;
_lastVitalCastAt = RynthClock.Now;
@@ -2663,6 +2776,7 @@ public partial class BuffManager : IDisposable
if (ConsumableLookup.Resolve(_worldObjectCache, rule) is not WorldObject potion) continue;
if (IsKitName(potion.Name)) continue;
if (Array.FindIndex(types, t => t.Equals(DrinkType(rule, potion), StringComparison.OrdinalIgnoreCase)) < 0) continue;
+ if (_fastVitalTick) return FastTickItemWait("the potion");
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
_host.Log($"[RynthAi] Vitals: drinking {rule.Name} ({rule.Type})" + (potion.Id != rule.Id ? " from a new stack." : "."));
_host.UseFor(unchecked((uint)potion.Id), "Buff", $"vitals: drink {rule.Name} ({rule.Type}) from the Items list");
@@ -2680,6 +2794,7 @@ public partial class BuffManager : IDisposable
string? kind = RynthCore.Plugin.RynthAi.LegacyUi.LegacyWeaponsUi.PotionType(wo);
if (kind == null || Array.FindIndex(types, t => t.Equals(kind, StringComparison.OrdinalIgnoreCase)) < 0) continue;
if (IsKitName(wo.Name)) continue;
+ if (_fastVitalTick) return FastTickItemWait("the potion");
if (HeldCastBlocksItemUse(out string heldWhy)) return VitalNo(heldWhy);
_host.Log($"[RynthAi] Vitals: using {wo.Name} from the pack ({kind}).");
_host.UseFor(unchecked((uint)wo.Id), "Buff", $"vitals: {kind} potion from the pack");
@@ -2774,6 +2889,7 @@ public partial class BuffManager : IDisposable
uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0;
// Combat has the tick (BuffManager.HealHold.cs): no peace switch goes out, so the chance is the stance it is in.
if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits && !_vitalsNoPeaceSwitch, _settings.KitMinSuccessPct)) return VitalNo($"{kit.Name} under Kit Min Success %");
+ if (_fastVitalTick) return FastTickItemWait("the healing kit");
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && _vitalsNoPeaceSwitch)
NoteHealHoldRefusal(peace: true, "the healing kit");
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && !_vitalsNoPeaceSwitch)
@@ -2825,6 +2941,7 @@ public partial class BuffManager : IDisposable
underMinSuccess = true;
return false;
}
+ if (_fastVitalTick) return FastTickItemWait("the stamina kit");
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && _vitalsNoPeaceSwitch)
NoteHealHoldRefusal(peace: true, "the stamina kit");
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode && !_vitalsNoPeaceSwitch)
@@ -2867,22 +2984,35 @@ public partial class BuffManager : IDisposable
private bool _kitSawAnimating; // the motion queue read busy since the send
// 3.5 s: the longest healthy kit answer is 2.5 s (ActionPacer's time limits). Stamina kits share it.
internal const double KitResultTimeoutMs = 3500;
- private const double KitLandGraceMs = 700;
+ // A UseDone(0) for the kit with no line: how long to wait for a line after all.
+ internal const double KitLandGraceMs = 700;
+ // After the kit's result line (2026-11-20): the next kit waited KitLandGraceMs (700 ms) after every
+ // line for the vitals to catch up, sized on 10-03 when the vitals were read every 30th tick (1-3 s).
+ // Since 10-05 they are read every 100 ms (RynthAiPlugin.VitalsPollMs) from the engine's snapshot,
+ // which ACE's vital update (sent before the line, Healer.DoHealing) has already reached when the
+ // line arrives. The wait now ends as soon as the vitals show the healed amount the line names
+ // (KitVitalsCaughtUp), or KitVitalsCatchUpMs after the line (a failed kit names none): 3 vitals reads.
+ // Stamina kits chained 3.1 s apart in the logs (16:46:45.572 line, next kit 46.302); now ~2.5 s.
+ internal const double KitVitalsCatchUpMs = 300;
/// Kits let go with no result line (heal grace or the time limit) (tests, status).
internal int KitRetries { get; private set; }
+ // The kit's vital (health, or stamina for a stamina kit) when it went out, and what its line said it healed (0 = none named).
+ private uint _kitVitalAtUse;
+ private int _kitLineAmount;
internal enum KitWaitEnd { Waiting, Landed, Answered, NotTaken, TimedOut }
///
/// The kit wait, from what has been seen since the send (pure; a ms value below 0 = not seen): the
- /// result line plus KitLandGraceMs; the kit's UseDone(0) with no line plus KitLandGraceMs, with no
- /// motion playing; nothing at all from the server ( false) and no
- /// motion playing after ActionPacer.HealGraceMs; or KitResultTimeoutMs whatever happened.
+ /// result line, then the vitals showing its heal () or KitVitalsCatchUpMs;
+ /// the kit's UseDone(0) with no line plus KitLandGraceMs, with no motion playing; nothing at all from
+ /// the server ( false) and no motion playing after ActionPacer.HealGraceMs;
+ /// or KitResultTimeoutMs whatever happened.
///
internal static KitWaitEnd KitWaitVerdict(double msSinceUse, double msSinceLanded, double msSinceAnswered,
- bool serverTookIt, bool animatingNow)
+ bool serverTookIt, bool animatingNow, bool vitalsCaughtUp = false)
{
- if (msSinceLanded >= 0) return msSinceLanded >= KitLandGraceMs ? KitWaitEnd.Landed : KitWaitEnd.Waiting;
+ if (msSinceLanded >= 0) return vitalsCaughtUp || msSinceLanded >= KitVitalsCatchUpMs ? KitWaitEnd.Landed : KitWaitEnd.Waiting;
if (msSinceAnswered >= KitLandGraceMs && !animatingNow) return KitWaitEnd.Answered;
if (!serverTookIt && !animatingNow && msSinceUse >= ActionPacer.HealGraceMs) return KitWaitEnd.NotTaken;
if (msSinceUse >= KitResultTimeoutMs) return KitWaitEnd.TimedOut;
@@ -2912,6 +3042,30 @@ public partial class BuffManager : IDisposable
_kitSawAnimating = false;
_kitIsStamina = stamina;
_kitSeqAtUse = UseDoneSeqNow();
+ _kitVitalAtUse = stamina ? _vitals.CurrentStamina : _vitals.CurrentHealth;
+ _kitLineAmount = 0;
+ }
+
+ private static readonly System.Text.RegularExpressions.Regex KitAmountRx =
+ new(@"heal yourself for ([\d,]+) (health|stamina) point", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
+
+ /// The amount a kit's result line says it healed ("You heal yourself for 52 Health points."), 0 if none.
+ internal static int KitLineAmount(string lower)
+ {
+ var m = KitAmountRx.Match(lower);
+ return m.Success && int.TryParse(m.Groups[1].Value.Replace(",", ""), out int n) ? n : 0;
+ }
+
+ /// The vitals already show the heal the kit's line named: its vital at or over what it was
+ /// at the use plus that amount (capped at the maximum). Nothing named (a failed kit): false.
+ private bool KitVitalsCaughtUp()
+ {
+ if (_kitLandedAt == DateTime.MinValue || _kitLineAmount <= 0) return false;
+ uint cur = _kitIsStamina ? _vitals.CurrentStamina : _vitals.CurrentHealth;
+ uint max = _kitIsStamina ? _vitals.MaxStamina : _vitals.MaxHealth;
+ if (max == 0) return false;
+ uint want = Math.Min(max, _kitVitalAtUse + (uint)_kitLineAmount);
+ return cur >= want;
}
private bool MotionQueueBusy => _host.HasGetCastBusyState && !_host.CanCastNow;
@@ -2954,7 +3108,7 @@ public partial class BuffManager : IDisposable
var end = KitWaitVerdict(sinceUse,
_kitLandedAt != DateTime.MinValue ? (now - _kitLandedAt).TotalMilliseconds : -1,
_kitAnsweredAt != DateTime.MinValue ? (now - _kitAnsweredAt).TotalMilliseconds : -1,
- KitServerTookIt(), MotionQueueBusy);
+ KitServerTookIt(), MotionQueueBusy, KitVitalsCaughtUp());
if (end == KitWaitEnd.Waiting) return true;
if (end != KitWaitEnd.Landed)
{
@@ -3026,6 +3180,17 @@ public partial class BuffManager : IDisposable
/// Kit Min Success % with a melee or missile weapon out, when Kit Min Success is higher.
internal const int WeaponOutKitMinPct = 30;
+ /// A vital spell now would need a wand swap first: a melee or missile stance, or out of Magic
+ /// stance with a wand to swap to that is not in hand (peace with the weapon still wielded).
+ private bool SpellNeedsWandSwap()
+ {
+ int mode = CurrentCombatMode;
+ if (mode == CombatMode.Melee || mode == CombatMode.Missile) return true;
+ if (mode == CombatMode.Magic) return false;
+ int wand = FindWandInItems();
+ return wand != 0 && !IsBuffWandWielded(wand);
+ }
+
///
/// True when a kit may be used: (Kit Min Success % for healing kits,
/// Stamina Kit Min Success % for stamina kits) is 0, or the kit's chance of working on
@@ -3040,7 +3205,9 @@ public partial class BuffManager : IDisposable
// (2026-11-13): low stamina doesn't kill, and the bar hid Stamina Kit Min Success % (50 read
// as 30, a 16% Greater Stamina Kit every 3 s).
bool staminaKit = kitName.EndsWith("Stamina Kit", StringComparison.OrdinalIgnoreCase);
- if (!staminaKit && (CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
+ // Peace with the weapon still in hand is the same swap (2026-11-22: a 53% kit skipped in peace
+ // with hand wraps wielded; the wand swap, the stance and a fizzle took 9 s for one +115 heal).
+ if (!staminaKit && SpellNeedsWandSwap())
minPct = Math.Min(minPct, WeaponOutKitMinPct);
if (minPct <= 0 || _charSkills == null) return true;
@@ -3143,6 +3310,35 @@ public partial class BuffManager : IDisposable
return ShieldBuffBelowThreshold(desiredBuffs, thresholdSec);
}
+ ///
+ /// How many buffs a rebuff with as its line would cast: the character's own,
+ /// the item spells (weapon auras, armor banes) and the shield's; a missing or dispelled one counts, a parked
+ /// one doesn't (as AnyBuffBelowThreshold). -1 with buffing off. For scripts, through rabuffsdue[seconds]
+ /// (2026-11-20): a script that reads only the character's enchantments, so before a Thread it never saw
+ /// thirteen item spells with 14 minutes left, and RynthAi recast them in the Thread.
+ ///
+ public int CountBuffsDue(int thresholdSec)
+ {
+ if (!_settings.EnableBuffing) return -1;
+ var desiredBuffs = BuildDynamicBuffList();
+ int sec = Math.Max(0, thresholdSec);
+ int due = 0;
+ DateTime now = RynthClock.Now;
+ foreach (string buffBaseName in desiredBuffs)
+ {
+ AcSkillType castSkill = SkillFor(buffBaseName);
+ if (!IsSkillUsable(castSkill)) continue;
+ int spellId = FindBestSpellId(buffBaseName, castSkill);
+ if (spellId == 0) continue;
+ int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
+ if (family != 0 && _buffFailCooldownUntil.TryGetValue(family, out DateTime coolUntil) && now < coolUntil)
+ continue;
+ if (!IsBuffActive(spellId, sec)) due++;
+ }
+ if (ShieldBuffBelowThreshold(desiredBuffs, sec)) due++;
+ return due;
+ }
+
// "[FR] skip ..." lines while a rebuff runs: the selector runs every tick (~30 ms), and a
// parked buff logged on each one - 47,000 lines in 10 minutes on 2026-10-11, so the log
// rotated every few minutes and held nothing from before. Once per buff and reason a minute.
@@ -4713,6 +4909,7 @@ public partial class BuffManager : IDisposable
if (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue && IsKitResultLine(lower))
{
_kitLandedAt = RynthClock.Now;
+ _kitLineAmount = KitLineAmount(lower);
NoteKitResultLine(text, lower); // "... is used up." naming it: kit picks skip it (BuffManager.KitUsedUp.cs)
ClearKitRefusedStreaks(); // a kit landed: the refusal streaks end (BuffManager.VitalWandGate.cs)
}
@@ -4781,6 +4978,8 @@ public partial class BuffManager : IDisposable
_host.Log($"[BuffChat] PARKED pending={_pendingSpellId}{(PendingIsShield ? " (on the shield)" : "")} — AC too busy (cast gesture in progress); throttle kept, backing off before re-issue.");
if (_pendingSpellId != _pendingVitalSpellId)
_chain.TooBusyLine(_pendingSpellId, s => _host.Log(s));
+ else
+ _chain.TooBusyLineVital(_pendingSpellId, Now, s => _host.Log(s));
}
if (!pendingRunning) _pendingSpellId = 0;
@@ -5144,6 +5343,35 @@ public partial class BuffManager : IDisposable
_host.GetUseDoneSeq(), Now, out _fastChainWhy);
}
+ ///
+ /// The vital fast path for this tick (BuffCastChain, "Vital casts in the between-fights top-off"):
+ /// the setting and the pacing are on, the character is in Magic stance, no monster is within
+ /// Monster Range and health isn't falling (InCombatNow: in a fight nothing changes), a vital is
+ /// under a line (else the buff chain's own rules), no kit is in flight, no held stop, and the last
+ /// action was our own vital cast answered by UseDone(0) moments ago. Only a vital cast rides it.
+ ///
+ private bool FastVitalChainNow()
+ {
+ if (!_settings.FastBuffChain || !ActionPacer.Enabled) return false;
+ if (!_host.HasUseDoneSeq || CurrentCombatMode != CombatMode.Magic) return false;
+ if (_vitals.MaxHealth == 0 || KitPending() || VitalsClearOfEveryLine()) return false;
+ if (InCombatNow()) return false;
+ if (MoveAudit.HasPendingStop) return false;
+ bool hasLast = _host.TryGetLastUseDone(out int lastSeq, out uint lastErr);
+ return _chain.EligibleVital(ActionPacer.Started, ActionPacer.AttacksSent, MoveAudit.MovementSends, hasLast, lastSeq, lastErr,
+ _host.GetUseDoneSeq(), Now, out _fastChainWhy);
+ }
+
+ /// A kit, potion or peace switch on a vital fast-path tick: not sent (the animation gate was
+ /// skipped for a cast only); handled, so nothing else stands in for it, and it goes next tick.
+ private bool FastTickItemWait(string what)
+ {
+ _chain.HoldForAnimation(); // no fast path again until the next cast: the kit goes once the animation ends
+ _vitalWhy = $"{what} waits for the animation (this tick only lets a vital cast go)";
+ _healWaitKind = "cast gate (a gesture is animating)";
+ return true;
+ }
+
/// True when health, stamina and mana are at or over every line the vitals step acts on
/// (combat and idle, emergency included), and no kit or stamina run is in progress.
private bool VitalsClearOfEveryLine()
@@ -5528,7 +5756,8 @@ public partial class BuffManager : IDisposable
private bool HealIsUrgent(int hp, int stamPct)
{
string line = ActiveHealLine(hp, stamPct, out _, out bool inCombat);
- return line is "Emergency Heal At" or "Stamina To Health At" || (line == "Heal At" && inCombat);
+ // Top Off HP while being hit with Combat off (FightHealthLine) is as urgent as Heal At in a fight.
+ return line is "Emergency Heal At" or "Stamina To Health At" || (line is "Heal At" or "Top Off HP" && inCombat);
}
private bool EnsureMagicMode(bool forBuff = false, bool urgentHeal = false)
@@ -5745,7 +5974,7 @@ public partial class BuffManager : IDisposable
// one of these two branches fires per call — no same-tick wield/unwield race.
if (wandId != 0 && IsWieldedLive(wandId))
{
- int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
+ int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1, new[] { wandId });
if (openPack != 0) _host.MoveItemInternal((uint)wandId, (uint)openPack, 0, 1);
}
else if (bowId != 0 && !IsWieldedLive(bowId))
@@ -5838,7 +6067,7 @@ public partial class BuffManager : IDisposable
case HandSwapSequence.Act.MoveToPack:
{
- int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
+ int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1, new[] { step.Id });
if (pack == 0)
{
WorldObjectCache.WarnPackFull(_host, "can't put the weapon away to switch to the wand, so buffs and spell heals can't cast");
@@ -5966,7 +6195,7 @@ public partial class BuffManager : IDisposable
if ((now - _modeChangedAt).TotalMilliseconds < BurstQuietMs) return 0;
var moves = _wandSwap.Blockers(hands);
if (moves.Count == 0 || moves.Count > 2) return 0;
- int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: moves.Count);
+ int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: moves.Count, moves);
if (pack == 0) return 0;
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "wand swap burst: peace, the hands and the wand at once")) return 1;
foreach (int id in moves)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs
index 865981a..bcc0998 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Ammo.cs
@@ -324,6 +324,43 @@ public partial class CombatManager
private static string LabelOf(AmmoCandidate a) => a.Untyped ? "ammo" : MissileAmmo.Label(a.AmmoType);
+ // ── Ammo by element (R-20261121-163725-da49, 2026.11.19.1) ────────────────────────────────────
+ // "Bows will swap correctly but not ammo": the ammo step chose a stack only for an empty slot or
+ // ammo of another type, so after a bow-to-bow swap for a monster weak to Fire, the Cold arrows
+ // the last bow shot stayed on. Now, with ammo the launcher can shoot already on, the stack
+ // MissileAmmo.Choose would pick for this target is wielded instead when its element ranks
+ // strictly better (the Monsters rule's damage type, then the target's weaknesses). Choose's own
+ // order still comes first (the listed ammo, then infinite ammo), so this only moves between
+ // stacks the player would be given anyway. At most one such swap per launcher every
+ // AmmoElementSwapRestSec, so a target with two equal weaknesses can't flip it back and forth.
+ internal const double AmmoElementSwapRestSec = 15;
+ private readonly Dictionary _ammoElementSwapAt = new();
+
+ /// The stack to put on instead of for , or null.
+ private AmmoCandidate? BetterAmmoFor(int launcherId, WorldObject wo, int lt, IReadOnlyList pack,
+ AmmoCandidate wielded, WorldObject? target, MonsterRule? rule, DateTime now)
+ {
+ if (target == null || AmmoTracker.PendingId != 0 || _ammoDequipPendingId != 0) return null;
+ if (_ammoElementSwapAt.TryGetValue(launcherId, out var last) && (now - last).TotalSeconds < AmmoElementSwapRestSec) return null;
+ var rank = AmmoRank(RuleElementOf(rule), WeaknessFor(target));
+ string launcherElement = LauncherElement(launcherId, wo);
+ var usable = pack.Where(a => a.Id == wielded.Id || !AmmoTracker.Resting(a.Id, now)).ToList();
+ var pick = MissileAmmo.Choose(lt, launcherElement, usable, rank);
+ if (pick == null || pick.Id == wielded.Id) return null;
+ if (rank(ElementOrPierce(pick, launcherElement)) >= rank(ElementOrPierce(wielded, launcherElement))) return null;
+ _ammoElementSwapAt[launcherId] = now;
+ _host.Log($"[EquipDiag] ammo by element: '{target.Name}' takes {ElementOrPierce(pick, launcherElement)} better than " +
+ $"{ElementOrPierce(wielded, launcherElement)}: 0x{(uint)wielded.Id:X8} '{wielded.Name}' -> 0x{(uint)pick.Id:X8} '{pick.Name}' " +
+ $"for 0x{(uint)launcherId:X8} '{wo.Name}'");
+ return pick;
+ }
+
+ private static string ElementOrPierce(AmmoCandidate a, string launcherElement)
+ {
+ string e = MissileAmmo.EffectiveElement(a, launcherElement);
+ return e.Length > 0 ? e : "Pierce";
+ }
+
private void ArmAmmoFollowUp(int launcherId, DateTime now)
{
if (_ammoFollowUpFor == launcherId && now < _ammoFollowUpUntil) return;
@@ -390,6 +427,14 @@ public partial class CombatManager
EndAmmoFollowUp();
ClearAmmoDequip();
_noAmmoSaid.Remove(launcherId);
+ // A stack with a better element for this target (CombatManager.Ammo.cs, "Ammo by element"):
+ // this one goes into the pack, and the empty slot's step below wields that one.
+ if (BetterAmmoFor(launcherId, wo, lt, pack, wielded, target, rule, now) is { } better)
+ {
+ var prep = PutAmmoAway(wielded, launcherId,
+ $"for '{better.Name}' ({ElementOrPierce(better, LauncherElement(launcherId, wo))}, a better element for '{target.Name}')", now);
+ if (prep != AmmoPrep.Blocked) return true; // the slot empties, then the better stack goes on
+ }
canShoot = true;
return false;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.DebuffPass.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.DebuffPass.cs
new file mode 100644
index 0000000..f744b17
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.DebuffPass.cs
@@ -0,0 +1,202 @@
+// ============================================================================
+// RynthSuite - Combat/CombatManager.DebuffPass.cs
+// "Debuff every monster in range before attacking" (2026-11-22, setting
+// DebuffAllBeforeAttacking, off by default; /ra debuffall [on|off]). With
+// several monsters in Monster Range, each one's own debuffs (its Monsters
+// rule: Imperil, vulns, Void debuffs, typed-in ones) are cast on all of them,
+// nearest first, before anything is attacked, so pets and the attack spells
+// that follow land on debuffed monsters. The order and the caps are
+// DebuffPass's (pure, tested); this file feeds it the scan, casts what it
+// picks and holds the pet summon while the pass runs.
+//
+// Debuffs go out through the same cast path as the fight target's own: one
+// at a time, its result read from chat (landed, resisted, fizzled, refused).
+// Melee and missile with a weapon in hand cast no debuffs at all (the wand
+// swap doesn't work there), so the pass doesn't run in those modes.
+// ============================================================================
+
+using System;
+using System.Collections.Generic;
+
+namespace RynthCore.Plugin.RynthAi;
+
+public partial class CombatManager
+{
+ private DebuffPass? _passState;
+ private readonly List _passCandidates = new();
+ private readonly List _passInRange = new();
+ private bool _pendingDebuffFromPass;
+ private bool _petHoldLogged;
+
+ // A monster's melee hits on the character, by name (the hit lines name it, not its object).
+ private readonly Dictionary _hitOnMeAt = new(StringComparer.OrdinalIgnoreCase);
+ /// A monster this close that hit the character this recently is "on you".
+ internal const double OnYouYards = 6.0;
+ internal const double OnYouSeconds = 4.0;
+
+ /// The pass's state (tests read it).
+ internal DebuffPass DebuffPassState => _passState ??= new DebuffPass
+ {
+ Log = s => _host.Log(s),
+ NameOf = id => _worldFilter[id]?.Name ?? "",
+ };
+
+ ///
+ /// The pet summon waits while the first pass runs (PetManager), so the pet's first hits land on
+ /// debuffed monsters. Bounded by the pass's time cap; never while a monster is on you.
+ ///
+ internal bool DebuffPassHoldsPets
+ {
+ get
+ {
+ if (!_settings.DebuffAllBeforeAttacking || !_settings.EnableCombat || _passState == null) return false;
+ bool hold = _passState.Holding(RynthClock.Now);
+ // Before the fight's first cast: only when the pass can run (no melee or missile weapon
+ // out, nothing hitting you) and some monster in range has a debuff to get.
+ if (hold && _passState.Phase == DebuffPass.Stage.Idle)
+ {
+ int mode = CurrentCombatMode;
+ hold = mode != CombatMode.Melee && mode != CombatMode.Missile && !MonsterOnYou() && AnyInRangeNeedsDebuff();
+ }
+ if (hold && !_petHoldLogged) _host.Log("[DebuffPass] the pet summon waits for the debuff pass");
+ _petHoldLogged = hold;
+ return hold;
+ }
+ }
+
+ private bool AnyInRangeNeedsDebuff()
+ {
+ FillPassCandidates();
+ for (int i = 0; i < _passCandidates.Count; i++)
+ if (PassDebuffFor(_passCandidates[i], out _, out _, out _, out _)) return true;
+ return false;
+ }
+
+ private void FillPassCandidates()
+ {
+ _passCandidates.Clear();
+ double range = Math.Max(1, _settings.MonsterRange);
+ for (int i = 0; i < _scannedTargets.Count; i++) // sorted nearest first
+ if (_scannedTargets[i].Distance <= range) _passCandidates.Add(_scannedTargets[i].Id);
+ }
+
+ /// AttackWithMagic, before the fight target's own debuffs: the fight's first cast begins the pass.
+ private void BeginDebuffPass()
+ {
+ if (!_settings.DebuffAllBeforeAttacking || _spellManager == null) return;
+ if (_passState != null && _passState.Phase != DebuffPass.Stage.Idle) return;
+ FillPassCandidates();
+ DebuffPassState.Begin(_passCandidates, RynthClock.Now);
+ }
+
+ /// ScanNearbyTargets, after the sort: the pass sees who is in range.
+ private void ObserveDebuffPass()
+ {
+ if (!_settings.DebuffAllBeforeAttacking)
+ {
+ if (_passState != null && _passState.Phase != DebuffPass.Stage.Idle) _passState.Reset();
+ return;
+ }
+ _passInRange.Clear();
+ double range = Math.Max(1, _settings.MonsterRange);
+ for (int i = 0; i < _scannedTargets.Count; i++)
+ if (_scannedTargets[i].Distance <= range) _passInRange.Add(_scannedTargets[i].Id);
+ DebuffPassState.Observe(_passInRange, activeTargetId != 0, RynthClock.Now);
+ }
+
+ /// LearnFromCombatChat: a monster's hit on the character.
+ private void NoteHitOnMe(string name)
+ {
+ if (string.IsNullOrEmpty(name)) return;
+ if (_hitOnMeAt.Count >= 64 && !_hitOnMeAt.ContainsKey(name)) _hitOnMeAt.Clear();
+ _hitOnMeAt[name] = RynthClock.Now;
+ }
+
+ ///
+ /// A monster is hitting the character in melee: one within whose name
+ /// hit us in the last .
+ ///
+ internal bool MonsterOnYou()
+ {
+ if (_hitOnMeAt.Count == 0) return false;
+ DateTime now = RynthClock.Now;
+ for (int i = 0; i < _scannedTargets.Count; i++)
+ {
+ var t = _scannedTargets[i];
+ if (t.Distance > OnYouYards) continue;
+ string name = t.Name ?? _worldFilter[t.Id]?.Name ?? "";
+ if (name.Length > 0 && _hitOnMeAt.TryGetValue(name, out DateTime at) && (now - at).TotalSeconds <= OnYouSeconds)
+ return true;
+ }
+ return false;
+ }
+
+ /// Tests: a hit line from just now.
+ internal void NoteHitOnMeForTests(string name) => NoteHitOnMe(name);
+
+ /// The rule's next debuff for this monster (not on it, castable), or false.
+ private bool PassDebuffFor(int id, out string key, out int spellId, out int tier, out bool renewal)
+ {
+ key = ""; spellId = 0; tier = 0; renewal = false;
+ if (!IsLiveMonster(id)) return false;
+ if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable((uint)id)) return false;
+ var wo = _worldFilter[id];
+ if (wo == null) return false;
+ var rule = GetRuleForTarget(wo);
+ if (rule == null) return false;
+ string element = GetPreferredElement(wo, rule);
+ return NextDebuffFor(id, rule, element, RynthClock.Now, out key, out spellId, out tier, out renewal);
+ }
+
+ /// The monster the pass would debuff now, or 0 (attack). Setting off: 0.
+ private int PassPick()
+ {
+ if (!_settings.DebuffAllBeforeAttacking || _spellManager == null) return 0;
+ FillPassCandidates();
+ return DebuffPassState.Next(_passCandidates, activeTargetId,
+ id => PassDebuffFor(id, out _, out _, out _, out _), MonsterOnYou(), RynthClock.Now);
+ }
+
+ /// The pass has a debuff to cast before the next attack.
+ private bool PassWantsDebuff() => PassPick() != 0;
+
+ ///
+ /// AttackWithMagic, after the fight target's own debuffs: cast the pass's next debuff (at another
+ /// monster) instead of attacking. True when a debuff went out or it waits for mana.
+ ///
+ private bool TryDebuffPassCast()
+ {
+ int id = PassPick();
+ if (id == 0) return false;
+ if (!PassDebuffFor(id, out string key, out int spellId, out int tier, out bool renewal)) return false;
+ if (ManaHoldsCast(spellId)) return true; // mana reserve: Stamina to Mana first, or regenerate
+ var wo = _worldFilter[id];
+ double dist = DistanceInScan(id);
+ _host.Log($"[DebuffPass] {(renewal ? "renewing" : "casting")} {key} (T{tier}) on 0x{(uint)id:X8} '{wo?.Name}' at {dist:0.0} yd" +
+ (DebuffPassState.Phase == DebuffPass.Stage.Attacking ? " (came into range mid-fight)" : "") +
+ $", the fight target 0x{(uint)activeTargetId:X8} waits");
+ if (!CastDebuffAt(id, wo?.Name ?? "", key, spellId, tier, renewal)) return false;
+ _pendingDebuffFromPass = true;
+ DebuffPassState.NoteCast(id, RynthClock.Now);
+ LastCombatSkipReason = "debuff-pass"; // D4 record-only
+ return true;
+ }
+
+ private double DistanceInScan(int id)
+ {
+ for (int i = 0; i < _scannedTargets.Count; i++)
+ if (_scannedTargets[i].Id == id) return _scannedTargets[i].Distance;
+ return double.NaN;
+ }
+
+ /// An attack went out at the fight target: an arrival may get the next debuff.
+ private void NotePassAttack() => _passState?.NoteAttack();
+
+ /// The pending debuff's result: the pass counts failures on its own monsters.
+ private void NotePassDebuffResult(bool failed)
+ {
+ if (!_pendingDebuffFromPass) return;
+ _pendingDebuffFromPass = false;
+ if (failed) _passState?.NoteFailed(_pendingDebuffTargetId);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs
index d08d882..ddc9442 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.Offhand.cs
@@ -337,7 +337,7 @@ public partial class CombatManager
_host.Log($"[EquipDiag] off hand 0x{(uint)offId:X8} '{name}' didn't come off after {OffDequipMaxTries} tries — leaving the hands as they are for 2 min");
return OffPrep.Blocked;
}
- int packId = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
+ int packId = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1, new[] { offId });
if (packId == 0 || !_host.HasMoveItemInternal)
{
if (packId == 0) WorldObjectCache.WarnPackFull(_host, "can't put the shield away to change weapons");
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs
index 598e3e6..de9c86e 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs
@@ -50,6 +50,7 @@ public partial class CombatManager
internal const double PassedOverBeyondRangeM = 15.0;
internal const string PassedOverLos = "line of sight blocked";
+ internal const string PassedOverWindow = "in a building (or outside it) seen through a window: melee goes in by a door";
internal const string PassedOverOtherLevel = "too far above or below for melee";
internal const string PassedOverBlacklisted = "blacklisted";
internal const string PassedOverNeverAttack = "on the never-attack list";
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
index 8ff7cb1..cef5df1 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
@@ -309,11 +309,19 @@ public partial class CombatManager : IDisposable
///
/// True = don't lock a new target yet. RynthAi answers true with Boost Loot Priority on while
/// our kill's corpse forms or is looted (RynthAiPlugin.BoostLootHoldsNewTarget): one kill, one
- /// loot. A monster within CloseAttackYards is still fought at once. Null = never hold.
+ /// loot. A monster within CloseAttackYards, or one in the scan hitting us, is still fought at
+ /// once. Null = never hold.
///
public Func? HoldNewTarget { get; set; }
/// Why HoldNewTarget holds, for its one log line (null: Boost Loot Priority's words).
public Func? HoldNewTargetWhy { get; set; }
+
+ ///
+ /// True = leave this monster (its id) out of the scan. The hunt fence answers true for a monster
+ /// outside its circle (RynthAiPlugin.FenceSkipsTarget). The target being fought and a forced one
+ /// are never asked. Null = never skip.
+ ///
+ public Func? SkipTarget { get; set; }
private bool _newTargetHeldLogged;
///
@@ -901,16 +909,95 @@ public partial class CombatManager : IDisposable
/// scan always runs and has no side effects, so a close-range scanned mob
/// is the non-circular signal.
///
- public bool IsUnderCloseAttack => IsActivelyEngaged || HasCloseThreat(CloseAttackYards);
+ public bool IsUnderCloseAttack => IsActivelyEngaged || HasCloseThreat(CloseAttackYards) || IsBeingHitByScanned;
///
- /// HoldNewTarget says wait (Boost Loot Priority, a kill's corpse to loot) and no monster is
- /// within CloseAttackYards. One log line per hold.
+ /// A monster in the scan (inside Monster Range, in sight, attackable) hit us, or swung and
+ /// missed, within HitTakenRecentMs (2026-11-22). "On top of me" was distance only: a monster
+ /// beyond CloseAttackYards that is hitting the character (an archer, a caster, a big monster
+ /// whose middle stands more than 5 yd off) counted as no fight, so with Boost Loot Priority the
+ /// looter kept the tick and combat locked nothing while it hit (#rynthsuite 11-15: "a mob
+ /// spawns and approaches me ... I just stand there and take hits"). A hit line names the monster,
+ /// not its object: any scanned monster of that name counts. No side effects (the arbiter's path).
+ ///
+ public bool IsBeingHitByScanned
+ {
+ get
+ {
+ if (_hitTakenAt.Count == 0 || _scannedTargets.Count == 0) return false;
+ DateTime now = TargetClock();
+ for (int i = 0; i < _scannedTargets.Count; i++)
+ {
+ string? name = _scannedTargets[i].Name;
+ if (!string.IsNullOrEmpty(name) && _hitTakenAt.TryGetValue(name, out DateTime at)
+ && (now - at).TotalMilliseconds <= HitTakenRecentMs)
+ return true;
+ }
+ return false;
+ }
+ }
+
+ /// A monster's hit or miss on us counts as "on me" this long (a swing every 1-3 s; a
+ /// bow or a spell a little slower).
+ internal const double HitTakenRecentMs = 4000;
+
+ // Monster name -> when its last hit or miss on us came (NoteHitTaken). Names are the hit lines'.
+ private readonly Dictionary _hitTakenAt = new(StringComparer.OrdinalIgnoreCase);
+
+ // "You evaded Olthoi Warrior!": the monster swung at us and missed.
+ private static readonly System.Text.RegularExpressions.Regex EvadedIncoming = new(
+ @"^You evaded (?:the )?(?.+?)!",
+ System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant);
+
+ /// A combat chat line: a monster's hit on us ("X slashes your leg for N points of ...")
+ /// or its miss ("You evaded X!") is noted for .
+ internal void NoteHitTaken(string text)
+ {
+ string? name = null;
+ if (text.StartsWith("You ", StringComparison.Ordinal))
+ {
+ var e = EvadedIncoming.Match(text);
+ if (e.Success) name = e.Groups["name"].Value.Trim();
+ }
+ else
+ {
+ var m = IncomingDamage.Match(text);
+ if (m.Success) name = m.Groups["name"].Value.Trim();
+ }
+ if (string.IsNullOrEmpty(name)) return;
+ DateTime now = TargetClock();
+ if (_hitTakenAt.Count >= 64)
+ {
+ _hitTakenPruneScratch.Clear();
+ foreach (var kv in _hitTakenAt)
+ if ((now - kv.Value).TotalMilliseconds > HitTakenRecentMs) _hitTakenPruneScratch.Add(kv.Key);
+ foreach (string k in _hitTakenPruneScratch) _hitTakenAt.Remove(k);
+ }
+ _hitTakenAt[name] = now;
+ }
+ private readonly List _hitTakenPruneScratch = new();
+
+ ///
+ /// Boost Loot Priority's "corpses first" (2026-11-22, RynthAiPlugin.BoostLootFirst.cs): true while the
+ /// hold below applies with a monster within CloseAttackYards too. Null or false: the old rule (a close
+ /// monster is fought at once).
+ ///
+ public Func? HoldNewTargetThroughThreat { get; set; }
+
+ ///
+ /// HoldNewTarget says wait (Boost Loot Priority, a kill's corpse to loot), no monster is
+ /// within CloseAttackYards and none in the scan is hitting us (IsBeingHitByScanned). One log
+ /// line per hold.
+ /// HoldNewTargetThroughThreat (Boost Loot Priority, corpses first) holds it through both.
///
private bool NewTargetHeldForLoot()
{
bool held;
- try { held = HoldNewTarget?.Invoke() == true && !HasCloseThreat(CloseAttackYards); }
+ try
+ {
+ held = HoldNewTarget?.Invoke() == true
+ && ((!HasCloseThreat(CloseAttackYards) && !IsBeingHitByScanned) || HoldNewTargetThroughThreat?.Invoke() == true);
+ }
catch { held = false; }
if (!held)
{
@@ -1198,6 +1285,9 @@ public partial class CombatManager : IDisposable
_beyondRange.Add(new PassedOverMonster { Id = wo.Id, Distance = dist, Why = "" });
continue;
}
+ // The hunt fence (RynthAiPlugin.HuntFence.cs): a monster outside it is left alone. The one
+ // being fought is kept.
+ if (!isEngaged && !isForced && SkipTarget != null && SkipTarget(wo.Id)) continue;
// Left out below for a reason that can hide a monster worth fighting: noted for the
// lock line's "passed over" (CombatManager.PassedOver.cs). In range, not the target.
bool notePassed = !isEngaged && dist <= maxDist;
@@ -1303,6 +1393,17 @@ public partial class CombatManager : IDisposable
losBlocked = false;
}
+ // Through a window (2026-11-17: "it tries to run through windows as if they are openings"): one of
+ // the two in a building's rooms and the other outside, the line clear (a window, an opening the raycast
+ // sees through) and farther than melee reaches across a doorway: melee ran straight at the wall under the
+ // window. Left to the hunt, which walks in by a door; not counted as out of sight (the walk isn't held).
+ if (!losBlocked && hasPlayerPos && dist > MeleeAcrossDoorwayM && MeleeIsTheAttackOn(wo, attackType)
+ && AcrossBuildingWall(meCell, (uint)wo.Id))
+ {
+ if (notePassed) NotePassedOver(wo.Id, dist, PassedOverWindow);
+ continue;
+ }
+
// Don't blacklist from scan — just exclude from this result.
// Blacklisting only happens when an active target fails LOS during attack.
if (losBlocked)
@@ -1342,6 +1443,8 @@ public partial class CombatManager : IDisposable
LastScanInRing = scanRing;
LastScanPossible = _scannedTargets.Count;
LastScanLosBlocked = _nearbyNoLos;
+
+ ObserveDebuffPass(); // who is in range, for "Debuff every monster in range before attacking"
}
public CombatManager(RynthCoreHost host, LegacyUiSettings settings, WorldObjectCache worldFilter, SpellManager? spellManager = null)
@@ -1394,6 +1497,7 @@ public partial class CombatManager : IDisposable
_pendingDebuffTargetId = 0;
}
_debuffs.Forget(id);
+ _passState?.Forget(id);
}
public void SetPlayerId(uint playerId)
{
@@ -1729,6 +1833,7 @@ public partial class CombatManager : IDisposable
var m = IncomingDamage.Match(text);
if (!m.Success) return;
string name = m.Groups["name"].Value.Trim();
+ NoteHitOnMe(name); // "on you" for the debuff pass
uint src = WcidForName(name);
if (src == 0) return;
if (int.TryParse(m.Groups["n"].Value, out int amount))
@@ -1751,6 +1856,7 @@ public partial class CombatManager : IDisposable
if (text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase) > 0)
NoteSwingEvidence("miss");
NoteAttackReachedFromChat(text);
+ try { NoteHitTaken(text); } catch { } // a monster hitting us is a fight (IsBeingHitByScanned)
if (_damageStore == null) return;
try { LearnFromCombatChat(text); } catch { }
@@ -2125,6 +2231,7 @@ public partial class CombatManager : IDisposable
///
private void NoteDebuffFailed(string what)
{
+ NotePassDebuffResult(failed: true); // the debuff pass's own count (CombatManager.DebuffPass.cs)
if (_debuffs.Failed(_pendingDebuffTargetId, _pendingDebuffKey ?? "")) // skip it for this target
{
_host.WriteToChat($"[RynthAi] {what}: {_pendingDebuffKey} — {DebuffTimers.MaxFailures} tries on this target, skipping it", 2);
@@ -2145,6 +2252,7 @@ public partial class CombatManager : IDisposable
///
private void NoteDebuffLanded()
{
+ NotePassDebuffResult(failed: false);
int seconds = SpellDatabase.DurationSeconds(_pendingDebuffSpellId);
_debuffs.Landed(_pendingDebuffTargetId, _pendingDebuffKey ?? "", seconds, RynthClock.Now);
if (seconds > 0)
@@ -4215,7 +4323,8 @@ public partial class CombatManager : IDisposable
{
var rule2 = GetRuleForTarget(targetObj);
string elem2 = GetPreferredElement(targetObj, rule2);
- if (rule2 != null && !HasPendingDebuffs(rule2, elem2))
+ // The debuff pass (DebuffAllBeforeAttacking) keeps the wand out until it is done too.
+ if (rule2 != null && !HasPendingDebuffs(rule2, elem2) && !PassWantsDebuff())
{
_returnToPhysicalCombat = false;
if (_savedWeaponId != 0
@@ -4235,7 +4344,8 @@ public partial class CombatManager : IDisposable
if (rule != null && _spellManager != null && !_returnToPhysicalCombat)
{
string elem = GetPreferredElement(targetObj, rule);
- if (HasPendingDebuffs(rule, elem))
+ bool ownPending = HasPendingDebuffs(rule, elem);
+ if (ownPending || _settings.DebuffAllBeforeAttacking)
{
int wandId = FindWandInItems();
// This quick swap (UseObject wand + Magic in one go) can't work with a
@@ -4245,16 +4355,19 @@ public partial class CombatManager : IDisposable
// It only cost each new target a refused swap, a lost attack cycle and
// the swap gate. Skip it then; it still runs when the hands are empty.
// A shield or an off-hand weapon blocks the wand the same way (ACE refuses a caster beside it).
- if (wandId != 0 && (FindWieldedNonWandWeapon(wandId) != 0 || OffhandInSlot() != 0))
+ // The debuff pass (DebuffAllBeforeAttacking) only takes the wand when the hands
+ // are free; with a weapon in hand it doesn't run (no debuffs are cast there).
+ bool handsBlocked = wandId != 0 && (FindWieldedNonWandWeapon(wandId) != 0 || OffhandInSlot() != 0);
+ if (handsBlocked)
{
- if (!_physicalDebuffSkipWarned)
+ if (ownPending && !_physicalDebuffSkipWarned)
{
_physicalDebuffSkipWarned = true;
_host.Log($"[CombatCast] debuffs for '{rule.Name}' skipped in {CombatModeName(CurrentCombatMode)} mode — can't swap to the wand with a weapon in hand");
_host.WriteToChat($"[RynthAi] Debuffs aren't cast in melee/missile mode with a weapon in hand (the wand swap doesn't work there). Fighting without them.", 2);
}
}
- else if (wandId != 0
+ else if (wandId != 0 && (ownPending || PassWantsDebuff())
&& (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("combat-debuff-wand")))
{
// TODO: Save current equipped weapon when inventory API is available.
@@ -4275,7 +4388,7 @@ public partial class CombatManager : IDisposable
// Physical combat always attacks — spell shape flags (UseArc/Bolt/Ring/Streak)
// are only relevant in magic mode and must not gate melee/missile attacks.
physicalSent = AttackTarget();
- if (physicalSent) _attackedThisTick = true;
+ if (physicalSent) { _attackedThisTick = true; NotePassAttack(); }
}
// Ring spells hit an area — no per-target damage feedback is generated,
@@ -4666,7 +4779,7 @@ public partial class CombatManager : IDisposable
}
else
{
- int pack = WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
+ int pack = WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1, new[] { unchecked((int)wid) });
if (pack == 0 || !_host.HasMoveItemInternal)
{
_host.Log($"{head} re-wield: skipped — no pack with room to put 0x{wid:X8} '{wo.Name}' in");
@@ -5066,31 +5179,41 @@ public partial class CombatManager : IDisposable
{
// Target Lock on: keep it until it is no longer valid. A higher priority it holds off is
// logged once per pair, so a report shows the lock, not a priority ignored.
+ // Closest is the one exception (2026-11-22): a monster on you takes the lock from one
+ // that isn't (LockGivesWayToMonsterOnYou).
if (_settings.TargetLock)
{
- if (_lockedPriority < topPriority && best.Id != _lockedTargetId
- && _lockHeldOverLogged != (_lockedTargetId, best.Id))
+ string? onYou = LockGivesWayToMonsterOnYou(scheme, inc, incInScan != null, best);
+ if (onYou == null)
{
- _lockHeldOverLogged = (_lockedTargetId, best.Id);
- _host.Log($"[CombatTarget] Target Lock keeps 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' priority {_lockedPriority} " +
- $"over 0x{best.Id:X8} '{_worldFilter[best.Id]?.Name}' priority {PriorityOf(best.Id)} (it holds until the target dies or leaves Monster Range)");
+ if (_lockedPriority < topPriority && best.Id != _lockedTargetId
+ && _lockHeldOverLogged != (_lockedTargetId, best.Id))
+ {
+ _lockHeldOverLogged = (_lockedTargetId, best.Id);
+ _host.Log($"[CombatTarget] Target Lock keeps 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' priority {_lockedPriority} " +
+ $"over 0x{best.Id:X8} '{_worldFilter[best.Id]?.Name}' priority {PriorityOf(best.Id)} (it holds until the target dies or leaves Monster Range)");
+ }
+ return;
}
- return;
+ switchWhy = onYou;
}
- if (best.Id == _lockedTargetId) return;
+ else
+ {
+ if (best.Id == _lockedTargetId) return;
- // Target Lock off: switch only to a clearly better one, and never with an attack
- // at the incumbent still on its way.
- // Not while the incumbent is out of this tick's scan (inside the scan grace): its
- // values are the last ones seen, and judging fresh candidates against them switched
- // away from a monster closing in. R-20261031-201214-8be7: a Brier Wasp Swarm last
- // scanned at 4.3 m, live at 1.9 m, lost to a wasp at 2.4 m as "clearly better",
- // 124 ms after a bolt went out at it.
- if (incInScan == null) return;
- double incKey = SchemeKey(scheme, inc);
- if (incKey - bestKey < SchemeMargin(scheme)) return;
- if (AttackInFlightAtLocked(now)) return;
- switchWhy = $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, inc)}, another is clearly better";
+ // Target Lock off: switch only to a clearly better one, and never with an attack
+ // at the incumbent still on its way.
+ // Not while the incumbent is out of this tick's scan (inside the scan grace): its
+ // values are the last ones seen, and judging fresh candidates against them switched
+ // away from a monster closing in. R-20261031-201214-8be7: a Brier Wasp Swarm last
+ // scanned at 4.3 m, live at 1.9 m, lost to a wasp at 2.4 m as "clearly better",
+ // 124 ms after a bolt went out at it.
+ if (incInScan == null) return;
+ double incKey = SchemeKey(scheme, inc);
+ if (incKey - bestKey < SchemeMargin(scheme)) return;
+ if (AttackInFlightAtLocked(now)) return;
+ switchWhy = $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, inc)}, another is clearly better";
+ }
}
else if (_lockedTargetId != 0)
{
@@ -5105,6 +5228,30 @@ public partial class CombatManager : IDisposable
LockTarget(best, bestPriority, $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, best)}, priority {bestPriority}, {DescribeTargetPos(best.Id)}", switchWhy);
}
+ ///
+ /// Target Lock with Targeting "Closest" (2026-11-22, #rynthsuite 11-15: "surrounded by mobs and
+ /// watched it target mobs 40 yds out"). The lock held a far monster while others walked up and
+ /// hit the character: on the PC (pid 1792, 11-20 19:41:45) a missile character locked an Obsidian
+ /// Hurler at 24.5 m, the only one in sight; an Obsidian Gigas came up and landed 16 hits for 476
+ /// damage in 32 s, and the bot kept shooting the Hurler for 59 s, locking the Gigas (1.6 m) only
+ /// when the Hurler died. Now a candidate within CloseAttackYards (on you) takes the lock from a
+ /// target more than LockYieldFarM off. The other schemes keep the lock as before (Farthest picks
+ /// far ones on purpose), and so does a lock the player picked. Returns the switch's reason, or
+ /// null to keep the lock.
+ ///
+ private string? LockGivesWayToMonsterOnYou(TargetScheme scheme, in ScannedTarget inc, bool incFresh, in ScannedTarget best)
+ {
+ if (scheme != TargetScheme.Closest || _lockByPlayer || !incFresh) return null;
+ if (best.Id == 0 || best.Id == _lockedTargetId) return null;
+ if (best.Distance > CloseAttackYards || inc.Distance <= LockYieldFarM) return null;
+ return $"Target Lock: a monster is on you at {best.Distance:0.0} m and the target is {inc.Distance:0.0} m off";
+ }
+
+ /// A locked target farther than this gives way to a monster within CloseAttackYards
+ /// (Target Lock, Closest). The 1.5 m over CloseAttackYards keeps two monsters near you from
+ /// trading the lock.
+ private const double LockYieldFarM = CloseAttackYards + CloserFartherMarginM;
+
/// Makes the fight target (one log line; the switch says why).
private void LockTarget(ScannedTarget best, int bestPriority, string picked, string? switchWhy)
{
@@ -5840,7 +5987,7 @@ public partial class CombatManager : IDisposable
case HandSwapSequence.Act.MoveToPack:
{
- int pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
+ int pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1, new[] { step.Id });
if (pack == 0)
{
WorldObjectCache.WarnPackFull(_host, "can't put the wand away to put the weapons back");
@@ -5946,7 +6093,7 @@ public partial class CombatManager : IDisposable
int pack = 0;
if (moves.Count > 0)
{
- pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: moves.Count);
+ pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: moves.Count, moves);
if (pack == 0) return 0;
}
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", $"{HandsSwapLabel} burst: peace, the wand out and the weapons on at once")) return 1;
@@ -6998,7 +7145,7 @@ public partial class CombatManager : IDisposable
if (IsWieldedLive(bowId))
{
- int openPack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
+ int openPack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1, new[] { bowId });
if (openPack == 0 || _combatBowDequipAttempts >= CombatBowDequipMaxAttempts)
{
// No verified-open pack to receive the bow, or repeated failures — the swap
@@ -7168,6 +7315,10 @@ public partial class CombatManager : IDisposable
/// The line-of-sight check is skipped for melee within this (same units as Monster Range).
internal const double MeleeIgnoresLosWithin = 4.0;
+ /// Melee hits across a doorway this far (one inside a building, the other on the step outside); farther,
+ /// across the building's wall, it goes in by a door (the hunt's walk), not at the wall under a window.
+ internal const double MeleeAcrossDoorwayM = 3.5;
+
/// Melee leaves out a monster more than this above or below the character...
internal const double MeleeMaxRiseM = 3.0;
/// ...when it is also this steep from here (rise over run, about 37 degrees): a monster up a ramp
@@ -7896,49 +8047,19 @@ public partial class CombatManager : IDisposable
var rule = GetRuleForTarget(target);
string element = GetPreferredElement(target, rule);
- if (rule != null)
+ BeginDebuffPass(); // Debuff every monster in range before attacking: the fight's first cast begins it
+ if (rule != null
+ && NextDebuffFor(activeTargetId, rule, element, RynthClock.Now, out string debuffKey, out int debuffSpellId, out int castTier, out bool renewal))
{
- var pendingDebuffs = BuildDebuffList(rule, element);
- DateTime now = RynthClock.Now;
- foreach (var debuffKey in pendingDebuffs)
- {
- if (_debuffs.IsOn(activeTargetId, debuffKey, now)) continue;
- bool renewal = _debuffs.RenewAt(activeTargetId, debuffKey) != null;
-
- int spellId = 0;
- int castTier = 0;
- if (debuffKey.StartsWith("Vuln:"))
- spellId = FindBestVulnSpellWithTier(debuffKey.Substring(5), out castTier);
- else if (debuffKey.StartsWith("Custom:"))
- spellId = FindBestCustomDebuffWithTier(debuffKey.Substring(7), out castTier);
- else if (debuffKey.StartsWith("Void:"))
- spellId = FindBestVoidDebuffWithTier(debuffKey.Substring(5), out castTier);
- else
- spellId = FindBestDebuffSpellWithTier(debuffKey, out castTier);
-
- if (spellId == 0) continue;
- if (ManaHoldsCast(spellId)) return; // mana reserve: Stamina to Mana first, or regenerate
-
- try
- {
- _host.CastSpellFor((uint)activeTargetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
- MarkCombatCastIssued();
- StartCastChatTrace(spellId, activeTargetId);
- _lastSpellCast = RynthClock.Now;
- _lastCastWasRing = false;
- _pendingDebuffKey = debuffKey;
- _pendingDebuffTargetId = activeTargetId;
- _pendingDebuffSpellId = spellId;
- _pendingDebuffTier = castTier;
- _waitingForDebuffResult = true;
- _pendingDebuffCastTime = RynthClock.Now;
- _host.WriteToChat($"[RynthAi] {(renewal ? "Renewing" : "Casting")}: {debuffKey} (T{castTier}) on {target.Name}", 5);
- }
- catch { }
- return;
- }
+ if (ManaHoldsCast(debuffSpellId)) return; // mana reserve: Stamina to Mana first, or regenerate
+ CastDebuffAt(activeTargetId, target.Name, debuffKey, debuffSpellId, castTier, renewal);
+ return;
}
+ // Debuff every monster in range before attacking (CombatManager.DebuffPass.cs): the next
+ // monster's debuff instead of the attack, while the pass has one.
+ if (_settings.DebuffAllBeforeAttacking && TryDebuffPassCast()) return;
+
// A rule with no attack shape on means no offensive cast at this monster: a script's choice
// is no exception (it used to be asked first, and cast at a monster the owner turned casting off for).
if (rule != null && PickBaseShape(rule) < 0)
@@ -8008,6 +8129,7 @@ public partial class CombatManager : IDisposable
MarkCombatCastIssued();
StartCastChatTrace(offensiveSpellId, activeTargetId);
SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal
+ NotePassAttack(); // the debuff pass: an arrival may get the next cast
CastsSinceLastKill++; // reset in OnKillNotification when a kill lands
_lastSpellCast = RynthClock.Now;
_lastCastWasRing = multiTarget; // walls too: area casts (2026-10-08)
@@ -8166,6 +8288,60 @@ public partial class CombatManager : IDisposable
return FindBestShapedSpell(element, rule, out _) != 0;
}
+ ///
+ /// The first of the rule's debuffs that isn't on and that this
+ /// character can cast (a debuff with no castable spell is passed over), or false.
+ ///
+ private bool NextDebuffFor(int targetId, MonsterRule rule, string element, DateTime now,
+ out string key, out int spellId, out int tier, out bool renewal)
+ {
+ foreach (var debuffKey in BuildDebuffList(rule, element))
+ {
+ if (_debuffs.IsOn(targetId, debuffKey, now)) continue;
+ int id;
+ int castTier;
+ if (debuffKey.StartsWith("Vuln:"))
+ id = FindBestVulnSpellWithTier(debuffKey.Substring(5), out castTier);
+ else if (debuffKey.StartsWith("Custom:"))
+ id = FindBestCustomDebuffWithTier(debuffKey.Substring(7), out castTier);
+ else if (debuffKey.StartsWith("Void:"))
+ id = FindBestVoidDebuffWithTier(debuffKey.Substring(5), out castTier);
+ else
+ id = FindBestDebuffSpellWithTier(debuffKey, out castTier);
+ if (id == 0) continue;
+ key = debuffKey;
+ spellId = id;
+ tier = castTier;
+ renewal = _debuffs.RenewAt(targetId, debuffKey) != null;
+ return true;
+ }
+ key = ""; spellId = 0; tier = 0; renewal = false;
+ return false;
+ }
+
+ /// One debuff cast at ; its result is read from chat (HandleChatForDebuffs).
+ private bool CastDebuffAt(int targetId, string targetName, string debuffKey, int spellId, int castTier, bool renewal)
+ {
+ try
+ {
+ _host.CastSpellFor((uint)targetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
+ MarkCombatCastIssued();
+ StartCastChatTrace(spellId, targetId);
+ _lastSpellCast = RynthClock.Now;
+ _lastCastWasRing = false;
+ _pendingDebuffKey = debuffKey;
+ _pendingDebuffTargetId = targetId;
+ _pendingDebuffSpellId = spellId;
+ _pendingDebuffTier = castTier;
+ _pendingDebuffFromPass = false;
+ _waitingForDebuffResult = true;
+ _pendingDebuffCastTime = RynthClock.Now;
+ _host.WriteToChat($"[RynthAi] {(renewal ? "Renewing" : "Casting")}: {debuffKey} (T{castTier}) on {targetName}", 5);
+ return true;
+ }
+ catch { return false; }
+ }
+
private bool HasPendingDebuffs(MonsterRule rule, string element)
{
if (rule == null) return false;
@@ -8693,6 +8869,7 @@ public partial class CombatManager : IDisposable
/// "ceiling 2.1 m out", "wall in the straight line": why an arc verdict is blocked.
internal static string DescribeArcBlock(in TargetingFSM.LosDetail d)
{
+ if (d.TerrainBlocked) return $"a hill {d.TerrainAlong:0} m out";
if (d.LineBlocked) return "wall in the straight line";
if (d.Arc.OutOfReach) return "out of reach";
if (d.Arc.Blocked)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffPass.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffPass.cs
new file mode 100644
index 0000000..fe4e9e0
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffPass.cs
@@ -0,0 +1,285 @@
+using System;
+using System.Collections.Generic;
+
+namespace RynthCore.Plugin.RynthAi;
+
+///
+/// "Debuff every monster in range before attacking" (setting DebuffAllBeforeAttacking, off by
+/// default). Which monster gets the next debuff cast, and when attacking may start. Pure state, no
+/// host calls; CombatManager feeds it the scan (nearest first) and says which monsters still need a
+/// debuff (the monster's own rule: Imperil, vulns, Void ones, typed-in ones, not on it and castable).
+///
+/// * A fight starts with the pass: the monsters in Monster Range that need a debuff get them,
+/// nearest first, one cast at a time. Nothing is attacked until every one has them, or has
+/// failed tries (resists, fizzles, refusals) or
+/// casts in all, or the pass has run .
+/// The fight target's own debuffs are cast by the usual per-target code just before this.
+/// * A monster hitting the character in melee ("on you") stops the pass while it does: the fight
+/// goes on as without the setting (the fight target's own debuffs, then the attack), and the pass
+/// picks up again once nothing is on you (while its time lasts). No arrival is debuffed meanwhile.
+/// * Once attacking has started, a monster that comes into range later (an arrival) gets its debuffs
+/// too, one cast between two attacks on the fight target, for after it
+/// came. The fight target is never changed for it. Monsters of the first pass aren't renewed here
+/// (the fight target's own code renews the target's).
+/// * The pet summon waits while the pass runs (), and for at most
+/// before the fight's first cast begins it.
+/// * The fight ends when nothing has been in range and nothing engaged for
+/// : everything starts over for the next one.
+///
+internal sealed class DebuffPass
+{
+ public const int MaxFailsPerMonster = 3;
+ public const int MaxTriesPerMonster = 8;
+ public const double PassSeconds = 30.0;
+ public const double ArrivalSeconds = 30.0;
+ public const double FightOverSeconds = 3.0;
+ /// The pet summon's wait before the pass has begun (the fight's first cast is coming).
+ public const double IdleHoldSeconds = 5.0;
+ private const int MaxMonsters = 256;
+
+ public enum Stage { Idle, Debuffing, Attacking }
+
+ private sealed class Mon
+ {
+ public DateTime FirstSeen;
+ public DateTime LastSeen;
+ public bool Arrival;
+ public int Tries;
+ public int Fails;
+ public bool GaveUp;
+ }
+
+ private readonly Dictionary _mons = new();
+ private DateTime _emptySince = DateTime.MinValue;
+ private bool _castSinceAttack;
+ private bool _onYouLogged;
+
+ public Stage Phase { get; private set; } = Stage.Idle;
+ public DateTime StartedAt { get; private set; } = DateTime.MinValue;
+ public DateTime EndedAt { get; private set; } = DateTime.MinValue;
+ /// Why the last pass ended ("" while none has).
+ public string EndReason { get; private set; } = "";
+ /// Debuff casts the pass (or an arrival) sent this fight.
+ public int Casts { get; private set; }
+
+ /// One [DebuffPass] line (CombatManager: the RynthAi log).
+ public Action? Log { get; set; }
+ /// A monster's name for the log lines.
+ public Func? NameOf { get; set; }
+
+ ///
+ /// Every scan: the monsters in Monster Range that passed the scan's filters, and whether a target
+ /// is engaged. New ones are noted (an arrival once attacking has started); a fight with nothing in
+ /// range and nothing engaged for is over.
+ ///
+ public void Observe(IReadOnlyList inRange, bool engaged, DateTime now)
+ {
+ InRange = inRange.Count;
+ if (inRange.Count > 0 && FightSeenAt == DateTime.MinValue) FightSeenAt = now;
+ if (inRange.Count == 0 && !engaged)
+ {
+ if (Phase == Stage.Idle && _mons.Count == 0) return;
+ if (_emptySince == DateTime.MinValue) _emptySince = now;
+ else if ((now - _emptySince).TotalSeconds >= FightOverSeconds)
+ {
+ if (Phase != Stage.Idle)
+ Log?.Invoke($"[DebuffPass] fight over: {Casts} debuff casts; the next fight starts a new pass");
+ Reset();
+ }
+ return;
+ }
+ _emptySince = DateTime.MinValue;
+ for (int i = 0; i < inRange.Count; i++)
+ {
+ int id = inRange[i];
+ if (_mons.TryGetValue(id, out Mon? m)) { m.LastSeen = now; continue; }
+ if (_mons.Count >= MaxMonsters) Prune(now);
+ _mons[id] = new Mon { FirstSeen = now, LastSeen = now, Arrival = Phase == Stage.Attacking };
+ }
+ }
+
+ ///
+ /// The monster to debuff now, or 0 to attack (or when there is nothing to do). Starts the pass at
+ /// a fight's first call and ends it when every monster has its debuffs, is given up on, or time is
+ /// up. : the scan's monsters in Monster Range, nearest first;
+ /// : one of its debuffs isn't on it and this character can cast it.
+ ///
+ public int Next(IReadOnlyList nearestFirst, int fightTarget, Func needsDebuff, bool monsterOnYou, DateTime now)
+ {
+ Begin(nearestFirst, now);
+ if (Phase == Stage.Idle) return 0;
+
+ if (Phase == Stage.Debuffing)
+ {
+ if (monsterOnYou)
+ {
+ if (!_onYouLogged)
+ {
+ _onYouLogged = true;
+ Log?.Invoke("[DebuffPass] a monster is hitting you in melee: the fight target is debuffed and attacked first; the pass waits");
+ }
+ return 0;
+ }
+ if (_onYouLogged)
+ {
+ _onYouLogged = false;
+ Log?.Invoke("[DebuffPass] nothing on you now: the pass goes on");
+ }
+ if ((now - StartedAt).TotalSeconds >= PassSeconds)
+ {
+ End(now, $"time cap ({PassSeconds:0} s)");
+ return 0;
+ }
+ foreach (int id in nearestFirst)
+ {
+ if (id == fightTarget || !Eligible(id)) continue;
+ if (needsDebuff(id)) return id;
+ }
+ End(now, "every monster in range has its debuffs or was given up on");
+ return 0;
+ }
+
+ // Attacking: newcomers only, one debuff between two attacks on the fight target; none while
+ // something is hitting you.
+ if (_castSinceAttack || monsterOnYou) return 0;
+ foreach (int id in nearestFirst)
+ {
+ if (id == fightTarget || !Eligible(id)) continue;
+ Mon m = _mons[id];
+ if (!m.Arrival || (now - m.FirstSeen).TotalSeconds > ArrivalSeconds) continue;
+ if (needsDebuff(id)) return id;
+ }
+ return 0;
+ }
+
+ ///
+ /// A fight's first attack decision (Magic mode): two or more monsters in range start the pass
+ /// (logged); one alone starts the fight attacking (a later one is an arrival). Nothing otherwise.
+ ///
+ public void Begin(IReadOnlyList nearestFirst, DateTime now)
+ {
+ if (Phase != Stage.Idle || nearestFirst.Count == 0) return;
+ foreach (int id in nearestFirst)
+ if (!_mons.ContainsKey(id)) _mons[id] = new Mon { FirstSeen = now, LastSeen = now };
+ foreach (var m in _mons.Values) m.Arrival = false;
+ StartedAt = now;
+ EndReason = "";
+ Casts = 0;
+ if (nearestFirst.Count < 2)
+ {
+ // One monster: nothing to wait for (its own debuffs come first as always).
+ Phase = Stage.Attacking;
+ EndedAt = now;
+ EndReason = "one monster";
+ return;
+ }
+ Phase = Stage.Debuffing;
+ Log?.Invoke($"[DebuffPass] start: {nearestFirst.Count} monsters in range, debuffing each before attacking");
+ }
+
+ private bool Eligible(int id)
+ {
+ if (!_mons.TryGetValue(id, out Mon? m))
+ {
+ // Not observed yet (the caller's list is newer than the last scan): treat it as seen now.
+ _mons[id] = m = new Mon { FirstSeen = DateTime.MinValue, LastSeen = DateTime.MinValue, Arrival = false };
+ }
+ return !m.GaveUp;
+ }
+
+ ///
+ /// True while the pass holds the pet summon: debuffing, inside its time, nothing on you; or, before
+ /// the fight's first attack decision, for after two or more monsters
+ /// came into range (the caller checks the pass can run at all).
+ ///
+ public bool Holding(DateTime now) => Phase switch
+ {
+ Stage.Debuffing => (now - StartedAt).TotalSeconds < PassSeconds && !_onYouLogged,
+ Stage.Idle => InRange >= 2 && FightSeenAt != DateTime.MinValue && (now - FightSeenAt).TotalSeconds < IdleHoldSeconds,
+ _ => false,
+ };
+
+ /// Monsters in range at the last .
+ public int InRange { get; private set; }
+ /// When this fight's first monster came into range (MinValue between fights).
+ public DateTime FightSeenAt { get; private set; } = DateTime.MinValue;
+
+ /// A pass debuff went out at .
+ public void NoteCast(int id, DateTime now)
+ {
+ Casts++;
+ if (Phase == Stage.Attacking) _castSinceAttack = true;
+ if (!_mons.TryGetValue(id, out Mon? m)) _mons[id] = m = new Mon { FirstSeen = now, LastSeen = now };
+ if (++m.Tries >= MaxTriesPerMonster && !m.GaveUp)
+ {
+ m.GaveUp = true;
+ Log?.Invoke($"[DebuffPass] 0x{(uint)id:X8} '{Name(id)}': {MaxTriesPerMonster} debuff casts this fight, no more from the pass");
+ }
+ }
+
+ /// A pass debuff at was resisted, fizzled or refused. True when that gave it up.
+ public bool NoteFailed(int id)
+ {
+ if (!_mons.TryGetValue(id, out Mon? m)) return false;
+ if (m.GaveUp || ++m.Fails < MaxFailsPerMonster) return false;
+ m.GaveUp = true;
+ Log?.Invoke($"[DebuffPass] 0x{(uint)id:X8} '{Name(id)}': {MaxFailsPerMonster} failed tries, skipped (the pass doesn't wait on it)");
+ return true;
+ }
+
+ /// An attack (war/void cast, swing or shot) went out at the fight target.
+ public void NoteAttack() => _castSinceAttack = false;
+
+ /// The monster died or went away.
+ public void Forget(int id) => _mons.Remove(id);
+
+ public bool GaveUp(int id) => _mons.TryGetValue(id, out Mon? m) && m.GaveUp;
+ public int Tries(int id) => _mons.TryGetValue(id, out Mon? m) ? m.Tries : 0;
+ public bool IsArrival(int id) => _mons.TryGetValue(id, out Mon? m) && m.Arrival;
+ public int Known => _mons.Count;
+
+ public void Reset()
+ {
+ _mons.Clear();
+ Phase = Stage.Idle;
+ _emptySince = DateTime.MinValue;
+ _castSinceAttack = false;
+ _onYouLogged = false;
+ StartedAt = DateTime.MinValue;
+ FightSeenAt = DateTime.MinValue;
+ InRange = 0;
+ Casts = 0;
+ }
+
+ private void End(DateTime now, string why)
+ {
+ Phase = Stage.Attacking;
+ EndedAt = now;
+ EndReason = why;
+ int gaveUp = 0;
+ foreach (var m in _mons.Values) if (m.GaveUp) gaveUp++;
+ Log?.Invoke($"[DebuffPass] done after {(now - StartedAt).TotalSeconds:0.0} s ({why}): {Casts} debuff casts" +
+ (gaveUp > 0 ? $", {gaveUp} monster{(gaveUp == 1 ? "" : "s")} skipped" : "") + "; attacking now");
+ }
+
+ private string Name(int id)
+ {
+ try { return NameOf?.Invoke(id) ?? ""; } catch { return ""; }
+ }
+
+ private void Prune(DateTime now)
+ {
+ List? drop = null;
+ foreach (var kv in _mons)
+ if ((now - kv.Value.LastSeen).TotalSeconds > 60) (drop ??= new()).Add(kv.Key);
+ if (drop != null) foreach (int id in drop) _mons.Remove(id);
+ while (_mons.Count >= MaxMonsters)
+ {
+ int oldest = 0;
+ DateTime best = DateTime.MaxValue;
+ foreach (var kv in _mons)
+ if (kv.Value.LastSeen < best) { best = kv.Value.LastSeen; oldest = kv.Key; }
+ _mons.Remove(oldest);
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/DirtyFightingHeights.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/DirtyFightingHeights.cs
index bc6e19e..345b491 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/DirtyFightingHeights.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/DirtyFightingHeights.cs
@@ -51,8 +51,18 @@ internal static class DirtyFightingHeights
public const string DefaultOrder = "HML";
- /// Every order the setting can hold, in the order the UI lists them.
- public static readonly string[] OrderChoices = { "HML", "HLM", "MHL", "MLH", "LHM", "LMH" };
+ ///
+ /// Every order the setting can hold, in the order the UI lists them: all three heights, then two,
+ /// then one (R-20261120-014055-59be: "pick just 1 or 2 heights"). A height left out is never aimed
+ /// at for its effect; the Then attack height still applies once the chosen ones are on. The engine's
+ /// Settings window lists the same (SettingsData.DfOrders).
+ ///
+ public static readonly string[] OrderChoices =
+ {
+ "HML", "HLM", "MHL", "MLH", "LHM", "LMH",
+ "HM", "HL", "MH", "ML", "LH", "LM",
+ "H", "M", "L",
+ };
public static readonly string[] HeightNames = { "Low", "Medium", "High" };
@@ -70,7 +80,7 @@ internal static class DirtyFightingHeights
public static string HeightName(int height) =>
height >= 0 && height < HeightNames.Length ? HeightNames[height] : "?";
- /// A valid order ("HML" and the like: H, M and L once each), else .
+ /// A valid order ("HML", "HM", "L" and the like: one to three of H, M and L, each at most once), else .
public static string NormalizeOrder(string? order)
{
if (string.IsNullOrWhiteSpace(order)) return DefaultOrder;
@@ -84,17 +94,17 @@ internal static class DirtyFightingHeights
public static int[] ParseOrder(string? order)
{
string o = NormalizeOrder(order);
- var heights = new int[3];
- for (int i = 0; i < 3; i++)
+ var heights = new int[o.Length];
+ for (int i = 0; i < o.Length; i++)
heights[i] = o[i] switch { 'H' => High, 'M' => Medium, _ => Low };
return heights;
}
- /// "High, Medium, Low".
+ /// "High, Medium, Low"; "High, Medium"; "Low only".
public static string OrderLabel(string? order)
{
int[] h = ParseOrder(order);
- return $"{HeightName(h[0])}, {HeightName(h[1])}, {HeightName(h[2])}";
+ return h.Length == 1 ? HeightName(h[0]) + " only" : string.Join(", ", Array.ConvertAll(h, HeightName));
}
///
@@ -147,7 +157,7 @@ internal static class DirtyFightingHeights
/// The height for the next attack. The fixed height (the Melee/Missile Attack Height setting)
/// when the rotation is off or Dirty Fighting isn't trained. Otherwise the first height in
/// whose effect is missing or due to run out within
- /// ; with all three on,
+ /// ; with every height in the order on,
/// ( = the fixed height).
/// may be null (nothing known about this target: a fresh one).
///
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs
index 5900e44..01f9d61 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/HealLatencyTracker.cs
@@ -107,6 +107,28 @@ internal sealed class HealLatencyTracker
}
}
+ ///
+ /// The macro is off: an open episode ends here, said once when it lasted NoHealLogMs or more. It
+ /// used to stay open, and the heal after a restart counted the whole stop (2026-11-22: "13871 ms",
+ /// of which 12 s with the macro off).
+ ///
+ public void MacroOff(DateTime now, int hp)
+ {
+ if (_open && !_healed)
+ {
+ double ms = (now - _start).TotalMilliseconds;
+ if (ms >= NoHealLogMs)
+ {
+ _noHeal++;
+ _log($"[HealLatency] no heal in {ms:0} ms: health {_startHp}% under {_line} {_lineValue}%{Where(_inCombat)}{(_followUp ? " (follow-up)" : "")}, " +
+ $"then the macro stopped at {hp}%; held by: {Held()}{Arb()}");
+ }
+ }
+ _open = false;
+ _healed = false;
+ _followUp = false;
+ }
+
/// Once per heartbeat, after the tick's work: why no heal went out this tick.
public void EndTick(DateTime now, string heldBy, string detail, string arbiterActivity)
{
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetChoice.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetChoice.cs
index 8808b28..c708f72 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetChoice.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetChoice.cs
@@ -10,9 +10,12 @@ namespace RynthCore.Plugin.RynthAi;
/// Which combat pet to summon for a monster. The Damage panel stores a choice per
/// monster (wcid): Auto (""), an element ("E:Cold"), or a specific essence
/// ("I:<id>"). Auto picks an element from, in order: the Monsters-tab rule
-/// (Pet damage, else damage type), the monster's learned resists, then the
-/// element that has done best on it in the Damage tab; with none of those the
-/// Items-panel order is kept. Combat pets can't be swapped while one is out
+/// (Pet damage, else damage type), the Summons settings' Pet element (2026-11-22;
+/// "" = Any, the default, skips it), the Default row's pet damage, the monster's
+/// learned resists, then the element that has done best on it in the Damage tab;
+/// with none of those the Items-panel order is kept. An item whose pets deal more
+/// than one element (a server's holder of two summons, PetElements) fits an element
+/// by : all its pets first, then its first pet, then a later one. Combat pets can't be swapped while one is out
/// (ACE: "already active"), so the choice is made at each summon.
///
internal static class PetChoice
@@ -21,25 +24,40 @@ internal static class PetChoice
public static readonly string[] Elements =
{ "Fire", "Cold", "Lightning", "Acid", "Nether", "Slash", "Pierce", "Bludgeon" };
+ /// The Summons settings' Pet element choices: "Any" (stored as "") then every element.
+ public static readonly string[] SettingChoices =
+ { "Any", "Fire", "Cold", "Acid", "Lightning", "Nether", "Slash", "Pierce", "Bludgeon" };
+
+ /// The tooltip both Pet element controls show.
+ public const string SettingTooltip =
+ "The element combat pets are summoned for. Any: each monster's own choice (a Damage-panel pick,\n" +
+ "its Monsters rule, then the element it is weakest to). Another element: an essence of it is\n" +
+ "summoned first, unless the monster has a Damage-panel pick or a Monsters rule of its own.\n" +
+ "A summon that holds two (two pets, two elements) counts when either of its pets deals it.";
+
+ /// The index of a stored Pet element in (0 = Any).
+ public static int SettingIndex(string? stored)
+ {
+ string e = NormalizeElement(stored);
+ int i = e.Length == 0 ? 0 : Array.IndexOf(SettingChoices, e);
+ return i < 0 ? 0 : i;
+ }
+
+ /// The stored Pet element for a index ("" = Any).
+ public static string SettingValue(int index)
+ => index <= 0 || index >= SettingChoices.Length ? "" : SettingChoices[index];
+
///
- /// A summoning essence's element. From UiEffects (int 18), which essences carry
- /// in their public data (Fire K'nath 32, Frost 128, Acid 256 ...), else from
- /// words in the name. "" if unknown.
+ /// A summoning essence's element: its first pet's ().
+ /// From UiEffects (int 18), which essences carry in their public data (Fire K'nath 32, Frost 128,
+ /// Acid 256 ...), else from words in the name. "" if unknown.
///
public static string ElementOf(RynthCoreHost host, uint deviceId, string name)
{
- if (host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(deviceId, 18, out int fx) && fx != 0)
- {
- if ((fx & 0x0020) != 0) return "Fire";
- if ((fx & 0x0040) != 0) return "Lightning";
- if ((fx & 0x0080) != 0) return "Cold";
- if ((fx & 0x0100) != 0) return "Acid";
- if ((fx & 0x1000) != 0) return "Nether";
- if ((fx & 0x0200) != 0) return "Bludgeon";
- if ((fx & 0x0400) != 0) return "Slash";
- if ((fx & 0x0800) != 0) return "Pierce";
- }
- return ElementFromName(name);
+ var info = PetElements.Describe(host, deviceId, name);
+ foreach (string e in info.Elements)
+ if (e.Length > 0) return e;
+ return "";
}
public static string ElementFromName(string name)
@@ -73,12 +91,45 @@ internal static class PetChoice
/// Orders (id, name) for summoning against a monster:
/// the chosen essence first, or the chosen element's essences first, or (Auto) the
/// element the monster takes most damage from. Stable, so ties keep the Items-panel order.
+ /// is the Summons settings' Pet element ("" = Any);
+ /// the Monsters tab Default row's pet damage, for a monster
+ /// with no rule of its own (or one left on Auto).
///
public static List<(int Id, string Name, string Element)> Order(
RynthCoreHost host, IEnumerable<(int Id, string Name)> devices, string choice,
- CreatureData.CreatureWeakness.Ranking? weakness, out string reason, string ruleElement = "")
+ CreatureData.CreatureWeakness.Ranking? weakness, out string reason, string ruleElement = "",
+ string preferElement = "", string defaultElement = "")
{
- var list = devices.Select(d => (d.Id, d.Name, Element: ElementOf(host, unchecked((uint)d.Id), d.Name))).ToList();
+ var list = devices.Select(d => (d.Id, d.Name, Info: PetElements.Describe(host, unchecked((uint)d.Id), d.Name))).ToList();
+ return Order(list, choice, weakness, out reason, ruleElement, preferElement, defaultElement);
+ }
+
+ ///
+ /// How well an item's pets fit : 0 every pet deals it (a plain essence of
+ /// it), 1 its first pet does (a holder's first held summon), 2 a later pet does (a holder's second,
+ /// out only when the character can have two pets), 3 none does or none is known.
+ ///
+ public static int Rank(PetDeviceInfo info, string element)
+ {
+ var e = info.Elements;
+ if (e.Count == 0 || element.Length == 0) return 3;
+ bool first = e[0].Equals(element, StringComparison.OrdinalIgnoreCase);
+ bool all = true;
+ foreach (string x in e)
+ if (!x.Equals(element, StringComparison.OrdinalIgnoreCase)) { all = false; break; }
+ if (all) return 0;
+ if (first) return 1;
+ return info.Has(element) ? 2 : 3;
+ }
+
+ /// PURE. on described items.
+ public static List<(int Id, string Name, string Element)> Order(
+ List<(int Id, string Name, PetDeviceInfo Info)> list, string choice,
+ CreatureData.CreatureWeakness.Ranking? weakness, out string reason, string ruleElement = "",
+ string preferElement = "", string defaultElement = "")
+ {
+ static List<(int Id, string Name, string Element)> Out(IEnumerable<(int Id, string Name, PetDeviceInfo Info)> l)
+ => l.Select(d => (d.Id, d.Name, d.Info.ElementText)).ToList();
choice ??= "";
if (choice.StartsWith("I:", StringComparison.Ordinal)
@@ -91,9 +142,10 @@ internal static class PetChoice
if (idx >= 0)
{
var pick = list[idx];
- list.RemoveAt(idx);
- list.Insert(0, pick);
- return list;
+ var rest = new List<(int Id, string Name, PetDeviceInfo Info)>(list);
+ rest.RemoveAt(idx);
+ rest.Insert(0, pick);
+ return Out(rest);
}
choice = "";
}
@@ -101,22 +153,35 @@ internal static class PetChoice
if (choice.StartsWith("E:", StringComparison.Ordinal))
{
string want = choice.Substring(2);
- var ordered = list.OrderBy(d => d.Element.Equals(want, StringComparison.OrdinalIgnoreCase) ? 0 : 1).ToList();
- reason = ordered.Count > 0 && ordered[0].Element.Equals(want, StringComparison.OrdinalIgnoreCase)
+ var ordered = list.OrderBy(d => Rank(d.Info, want)).ToList();
+ reason = ordered.Count > 0 && Rank(ordered[0].Info, want) < 3
? $"{want} chosen" : $"{want} chosen, but no {want} essence; using the first";
- return ordered;
+ return Out(ordered);
}
// Auto. 1) the Monsters-tab rule's pet damage / damage type for this monster;
- // 2) the owned element the monster takes most damage from: server data, else
+ // 2) the Summons settings' Pet element; 3) the Default row's pet damage;
+ // 4) the owned element the monster takes most damage from: server data, else
// what the Damage tab learned, else its creature type (CreatureWeakness). The
// old step read resists ACE never sends and took the lowest, the element the
// monster resists most (2026-09-29). Without any of these the Items order stands.
- var have = new HashSet(list.Where(d => d.Element.Length > 0).Select(d => d.Element), StringComparer.OrdinalIgnoreCase);
+ var have = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var d in list)
+ foreach (string e in d.Info.Elements)
+ if (e.Length > 0) have.Add(e);
string autoElem = "";
string why = "";
+ string note = "";
string re = NormalizeElement(ruleElement);
if (re.Length > 0 && have.Contains(re)) { autoElem = re; why = "Monsters rule"; }
+ string pe = NormalizeElement(preferElement);
+ if (autoElem.Length == 0 && pe.Length > 0)
+ {
+ if (have.Contains(pe)) { autoElem = pe; why = "Pet element setting"; }
+ else note = $"Pet element {pe}, but no {pe} essence; ";
+ }
+ string de = NormalizeElement(defaultElement);
+ if (autoElem.Length == 0 && de.Length > 0 && have.Contains(de)) { autoElem = de; why = "Monsters rule"; }
if (autoElem.Length == 0 && weakness != null)
foreach (var (elem, mult) in weakness.Order)
{
@@ -128,10 +193,10 @@ internal static class PetChoice
if (autoElem.Length == 0)
{
- reason = "Auto: no element data for this monster, using Items order";
- return list;
+ reason = note + "Auto: no element data for this monster, using Items order";
+ return Out(list);
}
- reason = $"Auto: {autoElem} ({why})";
- return list.OrderBy(d => d.Element.Equals(autoElem, StringComparison.OrdinalIgnoreCase) ? 0 : 1).ToList();
+ reason = $"{note}Auto: {autoElem} ({why})";
+ return Out(list.OrderBy(d => Rank(d.Info, autoElem)));
}
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetDeviceKind.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetDeviceKind.cs
index b1c6eaa..e209b36 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetDeviceKind.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetDeviceKind.cs
@@ -44,6 +44,10 @@ internal static class PetDeviceKind
{
if (host.HasGetObjectWcid && host.TryGetObjectWcid(id, out uint w) && w is >= 787801001 and <= 787801072)
return Verdict.Combat; // ACECustom combat essence block
+ // A server's holder of combat summons (PetElements, the server plugin's "summons" rows): a
+ // combat pet device even before it holds anything (the summoner skips it until it is full).
+ if (PetElements.IsHolder(host, id, null))
+ return Verdict.Combat;
if (host.HasGetObjectIntProperty)
{
if (host.TryGetObjectIntProperty(id, IntStructure, out _) || host.TryGetObjectIntProperty(id, IntMaxStructure, out _))
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetElements.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetElements.cs
new file mode 100644
index 0000000..41bcd3e
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetElements.cs
@@ -0,0 +1,186 @@
+using System;
+using System.Collections.Generic;
+using RynthCore.Plugin.Shared;
+using RynthCore.PluginSdk;
+
+namespace RynthCore.Plugin.RynthAi;
+
+///
+/// What a summoning item brings out, for the combat summoner's element pick: the element of each pet
+/// one use can bring, in summon order, and whether the item can summon at all.
+///
+/// The element of each pet, in summon order ("" where it isn't known).
+/// For a holder: the held items' names, in summon order (empty for a plain essence).
+/// The item holds other summoning items (a server's own summon item, ServerSummonView).
+/// The item can summon: a plain essence always; a holder once it holds items.
+/// The items a holder needs before it summons (1 for a plain essence).
+internal sealed record PetDeviceInfo(IReadOnlyList Elements, IReadOnlyList Held, bool IsHolder, bool Ready, int Slots)
+{
+ /// The known elements, joined: "Fire", "Fire+Cold"; "" when none is known.
+ public string ElementText
+ {
+ get
+ {
+ var known = new List();
+ foreach (string e in Elements)
+ if (e.Length > 0 && !known.Contains(e)) known.Add(e);
+ return string.Join("+", known);
+ }
+ }
+
+ /// True when one of its pets deals .
+ public bool Has(string element)
+ {
+ foreach (string e in Elements)
+ if (e.Length > 0 && e.Equals(element, StringComparison.OrdinalIgnoreCase)) return true;
+ return false;
+ }
+}
+
+///
+/// Reads a summoning item's elements (). A plain essence has one: its
+/// UiEffects element bits, else words in its name ().
+///
+/// A "holder" is a server's own summon item that holds other summoning items, named by the active
+/// server plugin's profile ("summons", ; RynthAi names no server). Its
+/// appraisal description lists the held items ("Summon 1: Fire Moar Essence (180)"); one use brings
+/// out the first held item's pet, and the next ones' too when the character can have more pets out.
+/// Each held item's element is read from its name; with "elementIsLast" the item's own UiEffects is
+/// the last held item's element (the server writes it there). Until it holds every slot it summons
+/// nothing ( false), and the summoner skips it.
+///
+internal static class PetElements
+{
+ private const uint IntUiEffects = 18;
+ private const uint IntMaxStructure = 91;
+ private const uint IntStructure = 92;
+ private const uint StringLongDesc = 16;
+
+ private static volatile IReadOnlyList _serverSummons = Array.Empty();
+
+ ///
+ /// The active server plugin's holder rows (its profile's "summons"; empty without one). Set by the
+ /// Mini Remote's server poll (MiniRemoteContext.PollServer), and by the tests. Any thread.
+ ///
+ public static IReadOnlyList ServerSummons
+ {
+ get => _serverSummons;
+ set => _serverSummons = value ?? Array.Empty();
+ }
+
+ /// The element of a UiEffects value's element bits ("" for none).
+ public static string FromUiEffects(int fx)
+ {
+ if (fx == 0) return "";
+ if ((fx & 0x0020) != 0) return "Fire";
+ if ((fx & 0x0040) != 0) return "Lightning";
+ if ((fx & 0x0080) != 0) return "Cold";
+ if ((fx & 0x0100) != 0) return "Acid";
+ if ((fx & 0x1000) != 0) return "Nether";
+ if ((fx & 0x0200) != 0) return "Bludgeon";
+ if ((fx & 0x0400) != 0) return "Slash";
+ if ((fx & 0x0800) != 0) return "Pierce";
+ return "";
+ }
+
+ /// The holder row for an item, or null (a plain essence, or no server rows).
+ public static ServerSummonView? HolderRule(uint wcid, string? name, IReadOnlyList? rules)
+ {
+ if (rules == null) return null;
+ foreach (var r in rules)
+ if (r.Matches(wcid, name)) return r;
+ return null;
+ }
+
+ ///
+ /// The held items' names from a holder's description: each line that starts with
+ /// , a number and ":" ("Summon 2: Frost K'nath Essence (180)"), in order.
+ ///
+ public static List HeldItems(string? longDesc, string prefix)
+ {
+ var held = new List();
+ if (string.IsNullOrEmpty(longDesc) || string.IsNullOrWhiteSpace(prefix)) return held;
+ foreach (string raw in longDesc.Split('\n'))
+ {
+ string line = raw.Trim();
+ if (!line.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
+ int i = prefix.Length;
+ while (i < line.Length && line[i] == ' ') i++;
+ int digits = i;
+ while (i < line.Length && char.IsDigit(line[i])) i++;
+ if (i == digits || i >= line.Length || line[i] != ':') continue;
+ string name = line[(i + 1)..].Trim();
+ if (name.Length > 0) held.Add(name);
+ }
+ return held;
+ }
+
+ ///
+ /// PURE. What an item brings out, from what the client knows of it: its name, wcid (0 = not known),
+ /// UiEffects (0 = none), appraisal description (null = not appraised yet) and whether it carries a
+ /// charge count; are the server's holder rows.
+ ///
+ public static PetDeviceInfo Describe(string? name, uint wcid, int uiEffects, string? longDesc, bool hasCharges,
+ IReadOnlyList? rules)
+ {
+ name ??= "";
+ string own = FromUiEffects(uiEffects);
+ var rule = HolderRule(wcid, name, rules);
+ if (rule == null)
+ {
+ string e = own.Length > 0 ? own : PetChoice.ElementFromName(name);
+ return new PetDeviceInfo(e.Length > 0 ? new[] { e } : Array.Empty(), Array.Empty(), false, true, 1);
+ }
+
+ var held = HeldItems(longDesc, rule.SlotPrefix);
+ var elements = new List(Math.Max(held.Count, rule.Slots));
+ for (int i = 0; i < held.Count; i++)
+ {
+ bool last = i == held.Count - 1 && held.Count >= rule.Slots;
+ string e = last && rule.ElementIsLast && own.Length > 0 ? own : PetChoice.ElementFromName(held[i]);
+ elements.Add(e);
+ }
+ // Not appraised yet (no description): a holder with charges is a full one (the server gives
+ // charges only when it binds); its own element is the last slot's.
+ bool undescribed = string.IsNullOrEmpty(longDesc);
+ if (held.Count == 0 && undescribed && hasCharges)
+ {
+ for (int i = 0; i < rule.Slots; i++)
+ elements.Add(i == rule.Slots - 1 && rule.ElementIsLast ? own : "");
+ }
+ bool ready = held.Count >= rule.Slots || (held.Count == 0 && undescribed && hasCharges);
+ return new PetDeviceInfo(elements, held, true, ready, rule.Slots);
+ }
+
+ /// What the item brings out, read from the client (see the pure overload).
+ public static PetDeviceInfo Describe(RynthCoreHost host, uint id, string? name)
+ {
+ var rules = ServerSummons;
+ uint wcid = 0;
+ if (host.HasGetObjectWcid) host.TryGetObjectWcid(id, out wcid);
+ int fx = 0;
+ bool charges = false;
+ if (host.HasGetObjectIntProperty)
+ {
+ if (!host.TryGetObjectIntProperty(id, IntUiEffects, out fx)) fx = 0;
+ charges = (host.TryGetObjectIntProperty(id, IntMaxStructure, out int max) && max > 0)
+ || host.TryGetObjectIntProperty(id, IntStructure, out _);
+ }
+ string? desc = null;
+ if (rules.Count > 0 && HolderRule(wcid, name, rules) != null && host.HasGetObjectStringProperty
+ && host.TryGetObjectStringProperty(id, StringLongDesc, out string d) && !string.IsNullOrWhiteSpace(d))
+ desc = d;
+ return Describe(name, wcid, fx, desc, charges, rules);
+ }
+
+ /// True when the item is one of the active server's holders (cheap: no description read).
+ public static bool IsHolder(RynthCoreHost host, uint id, string? name)
+ {
+ var rules = ServerSummons;
+ if (rules.Count == 0) return false;
+ uint wcid = 0;
+ if (host.HasGetObjectWcid) host.TryGetObjectWcid(id, out wcid);
+ if (name == null && host.TryGetObjectName(id, out string n)) name = n;
+ return HolderRule(wcid, name, rules) != null;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
index d51ab7d..f0f5e74 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/PetManager.cs
@@ -193,6 +193,8 @@ internal sealed class PetManager
private int _landedDeviceId;
private long _landedCheckUntil;
private readonly HashSet _passivePets = new();
+ // Holders (PetElements) skipped because they don't hold all their summons yet, each logged once.
+ private readonly HashSet _holderNotReadyLogged = new();
/// A listed essence not appraised yet waits this long for its appraisal, once.
private const long AppraisalWaitMs = 3_000;
/// After a summon lands, its essence is judged again this long (its appraisal may still come).
@@ -254,8 +256,9 @@ internal sealed class PetManager
// or the summoned creature is now visible in the cache.
if (SummonLanded() || IsPetActive())
{
- _summonElement = PetChoice.ElementOf(_host, unchecked((uint)_activeDeviceId),
- _objectCache[_activeDeviceId]?.Name ?? "");
+ // "Fire", or "Fire+Cold" for a holder of two summons (PetElements).
+ _summonElement = PetElements.Describe(_host, unchecked((uint)_activeDeviceId),
+ _objectCache[_activeDeviceId]?.Name ?? "").ElementText;
_summonCooldownUntil = _actionIssuedAt + DeviceUseCooldownMs; // every essence's, not only this one's
AssumePetFor(now, AssumeActiveAfterSummonMs);
// Judge the essence again now its pet is out: one used before its appraisal landed
@@ -472,6 +475,9 @@ internal sealed class PetManager
return;
}
if (HoldSummons?.Invoke() == true) return;
+ // Debuff every monster in range before attacking: the pet comes out once the pass is done, so
+ // its first hits land on debuffed monsters (bounded by the pass's time cap; logged there).
+ if (_combat?.DebuffPassHoldsPets == true) return;
// Only summon when mobs are near (the user's trigger).
if (!MonstersNearby()) return;
@@ -836,14 +842,24 @@ internal sealed class PetManager
{
if (!rule.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(rule.Name)) continue;
if (PetDeviceKind.IsNotCombat(_host, unchecked((uint)rule.Id))) continue; // a passive pet's essence names no combat pet
- string n = rule.Name;
- int i = n.IndexOf(" Essence", StringComparison.OrdinalIgnoreCase);
- string b = (i > 0 ? n[..i] : n).Trim();
- if (b.Length >= 3 && petName.Contains(b, StringComparison.OrdinalIgnoreCase)) return true;
+ if (NamedFor(petName, rule.Name)) return true;
+ // A server's holder ("Duo Summon Gem") is no pet's name: its pets are named for the
+ // summoning items it holds (PetElements), so a pet out after a reload still counts.
+ if (PetElements.IsHolder(_host, unchecked((uint)rule.Id), rule.Name))
+ foreach (string held in PetElements.Describe(_host, unchecked((uint)rule.Id), rule.Name).Held)
+ if (NamedFor(petName, held)) return true;
}
return false;
}
+ /// The pet is named for the essence: "<me>'s Fire Moar" for "Fire Moar Essence (50)".
+ private static bool NamedFor(string petName, string essenceName)
+ {
+ int i = essenceName.IndexOf(" Essence", StringComparison.OrdinalIgnoreCase);
+ string b = (i > 0 ? essenceName[..i] : essenceName).Trim();
+ return b.Length >= 3 && petName.Contains(b, StringComparison.OrdinalIgnoreCase);
+ }
+
///
/// False for a pet the client no longer has (the cache missed its delete) or one the server
/// has said nothing about for (a ghost: the client still shows
@@ -944,6 +960,21 @@ internal sealed class PetManager
foreach (int id in ids)
{
uint uid = unchecked((uint)id);
+ // A server's holder that doesn't hold all its summons yet summons nothing (the server
+ // refuses it, and the 45 s park would follow): skipped, logged once until it is full.
+ if (PetElements.IsHolder(_host, uid, _objectCache[id]?.Name))
+ {
+ var info = PetElements.Describe(_host, uid, _objectCache[id]?.Name);
+ if (!info.Ready)
+ {
+ if (_holderNotReadyLogged.Count > 64) _holderNotReadyLogged.Clear();
+ if (_holderNotReadyLogged.Add(id))
+ _host.Log($"[RynthAi] Pet: '{_objectCache[id]?.Name ?? "?"}' (0x{uid:X8}) holds {info.Held.Count} of the {info.Slots} summons " +
+ "it needs before it can summon; the combat summoner skips it until it holds them all.");
+ continue;
+ }
+ _holderNotReadyLogged.Remove(id);
+ }
var v = PetDeviceKind.IsLearned(id) ? PetDeviceKind.Verdict.NotCombat : PetDeviceKind.Judge(_host, uid);
if (v == PetDeviceKind.Verdict.NotCombat)
{
@@ -1042,15 +1073,19 @@ internal sealed class PetManager
// weapon damage type. Same name match combat uses.
var rule = _settings.MonsterRules.Find(r => r.Name.Length > 0 && !r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)
&& tname.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0);
- // No rule of its own, or one left on Auto: the Default row's pet damage, when it names one.
- var defaultRow = _settings.MonsterRules.Find(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
- if ((rule == null || (PetChoice.NormalizeElement(rule.PetDamage).Length == 0 && PetChoice.NormalizeElement(rule.DamageType).Length == 0))
- && defaultRow != null && PetChoice.NormalizeElement(defaultRow.PetDamage).Length > 0)
- rule = defaultRow;
string ruleElem = rule == null ? "" :
(PetChoice.NormalizeElement(rule.PetDamage).Length > 0 ? rule.PetDamage : rule.DamageType);
+ // No rule of its own, or one left on Auto: the Summons settings' Pet element, then the Default
+ // row's pet damage, when it names one (PetChoice.Order).
+ string defaultElem = "";
+ if (PetChoice.NormalizeElement(ruleElem).Length == 0)
+ {
+ ruleElem = "";
+ var defaultRow = _settings.MonsterRules.Find(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
+ if (defaultRow != null) defaultElem = defaultRow.PetDamage;
+ }
var weak = _combat.WeaknessFor(wcid, tname, target);
- var ordered = PetChoice.Order(_host, raw, choice, weak, out string why, ruleElem);
+ var ordered = PetChoice.Order(_host, raw, choice, weak, out string why, ruleElem, _settings.PetElement, defaultElem);
if (target != _lastChoiceTarget || why != _lastChoiceReason)
{
_lastChoiceTarget = target;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
index bd5c635..733d268 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/WorldObjectCache.cs
@@ -1505,11 +1505,17 @@ public class WorldObjectCache
// buffing ignore it and try every other one. So only a side pack, or the main pack with
// the item's own container field set and no wielder, means "in a pack". Buffing's wand
// swap puts the weapons into a side pack (the stale-record case of 2026-10-17/18).
- if (containerId != playerId) _packWalkIds.Add(unchecked((int)itemId));
+ bool inPack = false;
+ if (containerId != playerId) inPack = true;
else if (_host.HasGetObjectOwnershipInfo
&& _host.TryGetObjectOwnershipInfo(itemId, out uint inContainer, out uint byWielder, out _)
&& inContainer != 0 && byWielder == 0)
+ inPack = true;
+ if (inPack)
+ {
_packWalkIds.Add(unchecked((int)itemId));
+ NoteHomePack(unchecked((int)itemId), unchecked((int)containerId));
+ }
if (isContainer && seenContainers.Add(itemId))
pendingContainers.Enqueue(itemId);
@@ -1553,6 +1559,80 @@ public class WorldObjectCache
// both snapshot disciplines: the (cache) overload force-refreshes for the AV-
// risky dequip paths (must not read stale); the (inv) overload reuses a caller-
// supplied snapshot (AutoCram's single per-tick snapshot — no double BFS).
+ // ── A weapon goes back where it came from (R-20261121-040524-f6ed) ──────────
+ // The pack walk notes the pack each item was last seen in (the main pack = the player's id).
+ // A wand swap put the weapons it took off into the side pack with the most free slots, which
+ // changes as packs fill: "it randomly throws them into pack 1, 2 or 4". Now the swaps ask for
+ // the pack the weapon came from first.
+ private readonly Dictionary _homePack = new();
+
+ private void NoteHomePack(int itemId, int containerId)
+ {
+ if (_homePack.Count >= 4096) _homePack.Clear(); // a bound, not a cut: inventories hold a few hundred
+ _homePack[itemId] = containerId;
+ }
+
+ /// The pack was last seen in (the player's id = the main pack), or 0.
+ public int HomePackOf(int itemId)
+ {
+ lock (_gate) return _homePack.TryGetValue(itemId, out int p) ? p : 0;
+ }
+
+ ///
+ /// As , for putting
+ /// away: the pack they all came from when it still has
+ /// free slots (the main pack only with ),
+ /// else the usual choice.
+ ///
+ public static int FindPackFor(RynthCoreHost host, WorldObjectCache? cache,
+ bool includeMainPack, int requireFree, IReadOnlyList forItems)
+ {
+ if (cache == null) return 0;
+ int playerId = unchecked((int)host.GetPlayerId());
+ if (playerId == 0) return 0;
+ var inv = cache.GetDirectInventory(forceRefresh: true);
+ int home = 0;
+ foreach (int id in forItems)
+ {
+ int h = id == 0 ? 0 : cache.HomePackOf(id);
+ if (h == 0 || (home != 0 && h != home)) { home = 0; break; }
+ home = h;
+ }
+ if (home != 0 && (home != playerId || includeMainPack)
+ && FreeSlotsIn(inv, playerId, home, host) >= Math.Max(1, requireFree))
+ return home;
+ return FindPackFor(inv, playerId, includeMainPack, requireFree, host);
+ }
+
+ /// Free item slots in one of the player's packs (the player's id = the main pack), or -1 when unknown.
+ internal static int FreeSlotsIn(IReadOnlyList inv, int playerId, int packId, RynthCoreHost? host)
+ {
+ if (packId == playerId)
+ {
+ int mainUsed = 0;
+ foreach (var p in inv)
+ {
+ if (p.Container != playerId) continue;
+ if (p.ObjectClass == AcObjectClass.Container || p.ObjectClass == AcObjectClass.Foci) continue;
+ if (p.Values(LongValueKey.EquippedSlots, 0) != 0) continue;
+ if (host.HasValue && IsWieldable(p) && IsWieldedByPlayer(host.Value, p)) continue;
+ mainUsed++;
+ }
+ return 102 - mainUsed;
+ }
+ WorldObject? pack = null;
+ foreach (var p in inv)
+ if (p.Id == packId) { pack = p; break; }
+ if (pack == null || pack.ObjectClass != AcObjectClass.Container || pack.Container != playerId) return -1;
+ if (!string.IsNullOrEmpty(pack.Name) && pack.Name.IndexOf("Foci", StringComparison.OrdinalIgnoreCase) >= 0) return -1;
+ int capacity = pack.Values(LongValueKey.ItemsCapacity, 0);
+ if (capacity <= 0) return -1;
+ int used = 0;
+ foreach (var it in inv)
+ if (it.Container == packId && it.ObjectClass != AcObjectClass.Container) used++;
+ return capacity - used;
+ }
+
public static int FindPackFor(RynthCoreHost host, WorldObjectCache? cache,
bool includeMainPack, int requireFree)
{
diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
index a98987b..cebbb71 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs
@@ -562,7 +562,7 @@ public sealed partial class RynthAiPlugin
{
_processedCorpseItems.Clear();
_corpseItemAttempts.Clear();
- _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
+ _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
}
LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}.");
_consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again
@@ -760,6 +760,7 @@ public sealed partial class RynthAiPlugin
SyncCorpseContainerState();
WatchLateLandings(CorpseNowMs);
+ PrunePerDay();
TickDeferredClose(settings);
TakeLootThisRequest(settings); // /ra lootthis (RynthAiPlugin.VTankHotkeys.cs)
TakeChestKeyRequest(); // the Item Tool's chest looter (RynthAiPlugin.ItemTool.cs)
@@ -1226,6 +1227,8 @@ public sealed partial class RynthAiPlugin
_corpseCooldownUntil.Remove(candidate.Id);
}
+ if (StillBehindWall(candidate.Id, now)) // set aside behind a wall, and the wall is still there
+ continue;
CorpseLootDecision decision = EvaluateCorpseLootDecision(candidate);
if (!decision.ShouldLoot)
@@ -1387,6 +1390,23 @@ public sealed partial class RynthAiPlugin
}
}
+ // Loot Only Rare Corpses: only a corpse that generated a rare is opened (VTank's option). The
+ // ownership rules below still apply to it.
+ if (settings.LootOnlyRareCorpses && RareCorpseRefusal(longDesc) is { } notRare)
+ {
+ return new CorpseLootDecision
+ {
+ ShouldLoot = false,
+ ModeName = modeName,
+ Reason = notRare,
+ KillerName = killerName,
+ PlayerName = myName,
+ LongDesc = longDesc,
+ InFellowship = inFellowship,
+ KillerIsFellow = killerIsFellow
+ };
+ }
+
if (lootOwnership >= 2)
{
return new CorpseLootDecision
@@ -1555,6 +1575,13 @@ public sealed partial class RynthAiPlugin
int lineEnd = remainder.IndexOfAny(new[] { '\r', '\n' });
if (lineEnd >= 0)
remainder = remainder[..lineEnd];
+ // A corpse that generated a rare reads "Killed by . This corpse generated a rare item!"
+ // (ACE appends the sentence on the same line). Read whole, the killer was ". This corpse
+ // generated a rare item!", so My Kills Only never matched the player and every rare corpse of
+ // their own kills was left unopened (2026-11-22).
+ int rare = remainder.IndexOf(RareCorpseText, StringComparison.OrdinalIgnoreCase);
+ if (rare >= 0)
+ remainder = remainder[..rare];
remainder = remainder.Trim().TrimEnd('.').Trim();
return remainder.Length == 0 ? null : remainder;
}
@@ -2033,6 +2060,8 @@ public sealed partial class RynthAiPlugin
// is in the pack. Noted on send for the same reason as salvage above.
if (matchActionLabel == ScrollLearner.ReadAction)
_scrollLearner?.NoteLooted(firstMatchId, matchItemName, fromProfile: matchRuleLabel != ScrollLearner.RuleLabel);
+ // Keep # per day: on its way, so it counts until it lands (then it is recorded).
+ NotePerDaySent(firstMatchId);
_currentLootItemMovePending = true;
_currentLootItemMoveRequestedAt = now;
// A queued move that the client or server turned away (the client's one-request
@@ -2458,6 +2487,7 @@ public sealed partial class RynthAiPlugin
{
bool wasMarked = _packRefusals.IsRefused(container, now);
_packRefusals.Accepted(container);
+ NotePerDayPickedUp(kv.Key); // a Keep # per day item that landed late still counts
LootDiag($"[RynthAi] {LootTag}: 0x{(uint)kv.Key:X8} landed in {LootPackName(container)} {now - kv.Value.SentAt} ms after its last send, after it was given up" +
(wasMarked ? $"; {LootPackName(container)} has room after all and is no longer treated as full." : "."));
(done ??= new()).Add(kv.Key);
@@ -3093,6 +3123,7 @@ public sealed partial class RynthAiPlugin
if (answered) _currentLootItemDestsTried.Clear(); // landed: nothing to watch for (ResetCurrentLootItem)
_processedCorpseItems.Add(_currentLootItemId);
_corpseItemsLooted++;
+ NotePerDayPickedUp(itemId); // Keep # per day: it left the corpse into the pack
bool noMotion = answered && JumpPickupHadNoMotion();
long jumpSentAt = _currentLootItemMoveRequestedAt;
LootDiag($"[RynthAi] {LootTag}: pickup confirmed for 0x{(uint)_currentLootItemId:X8}; {reason}" +
@@ -3419,6 +3450,8 @@ public sealed partial class RynthAiPlugin
continue;
if (_corpseCooldownUntil.TryGetValue(candidate.Id, out long blockedUntil) && blockedUntil > now)
continue;
+ if (StillBehindWall(candidate.Id, now)) // set aside behind a wall, and the wall is still there
+ continue;
CorpseLootDecision decision = EvaluateCorpseLootDecision(candidate);
if (!decision.ShouldLoot)
continue;
@@ -3448,11 +3481,13 @@ public sealed partial class RynthAiPlugin
///
/// The arbiter's LootStarved input: looting wants the tick, combat wants it too, a corpse
/// has waited LootStarveMs (HasLootWork set _lootStarved this tick), and no monster is
- /// within LootStarveCloseYards. Melee fights keep combat in charge (the mob is on you).
+ /// within LootStarveCloseYards. Melee fights keep combat in charge (the mob is on you), and so
+ /// does a monster in the scan that is hitting us from farther off (2026-11-22, IsBeingHitByScanned).
///
private bool IsLootStarvedTurn(bool wantLoot, bool wantCombat)
=> wantLoot && wantCombat && _lootStarved
- && _combatManager?.HasCloseThreat(LootStarveCloseYards) != true;
+ && _combatManager?.HasCloseThreat(LootStarveCloseYards) != true
+ && _combatManager?.IsBeingHitByScanned != true;
// -- Boost Loot Priority: one kill, one loot (2026-10-14) --------------------------------
// Combat locked its next target a few ms after each kill, and ACE creates the corpse 1-3 s
@@ -3634,7 +3669,14 @@ public sealed partial class RynthAiPlugin
if (nativeAction == LootAction.KeepUpTo)
{
var rule = nativeRule;
- if (!UnderKeepCap("n:" + ruleLabel, ruleLabel, item, rule.KeepCount,
+ int perDay = LootPerDay.Clamp(rule.PerDayHours);
+ if (perDay > 0)
+ {
+ // Keep # per day: counted by pickups in the window, not by the pack.
+ if (!UnderDailyCap(LootPerDay.Key(rule.Name, nativeProfile.Rules.IndexOf(rule)), ruleLabel, item, rule.KeepCount, perDay, preview))
+ return false;
+ }
+ else if (!UnderKeepCap("n:" + ruleLabel, ruleLabel, item, rule.KeepCount,
inv => LootEvaluator.Matches(rule, inv, _charSkills), preview))
return false;
}
@@ -3670,7 +3712,14 @@ public sealed partial class RynthAiPlugin
if (matchedRule.Action == VTankLootAction.KeepUpTo)
{
var rule = matchedRule;
- if (!UnderKeepCap("v:" + matchedRuleIndex + ":" + ruleLabel, ruleLabel, item, rule.KeepCount ?? 0,
+ int perDay = LootPerDay.Clamp(rule.PerDayHours);
+ if (perDay > 0)
+ {
+ // Keep # per day: counted by pickups in the window, not by the pack.
+ if (!UnderDailyCap(LootPerDay.Key(rule.Name, matchedRuleIndex), ruleLabel, item, rule.KeepCount ?? 0, perDay, preview))
+ return false;
+ }
+ else if (!UnderKeepCap("v:" + matchedRuleIndex + ":" + ruleLabel, ruleLabel, item, rule.KeepCount ?? 0,
inv => VTankLootEvaluator.Match(rule, inv, lootCtx), preview))
return false;
}
@@ -4132,7 +4181,7 @@ public sealed partial class RynthAiPlugin
_corpseItemAttempts.Clear();
_corpseIdsRequested = false;
_corpseItemIdReaskedAt.Clear();
- _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
+ _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
ResetCurrentLootItem();
// Close the loot window (CloseCorpseContainer: the client's own close packet, which
@@ -4317,6 +4366,9 @@ public sealed partial class RynthAiPlugin
private bool AttemptOpenCorpse(int corpseId)
{
long now = CorpseNowMs;
+ // A re-send for a corpse that didn't open, with a wall in the way: set aside (RynthAiPlugin.CorpseBehindWall.cs).
+ if (SetAsideBehindWall(corpseId, now))
+ return false;
bool watch = Host.HasUseDoneSeq;
if (watch)
{
@@ -4592,7 +4644,7 @@ public sealed partial class RynthAiPlugin
{
_processedCorpseItems.Clear();
_corpseItemAttempts.Clear();
- _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
+ _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
}
_targetCorpseId = rawOpen;
@@ -4632,7 +4684,7 @@ public sealed partial class RynthAiPlugin
ResetCurrentLootItem();
_processedCorpseItems.Clear();
_corpseItemAttempts.Clear();
- _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
+ _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear();
}
private void HandleCorpseObjectDeleted(uint objectId)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs
index b1d35a1..6c6677a 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs
@@ -90,6 +90,8 @@ internal interface IDashboardHost
bool AutoSortMoving { get; }
/// Fight the monster I select (combat setting), for the options menu's toggle.
bool FightSelectedTarget { get; }
+ /// Debuff every monster in range before attacking (combat setting), for the options menu's toggle.
+ bool DebuffAllBeforeAttacking { get; }
void SetAutoSort(bool on);
/// RynthSort's own window, shown or hidden.
void ToggleSortWindow();
@@ -1143,6 +1145,17 @@ internal sealed unsafe class InstrumentDashboard
ImGui.CloseCurrentPopup();
_d.Command("/ra fightselected");
}
+ // Debuff every monster in range before attacking (also Settings > Combat > Targeting): a
+ // toggle, the command's reply says the new state.
+ bool debuffAll = _d.DebuffAllBeforeAttacking;
+ if (MenuItem(dl, ref p, w, "##m_debuffall", RynthIcons.Flask,
+ "Debuff every monster first", debuffAll ? "ON" : "OFF",
+ "Casts each monster's Monsters-rule debuffs on every monster in range, nearest first, before attacking any\n" +
+ "(/ra debuffall). Click to turn it " + (debuffAll ? "off." : "on.")))
+ {
+ ImGui.CloseCurrentPopup();
+ _d.Command("/ra debuffall");
+ }
// Which worn items have their magic on (RynthAiPlugin.ActiveGear.cs): its own window, no bar button.
if (MenuItem(dl, ref p, w, "##m_gear", RynthIcons.BatteryCharging, "Active gear", "/ra gear",
"Which worn items have their magic on, their mana and how long it lasts (the Active Gear window)."))
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs
index 04077ca..cae96ca 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Diagnostics/TickGuard.cs
@@ -47,6 +47,7 @@ internal enum TickStep
AutoVendor,
AutoTrade,
WeaponElements,
+ AutoKits,
CramStack,
InventoryStatus,
CombatTelemetry,
@@ -138,6 +139,7 @@ internal sealed class TickGuard
Add(TickStep.AutoVendor, "AutoVendor", LogCat.Vendor);
Add(TickStep.AutoTrade, "AutoTrade", LogCat.Vendor);
Add(TickStep.WeaponElements, "weapon elements", LogCat.Combat);
+ Add(TickStep.AutoKits, "make kits when low", LogCat.Crafting);
Add(TickStep.CramStack, "AutoCram/AutoStack", LogCat.Inventory);
Add(TickStep.InventoryStatus, "inventory status", LogCat.Inventory);
Add(TickStep.CombatTelemetry, "combat telemetry", LogCat.Combat);
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
index 68de652..0b37432 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonGeometry.cs
@@ -41,6 +41,38 @@ internal sealed class DungeonDoorway
public (double Nx, double Ny) NormalFrom(uint fromCell) => fromCell == CellA ? (Nx, Ny) : (-Nx, -Ny);
}
+/// What a placed object is to a body on the floor it stands on (DungeonGeometry's placed objects).
+internal enum PlacedClass
+{
+ /// In the body band, and nothing else here: walked round.
+ Obstacle,
+ /// Its top no more than the step-up (0.60 m) over its floor, with somewhere to stand on it.
+ StepOver,
+ /// Walkable faces climbed onto from its floor reaching 1 m and more (stairs, ramps, platforms), or a slab that is a floor the map lacks.
+ Connector,
+ /// All of it under the band (under its floor + 0.45 m).
+ Low,
+ /// All of it over the band (over its floor + 1.83 m).
+ Overhead,
+ /// Nothing of it in the band, though it reaches both under and over it (an arch's beam with no posts).
+ Clear,
+}
+
+/// One placed object as the map took it: model, cell, class, whether it went on the map, world box, its floor (L),
+/// whether that floor is the map's, its footprint at L (m2), and where it came from.
+internal readonly record struct PlacedInfo(uint Setup, uint Cell, PlacedClass Class, bool OnMap,
+ double MinX, double MinY, double MinZ, double MaxX, double MaxY, double MaxZ,
+ double Floor, bool FloorFound, double FootprintArea, string Source);
+
+/// Which placed objects go on the map, and the tag their layer gets.
+internal sealed record PlacedObjectOptions
+{
+ /// Null: obstacles, step-overs and connectors (whatever is in the body band at its floor).
+ public Func? Keep { get; init; }
+ /// Where the objects came from ("dats" for the base layer by default).
+ public string? Source { get; init; }
+}
+
internal sealed class DungeonGeometry
{
/// An opening at least this wide joins two cells of one room (a 10 m cell side is
@@ -126,7 +158,7 @@ internal sealed class DungeonGeometry
if (!IsUpwardFloor(v)) continue; // the "floor" list holds ceilings too
if (!g._floors.TryGetValue(cell, out var list)) g._floors[cell] = list = new List();
list.Add(v);
- g.AddFloorToGrid(v);
+ g.AddFloorToGrid(v, cell);
}
foreach (var (cell, v) in wallPolys)
@@ -297,6 +329,9 @@ internal sealed class DungeonGeometry
public bool TryGetDoorway(uint a, uint b, out DungeonDoorway door) => _doorways.TryGetValue(EdgeKey(a, b), out door!);
+ /// Every opening paired between two cells (the jump-downs look at them all: a closed ledge is gone from the graph, not from here).
+ internal IEnumerable AllDoorways => _doorways.Values;
+
/// Openings whose centre is within r (horizontally) of (x, y) and of height z.
public IEnumerable DoorwaysNear(double x, double y, double z, double r, double dz = 2.0)
{
@@ -401,20 +436,25 @@ internal sealed class DungeonGeometry
}
}
- // Walls.
+ // Walls (the cells' own and the placed objects' filed under them; an overlay's too).
double zLo = Math.Min(z0, z1) + WallBandLow, zHi = Math.Max(z0, z1) + WallBandHigh;
- foreach (uint c in cells)
+ bool Crossed(Dictionary> byCell)
{
- if (!_walls.TryGetValue(c, out var list)) continue;
- foreach (var w in list)
+ foreach (uint c in cells)
{
- if (w.ZMax < zLo || w.ZMin > zHi) continue;
- if (SegmentsCross(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1)) return false;
- if (SegmentsCross(x0 + ox, y0 + oy, x1 + ox, y1 + oy, w.X0, w.Y0, w.X1, w.Y1)) return false;
- if (SegmentsCross(x0 - ox, y0 - oy, x1 - ox, y1 - oy, w.X0, w.Y0, w.X1, w.Y1)) return false;
+ if (!byCell.TryGetValue(c, out var list)) continue;
+ foreach (var w in list)
+ {
+ if (w.ZMax < zLo || w.ZMin > zHi) continue;
+ if (SegmentsCross(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1)) return true;
+ if (SegmentsCross(x0 + ox, y0 + oy, x1 + ox, y1 + oy, w.X0, w.Y0, w.X1, w.Y1)) return true;
+ if (SegmentsCross(x0 - ox, y0 - oy, x1 - ox, y1 - oy, w.X0, w.Y0, w.X1, w.Y1)) return true;
+ }
}
+ return false;
}
- return true;
+ if (Crossed(_walls)) return false;
+ return _placedOverlay == null || !Crossed(_placedOverlay.CellWalls);
}
// ── Clearance from walls ────────────────────────────────────────────────
@@ -446,18 +486,19 @@ internal sealed class DungeonGeometry
public double Nx, Ny, Nz, Px, Py, Pz; // unit normal and a point on the plane
public double MinX, MinY, MaxX, MaxY;
public bool Walkable;
+ public uint Cell; // the cell it is the floor of (a placed object's walls go to it too)
public double HeightAt(double x, double y) => Pz - (Nx * (x - Px) + Ny * (y - Py)) / Nz;
}
private static long GridKey(int gx, int gy) => ((long)gx << 32) ^ (uint)gy;
private static int GridOf(double v) => (int)Math.Floor(v / GridCell);
- private void AddFloorToGrid(Vector3[] v)
+ private void AddFloorToGrid(Vector3[] v, uint cell)
{
NewellNormal(v, out double nx, out double ny, out double nz);
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-9 || nz <= 1e-9) return;
- var f = new FloorPoly { V = v, Nx = nx / len, Ny = ny / len, Nz = nz / len, MinX = double.MaxValue, MinY = double.MaxValue, MaxX = double.MinValue, MaxY = double.MinValue };
+ var f = new FloorPoly { V = v, Cell = cell, Nx = nx / len, Ny = ny / len, Nz = nz / len, MinX = double.MaxValue, MinY = double.MaxValue, MaxX = double.MinValue, MaxY = double.MinValue };
double sx = 0, sy = 0, sz = 0;
foreach (var p in v)
{
@@ -478,15 +519,17 @@ internal sealed class DungeonGeometry
}
}
- private void AddWallToGrid(WallSeg w)
+ private void AddWallToGrid(WallSeg w) => AddWallTo(_wallAll, _wallGrid, w);
+
+ private static void AddWallTo(List all, Dictionary> grid, WallSeg w)
{
- int idx = _wallAll.Count;
- _wallAll.Add(w);
+ int idx = all.Count;
+ all.Add(w);
for (int gx = GridOf(Math.Min(w.X0, w.X1)); gx <= GridOf(Math.Max(w.X0, w.X1)); gx++)
for (int gy = GridOf(Math.Min(w.Y0, w.Y1)); gy <= GridOf(Math.Max(w.Y0, w.Y1)); gy++)
{
long k = GridKey(gx, gy);
- if (!_wallGrid.TryGetValue(k, out var list)) _wallGrid[k] = list = new List();
+ if (!grid.TryGetValue(k, out var list)) grid[k] = list = new List();
list.Add(idx);
}
}
@@ -537,6 +580,7 @@ internal sealed class DungeonGeometry
if (FloorNear(x, y, z)) return 0; // past the floor's edge: in or behind a wall
h0 = z;
}
+ if (InsidePlaced(x, y, h0)) return 0; // inside an altar or a statue: its middle is far from its sides
double best = maxR;
for (int k = 0; k < ProbeDirs && best > 0; k++)
{
@@ -546,6 +590,371 @@ internal sealed class DungeonGeometry
return Math.Min(best, WallDistance(x, y, h0 + ClearWallLow, h0 + ClearWallHigh, best));
}
+ // ── Placed objects (2026-11-18) ─────────────────────────────────────────
+ //
+ // What a dungeon's cells place (an altar, a statue, a pillar: the EnvCells' stabs) isn't in the cells'
+ // walls and floors, so walks went through them. Thread 0x000A ("It also still doesn't see world
+ // objects such as this altar it tried to run through"): an explore leg ran straight through a 1 m altar
+ // in a hall, the character stuck there in a fight and died, four times in one run. Thread 0x00C1: a
+ // room's middle (a look-in point) inside a 9 x 9 m statue.
+ //
+ // Each object is a solid model (PlacedSolid: 0.1 m columns, each with the heights where it is solid),
+ // measured against a body: from the feet + PlacedBandLow (the map's step) to the top of the human setup's
+ // upper sphere (PlacedBandHigh, 1.83 m). At the floor it stands on (L) that gives its footprint. The
+ // footprint's outline is walls from L + 0.45 to L + 1.83 (within the object's own height): every clearance
+ // measure sees them, so the corner put into a leg brushing a wall, the straightener, the walk round a hole
+ // and the stuck detours go round. They are filed under every cell whose floor the footprint covers, so a
+ // straight line over the next cell sees an object reaching into it. A point is
+ // inside an object when, for a walker on the floor there, something of it is between that floor + 0.45 and
+ // + 1.83: a table's top counts all over (not only at its legs), a rail at 0.8 m closes, an arch's beam
+ // overhead and a block whose top is the floor walked on (a door sill's) don't, nor does anything on a floor
+ // 4 m up or down. An open plane (a fence, a web) is its line, never a filled area.
+ //
+ // Classes, at L: LOW (all of it under the band), OVERHEAD (all of it over), CLEAR (nothing of it in the
+ // band either way: an arch with no posts), STEP-OVER (top no more than the step-up, 0.60 m, over L, with a
+ // top to stand on), CONNECTOR (walkable faces a body could climb onto, 0.6 m at most at a time, from L and
+ // across other objects, reaching 1 m and more over L: stairs, ramps, platforms; or a slab that is a floor
+ // the map lacks), OBSTACLE (the rest). Only what is in the band at L goes on the map. Step-overs and
+ // connectors still do in this wave (the 0.60 m step-up isn't proven in game; taking a ramp's sides out was
+ // measured wrong in 0x0174), but they are tagged, for a map that leaves them out (AddPlacedObjects' options).
+ //
+ // The dats' objects sit in the base layer. A second, replaceable layer (objects found at run time, tagged
+ // with where they came from) joins it through SetPlacedOverlay and leaves through ClearPlacedOverlay, with
+ // walls of its own, without the base being built again.
+
+ /// The body a placed object is measured against, over the floor a walker stands on: from the map's
+ /// own step (ClearWallLow) to the top of the human setup 0x02000001's upper sphere (1.35 + 0.48).
+ internal const double PlacedBandLow = 0.45, PlacedBandHigh = 1.83;
+ /// The human setup's step-up height: an object no taller over its floor, with a top to stand on, is a step-over.
+ internal const double StepOverTop = 0.60;
+ // Connector chain: a step up at most this high between walkable faces at most this far apart (a step down
+ // any small drop), reaching at least this high over the object's floor.
+ private const double ConnectorRise = 0.6, ConnectorGap = 0.3, ConnectorDrop = 1.5, ConnectorReach = 1.0;
+ // A slab: walkable faces this big (m2), raised this far over its floor (or no floor under it), and the map
+ // has no floor within SlabFloorNear of most of them.
+ private const double SlabArea = 1.0, SlabRaised = 1.0, SlabFloorNear = 0.3;
+ // The floor an object stands on is looked for this far over and under its lowest point.
+ private const double PlacedFloorSearchUp = 2.0, PlacedFloorSearchDown = 3.0;
+ // A cell's floor this near an object's floor, under its footprint, gets the object's walls too.
+ private const double PlacedCellFloorBand = 2.0;
+
+ private sealed class PlacedObj
+ {
+ public uint Setup, Cell;
+ public PlacedShape Shape = null!;
+ public PlacedBand Band = null!;
+ public double Floor, ReachHigh = double.NegativeInfinity;
+ public bool FloorFound, OnMap;
+ public PlacedClass Class;
+ public string Source = "";
+
+ public PlacedInfo Info => new(Setup, Cell, Class, OnMap, Shape.MinX, Shape.MinY, Shape.MinZ, Shape.MaxX, Shape.MaxY, Shape.MaxZ,
+ Floor, FloorFound, Band.Area, Source);
+ }
+
+ // One list of placed objects with its grid. The base layer's walls are the map's walls; an overlay keeps its own.
+ private sealed class PlacedLayer
+ {
+ public readonly string Source;
+ public readonly bool OwnWalls;
+ public readonly List All = new();
+ public readonly List OnMap = new();
+ public readonly Dictionary> Grid = new();
+ public readonly List Walls = new();
+ public readonly Dictionary> WallGrid = new();
+ public readonly Dictionary> CellWalls = new();
+ public PlacedLayer(string source, bool ownWalls) { Source = source; OwnWalls = ownWalls; }
+ }
+
+ private readonly PlacedLayer _placedBase = new("dats", ownWalls: false);
+ private PlacedLayer? _placedOverlay;
+
+ /// How many placed objects stand in the way at body height (on the map, both layers).
+ public int PlacedCount => _placedBase.OnMap.Count + (_placedOverlay?.OnMap.Count ?? 0);
+
+ /// Every placed object given to the map (both layers), with its class, whether it went on the map, its box and floor.
+ internal IReadOnlyList PlacedObjects
+ {
+ get
+ {
+ var list = new List(_placedBase.All.Count + (_placedOverlay?.All.Count ?? 0));
+ foreach (var layer in PlacedLayers())
+ foreach (var p in layer.All) list.Add(p.Info);
+ return list;
+ }
+ }
+
+ ///
+ /// Adds the objects the cells place, each as its triangles in world metres (three vertices a triangle, closed or
+ /// open), to the base layer: each one's footprint in the body band at its floor becomes walls, and inside it is no
+ /// room. What isn't in the band there (or what leaves out) goes on the list only.
+ /// Returns how many went on the map.
+ ///
+ internal int AddPlacedObjects(IEnumerable<(uint SetupId, uint CellId, Vector3[] Triangles)> objects, PlacedObjectOptions? options = null)
+ => AddPlacedTo(_placedBase, objects, options);
+
+ ///
+ /// Replaces the overlay layer (objects found at run time) with , classified and walled
+ /// the same way, its walls kept apart from the map's so it can go again. Returns how many went on the map.
+ ///
+ internal int SetPlacedOverlay(IEnumerable<(uint SetupId, uint CellId, Vector3[] Triangles)> objects, PlacedObjectOptions? options = null)
+ {
+ var layer = new PlacedLayer(options?.Source ?? "overlay", ownWalls: true);
+ int n = AddPlacedTo(layer, objects, options);
+ _placedOverlay = layer;
+ InvalidateClearance();
+ return n;
+ }
+
+ /// Drops the overlay layer: the map is the cells and the dats' objects again.
+ internal void ClearPlacedOverlay()
+ {
+ if (_placedOverlay == null) return;
+ _placedOverlay = null;
+ InvalidateClearance();
+ }
+
+ /// Forgets every clearance worked out so far (after the map's walls or objects change).
+ internal void InvalidateClearance() => _clearanceMemo.Clear();
+
+ private static bool KeepByDefault(PlacedInfo p) => p.Class is PlacedClass.Obstacle or PlacedClass.StepOver or PlacedClass.Connector;
+
+ private int AddPlacedTo(PlacedLayer layer, IEnumerable<(uint SetupId, uint CellId, Vector3[] Triangles)> objects, PlacedObjectOptions? options)
+ {
+ var keep = options?.Keep ?? KeepByDefault;
+ string source = options?.Source ?? layer.Source;
+ var batch = new List();
+ foreach (var (setup, cell, tris) in objects)
+ {
+ var shape = PlacedSolid.Place(setup, tris);
+ if (shape == null) continue;
+ // The floor it stands on: under its middle, near its lowest point (none there: its lowest point).
+ // (A statue's mesh can reach 1 m and more under the floor: Thread 0x00C1's 020014A3 1.1 m.)
+ bool found = FloorUnder((shape.MinX + shape.MaxX) / 2, (shape.MinY + shape.MaxY) / 2, shape.MinZ, PlacedFloorSearchUp, PlacedFloorSearchDown, out double f, out _);
+ double floor = found ? f : shape.MinZ;
+ batch.Add(new PlacedObj
+ {
+ Setup = setup, Cell = cell, Shape = shape, Floor = floor, FloorFound = found, Source = source,
+ Band = shape.Band(floor + PlacedBandLow, floor + PlacedBandHigh),
+ });
+ }
+ ReachUp(batch);
+ int added = 0;
+ foreach (var p in batch)
+ {
+ p.Class = Classify(p);
+ layer.All.Add(p);
+ if (p.Band.Empty || !keep(p.Info)) continue;
+ p.OnMap = true;
+ PutOnMap(layer, p);
+ added++;
+ }
+ if (added > 0) InvalidateClearance();
+ return added;
+ }
+
+ private PlacedClass Classify(PlacedObj p)
+ {
+ double top = p.Shape.MaxZ - p.Floor, bottom = p.Shape.MinZ - p.Floor;
+ if (p.Band.Empty)
+ {
+ if (IsSlab(p, bottom)) return PlacedClass.Connector;
+ return top < PlacedBandLow ? PlacedClass.Low : bottom > PlacedBandHigh ? PlacedClass.Overhead : PlacedClass.Clear;
+ }
+ if (p.ReachHigh >= ConnectorReach) return PlacedClass.Connector;
+ if (top <= StepOverTop && p.Shape.Model.WalkableTop) return PlacedClass.StepOver;
+ return PlacedClass.Obstacle;
+ }
+
+ // A slab that is a floor the map doesn't have (stepping stones over a pit, a raised platform's floor plate).
+ private bool IsSlab(PlacedObj p, double bottom)
+ {
+ if (p.FloorFound && bottom <= SlabRaised) return false;
+ var m = p.Shape.Model;
+ double area = 0, missing = 0;
+ for (int k = 0; k < m.WalkFaceCount; k++)
+ {
+ double a = m.WalkFaceArea(k);
+ area += a;
+ p.Shape.WalkFaceCentre(k, out double x, out double y, out double z);
+ if (!TryFloorHeight(x, y, z, SlabFloorNear, out _)) missing += a;
+ }
+ return area >= SlabArea && missing >= area / 2;
+ }
+
+ // The connector chain: walkable faces reached from each object's floor, a step up at a time, across every object
+ // of the batch; each object's highest reached face over its own floor.
+ private static void ReachUp(List batch)
+ {
+ var faces = new List<(int Obj, double MinX, double MinY, double MaxX, double MaxY, double Z0, double Z1)>();
+ for (int o = 0; o < batch.Count; o++)
+ {
+ var s = batch[o].Shape;
+ for (int k = 0; k < s.Model.WalkFaceCount; k++)
+ {
+ s.WalkFace(k, out double x0, out double y0, out double x1, out double y1, out double z0, out double z1);
+ faces.Add((o, x0, y0, x1, y1, z0, z1));
+ }
+ }
+ if (faces.Count == 0) return;
+ const double bucket = 2.0;
+ static int B(double v) => (int)Math.Floor(v / bucket);
+ var grid = new Dictionary>();
+ for (int f = 0; f < faces.Count; f++)
+ for (int gx = B(faces[f].MinX); gx <= B(faces[f].MaxX); gx++)
+ for (int gy = B(faces[f].MinY); gy <= B(faces[f].MaxY); gy++)
+ {
+ long key = GridKey(gx, gy);
+ if (!grid.TryGetValue(key, out var l)) grid[key] = l = new List();
+ l.Add(f);
+ }
+ var reached = new bool[faces.Count];
+ var queue = new Queue();
+ for (int f = 0; f < faces.Count; f++)
+ {
+ double fl = batch[faces[f].Obj].Floor;
+ if (faces[f].Z0 - fl <= ConnectorRise && faces[f].Z1 - fl >= -ConnectorRise) { reached[f] = true; queue.Enqueue(f); }
+ }
+ while (queue.Count > 0)
+ {
+ var f = faces[queue.Dequeue()];
+ for (int gx = B(f.MinX - ConnectorGap); gx <= B(f.MaxX + ConnectorGap); gx++)
+ for (int gy = B(f.MinY - ConnectorGap); gy <= B(f.MaxY + ConnectorGap); gy++)
+ {
+ if (!grid.TryGetValue(GridKey(gx, gy), out var l)) continue;
+ foreach (int g in l)
+ {
+ if (reached[g]) continue;
+ var h = faces[g];
+ if (h.MinX > f.MaxX + ConnectorGap || h.MaxX < f.MinX - ConnectorGap || h.MinY > f.MaxY + ConnectorGap || h.MaxY < f.MinY - ConnectorGap) continue;
+ if (h.Z0 > f.Z1 + ConnectorRise || h.Z1 < f.Z0 - ConnectorDrop) continue;
+ reached[g] = true;
+ queue.Enqueue(g);
+ }
+ }
+ }
+ for (int f = 0; f < faces.Count; f++)
+ {
+ if (!reached[f]) continue;
+ var p = batch[faces[f].Obj];
+ p.ReachHigh = Math.Max(p.ReachHigh, faces[f].Z1 - p.Floor);
+ }
+ }
+
+ private void PutOnMap(PlacedLayer layer, PlacedObj p)
+ {
+ var s = p.Shape;
+ int idx = layer.OnMap.Count;
+ layer.OnMap.Add(p);
+ for (int gx = GridOf(s.MinX - 0.1); gx <= GridOf(s.MaxX + 0.1); gx++)
+ for (int gy = GridOf(s.MinY - 0.1); gy <= GridOf(s.MaxY + 0.1); gy++)
+ {
+ long key = GridKey(gx, gy);
+ if (!layer.Grid.TryGetValue(key, out var list)) layer.Grid[key] = list = new List();
+ list.Add(idx);
+ }
+ var cells = CellsUnder(p);
+ // The band at its floor, no higher or lower than the object itself: a walker on the floor over a block under a
+ // door sill (E74E: its top the floor walked on, 1.2 m over its own) is above its sides, not beside them.
+ double zLo = Math.Max(p.Floor + PlacedBandLow, s.MinZ), zHi = Math.Min(p.Floor + PlacedBandHigh, s.MaxZ);
+ var byCell = layer.OwnWalls ? layer.CellWalls : _walls;
+ var o = p.Band.Outline;
+ for (int k = 0; k + 3 < o.Length; k += 4)
+ {
+ s.ToWorld(o[k], o[k + 1], out double x0, out double y0);
+ s.ToWorld(o[k + 2], o[k + 3], out double x1, out double y1);
+ var w = new WallSeg(x0, y0, x1, y1, zLo, zHi);
+ if (layer.OwnWalls) AddWallTo(layer.Walls, layer.WallGrid, w);
+ else AddWallToGrid(w);
+ foreach (uint c in cells)
+ {
+ if (!byCell.TryGetValue(c, out var wl)) byCell[c] = wl = new List();
+ wl.Add(w);
+ }
+ }
+ }
+
+ // The object's own cell, and every cell with a floor under its footprint near its floor's height.
+ private List CellsUnder(PlacedObj p)
+ {
+ var cells = new List { p.Cell };
+ var s = p.Shape;
+ var tested = new HashSet();
+ double[]? centres = null;
+ for (int gx = GridOf(s.MinX); gx <= GridOf(s.MaxX); gx++)
+ for (int gy = GridOf(s.MinY); gy <= GridOf(s.MaxY); gy++)
+ {
+ if (!_floorGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
+ foreach (int fi in list)
+ {
+ var f = _floorAll[fi];
+ if (!tested.Add(fi) || cells.Contains(f.Cell)) continue;
+ if (f.MaxX < s.MinX || f.MinX > s.MaxX || f.MaxY < s.MinY || f.MinY > s.MaxY) continue;
+ if (centres == null)
+ {
+ centres = new double[p.Band.Cells.Length * 2];
+ for (int k = 0; k < p.Band.Cells.Length; k++) s.CellCentre(p.Band.Cells[k], out centres[2 * k], out centres[2 * k + 1]);
+ }
+ for (int k = 0; k < centres.Length; k += 2)
+ {
+ double x = centres[k], y = centres[k + 1];
+ if (x < f.MinX || x > f.MaxX || y < f.MinY || y > f.MaxY || !InsidePolygon2D(f.V, x, y)) continue;
+ if (Math.Abs(f.HeightAt(x, y) - p.Floor) > PlacedCellFloorBand) continue;
+ cells.Add(f.Cell);
+ break;
+ }
+ }
+ }
+ return cells;
+ }
+
+ /// True when a walker at (x, y), on a floor at , is inside a placed object:
+ /// something of one there between that floor + and + .
+ internal bool InsidePlaced(double x, double y, double floorZ)
+ => InsideLayer(_placedBase, x, y, floorZ, null) || (_placedOverlay != null && InsideLayer(_placedOverlay, x, y, floorZ, null));
+
+ /// InsidePlaced, counting only the objects whose class takes (a step-over, a connector).
+ internal bool InsidePlaced(double x, double y, double floorZ, Func which)
+ => InsideLayer(_placedBase, x, y, floorZ, which) || (_placedOverlay != null && InsideLayer(_placedOverlay, x, y, floorZ, which));
+
+ ///
+ /// A spot at height (where a character stands, a recorded waypoint) is up on something placed: it
+ /// reads as inside one for a walker on the map's floor under it (), and not at its own height,
+ /// which is over that object's top (a dais, a ramp, a platform). The map has no floor on an object's top, so every test
+ /// from the floor under such a spot takes it for one inside the object.
+ ///
+ internal bool OnTopOfPlaced(double x, double y, double z, double floorZ)
+ => z > floorZ && InsidePlaced(x, y, floorZ) && !InsidePlaced(x, y, z);
+
+ private static bool InsideLayer(PlacedLayer layer, double x, double y, double h, Func? which = null)
+ {
+ if (layer.OnMap.Count == 0 || !layer.Grid.TryGetValue(GridKey(GridOf(x), GridOf(y)), out var list)) return false;
+ double lo = h + PlacedBandLow, hi = h + PlacedBandHigh;
+ foreach (int i in list)
+ if ((which == null || which(layer.OnMap[i].Class)) && layer.OnMap[i].Shape.SolidIn(x, y, lo, hi)) return true;
+ return false;
+ }
+
+ /// The placed objects on the map near (x, y) within r, for offline inspection: model, cell, box, floor.
+ internal List<(uint Setup, uint Cell, double MinX, double MinY, double MaxX, double MaxY, double Floor)> PlacedNear(double x, double y, double r)
+ {
+ var outList = new List<(uint, uint, double, double, double, double, double)>();
+ foreach (var layer in PlacedLayers())
+ foreach (var p in layer.OnMap)
+ {
+ var s = p.Shape;
+ if (s.MaxX >= x - r && s.MinX <= x + r && s.MaxY >= y - r && s.MinY <= y + r)
+ outList.Add((p.Setup, p.Cell, s.MinX, s.MinY, s.MaxX, s.MaxY, p.Floor));
+ }
+ return outList;
+ }
+
+ private IEnumerable PlacedLayers()
+ {
+ yield return _placedBase;
+ if (_placedOverlay != null) yield return _placedOverlay;
+ }
+
// Clearance is asked again and again for the same spots (a patrol passes a doorway several
// times a lap; every standoff is tried in turn): remembered to the centimetre.
private readonly Dictionary<(long, long, long, int), double> _clearanceMemo = new();
@@ -728,16 +1137,27 @@ internal sealed class DungeonGeometry
private bool WallHit(double x0, double y0, double x1, double y1, double zLo, double zHi, out double t)
{
t = 1;
+ bool hit = WallHitIn(_wallAll, _wallGrid, x0, y0, x1, y1, zLo, zHi, ref t);
+ if (_placedOverlay is { Walls.Count: > 0 } ov) hit |= WallHitIn(ov.Walls, ov.WallGrid, x0, y0, x1, y1, zLo, zHi, ref t);
+ return hit;
+ }
+
+ private static bool WallHitIn(List all, Dictionary> grid, double x0, double y0, double x1, double y1, double zLo, double zHi, ref double t)
+ {
bool hit = false;
+ double bx0 = Math.Min(x0, x1), bx1 = Math.Max(x0, x1), by0 = Math.Min(y0, y1), by1 = Math.Max(y0, y1);
+ var span = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(all);
// Every bucket the step touches (a wall is in every bucket its own box touches).
- for (int gx = GridOf(Math.Min(x0, x1)); gx <= GridOf(Math.Max(x0, x1)); gx++)
- for (int gy = GridOf(Math.Min(y0, y1)); gy <= GridOf(Math.Max(y0, y1)); gy++)
+ for (int gx = GridOf(bx0); gx <= GridOf(bx1); gx++)
+ for (int gy = GridOf(by0); gy <= GridOf(by1); gy++)
{
- if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
+ if (!grid.TryGetValue(GridKey(gx, gy), out var list)) continue;
foreach (int i in list)
{
- var w = _wallAll[i];
+ ref readonly var w = ref span[i];
if (w.ZMax < zLo || w.ZMin > zHi) continue;
+ // Boxes apart: no crossing (a 0.1 m probe step against a 4 m bucket's walls, mostly).
+ if ((w.X0 < bx0 && w.X1 < bx0) || (w.X0 > bx1 && w.X1 > bx1) || (w.Y0 < by0 && w.Y1 < by0) || (w.Y0 > by1 && w.Y1 > by1)) continue;
if (!SegmentParam(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1, out double s) || s >= t) continue;
var (lo, hi) = w.ZRangeAt(x0 + (x1 - x0) * s, y0 + (y1 - y0) * s);
if (hi < zLo || lo > zHi) continue;
@@ -766,11 +1186,14 @@ internal sealed class DungeonGeometry
foreach (var v in list)
{
if (v.Length < 3) continue;
- double area = 0, cx = 0, cy = 0, cz = 0;
+ // In doubles, from the first corner: a.X * b.Y in floats at world coordinates (44388 * 15006)
+ // keeps about 40 m² of 6.7e8, so a small cell's floor came out with no area and the cell read
+ // as floorless (building E74E#14, 2026-11-17: 01B2, the west stairs 01BE and 01C0, its doorway cells).
+ double area = 0, cx = 0, cy = 0, cz = 0, ox = v[0].X, oy = v[0].Y;
for (int i = 0; i < v.Length; i++)
{
var a = v[i]; var b = v[(i + 1) % v.Length];
- area += a.X * b.Y - b.X * a.Y;
+ area += (a.X - ox) * (b.Y - oy) - (b.X - ox) * (a.Y - oy);
cx += a.X; cy += a.Y; cz += a.Z;
}
area = Math.Abs(area) * 0.5;
@@ -785,35 +1208,50 @@ internal sealed class DungeonGeometry
internal List<(double X0, double Y0, double X1, double Y1, double ZMin, double ZMax, double Dist)> WallsNear(double x, double y, double r)
{
var res = new List<(double, double, double, double, double, double, double)>();
- var seen = new HashSet();
- for (int gx = GridOf(x - r); gx <= GridOf(x + r); gx++)
- for (int gy = GridOf(y - r); gy <= GridOf(y + r); gy++)
- {
- if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
- foreach (int i in list)
+ void From(List all, Dictionary> grid)
+ {
+ var seen = new HashSet();
+ for (int gx = GridOf(x - r); gx <= GridOf(x + r); gx++)
+ for (int gy = GridOf(y - r); gy <= GridOf(y + r); gy++)
{
- if (!seen.Add(i)) continue;
- var w = _wallAll[i];
- double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
- var (lo, hi) = w.ZRangeAt(cx, cy); // its height range at the nearest point
- if (d <= r) res.Add((w.X0, w.Y0, w.X1, w.Y1, lo, hi, d));
+ if (!grid.TryGetValue(GridKey(gx, gy), out var list)) continue;
+ foreach (int i in list)
+ {
+ if (!seen.Add(i)) continue;
+ var w = all[i];
+ double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
+ var (lo, hi) = w.ZRangeAt(cx, cy); // its height range at the nearest point
+ if (d <= r) res.Add((w.X0, w.Y0, w.X1, w.Y1, lo, hi, d));
+ }
}
- }
+ }
+ From(_wallAll, _wallGrid);
+ if (_placedOverlay != null) From(_placedOverlay.Walls, _placedOverlay.WallGrid);
return res;
}
// Exact distance from (x, y) to the nearest wall reaching into zLo..zHi, up to maxR.
private double WallDistance(double x, double y, double zLo, double zHi, double maxR)
+ {
+ double best = WallDistanceIn(_wallAll, _wallGrid, x, y, zLo, zHi, maxR);
+ if (_placedOverlay is { Walls.Count: > 0 } ov) best = WallDistanceIn(ov.Walls, ov.WallGrid, x, y, zLo, zHi, best);
+ return best;
+ }
+
+ private static double WallDistanceIn(List all, Dictionary> grid, double x, double y, double zLo, double zHi, double maxR)
{
double best = maxR;
+ var span = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(all);
for (int gx = GridOf(x - maxR); gx <= GridOf(x + maxR); gx++)
for (int gy = GridOf(y - maxR); gy <= GridOf(y + maxR); gy++)
{
- if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
+ if (!grid.TryGetValue(GridKey(gx, gy), out var list)) continue;
foreach (int i in list)
{
- var w = _wallAll[i];
+ ref readonly var w = ref span[i];
if (w.ZMax < zLo || w.ZMin > zHi) continue;
+ // Its box farther off than the best so far: no nearer point on it.
+ if ((w.X0 < x - best && w.X1 < x - best) || (w.X0 > x + best && w.X1 > x + best) || (w.Y0 < y - best && w.Y1 < y - best) || (w.Y0 > y + best && w.Y1 > y + best)) continue;
double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
if (d >= best) continue;
var (lo, hi) = w.ZRangeAt(cx, cy);
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Blocked.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Blocked.cs
index 27d851f..d96b25c 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Blocked.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Blocked.cs
@@ -8,12 +8,28 @@
//
// GetGeometry closes each doorway a placed object stands across (both ways, as a wall), before the
// ledges are looked at, so every walk laid on the map (patrol, explore, dunroute, the stuck detours)
-// goes round. Blocked: walking lines straight through the doorway, 0.25 m apart across it, hit an
-// object's physics polygons within 1.2 m of the doorway at some body height (0.6 to 1.5 m: a web's
-// strands leave gaps a line slips through and a character doesn't), leaving no free gap of
-// BlockedGapMeters. An arch or a frame round a doorway leaves its
-// middle free; a pillar to one side leaves a gap. The objects come from StaticMeshSource (the plugin
-// points it at GeometryLoader.GetDungeonStaticMeshes once the raycast is up; null: nothing closed).
+// goes round. Blocked: walking lines straight through the doorway, 0.25 m apart across it, meet an
+// object within 1.2 m of the doorway in a body's way, leaving no free gap of BlockedGapMeters. An arch or a
+// frame round a doorway leaves its middle free; a pillar to one side leaves a gap.
+//
+// 2026-11-18: the objects are the map's own solid models (PlacedSolid) and a lane is a body's walk, not
+// rays. The rays (two of four heights, 0.6 to 1.5 m, hitting) counted a ray that went into an object's box
+// and met none of its polygons as a hit, so an arch round a doorway shut it (0x0150's 0x01000E60), the
+// bridge over 0x000A's hall shut the four doorways onto it (0x02000224: they open onto its deck, a body's
+// height clear between its rails), 0x039B's spiral stair shut the doorway that opens onto its foot, and
+// 0x238E's stair towers their doors. Now each lane is walked from free floor on either side: the feet on
+// the doorway's floor or on what is placed, a step up of StepOverTop at most at a time (onto the foot of a
+// ramp and up it to a platform: 0x8804's 0x0200033D), stopped by anything between the feet + PlacedBandLow
+// and + PlacedBandHigh (the band the placed objects' walls use). A web's strands at every height add up to
+// a closed line; a step block under a door sill (its top the doorway's floor) is stood on; a block taller
+// than a step (0x5456's 0x02000CCE) stops the walk. The objects come from StaticMeshSource (the plugin points
+// it at GeometryLoader.GetDungeonStaticMeshes once the raycast is up; null: nothing closed).
+//
+// 2026-11-18, landblocks with buildings: this map is the stuck detours' there (NavRecovery.PlanIndoor), and it
+// took every stab, stairs too, as walls and closed the doorways stairs stand in (1,094 building doorways
+// world-wide, 1,620 cells no door reached any more; 7D64 from its first doors 113 rooms to 99, E74E 155 to 129).
+// There the objects are BuildingMap's furniture: its stairs (BuildingMap.FurnitureFilter) are no walls and close
+// no doorway. Dungeons are as before.
using System;
using System.Collections.Generic;
@@ -31,11 +47,11 @@ internal static partial class DungeonPathfinder
/// A doorway with no free gap this wide left at body height is blocked.
internal const double BlockedGapMeters = 1.0;
- // Lanes this far apart across the doorway, none nearer its sides than the margin; each looked along from
- // BlockedNear before the doorway to BlockedNear past it (a web 0.8 m into the next cell is in it).
- private const double BlockedLaneStep = 0.25, BlockedEdgeMargin = 0.4, BlockedNear = 1.2;
- // A body's height: a web's strands leave gaps a thin line slips through, a character doesn't.
- private static readonly double[] BlockedHeights = { 0.6, 0.9, 1.2, 1.5 };
+ // Lanes this far apart across the doorway, none nearer its sides than the margin; each walked from
+ // BlockedNear before the doorway to BlockedNear past it (a web 0.8 m into the next cell is in it), a
+ // sample every BlockedAlong (half a column of the solid models). A lane starts on free floor, looked for
+ // up to BlockedRunUp further out (the foot of a ramp up to the doorway).
+ private const double BlockedLaneStep = 0.25, BlockedEdgeMargin = 0.4, BlockedNear = 1.2, BlockedAlong = 0.05, BlockedRunUp = 2.0;
/// What closing the blocked doorways did in the last dungeon (one line, for the build log), or null.
internal static string? BlockedNote;
@@ -51,13 +67,22 @@ internal static partial class DungeonPathfinder
var list = new List<(uint, uint, uint[])>();
if (statics.Count == 0) return list;
var seen = new HashSet();
+ var shapes = new Dictionary(); // each object's model, placed once
foreach (var n in graph.Values)
foreach (uint nb in n.Neighbors)
{
if (!graph.ContainsKey(nb) || !seen.Add(EdgeKey(n.CellId, nb))) continue;
if (!geo.TryGetDoorway(n.CellId, nb, out var d) || d.IsWide) continue;
- var near = statics.Where(s => s.Mesh.Max.X >= d.X - 4 && s.Mesh.Min.X <= d.X + 4 && s.Mesh.Max.Y >= d.Y - 4 && s.Mesh.Min.Y <= d.Y + 4
- && s.Mesh.Max.Z >= d.Z && s.Mesh.Min.Z <= d.Z + 2.5).ToList();
+ var near = new List<(uint SetupId, PlacedShape Shape)>();
+ for (int i = 0; i < statics.Count; i++)
+ {
+ var m = statics[i].Mesh;
+ if (m.MeshTriangles is not { Length: >= 3 }) continue;
+ if (m.Max.X < d.X - 4 || m.Min.X > d.X + 4 || m.Max.Y < d.Y - 4 || m.Min.Y > d.Y + 4
+ || m.Max.Z < d.Z || m.Min.Z > d.Z + 2.5) continue;
+ if (!shapes.TryGetValue(i, out var shape)) shapes[i] = shape = PlacedSolid.Place(statics[i].SetupId, m.MeshTriangles);
+ if (shape != null) near.Add((statics[i].SetupId, shape));
+ }
if (near.Count == 0) continue;
if (DoorwayBlocked(d, near, out var by)) list.Add((d.CellA, d.CellB, by));
}
@@ -69,30 +94,135 @@ internal static partial class DungeonPathfinder
return list;
}
- private static bool DoorwayBlocked(DungeonDoorway d, List<(uint SetupId, uint CellId, BoundingVolume Mesh)> near, out uint[] by)
+ private static bool DoorwayBlocked(DungeonDoorway d, List<(uint SetupId, PlacedShape Shape)> near, out uint[] by)
{
var setups = new HashSet();
- double tx = -d.Ny, ty = d.Nx, half = d.Width / 2 - BlockedEdgeMargin;
- var dir = new Vector3((float)d.Nx, (float)d.Ny, 0f);
+ double half = d.Width / 2 - BlockedEdgeMargin;
double run = 0, bestRun = 0;
+ var onLane = new List<(uint SetupId, PlacedShape Shape)>();
+ double reach = BlockedNear + BlockedRunUp;
for (double o = -half; o <= half + 1e-6; o += BlockedLaneStep)
{
- // Shut when something is in the way at two body heights or more (a step or a low kerb meets the lowest only).
- int heights = 0;
- foreach (double h in BlockedHeights)
- {
- var start = new Vector3((float)(d.X + tx * o - d.Nx * BlockedNear), (float)(d.Y + ty * o - d.Ny * BlockedNear), (float)(d.Z + h));
- foreach (var s in near)
- if (s.Mesh.RayIntersect(start, dir, (float)(2 * BlockedNear), out _)) { heights++; setups.Add(s.SetupId); break; }
- }
- bool shut = heights >= 2;
- if (shut) run = 0;
+ // The objects whose box the lane (with its run-ups) crosses: none, nothing to walk.
+ double lx = d.X - d.Ny * o, ly = d.Y + d.Nx * o;
+ double x0 = Math.Min(lx - d.Nx * reach, lx + d.Nx * reach) - 0.2, x1 = Math.Max(lx - d.Nx * reach, lx + d.Nx * reach) + 0.2;
+ double y0 = Math.Min(ly - d.Ny * reach, ly + d.Ny * reach) - 0.2, y1 = Math.Max(ly - d.Ny * reach, ly + d.Ny * reach) + 0.2;
+ onLane.Clear();
+ foreach (var s in near)
+ if (s.Shape.MaxX >= x0 && s.Shape.MinX <= x1 && s.Shape.MaxY >= y0 && s.Shape.MinY <= y1) onLane.Add(s);
+ // Open when a body gets through either way.
+ bool open = onLane.Count == 0 || LaneWalk(d, o, onLane, +1, setups) || LaneWalk(d, o, onLane, -1, setups);
+ if (!open) run = 0;
else { run += BlockedLaneStep; bestRun = Math.Max(bestRun, run); }
}
by = setups.ToArray();
return bestRun < BlockedGapMeters && setups.Count > 0;
}
+ // A body walking lane o of the doorway (dir +1: from CellA's side). It starts on free floor (nothing placed from the
+ // doorway's floor up to the body's top), at the lane's end or up to BlockedRunUp further out; its feet are on the
+ // doorway's floor or on the highest thing a step up at most from them; anything in its band over its feet stops it
+ // (that object's model goes into `by`).
+ private static bool LaneWalk(DungeonDoorway d, double o, List<(uint SetupId, PlacedShape Shape)> near, int dir, HashSet by)
+ {
+ double lx = d.X - d.Ny * o, ly = d.Y + d.Nx * o;
+ double startA = -dir * BlockedNear, endA = dir * BlockedNear;
+ bool Free(double a)
+ {
+ double x = lx + d.Nx * a, y = ly + d.Ny * a;
+ foreach (var s in near) if (s.Shape.SolidIn(x, y, d.Z + 0.05, d.Z + DungeonGeometry.PlacedBandHigh)) return false;
+ return true;
+ }
+ for (double ext = 0; ext <= BlockedRunUp + 1e-9; ext += BlockedAlong)
+ if (Free(startA - dir * ext)) { startA -= dir * ext; break; }
+ double feet = d.Z;
+ int n = (int)Math.Round((endA - startA) * dir / BlockedAlong);
+ for (int k = 0; k <= n; k++)
+ {
+ double a = startA + dir * k * BlockedAlong;
+ double x = lx + d.Nx * a, y = ly + d.Ny * a;
+ double stand = d.Z;
+ foreach (var s in near) stand = Math.Max(stand, s.Shape.TopAtMost(x, y, feet + DungeonGeometry.StepOverTop));
+ feet = stand;
+ foreach (var s in near)
+ if (s.Shape.SolidIn(x, y, feet + DungeonGeometry.PlacedBandLow, feet + DungeonGeometry.PlacedBandHigh)) { by.Add(s.SetupId); return false; }
+ }
+ return true;
+ }
+
+ /// Off: placed objects are no walls on the map (tests compare; the blocked doorways are apart).
+ internal static bool PlacedObjectsAsWalls = true;
+
+ // The stairs left off a building landblock's map (AddPlacedObjectsTo), by its geometry, for the blocked doorways.
+ private static readonly System.Runtime.CompilerServices.ConditionalWeakTable> _buildingStairs = new();
+
+ private static readonly Dictionary _hasBuildings = new();
+
+ /// The landblock's LandBlockInfo lists buildings (the outdoor world's towns and houses; a dungeon's lists none).
+ internal static bool HasBuildings(uint landblockKey, DatDatabase cellDat)
+ {
+ lock (_hasBuildings)
+ if (_hasBuildings.TryGetValue(landblockKey, out bool known)) return known;
+ bool has = false;
+ try
+ {
+ byte[]? info = cellDat.GetFileData((landblockKey << 16) | 0xFFFE);
+ if (info != null && info.Length >= 12)
+ {
+ uint numObjects = BitConverter.ToUInt32(info, 8);
+ long at = 12 + (long)numObjects * 32;
+ has = at + 2 <= info.Length && BitConverter.ToUInt16(info, (int)at) > 0;
+ }
+ }
+ catch { has = false; }
+ lock (_hasBuildings)
+ {
+ if (_hasBuildings.Count > 512) _hasBuildings.Clear();
+ _hasBuildings[landblockKey] = has;
+ }
+ return has;
+ }
+
+ /// What the placed objects added to the last dungeon's map (one line, for the build log), or null.
+ internal static string? PlacedNote;
+
+ /// GetGeometry's step: the objects the cells place (an altar, a statue) on the map by what they put in
+ /// a body's way at their floor, the outline as walls (DungeonGeometry.AddPlacedObjects), so every walk keeps
+ /// clear of them. On a landblock with buildings ( says), its furniture, the stairs left out.
+ private static void AddPlacedObjectsTo(uint landblockKey, DungeonGeometry geo, DatDatabase? cellDat = null)
+ {
+ PlacedNote = null;
+ var source = StaticMeshSource;
+ if (!PlacedObjectsAsWalls || source == null) return;
+ try
+ {
+ var statics = source(landblockKey);
+ if (statics == null || statics.Count == 0) return;
+ int added, stairs = 0;
+ bool buildings = cellDat != null && HasBuildings(landblockKey, cellDat);
+ if (buildings)
+ {
+ MarkBuildingMap(geo);
+ var f = BuildingMap.AddFurniture(geo, statics);
+ _buildingStairs.AddOrUpdate(geo, f.Stairs);
+ added = f.Kept;
+ stairs = f.Stairs.Count;
+ }
+ else added = geo.AddPlacedObjects(statics.Where(s => s.Mesh.MeshTriangles is { Length: >= 3 })
+ .Select(s => (s.SetupId, s.CellId, s.Mesh.MeshTriangles)));
+ var inv = CultureInfo.InvariantCulture;
+ var classes = geo.PlacedObjects.GroupBy(p => p.Class).OrderBy(g => g.Key)
+ .Select(g => string.Format(inv, "{0} {1}", g.Key.ToString().ToLowerInvariant(), g.Count()));
+ PlacedNote = string.Format(inv, "{0} of {1} placed object(s) stand in the way at body height: walls on the map ({2}){3}",
+ added, statics.Count, string.Join(", ", classes),
+ buildings ? string.Format(inv, "; a landblock with buildings: {0} stair(s) left out", stairs) : "");
+ }
+ catch (Exception e)
+ {
+ PlacedNote = "placed objects not added: " + e.GetType().Name;
+ }
+ }
+
/// GetGeometry's step: the cached graph of loses the doorways placed
/// objects stand across (both ways), then its ledges.
private static void CloseMapBlocksOf(uint landblockKey, Dictionary graph, DungeonGeometry geo)
@@ -111,6 +241,9 @@ internal static partial class DungeonPathfinder
{
var statics = source(landblockKey);
if (statics == null || statics.Count == 0) return;
+ // A building's stairs close no doorway (AddPlacedObjectsTo left them off its map).
+ if (_buildingStairs.TryGetValue(geo, out var stairs) && stairs.Count > 0)
+ statics = statics.Where(s => BuildingMap.KeyOf(s.SetupId, s.CellId, s.Mesh.MeshTriangles) is not BuildingMap.PieceKey k || !stairs.Contains(k)).ToList();
var blocked = FindBlockedDoorways(graph, geo, statics);
if (blocked.Count == 0) return;
foreach (var (a, b, _) in blocked)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Explore.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Explore.cs
index c4f6269..b2e1cb9 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Explore.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Explore.cs
@@ -69,6 +69,7 @@ internal static partial class DungeonPathfinder
out ExplorePlan plan,
IReadOnlySet? preferCells = null)
{
+ using var holes = CountHoles(); // one build: the note's "no way round" counts every walk round of it (Holes.cs)
LastPortalAvoidance = null;
var o = ((options ?? DungeonPatrolOptions.Default) with { Coverage = PatrolCoverage.Everything }).Clamped();
NavRouteParser route;
@@ -210,7 +211,8 @@ internal static partial class DungeonPathfinder
finally { ScanMiddles = null; }
if (mid != null) { Append(pts, Tag(mid, "explore-end")); middles.Add(mid); }
// Round a hole in a cell's floor, not over it (DungeonPathfinder.Holes.cs): before the
- // straightening, so its legs keep the clearance the walk round has.
+ // straightening, so its legs keep the clearance the walk round has. (EmitSteps walked its legs
+ // round placed objects already; this is the floor, and an object on the leg into the end too.)
int holes = WalkRoundHoles(pts, geo!);
if (holes > 0 || HolesLeft > 0)
MainRouteNote = (MainRouteNote == null ? "" : MainRouteNote + "; ") + $"holes: {holes} walked round" + (HolesLeft > 0 ? $", {HolesLeft} with no way round" : "");
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Holes.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Holes.cs
index 4fb32d8..3b38753 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Holes.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Holes.cs
@@ -15,9 +15,21 @@
// edges by HoleKeepOff. The A* path is then pulled straight wherever a leg stays on the floor and
// keeps that clearance. With no way round, the leg stays as laid (a drop the walk can't do
// otherwise) and the note says so.
+//
+// 2026-11-18, objects: a walk round can start inside something placed (a corner laid by a chair, the
+// character itself beside a table): every sample round it was too close to it, so there was no way
+// round at all (46 of the 139 legs the building survey still found through furniture). It may now
+// cross the samples of what it stands in, and the ring round it, until it is out. In a building map
+// (BuildingMap, or the dungeon map of a landblock with buildings) a walk point's height is often not
+// a floor's (a doorway's lowest corner, a corner on a stair the map has no floor for): the floor nearest
+// it within 3 m was the ground floor under the stair, and the walk round went down there (Holtburg
+// A9B3#0, 0104 to 0106 by 32626,34455 at 116.0 from a stair corner at 117.5). There it is the floor
+// within BuildingStartBand of the point, else the point's own height, and a walk round that leaves the
+// leg's heights by more than BuildingRoundBand is no way round.
using System;
using System.Collections.Generic;
+using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
@@ -33,18 +45,56 @@ internal static partial class DungeonPathfinder
private const double HolePad = 10.0; // the box round the leg (metres each way)
private const int HoleMaxGrid = 160 * 160;
private const double HoleStartBand = 3.0; // a walk point's floor, looked for this far above or below it
+ // In a building map: a walk point's floor within this of its height, and no walk round leaving the leg's
+ // heights by more than BuildingRoundBand.
+ internal const double BuildingStartBand = 1.0, BuildingRoundBand = 1.0;
+ // In a building map the box round a leg is this much each way (its rooms are small; with no way round, the A*
+ // went over every sample of a 10 m box, at a clearance each: most of a furnished walk's time).
+ internal const double BuildingHolePad = 4.0;
- /// How many legs over a hole the last walk had walked round, and how many it couldn't.
- internal static int HolesWalkedRound, HolesLeft;
+ /// How many legs over a hole (or through a placed object) the build walked round, and how many it couldn't:
+ /// running counts over one build (), every walk-round of the build added in (the patrol's
+ /// rooms, its cell walk, the portal step's legs, each stretch of a jump walk). A call outside any build counts on
+ /// its own. They were the last call's only, so a patrol's notes said 0 with no way round where 4 legs had none
+ /// (0x00FE, 0x00D6: re-walking the finished patrols found them).
+ [ThreadStatic] internal static int HolesWalkedRound, HolesLeft;
+ [ThreadStatic] private static int _holeCountDepth;
+
+ /// Begins a build's count (the outermost one only sets the counts to 0); dispose it when the build is done.
+ internal static HoleCount CountHoles()
+ {
+ if (_holeCountDepth++ == 0) HolesWalkedRound = HolesLeft = 0;
+ return new HoleCount();
+ }
+
+ internal readonly struct HoleCount : IDisposable
+ {
+ public void Dispose() { if (_holeCountDepth > 0) _holeCountDepth--; }
+ }
+
+ // The geometries that are a building's (BuildingMap's, or the dungeon map of a landblock with buildings).
+ private static readonly ConditionalWeakTable _buildingMaps = new();
+
+ /// Marks as a building's map: its walks round start on the floor at their own height.
+ internal static void MarkBuildingMap(DungeonGeometry geo) => _buildingMaps.AddOrUpdate(geo, _buildingMaps);
+
+ internal static bool IsBuildingMap(DungeonGeometry geo) => _buildingMaps.TryGetValue(geo, out _);
///
/// Replaces each leg of that leaves the floor with a walk round on it
- /// (see the file's comment). Returns how many legs were walked round.
+ /// (see the file's comment). Returns how many legs this call walked round (the build's counts
+ /// go up by as many, and by the legs it couldn't). , when given, must
+ /// take every leg of a walk round (from, to) or the leg stays as laid and counts as having no way
+ /// round: the portal step's (DungeonPathfinder.Portals.cs: a walk round an object must not go into
+ /// a portal's circle).
///
- internal static int WalkRoundHoles(List pts, DungeonGeometry geo)
+ internal static int WalkRoundHoles(List pts, DungeonGeometry geo, bool objectsOnly = false,
+ Func? accept = null)
{
- HolesWalkedRound = HolesLeft = 0;
+ using var count = CountHoles();
if (!HolesEnabled || pts.Count < 2) return 0;
+ if (objectsOnly && geo.PlacedCount == 0) return 0;
+ int walked = 0;
var outPts = new List(pts.Count + 16) { pts[0] };
for (int i = 0; i + 1 < pts.Count; i++)
{
@@ -52,29 +102,71 @@ internal static partial class DungeonPathfinder
var b = pts[i + 1];
double ax = DungeonGeometry.NavToWorld(a.EW), ay = DungeonGeometry.NavToWorld(a.NS), az = a.Z * 240.0;
double bx = DungeonGeometry.NavToWorld(b.EW), by = DungeonGeometry.NavToWorld(b.NS), bz = b.Z * 240.0;
- if (OnFloorAll(geo, ax, ay, az, bx, by, bz))
+ if (objectsOnly ? !LegMeetsPlaced(geo, ax, ay, az, bx, by, bz) : OnFloorAll(geo, ax, ay, az, bx, by, bz))
{
outPts.Add(b);
continue;
}
var round = FloorPath(geo, ax, ay, az, bx, by, bz);
- if (round == null)
+ List? laid = null;
+ if (round != null)
+ {
+ laid = new List(round.Count);
+ foreach (var (x, y, z) in round)
+ laid.Add(new NavPoint { Type = NavPointType.Point, NS = DungeonGeometry.WorldToNav(y), EW = DungeonGeometry.WorldToNav(x), Z = z / 240.0 });
+ if (accept != null)
+ {
+ var from = a;
+ for (int k = 0; k <= laid.Count; k++)
+ {
+ var p = k < laid.Count ? laid[k] : b;
+ if (!accept(from, p)) { laid = null; break; }
+ from = p;
+ }
+ }
+ }
+ if (laid == null)
{
HolesLeft++;
outPts.Add(b);
continue;
}
HolesWalkedRound++;
- foreach (var (x, y, z) in round)
- outPts.Add(new NavPoint { Type = NavPointType.Point, NS = DungeonGeometry.WorldToNav(y), EW = DungeonGeometry.WorldToNav(x), Z = z / 240.0 });
+ walked++;
+ outPts.AddRange(laid);
outPts.Add(b);
}
- if (HolesWalkedRound > 0)
+ if (walked > 0)
{
pts.Clear();
pts.AddRange(outPts);
}
- return HolesWalkedRound;
+ return walked;
+ }
+
+ /// The straight walk from a to b stays on the floor all the way (OnFloorAll): the hole rule's
+ /// test, and the straightener's (DungeonPathfinder.Straighten.cs).
+ internal static bool LegOnFloor(DungeonGeometry geo, NavPoint a, NavPoint b)
+ => OnFloorAll(geo, DungeonGeometry.NavToWorld(a.EW), DungeonGeometry.NavToWorld(a.NS), a.Z * 240.0,
+ DungeonGeometry.NavToWorld(b.EW), DungeonGeometry.NavToWorld(b.NS), b.Z * 240.0);
+
+ // The straight walk a-b goes through something the cells place (an altar, a statue) on the floor it
+ // follows; a stretch with no floor under it on the map is no concern here (the walk round holes is the
+ // explore's: a tube's floorless cells would be walked round to nowhere).
+ private static bool ThroughPlaced(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
+ {
+ double dx = bx - ax, dy = by - ay, len = Math.Sqrt(dx * dx + dy * dy);
+ if (len < HoleSample) return false;
+ if (!geo.TryFloorHeight(ax, ay, az, HoleStartBand, out double zf)) zf = az;
+ int steps = (int)Math.Ceiling(len / HoleSample);
+ for (int s = 1; s < steps; s++)
+ {
+ double t = (double)s / steps, x = ax + dx * t, y = ay + dy * t;
+ if (!geo.TryFloorHeight(x, y, zf, HoleStep, out double h) && !geo.TryFloorHeight(x, y, az + (bz - az) * t, HoleStep, out h)) continue;
+ zf = h;
+ if (geo.InsidePlaced(x, y, h)) return true;
+ }
+ return false;
}
// The straight walk a-b stays on the floor all the way: every sample has a floor within a step of
@@ -94,6 +186,9 @@ internal static partial class DungeonPathfinder
if (s == steps && Math.Abs(bz - zf) <= 1.5 && geo.TryFloorHeight(x, y, bz, HoleStep, out _)) return true;
return false;
}
+ // Through an altar or a statue the cells place (DungeonGeometry.AddPlacedObjects): no floor to
+ // walk there either, so the leg is walked round it like a hole (the far end is the walk's own).
+ if (s < steps && geo.InsidePlaced(x, y, h)) return false;
zf = h;
}
return true;
@@ -102,9 +197,11 @@ internal static partial class DungeonPathfinder
// A* round on the floor from a to b; the points between (pulled straight), or null with no way.
private static List<(double X, double Y, double Z)>? FloorPath(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
{
- double x0 = Math.Min(ax, bx) - HolePad, y0 = Math.Min(ay, by) - HolePad;
- int nx = (int)Math.Ceiling((Math.Abs(bx - ax) + 2 * HolePad) / HoleSample) + 1;
- int ny = (int)Math.Ceiling((Math.Abs(by - ay) + 2 * HolePad) / HoleSample) + 1;
+ bool building = IsBuildingMap(geo);
+ double pad = building ? BuildingHolePad : HolePad;
+ double x0 = Math.Min(ax, bx) - pad, y0 = Math.Min(ay, by) - pad;
+ int nx = (int)Math.Ceiling((Math.Abs(bx - ax) + 2 * pad) / HoleSample) + 1;
+ int ny = (int)Math.Ceiling((Math.Abs(by - ay) + 2 * pad) / HoleSample) + 1;
if (nx * ny > HoleMaxGrid) return null;
int Idx(int i, int j) => j * nx + i;
double Gx(int i) => x0 + i * HoleSample;
@@ -118,11 +215,33 @@ internal static partial class DungeonPathfinder
var from = new int[nx * ny];
for (int k = 0; k < g.Length; k++) { g[k] = double.MaxValue; from[k] = -1; }
- if (!geo.TryFloorHeight(ax, ay, az, HoleStartBand, out double sh)) sh = az;
+ if (!geo.TryFloorHeight(ax, ay, az, building ? BuildingStartBand : HoleStartBand, out double sh)) sh = az;
int start = Idx(si, sj), goal = Idx(ti, tj);
height[start] = sh; state[start] = 1; // the walk stands there already
g[start] = 0;
+ // A start inside something placed: the boxes of what it stands in, with the ring a sample keeps off them,
+ // where the walk may cross their samples on its way out (only from the start, or from a sample it reached so).
+ bool[]? esc = null;
+ byte[]? escState = null; // 0 unknown, 1 floor and not in a wall, 2 no
+ double ex0 = double.MaxValue, ey0 = double.MaxValue, ex1 = double.MinValue, ey1 = double.MinValue;
+ if (geo.PlacedCount > 0 && geo.InsidePlaced(ax, ay, sh))
+ {
+ foreach (var o in geo.PlacedNear(ax, ay, 0))
+ {
+ ex0 = Math.Min(ex0, o.MinX); ey0 = Math.Min(ey0, o.MinY);
+ ex1 = Math.Max(ex1, o.MaxX); ey1 = Math.Max(ey1, o.MaxY);
+ }
+ if (ex0 <= ex1)
+ {
+ double ring = HoleKeepOff + HoleSample;
+ ex0 -= ring; ey0 -= ring; ex1 += ring; ey1 += ring;
+ esc = new bool[nx * ny];
+ escState = new byte[nx * ny];
+ esc[start] = true;
+ }
+ }
+
// Floor at a step from `fromH`, and clear of walls and edges (the goal: only its floor).
bool Walkable(int i, int j, double fromH, bool isGoal, out double h)
{
@@ -139,6 +258,23 @@ internal static partial class DungeonPathfinder
return true;
}
+ // On the way out of what the start stands in: a floor sample in its box (or the ring round it), not in a wall.
+ bool Escapes(int i, int j, double fromH, out double h)
+ {
+ h = 0;
+ if (escState == null || i < 0 || j < 0 || i >= nx || j >= ny) return false;
+ double x = Gx(i), y = Gy(j);
+ if (x < ex0 || x > ex1 || y < ey0 || y > ey1) return false;
+ if (!geo.TryFloorHeight(x, y, fromH, HoleStep, out h)) return false;
+ int k = Idx(i, j);
+ if (escState[k] == 0)
+ escState[k] = geo.InsidePlaced(x, y, h) || geo.ClearanceMemo(x, y, h, HoleKeepOff + 0.1) > 0.05 ? (byte)1 : (byte)2;
+ return escState[k] == 1;
+ }
+
+ // A diagonal's side sample: walkable, or on the way out.
+ bool Side(int i, int j, double fromH, bool leaving) => Walkable(i, j, fromH, false, out _) || (leaving && Escapes(i, j, fromH, out _));
+
var open = new PriorityQueue();
open.Enqueue(start, HoleDist(ax, ay, bx, by));
var closed = new bool[nx * ny];
@@ -160,14 +296,22 @@ internal static partial class DungeonPathfinder
int k2 = Idx(i2, j2);
if (closed[k2]) continue;
bool isGoal = k2 == goal;
- if (!Walkable(i2, j2, height[k], isGoal, out double h2)) continue;
+ bool leaving = esc != null && esc[k]; // still on the way out of what the start stands in
+ bool viaEscape = false;
+ if (!Walkable(i2, j2, height[k], isGoal, out double h2))
+ {
+ if (!leaving || !Escapes(i2, j2, height[k], out h2)) continue;
+ viaEscape = true;
+ }
if (isGoal) height[k2] = h2;
// A diagonal step only between two floor samples (not across a corner of the hole).
- if (d >= 4 && !(Walkable(ci + di[d], cj, height[k], false, out _) && Walkable(ci, cj + dj[d], height[k], false, out _))) continue;
+ if (d >= 4 && !(Side(ci + di[d], cj, height[k], leaving) && Side(ci, cj + dj[d], height[k], leaving))) continue;
double ng = g[k] + (d >= 4 ? 1.41421356 : 1.0) * HoleSample;
if (ng >= g[k2]) continue;
g[k2] = ng;
from[k2] = k;
+ if (viaEscape) { height[k2] = h2; esc![k2] = true; }
+ else if (esc != null) esc[k2] = false;
open.Enqueue(k2, ng + HoleDist(Gx(i2), Gy(j2), bx, by));
}
}
@@ -176,6 +320,17 @@ internal static partial class DungeonPathfinder
var cells = new List();
for (int k = goal; k != -1; k = from[k]) cells.Add(k);
cells.Reverse();
+ // In a building map, a walk round that goes up or down a floor from the leg's own heights (down to the ground
+ // floor under a stair the map has no floor for) is no way round.
+ if (building)
+ {
+ // The leg's heights: its ends' and the floors under them (a doorway's height is its lowest corner, a metre
+ // over the floor under it in some of Holtburg's houses).
+ double zLo = Math.Min(Math.Min(az, bz), Math.Min(sh, height[goal])) - BuildingRoundBand;
+ double zHi = Math.Max(Math.Max(az, bz), Math.Max(sh, height[goal])) + BuildingRoundBand;
+ foreach (int k in cells)
+ if (height[k] < zLo || height[k] > zHi) return null;
+ }
var path = new List<(double X, double Y, double Z)>(cells.Count);
foreach (int k in cells) path.Add((Gx(k % nx), Gy(k / nx), height[k]));
path[0] = (ax, ay, az);
@@ -184,6 +339,17 @@ internal static partial class DungeonPathfinder
// Pulled straight: from each point, the farthest one a straight leg reaches on the floor, clear.
var kept = new List<(double X, double Y, double Z)>();
int at = 0;
+ if (esc != null)
+ {
+ // Out of what the start stands in: straight to the first sample clear of it (across it), pulled from there.
+ int e = 0;
+ while (e + 1 < cells.Count - 1 && esc[cells[e + 1]]) e++;
+ if (e > 0)
+ {
+ at = e + 1;
+ if (at < path.Count - 1) kept.Add(path[at]);
+ }
+ }
while (at < path.Count - 1)
{
int best = at + 1;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Jumps.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Jumps.cs
new file mode 100644
index 0000000..defaa2f
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Jumps.cs
@@ -0,0 +1,298 @@
+// DungeonPathfinder, jump-downs (2026-11-17).
+//
+// AC won't walk a character off a ledge (it slides along the edge): a jump goes over. DreamWeave Thread
+// 0x0169: the last three monsters were in a cave 9-12 m under the top floor, and the one way down is a
+// 20 m shaft in the middle of a hall (four open-air cells, no rim). The dungeon map had no walk there, so
+// the character was left there; a jump by hand took it in.
+//
+// A jump-down is one way (nobody climbs back up a ledge), so a walk takes one only when asked:
+// /ra dunnav-to jump, which a script sends only when no monster left can be walked to. In a
+// Thread that is safe: the cache and the exit appear where you stand once it is cleared.
+//
+// A jump-down is an opening (a doorway of the map) from a cell standing on its own floor to a side whose
+// floor, under the opening, is more than LedgeMeters lower, however much: the ledges, found from the
+// openings themselves (a closed ledge is gone from the graph, not from the geometry). It lands in the cell
+// whose own floor is under the spot a short hop past the edge. No depth limit (2026-11-18: "No limit
+// on jump down"; the fall doesn't matter): it was 15 m, and the floor under the far side was looked for
+// only as deep as the ledge pass looks (18 m); now all the way down to the dungeon's lowest floor.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RynthCore.Plugin.RynthAi.LegacyUi;
+using RynthCore.Plugin.RynthAi.Raycasting;
+
+namespace RynthCore.Plugin.RynthAi;
+
+/// A jump down off the edge of an opening: from cell (its floor at )
+/// at the opening's centre (, ), facing (, ), onto
+/// cell 's floor at (, , ).
+internal readonly record struct DungeonJump(uint From, uint Land, double X, double Y, double Z, double Nx, double Ny,
+ double LandX, double LandY, double LandZ)
+{
+ public double Drop => Z - LandZ;
+}
+
+internal static partial class DungeonPathfinder
+{
+ /// Below the ledge pass's look (18 m), the floor under a jump is looked for every this many metres
+ /// (each look covers LedgeDownBand either side) down to the dungeon's lowest floor.
+ internal const double JumpDownStep = 3.0;
+ /// A jump-down costs the path this much walk: any walk round is taken first.
+ internal const double JumpCostMeters = 40.0;
+ /// The jump's power (spacebar held, of 1000): a short hop over the edge.
+ internal const int JumpHoldMs = 300;
+ /// The walk lines up square to the edge from this far back ...
+ internal const double JumpApproachMeters = 1.5;
+ /// ... and jumps from this far short of it (the edge stops the character there anyway).
+ internal const double JumpBackMeters = 0.1;
+
+ // Where the hop is looked for a floor to land on: this far past the edge (the first that has one).
+ private static readonly double[] JumpLandInsets = { 2.0, 1.5, 3.0, 1.0, 4.0 };
+
+ /// Every jump-down of the dungeon (both ways of every opening looked at).
+ internal static List FindJumps(Dictionary graph, DungeonGeometry geo)
+ {
+ var list = new List();
+ if (graph.Count == 0) return list;
+ double lowest = LowestLook(graph); // under the lowest cell: the deepest look
+ var solids = new FallSolids(graph);
+ foreach (var d in geo.AllDoorways)
+ foreach (var (from, to) in new[] { (d.CellA, d.CellB), (d.CellB, d.CellA) })
+ {
+ if (!graph.ContainsKey(from) || !graph.ContainsKey(to)) continue;
+ var (nx, ny) = d.NormalFrom(from); // out of from, over the edge
+ if (OwnFloorInside(geo, from, d, -nx, -ny) is not { } top) continue; // standing on nothing: no jump from there
+ if (FloorInside(geo, to, d, nx, ny, LedgeFloorFallback ? lowest : double.NaN) is not { } low) continue;
+ double drop = top - low;
+ if (drop <= LedgeMeters) continue;
+ // Where the walk lines up and jumps from: nobody stands there inside something placed.
+ if (geo.InsidePlaced(d.X - nx * JumpApproachMeters, d.Y - ny * JumpApproachMeters, top)
+ || geo.InsidePlaced(d.X - nx * JumpBackMeters, d.Y - ny * JumpBackMeters, top)) continue;
+ if (!TryLanding(graph, geo, d, nx, ny, top, lowest, solids, out uint land, out double lx, out double ly, out double lz) || land == from) continue;
+ list.Add(new DungeonJump(from, land, d.X, d.Y, top, nx, ny, lx, ly, lz));
+ }
+ return list;
+ }
+
+ // ── What the cells place, in the way of a jump (2026-11-18) ──────────────────
+ // The landing was looked for on the cells' floors only. A spot inside an altar or a statue on that floor is no
+ // landing (the map's InsidePlaced), and a fall that meets something placed between the take-off and the floor
+ // lands on that instead: a platform or a bridge over a pit (0x000A's hall: the 0x02000224 bridge and the
+ // 0x02000222 slabs at z -12.8 over the hole near 0131/0132; 22 of 458 jumps in nine dungeons fell onto one).
+ // Those are looked for in every object the cells place (StaticMeshSource), the ones the map leaves off too (a
+ // slab has nothing in a body's band at its own floor), in the body's column at the landing spot.
+
+ /// The column a falling body sweeps: its middle and four points this far out.
+ internal const double JumpFallRadius = 0.4;
+ /// The fall is looked at from the landing floor + PlacedBandLow (lower is stepped over on landing) up to the
+ /// take-off height + this (a deck flush with the edge is walked onto, not jumped past).
+ internal const double JumpFallOverTop = 0.3;
+
+ // The objects the cells place, as solid models, placed the first time a landing spot needs them.
+ private sealed class FallSolids
+ {
+ private readonly List<(uint SetupId, uint CellId, BoundingVolume Mesh)>? _statics;
+ private readonly Dictionary _shapes = new();
+
+ public FallSolids(Dictionary graph)
+ {
+ var source = StaticMeshSource;
+ if (source == null || graph.Count == 0) return;
+ uint lb = 0;
+ foreach (uint c in graph.Keys) { lb = c >> 16; break; }
+ try { _statics = source(lb); } catch { _statics = null; }
+ }
+
+ /// Something placed is solid in the body's column at (x, y) between zLo and zHi.
+ public bool Hit(double x, double y, double zLo, double zHi)
+ {
+ if (_statics == null || zHi <= zLo) return false;
+ double r = JumpFallRadius;
+ for (int i = 0; i < _statics.Count; i++)
+ {
+ var m = _statics[i].Mesh;
+ if (m.MeshTriangles is not { Length: >= 3 }) continue;
+ if (m.Max.X < x - r || m.Min.X > x + r || m.Max.Y < y - r || m.Min.Y > y + r || m.Max.Z < zLo || m.Min.Z > zHi) continue;
+ if (!_shapes.TryGetValue(i, out var s)) _shapes[i] = s = PlacedSolid.Place(_statics[i].SetupId, m.MeshTriangles);
+ if (s == null) continue;
+ if (s.SolidIn(x, y, zLo, zHi) || s.SolidIn(x + r, y, zLo, zHi) || s.SolidIn(x - r, y, zLo, zHi)
+ || s.SolidIn(x, y + r, zLo, zHi) || s.SolidIn(x, y - r, zLo, zHi)) return true;
+ }
+ return false;
+ }
+ }
+
+
+ // The cell's own floor just inside the opening (none: null).
+ private static double? OwnFloorInside(DungeonGeometry geo, uint cell, DungeonDoorway d, double ux, double uy)
+ {
+ foreach (double inset in LedgeInsets)
+ {
+ double x = d.X + ux * inset, y = d.Y + uy * inset;
+ foreach (double dz in LedgeZRefs)
+ if (geo.TryCellFloorHeight(cell, x, y, d.Z + dz, out double h)) return h;
+ }
+ return null;
+ }
+
+ // The floor a hop past the edge lands on, and the cell it is the floor of: the first floor under the spot (the
+ // one a fall meets), clear of what the cells place there and on the way down; else the next inset.
+ private static bool TryLanding(Dictionary graph, DungeonGeometry geo, DungeonDoorway d,
+ double nx, double ny, double top, double lowest, FallSolids? solids,
+ out uint land, out double lx, out double ly, out double lz)
+ {
+ foreach (double inset in JumpLandInsets)
+ {
+ double x = d.X + nx * inset, y = d.Y + ny * inset;
+ bool found = false;
+ double fx = 0, fy = 0, fz = 0;
+ uint fc = 0;
+ for (double dz = 0; top + dz >= lowest && !found; dz -= JumpDownStep) // 0, -3, -6 ... as far down as the dungeon goes
+ {
+ if (!geo.TryFloorHeight(x, y, top + dz, LedgeDownBand, out double h) || h > top - LedgeMeters) continue;
+ foreach (var n in graph.Values)
+ if (geo.TryCellFloorHeight(n.CellId, x, y, h, out double hh) && Math.Abs(hh - h) < 0.5)
+ {
+ fc = n.CellId; fx = x; fy = y; fz = hh;
+ found = true;
+ break;
+ }
+ }
+ if (!found) continue;
+ // Inside an altar or a statue on that floor, or a platform on the way down: not here.
+ if (geo.InsidePlaced(fx, fy, fz)) continue;
+ if (solids != null && solids.Hit(fx, fy, fz + DungeonGeometry.PlacedBandLow, top + JumpFallOverTop)) continue;
+ land = fc; lx = fx; ly = fy; lz = fz;
+ return true;
+ }
+ land = 0; lx = ly = lz = 0;
+ return false;
+ }
+
+ ///
+ /// A* from to as , and the
+ /// jump-downs as one-way steps (each costs of walk). Each cell comes with
+ /// the jump taken into it (null: walked). Empty: unreachable even so.
+ ///
+ internal static List<(uint Cell, DungeonJump? Jump)> FindPathWithJumps(
+ uint start, uint goal, Dictionary graph, IReadOnlyList jumps,
+ IReadOnlySet? hazardCells = null)
+ {
+ var path = new List<(uint, DungeonJump?)>();
+ if (!graph.ContainsKey(start) || !graph.ContainsKey(goal)) return path;
+ var byFrom = jumps.GroupBy(j => j.From).ToDictionary(g => g.Key, g => g.ToList());
+ var goalNode = graph[goal];
+ var gScore = new Dictionary { [start] = 0.0 };
+ var cameFrom = new Dictionary();
+ var open = new PriorityQueue();
+ var closed = new HashSet();
+ open.Enqueue(start, H(graph[start], goalNode));
+ double jumpCost = JumpCostMeters / 240.0; // nav units
+
+ while (open.Count > 0)
+ {
+ uint current = open.Dequeue();
+ if (!closed.Add(current)) continue;
+ if (current == goal) break;
+ var cur = graph[current];
+ double gCur = gScore[current];
+
+ void Relax(uint nb, double cost, DungeonJump? jump)
+ {
+ if (closed.Contains(nb) || !graph.TryGetValue(nb, out var nbNode)) return;
+ if (nb != goal && hazardCells != null && hazardCells.Contains(nb)) return;
+ double g = gCur + cost;
+ if (g >= gScore.GetValueOrDefault(nb, double.MaxValue)) return;
+ gScore[nb] = g;
+ cameFrom[nb] = (current, jump);
+ open.Enqueue(nb, g + H(nbNode, goalNode));
+ }
+
+ foreach (uint nb in cur.Neighbors)
+ if (graph.TryGetValue(nb, out var nbNode) && !IsDropEdge(cur, nbNode)) Relax(nb, H(cur, nbNode), null);
+ if (byFrom.TryGetValue(current, out var js))
+ foreach (var j in js)
+ {
+ var landNode = graph[j.Land];
+ Relax(j.Land, H(cur, landNode) + jumpCost, j);
+ }
+ }
+ if (!closed.Contains(goal)) return path;
+ for (uint c = goal; ; )
+ {
+ if (cameFrom.TryGetValue(c, out var step)) { path.Add((c, step.Jump)); c = step.From; }
+ else { path.Add((c, null)); break; }
+ }
+ path.Reverse();
+ return path;
+ }
+
+ ///
+ /// Points for walking a path with jump-downs (from ), the destination
+ /// not included: each stretch walked as lays it; at each jump, a point
+ /// back from the edge (square to it), then a Jump point just short of
+ /// it facing over it; the next stretch starts where it lands.
+ ///
+ internal static List BuildJumpPathPoints(
+ List<(uint Cell, DungeonJump? Jump)> path, Dictionary graph, DungeonGeometry? geo,
+ IReadOnlySet? hazardCells, double startNS, double startEW, double startZ,
+ double destNS, double destEW, double destZ, out int jumps)
+ {
+ using var holes = CountHoles(); // one build: every stretch's walk-rounds count
+ var pts = new List();
+ jumps = 0;
+ int seg = 0;
+ double sNs = startNS, sEw = startEW, sZ = startZ;
+ for (int k = 1; k <= path.Count; k++)
+ {
+ if (k < path.Count && path[k].Jump is null) continue;
+ var cells = path.GetRange(seg, k - seg).Select(p => p.Cell).ToList();
+ if (k == path.Count)
+ {
+ pts.AddRange(BuildPathPoints(cells, graph, geo, hazardCells, sNs, sEw, sZ, destNS, destEW, destZ, out _));
+ break;
+ }
+ var j = path[k].Jump!.Value;
+ double aNs = DungeonGeometry.WorldToNav(j.Y - j.Ny * JumpApproachMeters), aEw = DungeonGeometry.WorldToNav(j.X - j.Nx * JumpApproachMeters);
+ // The stretch to the approach point: BuildPathPoints walks its legs round what the cells place, the leg
+ // into the approach point too (the stretch's destination, 2026-11-18).
+ pts.AddRange(BuildPathPoints(cells, graph, geo, hazardCells, sNs, sEw, sZ, aNs, aEw, j.Z, out _));
+ var approach = new NavPoint { Type = NavPointType.Point, NS = aNs, EW = aEw, Z = j.Z / 240.0 };
+ var jump = new NavPoint
+ {
+ Type = NavPointType.Jump,
+ NS = DungeonGeometry.WorldToNav(j.Y - j.Ny * JumpBackMeters),
+ EW = DungeonGeometry.WorldToNav(j.X - j.Nx * JumpBackMeters),
+ Z = j.Z / 240.0,
+ JumpHeading = JumpHeadingOf(j.Nx, j.Ny),
+ JumpShift = false,
+ JumpMs = JumpHoldMs,
+ Doorway = true, // the tight reach: jump at the edge, not a metre short of it
+ };
+ pts.Add(approach);
+ // The line-up to the edge (1.4 m, square to it) was never looked at either: an object on it is walked
+ // round to the Jump point, whose heading still faces over the edge.
+ if (geo != null && geo.PlacedCount > 0)
+ {
+ var lineUp = new List { approach, jump };
+ if (WalkRoundHoles(lineUp, geo, objectsOnly: true) > 0)
+ for (int q = 1; q + 1 < lineUp.Count; q++) pts.Add(lineUp[q]);
+ }
+ pts.Add(jump);
+ jumps++;
+ sNs = DungeonGeometry.WorldToNav(j.LandY);
+ sEw = DungeonGeometry.WorldToNav(j.LandX);
+ sZ = j.LandZ;
+ seg = k;
+ }
+ return pts;
+ }
+
+ /// The compass heading (0 north, 90 east) of the world direction (x east, y north).
+ internal static double JumpHeadingOf(double nx, double ny)
+ {
+ double deg = Math.Atan2(nx, ny) * (180.0 / Math.PI);
+ return deg < 0 ? deg + 360.0 : deg;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Ledges.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Ledges.cs
index dce5fc0..0ef74ce 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Ledges.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Ledges.cs
@@ -37,7 +37,7 @@ internal static partial class DungeonPathfinder
// ... at these heights from the opening's lowest vertex (a floor 6 m below a ledge's opening, say).
private static readonly double[] LedgeZRefs = { 0, 3, -3, 6, -6, 12, -12 };
// ... and, for a cell with no floor there, below the opening only.
- private static readonly double[] LedgeDownRefs = { 0, -3, -6, -9, -12, -18 };
+ private static readonly double[] LedgeDownRefs = { 0, -3, -6, -9, -12, -15, -18 };
/// What closing the ledges did in the last dungeon (one line, for the build log), or null.
internal static string? LedgeNote;
@@ -49,20 +49,30 @@ internal static partial class DungeonPathfinder
{
var list = new List();
var seen = new HashSet();
+ double lowest = LowestLook(graph);
foreach (var n in graph.Values)
foreach (uint nb in n.Neighbors)
{
if (!graph.ContainsKey(nb) || !seen.Add(EdgeKey(n.CellId, nb))) continue;
if (!geo.TryGetDoorway(n.CellId, nb, out var d)) continue;
var (nx, ny) = d.NormalFrom(n.CellId); // out of n, into nb
- double? ha = FloorInside(geo, n.CellId, d, -nx, -ny), hb = FloorInside(geo, nb, d, nx, ny);
+ double? ha = FloorInside(geo, n.CellId, d, -nx, -ny, lowest), hb = FloorInside(geo, nb, d, nx, ny, lowest);
if (ha is not { } a || hb is not { } b || Math.Abs(a - b) <= LedgeMeters) continue;
list.Add(a > b ? new DungeonLedge(n.CellId, nb, a - b, d.X, d.Y, d.Z) : new DungeonLedge(nb, n.CellId, b - a, d.X, d.Y, d.Z));
}
return list;
}
- private static double? FloorInside(DungeonGeometry geo, uint cell, DungeonDoorway d, double ux, double uy)
+ /// Under every cell of the graph: as deep as a look for a floor under an opening goes.
+ internal static double LowestLook(Dictionary graph)
+ => graph.Count == 0 ? 0 : graph.Values.Min(n => (double)n.Z) - 2 * JumpDownStep;
+
+ // The floor just inside the opening on the cell's side, its own or (none) any under it, looked for as
+ // deep as `lowest` (NaN: the LedgeDownRefs' 18 m). It went no deeper than 18 m (+1.5) before 2026-11-18:
+ // Thread 0x000A's hall has a 30 x 20 m hole in its middle down to a floor 24 m below, no ledge was seen
+ // round it, and its six floorless cells were walked across ("It tries to navigate over an opening
+ // in the floor which is impossible").
+ private static double? FloorInside(DungeonGeometry geo, uint cell, DungeonDoorway d, double ux, double uy, double lowest = double.NaN)
{
foreach (double inset in LedgeInsets)
{
@@ -75,20 +85,38 @@ internal static partial class DungeonPathfinder
// 0x039B's corridor at -6 opens through 0143 into a round room whose floor, at -12, is its other
// cells'): the floor UNDER that side, whichever cell it is. Only under it: a level above is no
// floor to land on (Tiny Hive's floorless tube cells found the next level's floor 5 m up).
+ // Each height looked at covers LedgeDownBand either side, so together they leave no gap (at
+ // 0.6 m round heights 3 m apart, a floor 9.7 m down was between two: Thread 0x0169's shaft, whose
+ // cave floor slopes from -9 to -12, had two of its eight openings found as no ledge).
foreach (double inset in LedgeInsets)
{
double x = d.X + ux * inset, y = d.Y + uy * inset;
foreach (double dz in LedgeDownRefs)
- if (geo.TryFloorHeight(x, y, d.Z + dz, 0.6, out double h) && h <= d.Z + 0.6) return h;
+ if (geo.TryFloorHeight(x, y, d.Z + dz, LedgeDownBand, out double h) && h <= d.Z + 0.6) return h;
+ }
+ if (double.IsNaN(lowest)) return null;
+ // Nothing within 18 m at any inset: deeper (only then, so the floors found before are found as before).
+ foreach (double inset in LedgeInsets)
+ {
+ double x = d.X + ux * inset, y = d.Y + uy * inset;
+ for (double z = d.Z + LedgeDownRefs[^1] - JumpDownStep; z >= lowest; z -= JumpDownStep)
+ if (geo.TryFloorHeight(x, y, z, LedgeDownBand, out double h) && h <= d.Z + 0.6) return h;
}
return null;
}
+ /// Half the 3 m between two LedgeDownRefs: every height below the opening is looked at.
+ private const double LedgeDownBand = 1.5;
+
///
/// Closes each ledge in (both ways) unless that leaves its two cells with no
/// other way between them; those are returned (the only way on). The graph is changed in place.
+ /// With , a ledge into air is closed even then: when nothing it alone
+ /// leads to has a floor of its own (Thread 0x0169's shaft, four open-air cells over a cave), it
+ /// leads nowhere to walk, and keeping it open had the walks step off into the shaft.
///
- internal static List CloseLedges(Dictionary graph, IReadOnlyList ledges, out int closed)
+ internal static List CloseLedges(Dictionary graph, IReadOnlyList ledges, out int closed,
+ Func? hasFloor = null)
{
closed = 0;
var kept = new List();
@@ -99,6 +127,7 @@ internal static partial class DungeonPathfinder
int loLinks = lo.Neighbors.RemoveAll(c => c == l.High);
if (hiLinks + loLinks == 0) continue;
if (Linked(graph, l.High, l.Low)) { closed++; continue; }
+ if (hasFloor != null && !Walked(graph, l.Low).Any(hasFloor)) { closed++; continue; } // only air beyond it
// The only way between them: put it back.
for (int i = 0; i < Math.Max(1, hiLinks); i++) hi.Neighbors.Add(l.Low);
for (int i = 0; i < Math.Max(1, loLinks); i++) lo.Neighbors.Add(l.High);
@@ -107,6 +136,21 @@ internal static partial class DungeonPathfinder
return kept;
}
+ // Every cell a walk (no drop edges) reaches from a, a included.
+ private static HashSet Walked(Dictionary graph, uint a)
+ {
+ var seen = new HashSet { a };
+ var queue = new Queue();
+ queue.Enqueue(a);
+ while (queue.Count > 0)
+ {
+ if (!graph.TryGetValue(queue.Dequeue(), out var n)) continue;
+ foreach (uint nb in n.Neighbors)
+ if (graph.TryGetValue(nb, out var o) && !IsDropEdge(n, o) && seen.Add(nb)) queue.Enqueue(nb);
+ }
+ return seen;
+ }
+
// a and b joined by a walk (no drop edges).
private static bool Linked(Dictionary graph, uint a, uint b)
{
@@ -132,7 +176,7 @@ internal static partial class DungeonPathfinder
var ledges = FindLedges(graph, geo);
LedgeNoteLandblock = landblockKey;
if (ledges.Count == 0) { LedgeNote = null; return; }
- var kept = CloseLedges(graph, ledges, out int closed);
+ var kept = CloseLedges(graph, ledges, out int closed, geo.HasFloor);
var inv = CultureInfo.InvariantCulture;
LedgeNote = string.Format(inv, "{0} ledge(s) (floors over {1:0.#} m apart across an opening): {2} closed, walked round",
ledges.Count, LedgeMeters, closed)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs
index 64c2cc5..8483eaf 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Portals.cs
@@ -155,16 +155,22 @@ internal static partial class DungeonPathfinder
var closed = PortalClosedOpenings(graph, geo, hazardCells, portals, startCell, startAt, reports);
double splitMs = clock.Elapsed.TotalMilliseconds;
int laid = 0;
+ // The walk-round counts are the last laying's (each round lays the whole walk again).
+ using var holes = CountHoles();
+ int walked0 = HolesWalkedRound, left0 = HolesLeft;
NavRouteParser route;
Dictionary g;
for (int round = 0; ; round++)
{
+ HolesWalkedRound = walked0; HolesLeft = left0;
g = WithoutOpenings(graph, closed, startCell);
route = lay(g);
laid++;
foreach (var r in reports) r.Moved = r.Dropped = r.Bent = 0; // the last laying's
+ var asLaid = geo != null && geo.PlacedCount > 0 ? LegsOf(route.Points, loop) : null;
var unresolved = KeepOutOfPortals(route.Points, closed: loop, g, geo, portals, reports, wall);
+ if (asLaid != null) WalkPortalLegsRoundObjects(route.Points, loop, geo!, portals, asLaid);
if (unresolved.Count == 0 || round >= PortalMaxRounds) break;
// Legs no bend gets round: cut off the cell there (never the start), and lay it again.
@@ -563,6 +569,58 @@ internal static partial class DungeonPathfinder
return unresolved;
}
+ // ── The portal step's legs and the placed objects (2026-11-18) ───────────────
+ // KeepOutOfPortals runs on the finished walk, after EmitSteps walked it round what the cells place. Its bend
+ // corners and moved points keep clear of objects (ClearanceMemo and LegClearance see their walls), but the leg
+ // a dropped point leaves (its neighbours joined) is never looked at, and a bend's legs are judged walkable at
+ // 0.25 m: with an object near the portal, a bent leg could cut into it. Every Thread has its exit portal, so
+ // every Thread patrol and explore takes this step. Each leg the step changed is checked again
+ // (ThroughPlaced) and walked round on the floor; a walk round that would go into a portal's circle is not
+ // taken: the portal keep-out wins (touching a portal takes the character through), and the leg counts in
+ // HolesLeft.
+
+ /// The legs of the walk as laid (by the points' identity), each with its two ends' positions.
+ private static Dictionary<(NavPoint, NavPoint), (double, double, double, double, double, double)> LegsOf(List pts, bool loop)
+ {
+ var legs = new Dictionary<(NavPoint, NavPoint), (double, double, double, double, double, double)>(pts.Count);
+ for (int i = 0; i < pts.Count; i++)
+ {
+ if (i + 1 >= pts.Count && !loop) break;
+ var a = pts[i]; var b = pts[(i + 1) % pts.Count];
+ legs[(a, b)] = (a.EW, a.NS, a.Z, b.EW, b.NS, b.Z);
+ }
+ return legs;
+ }
+
+ ///
+ /// Walks round the placed objects every leg of that is not in
+ /// as it was (a leg KeepOutOfPortals bent, or whose end it moved, or that a dropped point left), keeping every
+ /// new leg out of the portals' circles; a leg with no such way round stays as it is (HolesLeft). Returns how
+ /// many legs were walked round.
+ ///
+ internal static int WalkPortalLegsRoundObjects(List pts, bool loop, DungeonGeometry geo, IReadOnlyList portals,
+ Dictionary<(NavPoint, NavPoint), (double, double, double, double, double, double)> asLaid)
+ {
+ if (geo.PlacedCount == 0 || pts.Count < 2) return 0;
+ int walked = 0;
+ bool Keeps(NavPoint p, NavPoint q) => PortalLegClear(null, portals, p, q);
+ for (int i = 0; i < pts.Count; i++)
+ {
+ if (i + 1 >= pts.Count && !loop) break;
+ var a = pts[i]; var b = pts[(i + 1) % pts.Count];
+ if (asLaid.TryGetValue((a, b), out var was) && was == (a.EW, a.NS, a.Z, b.EW, b.NS, b.Z)) continue;
+ if (!LegMeetsPlaced(geo, X(a), Y(a), a.Z * 240.0, X(b), Y(b), b.Z * 240.0)) continue;
+ var leg = new List { a, b };
+ if (WalkRoundHoles(leg, geo, objectsOnly: true, accept: Keeps) == 0) continue;
+ var corners = leg.GetRange(1, leg.Count - 2);
+ foreach (var c in corners) { Tag(c, "object-round"); NotePortal(c, "round-object-by-portal"); }
+ pts.InsertRange(i + 1, corners);
+ i += corners.Count;
+ walked++;
+ }
+ return walked;
+ }
+
///
/// Where the character at (px, py, pz) walks first when it stands inside a portal's circle: to just
/// past the circle's edge, on walkable floor with some clearance, reached in a straight walk through
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
index 9da6433..eec78a4 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Rooms.cs
@@ -110,6 +110,7 @@ internal static partial class DungeonPathfinder
}
_cachedGeometry = DungeonGeometry.Build(graph, portals, floors, walls);
_geoLandblock = landblockKey;
+ AddPlacedObjectsTo(landblockKey, _cachedGeometry, cellDat);
// Doorways placed objects stand across (a spider web: DungeonPathfinder.Blocked.cs), then ledges
// (DungeonPathfinder.Ledges.cs): closed in the cached graph, so every walk goes round them.
if (ReferenceEquals(graph, _cachedGraph)) { CloseMapBlocksOf(landblockKey, graph, _cachedGeometry); _ledgesClosedOn = graph; }
@@ -340,6 +341,7 @@ internal static partial class DungeonPathfinder
out int doorways,
bool mergeSamePieces = true)
{
+ using var holes = CountHoles();
doorways = 0;
var pts = new List();
if (geo == null)
@@ -396,6 +398,10 @@ internal static partial class DungeonPathfinder
{
if (start != null && dest != null && rooms.RoomOf.TryGetValue(startCell, out int r0))
CrossRoom(pts, graph, geo, rooms, r0, start, startCell, dest, destCell, revisit: false, wall);
+ // One room, start to destination: the walk across it goes round what the cells place too (it went
+ // straight on through: a stuck detour inside the room it stuck in headed back into the table).
+ KeepPointsOutOfObjects(geo, pts, closed: false, wall, graph, rooms);
+ WalkRoundObjectsOf(geo, pts, closed: false, start, dest);
return pts;
}
@@ -446,9 +452,97 @@ internal static partial class DungeonPathfinder
DropCollinear(pts, closed);
KeepLegsOffWalls(geo, pts, closed, wall);
+ // A point laid inside something the cells place goes out of it (or goes) before the legs are walked round.
+ KeepPointsOutOfObjects(geo, pts, closed, wall, graph, rooms);
+ // Round something the cells place (an altar, a statue), not through it, on every walk laid here: the
+ // patrol, the explore, a walk to somewhere, a stuck detour (2026-11-18: Thread 0x000A's walks went
+ // through altars). A corner put in by KeepLegsOffWalls can't get a leg past an object in its middle
+ // (the push out of it goes along the leg); this walks round on the floor. Holes in the floor are
+ // still the explore's own pass (a tube's floorless cells would be walked round to nowhere).
+ WalkRoundObjectsOf(geo, pts, closed, start, dest);
return pts;
}
+ // WalkRoundHoles for placed objects only, the closing leg of a loop included. A walk that ends (a detour, a walk
+ // to somewhere) has its start and destination walked round too, then left off again (the caller has them): its
+ // first and last legs were never looked at, so a stuck detour's first leg headed straight back through the
+ // object it stuck on (0x0190 room 88's table, recovery #8: "stuck on the detour"), and of 648 walks laid past the
+ // objects of nine dungeons, 421 had an end leg through one (2026-11-18, real dats). That covers the stuck
+ // detours, dunroute, BuildingMap's end legs and each stretch of a jump walk (to its approach point).
+ private static void WalkRoundObjectsOf(DungeonGeometry geo, List pts, bool closed, NavPoint? start = null, NavPoint? dest = null)
+ {
+ if (geo.PlacedCount == 0) return;
+ var laid = KindLog != null || PointLog != null ? new HashSet(pts) : null;
+ if (closed)
+ {
+ if (pts.Count < 2) return;
+ pts.Add(pts[0]);
+ WalkRoundHoles(pts, geo, objectsOnly: true);
+ pts.RemoveAt(pts.Count - 1);
+ }
+ else
+ {
+ var walk = new List(pts.Count + 2);
+ if (start != null) walk.Add(start);
+ walk.AddRange(pts);
+ if (dest != null) walk.Add(dest);
+ if (walk.Count < 2 || WalkRoundHoles(walk, geo, objectsOnly: true) == 0) return;
+ // WalkRoundHoles keeps the first and the last point as they are, so the ends come off as they went on.
+ int from = start != null ? 1 : 0, to = walk.Count - (dest != null ? 1 : 0);
+ pts.Clear();
+ for (int i = from; i < to; i++) pts.Add(walk[i]);
+ }
+ if (laid != null)
+ foreach (var p in pts)
+ if (!laid.Contains(p)) Tag(p, "object-round");
+ }
+
+ // How far a point laid inside a placed object may be pushed to get out (a 9 x 9 m statue's middle: 4.5 m).
+ private const double ObjectPushMax = MiddlePushMax;
+
+ ///
+ /// A point laid inside something the cells place (an approach point on a pedestal, a corner the string pull put
+ /// under a table) is moved out of it to the wall distance, at most ObjectPushMax, as RoomMiddle's middle is; one
+ /// no push gets out is dropped (nobody stands there, and the walk round goes from point to point). A loop keeps
+ /// at least three points. With , the push stays on the floor of the point's room
+ /// () or of its cell and the cells next to it: the walk round goes round objects, not
+ /// through walls, so a point must not be pushed through one into the next room. Returns how many points were
+ /// moved or dropped.
+ ///
+ internal static int KeepPointsOutOfObjects(DungeonGeometry geo, List pts, bool closed, double wall = WallClearance,
+ Dictionary? graph = null, DungeonRooms? rooms = null)
+ {
+ if (geo.PlacedCount == 0) return 0;
+ int changed = 0;
+ for (int i = 0; i < pts.Count; i++)
+ {
+ var p = pts[i];
+ if (!NavRouteParser.IsPlainWaypoint(p.Type)) continue;
+ double x = DungeonGeometry.NavToWorld(p.EW), y = DungeonGeometry.NavToWorld(p.NS);
+ if (!geo.TryFloorHeight(x, y, p.Z * 240.0, HoleStartBand, out double h)) continue; // no floor: not the object's to say
+ if (!geo.InsidePlaced(x, y, h)) continue;
+ changed++;
+ IReadOnlyCollection? cells = null;
+ if (graph != null)
+ {
+ uint cell = CellAt(graph, geo, p);
+ if (rooms != null && rooms.RoomOf.ContainsKey(cell)) cells = RoomCells(rooms, cell);
+ else if (graph.TryGetValue(cell, out var node)) cells = new List(node.Neighbors) { cell };
+ }
+ geo.PushClear(ref x, ref y, h, wall, ObjectPushMax, cells);
+ if (!geo.InsidePlaced(x, y, h) && geo.OnWalkableFloor(x, y, h))
+ {
+ p.EW = DungeonGeometry.WorldToNav(x);
+ p.NS = DungeonGeometry.WorldToNav(y);
+ if (PointLog != null) Info(p).Why += Info(p).Why.Length > 0 ? ",out-of-object" : "out-of-object";
+ continue;
+ }
+ if (closed && pts.Count <= 3) continue;
+ pts.RemoveAt(i--);
+ }
+ return changed;
+ }
+
// A leg brushing a wall: its least clearance (away from its end points) under this, or under
// its end points' own when they are tighter (a narrow opening's centre).
private const double LegMinClearance = 0.6;
@@ -633,11 +727,15 @@ internal static partial class DungeonPathfinder
if (i == j)
{
if (!DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, wall, out approach, out exit, out narrow)) narrow = false;
+ OutOfPlaced(geo, rooms, approach, steps[i].From, steps[i].From, steps[i].To);
+ OutOfPlaced(geo, rooms, exit, steps[i].To, steps[i].From, steps[i].To);
return;
}
DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, wall, out approach, out _, out bool n0);
DoorwayPoints(graph, geo, rooms, steps[j].From, steps[j].To, wall, out _, out exit, out bool n1);
+ OutOfPlaced(geo, rooms, approach, steps[i].From, steps[i].From, steps[i].To);
+ OutOfPlaced(geo, rooms, exit, steps[j].To, steps[j].From, steps[j].To);
narrow = n0 || n1;
var doors = new List<(DungeonDoorway Door, uint From, int Step)>();
for (int k = i; k <= j; k++)
@@ -674,6 +772,84 @@ internal static partial class DungeonPathfinder
if (narrow) { approach.Doorway = true; exit.Doorway = true; }
}
+ // A doorway point inside something placed (2026-11-18: in buildings, beside a chair, a table or a bed, 20 of
+ // the survey's walk corners were) is slid along the doorway's normal, the nearest first, to where it is on the
+ // room's floor and in nothing; with no such spot, onto the opening's centre. The legs from it are then walked
+ // round what it was in (EmitSteps), which a point inside one never could be.
+ private const double OutOfPlacedStep = 0.25, OutOfPlacedSlide = 3.0, OutOfPlacedNearest = 0.5, FallbackFloorBand = 2.0;
+
+ private static void OutOfPlaced(DungeonGeometry geo, DungeonRooms rooms, NavPoint p, uint cell, uint a, uint b)
+ {
+ if (geo.PlacedCount == 0) return;
+ double x = DungeonGeometry.NavToWorld(p.EW), y = DungeonGeometry.NavToWorld(p.NS), z = p.Z * 240.0;
+ if (!InsidePlacedAt(geo, x, y, z)) return;
+ if (!geo.TryGetDoorway(a, b, out var d))
+ {
+ // No opening known (a cell-centre fallback point, which may lie between the two rooms). Its height is the
+ // two cells' centres' between, not a floor's (E74E#0: 32.6 over 0103's floor at 34.0, under the 0.45 m dais
+ // 02000117 there): first the floor under it within FallbackFloorBand; in nothing there, it is only
+ // put on that floor. Else the nearest spot round it, on any floor, that is in nothing.
+ if (geo.TryFloorHeight(x, y, z, FallbackFloorBand, out double fh) && Math.Abs(fh - z) > 1.0)
+ {
+ z = fh;
+ if (!geo.InsidePlaced(x, y, fh)) { p.Z = fh / 240.0; return; }
+ }
+ if (NearestOutOfPlaced(geo, ref x, ref y, z, OutOfPlacedSlide))
+ {
+ p.EW = DungeonGeometry.WorldToNav(x);
+ p.NS = DungeonGeometry.WorldToNav(y);
+ p.Z = z / 240.0;
+ }
+ return;
+ }
+ // Along the normal, on the point's own side of the opening, no nearer to it than OutOfPlacedNearest.
+ var (nx, ny) = d.NormalFrom(a);
+ double side = (x - d.X) * nx + (y - d.Y) * ny < 0 ? -1 : 1;
+ var cells = RoomCells(rooms, cell);
+ for (double s = OutOfPlacedStep; s <= OutOfPlacedSlide + 1e-9; s += OutOfPlacedStep)
+ foreach (double sign in new[] { 1.0, -1.0 })
+ {
+ double qx = x + nx * s * sign, qy = y + ny * s * sign;
+ if (((qx - d.X) * nx + (qy - d.Y) * ny) * side < OutOfPlacedNearest) continue;
+ if (!geo.OnFloorOfAny(cells, qx, qy, z) || InsidePlacedAt(geo, qx, qy, z)) continue;
+ if (geo.ClearanceMemo(qx, qy, z, 0.6) <= 0.05) continue; // in or against a wall
+ p.EW = DungeonGeometry.WorldToNav(qx);
+ p.NS = DungeonGeometry.WorldToNav(qy);
+ return;
+ }
+ if (InsidePlacedAt(geo, d.X, d.Y, d.Z)) return;
+ p.EW = DungeonGeometry.WorldToNav(d.X);
+ p.NS = DungeonGeometry.WorldToNav(d.Y);
+ p.Z = d.Z / 240.0;
+ }
+
+ /// Inside something placed, for a walker on the floor at (or within a metre of) z.
+ internal static bool InsidePlacedAt(DungeonGeometry geo, double x, double y, double z)
+ => geo.InsidePlaced(x, y, geo.TryFloorHeight(x, y, z, 1.0, out double h) ? h : z);
+
+ ///
+ /// Moves (x, y), inside something placed, to the nearest spot round it (rings 0.25 m apart out to
+ /// , 16 ways; on a ring the clearest) that is on the floor (of when
+ /// given), in nothing, and not against a wall. False (and the point left) when there is none.
+ ///
+ internal static bool NearestOutOfPlaced(DungeonGeometry geo, ref double x, ref double y, double z, double maxR, IReadOnlyCollection? cells = null)
+ {
+ for (double r = OutOfPlacedStep; r <= maxR + 1e-9; r += OutOfPlacedStep)
+ {
+ double bestC = 0.05, bx = 0, by = 0;
+ for (int k = 0; k < 16; k++)
+ {
+ double a = k * Math.PI / 8, qx = x + Math.Cos(a) * r, qy = y + Math.Sin(a) * r;
+ if (cells != null ? !geo.OnFloorOfAny(cells, qx, qy, z) : !geo.OnWalkableFloor(qx, qy, z)) continue;
+ if (InsidePlacedAt(geo, qx, qy, z)) continue;
+ double c = geo.ClearanceMemo(qx, qy, geo.TryFloorHeight(qx, qy, z, 1.0, out double h) ? h : z, 1.0);
+ if (c > bestC) { bestC = c; bx = qx; by = qy; }
+ }
+ if (bestC > 0.05) { x = bx; y = by; return true; }
+ }
+ return false;
+ }
+
// ── Doorway points ───────────────────────────────────────────────────────
///
@@ -922,6 +1098,9 @@ internal static partial class DungeonPathfinder
: Tag(WorldPoint(DungeonGeometry.NavToWorld(nearest.EW), DungeonGeometry.NavToWorld(nearest.NS), nearest.Z, false), "room-middle-cell");
// A one-cell dead end's origin is inside its end cap; a big room's middle can be a pillar.
PushOffWalls(geo, mid, cells, MiddlePushMax, wall);
+ // Still inside something the cells place (Thread 0x00C1 room 81: a 9 x 9 m statue fills the middle,
+ // the explore stuck at its side): no middle to go to. A statue that big is seen past anyway.
+ if (geo.InsidePlaced(DungeonGeometry.NavToWorld(mid.EW), DungeonGeometry.NavToWorld(mid.NS), mid.Z * 240.0)) return null;
return mid;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Straighten.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Straighten.cs
index 22280b2..a4bfeb2 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Straighten.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Straighten.cs
@@ -11,7 +11,14 @@
// - on walkable floor, keeping the walk's wall clearance, or at least as much as the legs it
// replaces had (LegClearance: a floor edge counts as a wall, so never over a ledge or a pit), and
// - passing through the room of every point it skips (the explore must still walk into each room
-// it was laid through).
+// it was laid through), and
+// - staying on the floor all the way, a step at a time (OnFloorAll, as the hole rule judges a leg).
+// 2026-11-17, a DreamWeave Thread in 0x0278: a ramp climbs south from a room at -36 to a corridor
+// at -30 that runs back north over that room. The walk went up the ramp and back along the
+// corridor; seen from above every point of that U-turn lies on one line, so one straight leg north
+// "passed through" all their rooms, and its samples kept their clearance (none fell in the 7 m with
+// no floor between the room's end and the corridor). The character ran north along the bottom
+// into the room's end wall and stuck there ("running into a wall in a place that makes no sense").
// Only plain waypoints are skipped, and never one in keepPoints: the middles of the rooms the explore walks
// into (2026-11-16, enter and scan). A look into a dead end, in and out by one doorway, passes "through" the
// room at its doorway: Thread 0x00B5's boss room lost its middle here and was only touched at the door.
@@ -85,6 +92,7 @@ internal static partial class DungeonPathfinder
double needClear, double wall)
{
if (LegLeast(geo, pts[i], pts[j], wall, out _, out _, out _) < needClear - 0.01) return false;
+ if (!LegOnFloor(geo, pts[i], pts[j])) return false;
var must = new HashSet();
for (int k = i; k < j; k++) must.UnionWith(legRooms[k]);
for (int k = i + 1; k < j; k++)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
index 4ca5bf3..6413780 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.cs
@@ -365,6 +365,7 @@ internal static partial class DungeonPathfinder
DungeonGeometry? geo = null, IReadOnlySet? hazardCells = null,
double startNS = double.NaN, double startEW = double.NaN, double startZ = 0, double destZ = 0)
{
+ using var holes = CountHoles();
var route = new NavRouteParser { RouteType = NavRouteType.Once };
// With the dungeon map geometry: straight on through doorways, straight across rooms.
@@ -854,6 +855,25 @@ internal static partial class DungeonPathfinder
DungeonPatrolOptions? options = null,
IReadOnlyList? portals = null,
(double X, double Y, double Z)? startAt = null)
+ {
+ // One build: every walk round of it counts (HolesWalkedRound / HolesLeft), and the patrol's notes say so.
+ using var holes = CountHoles();
+ bool outermost = _holeCountDepth == 1;
+ var route = BuildPatrolRouteCore(graph, startCell, hazardCells, geo, options, portals, startAt);
+ if (outermost && PointLog != null && (HolesWalkedRound > 0 || HolesLeft > 0))
+ MainRouteNote = (MainRouteNote == null ? "" : MainRouteNote + "; ")
+ + $"objects and holes: {HolesWalkedRound} leg(s) walked round" + (HolesLeft > 0 ? $", {HolesLeft} with no way round" : "");
+ return route;
+ }
+
+ private static NavRouteParser BuildPatrolRouteCore(
+ Dictionary graph,
+ uint startCell,
+ IReadOnlySet? hazardCells,
+ DungeonGeometry? geo,
+ DungeonPatrolOptions? options,
+ IReadOnlyList? portals,
+ (double X, double Y, double Z)? startAt)
{
LastPortalAvoidance = null;
var o = (options ?? DungeonPatrolOptions.Default).Clamped();
@@ -959,11 +979,95 @@ internal static partial class DungeonPathfinder
// The map geometry is there but the room patrol found nothing to walk (the start is cut
// off from every doorway): the cell walk's points still keep off the walls.
if (geo != null)
+ {
foreach (var p in route.Points)
PushOffWalls(geo, Tag(p, "cell-walk"), null, CornerPushMax, o.WallClearance);
+ // And round what the cells place, as the room patrol's walks are (EmitSteps): with the loader's posts,
+ // pillars and spheres on the map (2026-11-18), Thread 0x0169's cell walk went through 20 of them, every
+ // one with a way round on the floor. A cell's centre under one (a pillar in the middle of a room) goes
+ // out of it first: the walk round goes from point to point.
+ KeepPointsOutOfObjects(geo, route.Points, closed: true, o.WallClearance, graph);
+ WalkRoundObjectsOf(geo, route.Points, closed: true);
+ }
return route;
}
+ ///
+ /// The straight walk a-b at a body's height on the dungeon map: on the floor all the way (LegOnFloor, the hole
+ /// rule's test, which also stops at a placed object on the floor it follows) and through nothing the cells place
+ /// (ThroughPlaced). A sight line at eye height doesn't say that: one that raises the eye 1.2 m and looks from
+ /// 1.45 m up, so a 1 m altar or a 0.9 m table (0x0190's 0x020002FB) never blocked it, and the line of sight to a
+ /// later waypoint skipped the corners laid round one (2026-11-18). The patrol's first
+ /// waypoint go by it. An end up on something placed is judged from where the leg leaves it; an end the map can't
+ /// place clear of what is there leaves the walk to the sight line (true).
+ ///
+ internal static bool StraightWalkClear(DungeonGeometry geo, NavPoint a, NavPoint b)
+ {
+ if (geo.PlacedCount > 0 && !(FromWhereItStands(geo, ref a, b) && FromWhereItStands(geo, ref b, a))) return true;
+ return LegOnFloor(geo, a, b) && !LegMeetsPlaced(geo, X(a), Y(a), a.Z * 240.0, X(b), Y(b), b.Z * 240.0);
+ }
+
+ // One end of the walk test. The leg tests measure from the map's floor under a point, so a character standing on a
+ // dais, half way up a ramp or on a platform read as inside it, and every leg failed at its first sample: a patrol
+ // started from there went for waypoint 0, across the room behind a pillar maybe (the "runs into a wall on login" the
+ // first-waypoint pick is there for) (review of wf/obst-int). An end up
+ // on something placed (DungeonGeometry.OnTopOfPlaced) is moved along the leg to where it leaves what is under it: that
+ // stretch is the walk across its top. False, the walk not judged, for an end inside something at its own height too
+ // (wedged against it where the footprint is a little big), or a leg that never leaves what it stands on.
+ private static bool FromWhereItStands(DungeonGeometry geo, ref NavPoint end, NavPoint other)
+ {
+ double ex = X(end), ey = Y(end), ez = end.Z * 240.0;
+ if (!geo.TryFloorHeight(ex, ey, ez, HoleStartBand, out double zf)) zf = ez;
+ if (!geo.InsidePlaced(ex, ey, zf)) return true;
+ if (!geo.OnTopOfPlaced(ex, ey, ez, zf)) return false;
+ double ox = X(other), oy = Y(other), oz = other.Z * 240.0;
+ double dx = ox - ex, dy = oy - ey, len = Math.Sqrt(dx * dx + dy * dy);
+ int n = (int)Math.Ceiling(len / PlacedFineStep);
+ for (int s = 1; s <= n; s++)
+ {
+ double t = (double)s / n, x = ex + dx * t, y = ey + dy * t;
+ if (geo.TryFloorHeight(x, y, zf, HoleStep, out double h) || geo.TryFloorHeight(x, y, ez + (oz - ez) * t, HoleStep, out h)) zf = h;
+ if (geo.InsidePlaced(x, y, zf)) continue;
+ end = new NavPoint { Type = NavPointType.Point, EW = DungeonGeometry.WorldToNav(x), NS = DungeonGeometry.WorldToNav(y), Z = zf / 240.0 };
+ return true;
+ }
+ return false;
+ }
+
+ /// The straight walk a-b goes through something the cells place, on the floor it follows: ThroughPlaced,
+ /// or a crossing between its samples (CrossesPlaced).
+ internal static bool LegMeetsPlaced(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
+ => ThroughPlaced(geo, ax, ay, az, bx, by, bz) || CrossesPlaced(geo, ax, ay, az, bx, by, bz);
+
+ // ThroughPlaced looks every 0.5 m, and a rail (0x020003B3 is 0.13 m across), a post or a narrow end of a bench fits
+ // between two looks: a leg across one was taken as clear and went on as laid. This looks at the solid models' own
+ // spacing (0.1 m); the floor is found every HoleSample as ThroughPlaced finds it, the looks between at the last
+ // floor found. Samples with no floor are left out as there.
+ private const double PlacedFineStep = 0.1;
+
+ internal static bool CrossesPlaced(DungeonGeometry geo, double ax, double ay, double az, double bx, double by, double bz)
+ {
+ if (geo.PlacedCount == 0) return false;
+ double dx = bx - ax, dy = by - ay, len = Math.Sqrt(dx * dx + dy * dy);
+ if (len < 2 * PlacedFineStep) return false;
+ if (!geo.TryFloorHeight(ax, ay, az, HoleStartBand, out double zf)) zf = az;
+ int n = (int)Math.Ceiling(len / PlacedFineStep);
+ bool floor = true;
+ double nextFloorAt = 0;
+ for (int s = 1; s < n; s++)
+ {
+ double t = (double)s / n, d = t * len, x = ax + dx * t, y = ay + dy * t;
+ if (d >= nextFloorAt)
+ {
+ floor = geo.TryFloorHeight(x, y, zf, HoleStep, out double h) || geo.TryFloorHeight(x, y, az + (bz - az) * t, HoleStep, out h);
+ if (floor) zf = h;
+ nextFloorAt = d + HoleSample;
+ }
+ if (floor && geo.InsidePlaced(x, y, zf)) return true;
+ }
+ return false;
+ }
+
// Canonical undirected-edge key (order-independent).
private static ulong EdgeKey(uint a, uint b)
=> a < b ? ((ulong)a << 32) | b : ((ulong)b << 32) | a;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs
index 3626d83..eeae983 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/GroundLootController.cs
@@ -214,6 +214,7 @@ public sealed partial class RynthAiPlugin
if (!_objectCache.IsOnGround(id) && _objectCache.GetContainerId(id) != 0)
{
LootDiag($"[RynthAi] Ground loot: pickup confirmed for 0x{(uint)id:X8} '{_groundTargetName}'.");
+ NotePerDayPickedUp(id); // Keep # per day: it counts now
if (DescribeLootPickup(id, _groundTargetAction, _groundTargetName, _groundTargetRule,
_groundTargetIsSalvage, IsStackAtSend(id), where: "ground") is { } described)
WriteItemInfoLine(described.Line, described.ChatType);
@@ -284,6 +285,7 @@ public sealed partial class RynthAiPlugin
: Host.UseObject(uid);
_groundPickupAttempts++;
_groundPickupRequestedAt = now;
+ if (sent) NotePerDaySent(unchecked((int)uid)); // Keep # per day: on its way
LootDiag($"[RynthAi] Ground loot: pickup {(sent ? "sent" : "rejected")} for 0x{uid:X8} attempt {_groundPickupAttempts}.");
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs
index c5486f5..f093f66 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/HudState.cs
@@ -39,6 +39,8 @@ public sealed class HudState
/// Pet row: the summon that is out (health, time left), else the next combat essence.
public bool MiniShowPet = true;
public bool MiniShowGems = true;
+ /// Loot row: the loot profile in use, a dropdown of LootProfiles that switches it.
+ public bool MiniShowLootProfile = true;
public bool MiniShowToggles = true;
/// Obsolete since 2026-10-20 (kept so huds.json loads): the Bank section's switch is RynthILT's (copied once).
public bool MiniShowBank = true;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs
index c5d5420..9855d98 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs
@@ -21,6 +21,8 @@
// Target the creature combat is attacking: name, health bar, distance
// Pet the summon that is out (health bar, time left), else (while a server plugin is active)
// the next combat essence and whether it is ready
+// Loot the loot profile in use, a dropdown of LootProfiles that switches it (the dashboard
+// pickers' list and path; chat says which profile is in use)
// Slots 5 × 6 quick-use item grid; click uses the item (an empty slot takes the selected
// pack item), right-click assigns / clears, and items dragged from the game's
// inventory or the RynthCore Inventory window drop straight into a slot. Ctrl+wheel
@@ -309,7 +311,7 @@ internal sealed class MiniRemoteHud
if (!s.MiniRemoteHorizontal) return colW;
int cols = 0;
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet) cols++;
- if (s.MiniShowGems || ShowToggles(s)) cols++;
+ if (s.MiniShowGems || s.MiniShowLootProfile || ShowToggles(s)) cols++;
if (s.MiniShowRebuff || s.MiniShowTranslate || _serverEconomyDrawn) cols++;
cols = Math.Max(1, cols);
return cols * colW + (cols - 1) * ImGui.GetStyle().ItemSpacing.X;
@@ -390,7 +392,7 @@ internal sealed class MiniRemoteHud
RenderStatusSections(s, remote);
ImGui.EndChild();
}
- if (s.MiniShowGems || ShowToggles(s))
+ if (s.MiniShowGems || s.MiniShowLootProfile || ShowToggles(s))
{
BeginColumn("##mrcolactions", colW);
RenderActionSections(s);
@@ -445,6 +447,7 @@ internal sealed class MiniRemoteHud
private void RenderActionSections(HudState s)
{
+ if (s.MiniShowLootProfile) RenderLootProfile(s);
if (s.MiniShowGems) RenderSlots(s);
if (ShowToggles(s)) RenderToggles(_hud.Dashboard.Settings);
}
@@ -784,11 +787,47 @@ internal sealed class MiniRemoteHud
ImGui.EndPopup();
}
+ // The Loot row's list while its dropdown is open (a copy of the dashboard's, taken each frame it shows).
+ private string[] _lootList = Array.Empty();
+
+ ///
+ /// The Loot row: the loot profile in use, and a dropdown of LootProfiles (*.utl, *.json; the
+ /// dashboard's list, which follows the folder within 3 s). A pick switches it on the pump thread
+ /// through the dashboard pickers' own path (SelectProfileAtIndex), which saves it and says so in chat.
+ ///
+ private void RenderLootProfile(HudState s)
+ {
+ var dash = _hud.Dashboard;
+ string shown = Loot.LootProfileList.ShownName(dash.Settings.CurrentLootPath);
+ SafeImGui.TextColored(ColLabel, "Loot:");
+ float labelW = ImGui.GetItemRectSize().X + ImGui.GetStyle().ItemSpacing.X;
+ ImGui.SameLine();
+ // A fixed width (the column's), so the auto-resizing window can't grow from it.
+ ImGui.SetNextItemWidth(Math.Max(80f, ColumnWidth(s) - labelW));
+ bool open = ImGui.BeginCombo("##mrloot", shown, ImGuiComboFlags.HeightLarge);
+ if (!open && ImGui.IsItemHovered())
+ SafeImGui.SetTooltip("The loot profile in use: " + shown + "\nPick another to switch to it (chat says so).\n" +
+ "Lists RynthAi\\LootProfiles; a file copied in shows within a few seconds.");
+ if (!open) return;
+ _lootList = dash.LootProfileNames();
+ for (int i = 0; i < _lootList.Length; i++)
+ {
+ string name = _lootList[i];
+ bool selected = string.Equals(name, shown, StringComparison.OrdinalIgnoreCase);
+ ImGui.PushID(i);
+ if (ImGui.Selectable(name, selected))
+ _hud.Post(() => dash.SelectLootProfileByName(name));
+ if (selected) ImGui.SetItemDefaultFocus();
+ ImGui.PopID();
+ }
+ ImGui.EndCombo();
+ }
+
private void RenderToggles(LegacyUiSettings settings)
{
var dash = _hud.Dashboard;
if (!ImGui.BeginTable("##mrtoggles", 3, ImGuiTableFlags.SizingStretchSame)) return;
- Toggle("Macro", settings.IsMacroRunning, _ => dash.TogglePanelMacro());
+ Toggle("Macro", settings.IsMacroRunning, _ => dash.TogglePanelMacro("the Mini Remote's Macro toggle"));
Toggle("Combat", settings.EnableCombat, on => dash.SetSubsystemEnabled(0, on));
Toggle("Buff", settings.EnableBuffing, on => dash.SetSubsystemEnabled(1, on));
Toggle("Nav", settings.EnableNavigation, on => dash.SetSubsystemEnabled(2, on));
@@ -836,6 +875,8 @@ internal sealed class MiniRemoteHud
Flag("Session stats", ref s.MiniShowStats);
Flag("Attack target", ref s.MiniShowTarget);
Flag("Pet / summon", ref s.MiniShowPet);
+ Flag("Loot profile", ref s.MiniShowLootProfile);
+ if (ImGui.IsItemHovered()) ImGui.SetTooltip("A Loot row: the loot profile in use, and a dropdown to switch it.");
Flag("Item slots", ref s.MiniShowGems);
// The drawer's dashboard has these switches already; the setting is for the windows.
if (!InDrawer) Flag("Toggles", ref s.MiniShowToggles);
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
index 4ccddd1..121b65d 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
@@ -813,13 +813,16 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetTooltip("Which monster to attack, among those of the highest priority inside Monster Range.\nLeast turning: the one needing the smallest turn to face. Unknown health counts as full.");
ImGui.Checkbox("Target Lock", ref _settings.TargetLock);
if (ImGui.IsItemHovered())
- ImGui.SetTooltip("On: keeps the target it picked until it dies or leaves Monster Range, even when a higher-priority monster shows up.\nOff: a higher-priority monster in range takes over at once, and it switches whenever another monster is clearly better by the Targeting rule.");
+ ImGui.SetTooltip("On: keeps the target it picked until it dies or leaves Monster Range, even when a higher-priority monster shows up.\nWith Targeting on Closest, a monster that reaches you (within 5 yd) takes over from a target more than 6.5 m off.\nOff: a higher-priority monster in range takes over at once, and it switches whenever another monster is clearly better by the Targeting rule.");
ImGui.Checkbox("Fight the monster I select", ref _settings.FightSelectedTarget);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(LegacyUiSettings.FightSelectedTargetTip);
ImGui.Checkbox("Melee through walls", ref _settings.MeleeThroughWalls);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(LegacyUiSettings.MeleeThroughWallsTip);
+ ImGui.Checkbox("Debuff every monster in range before attacking", ref _settings.DebuffAllBeforeAttacking);
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip(LegacyUiSettings.DebuffAllBeforeAttackingTip);
ImGui.Spacing();
ImGui.Text("Corpse Acquisition (Yards)");
@@ -1115,22 +1118,22 @@ internal sealed class LegacyAdvancedSettingsUi
break;
case "Looting":
- ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting);
- // The loot profile picker (the dashboard's LOOT list), and beside it Loot Mode, which
- // decides whether that profile is used at all.
+ // The loot profile picker first (the dashboard's LOOT list, the same switch), then Loot
+ // Mode, which decides whether that profile is used at all.
string[]? lootFiles = LootProfiles?.Invoke();
if (lootFiles != null && lootFiles.Length > 0 && SelectLootProfile != null)
{
int lootIdx = Math.Clamp(_settings.LootProfileIdx, 0, lootFiles.Length - 1);
- ImGui.SetNextItemWidth(200);
+ ImGui.SetNextItemWidth(240);
if (ImGui.Combo("Loot Profile", ref lootIdx, lootFiles, lootFiles.Length) && lootIdx != _settings.LootProfileIdx)
SelectLootProfile(lootIdx);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(Loot.LootModes.IsRares(_settings.LootMode)
? "The loot profile. Not used while Loot Mode is Rares and needed mana stones only."
- : "The loot profile: what corpses, chests and ground items give up.");
- ImGui.SameLine();
+ : "The loot profile: what corpses, chests and ground items give up.\n" +
+ "The same list as the dashboard's Loaded files (LOOT) and the Mini Remote's Loot row.");
}
+ ImGui.Checkbox("Enable Looting", ref _settings.EnableLooting);
_settings.LootMode = Loot.LootModes.Clamp(_settings.LootMode);
ImGui.SetNextItemWidth(240);
ImGui.Combo("Loot Mode", ref _settings.LootMode, Loot.LootModes.Labels, Loot.LootModes.Labels.Length);
@@ -1141,7 +1144,12 @@ internal sealed class LegacyAdvancedSettingsUi
"nothing else (no salvage, no Learn Unknown Spells, no Mana Tap). Recover My Corpse still works.\n" +
"Also /ra loot mode profile|rares, and the meta setting LootMode (0 or 1).");
ImGui.Checkbox("Boost Loot Priority", ref _settings.BoostLootPriority);
- // "Loot Only Rare Corpses" is hidden: nothing reads LootOnlyRareCorpses.
+ ImGui.Checkbox("Loot Only Rare Corpses", ref _settings.LootOnlyRareCorpses);
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip("Only a corpse that generated a rare is opened (its description says \"This corpse\n" +
+ "generated a rare item!\"); every other corpse is left closed, for rare farming.\n" +
+ "With Loot Mode \"Rares and needed mana stones only\" the rare is all it takes.\n" +
+ "Your own corpse (Recover My Corpse) is always recovered.");
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.");
@@ -1155,7 +1163,8 @@ internal sealed class LegacyAdvancedSettingsUi
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When the pickup is done the chest stays open and chat says what was taken,\n" +
"so you can check it and take anything your profile missed. Untick it and\n" +
- "RynthAi closes the chest when it's done (some chests lock again on close).");
+ "RynthAi closes the chest when it's done (some chests lock again on close).\n" +
+ "A chest it took nothing from is always left open.");
ImGui.Unindent();
}
ImGui.Checkbox("Loot Nearby Chests", ref _settings.LootNearbyChests);
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
index ca49c17..f652de4 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
@@ -454,7 +454,7 @@ internal sealed partial class LegacyDashboardRenderer
_settings.SelectedProfile = activeProfile;
ApplyUiStateFromSettings();
- _settings.IsMacroRunning = _settings.StartMacroOnLogin;
+ _settings.SetMacroRunning(_settings.StartMacroOnLogin, "Start Macro On Login (profile load)");
_settings.CurrentState = "Default";
_settings.BotAction = "Default";
@@ -542,7 +542,7 @@ internal sealed partial class LegacyDashboardRenderer
_charFolder = string.Empty;
_settingsFilePath = string.Empty;
_lastSavedJson = string.Empty;
- _settings.IsMacroRunning = false;
+ _settings.SetMacroRunning(false, "the character session ending (logout or character change)");
_settings.CurrentState = "Default";
_settings.BotAction = "Default";
}
@@ -1427,6 +1427,7 @@ internal sealed partial class LegacyDashboardRenderer
TargetLock = s.TargetLock,
FightSelectedTarget = s.FightSelectedTarget,
MeleeThroughWalls = s.MeleeThroughWalls,
+ DebuffAllBeforeAttacking = s.DebuffAllBeforeAttacking,
RingRange = s.RingRange,
ApproachRange = s.ApproachRange,
CorpseApproachRangeMax = s.CorpseApproachRangeMax,
@@ -1721,6 +1722,7 @@ internal sealed partial class LegacyDashboardRenderer
if (p.TargetLock is bool targetLock) s.TargetLock = targetLock; // absent = unchanged
if (p.FightSelectedTarget is bool fightSel) s.FightSelectedTarget = fightSel; // absent = unchanged
if (p.MeleeThroughWalls is bool meleeWalls) s.MeleeThroughWalls = meleeWalls; // absent = unchanged
+ if (p.DebuffAllBeforeAttacking is bool debuffAll) s.DebuffAllBeforeAttacking = debuffAll; // absent = unchanged
s.RingRange = p.RingRange;
s.ApproachRange = p.ApproachRange;
s.CorpseApproachRangeMax = p.CorpseApproachRangeMax;
@@ -2183,6 +2185,9 @@ internal sealed partial class LegacyDashboardRenderer
dst.UnboxAetheriaWhenIdle = tmp.UnboxAetheriaWhenIdle;
dst.AutoConfirmCraft = tmp.AutoConfirmCraft;
dst.AutoConfirmCraftPercent = tmp.AutoConfirmCraftPercent;
+ dst.MakeKitsWhenLow = tmp.MakeKitsWhenLow;
+ dst.MakeKitsBelow = Math.Clamp(tmp.MakeKitsBelow, 1, MiniRemote.Crafting.KitAuto.MaxBelow);
+ dst.MakeKitsUpTo = Math.Clamp(tmp.MakeKitsUpTo, 1, MiniRemote.Crafting.KitAuto.MaxUpTo);
dst.EnableCombineSalvage = tmp.EnableCombineSalvage;
dst.CombineBagsDuringSalvage = tmp.CombineBagsDuringSalvage;
dst.SalvageWithoutPanel = tmp.SalvageWithoutPanel;
@@ -2257,6 +2262,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.TargetLock = tmp.TargetLock;
dst.FightSelectedTarget = tmp.FightSelectedTarget;
dst.MeleeThroughWalls = tmp.MeleeThroughWalls;
+ dst.DebuffAllBeforeAttacking = tmp.DebuffAllBeforeAttacking;
dst.RingRange = tmp.RingRange;
dst.HandlerRingEvade = tmp.HandlerRingEvade; // obsolete (RynthILT's now): carried so the profile keeps it for RynthILT's one-time import
dst.ApproachRange = tmp.ApproachRange;
@@ -2275,6 +2281,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.CustomPetRange = tmp.CustomPetRange;
dst.PetMinMonsters = tmp.PetMinMonsters;
dst.PetAutoRefill = tmp.PetAutoRefill;
+ dst.PetElement = tmp.PetElement ?? string.Empty; // read through PetChoice.NormalizeElement
dst.AdvancedOptions = tmp.AdvancedOptions;
dst.MineOnly = tmp.MineOnly;
dst.ShowEditor = tmp.ShowEditor;
@@ -2791,14 +2798,15 @@ internal sealed partial class LegacyDashboardRenderer
private void RefreshNavFiles()
{
+ // The top of NavProfiles, then its subfolders as "Folder\Name" (NavFileList, 2026-11-22:
+ // VirindiTank navs dropped in as a folder never showed).
var list = new List { "None" };
int sel = 0;
- if (Directory.Exists(_navFolder))
- foreach (string file in Directory.GetFiles(_navFolder, "*.nav"))
- {
- list.Add(Path.GetFileNameWithoutExtension(file));
- if (file.Equals(_settings.CurrentNavPath, StringComparison.OrdinalIgnoreCase)) sel = list.Count - 1;
- }
+ foreach (string name in NavFileList.List(_navFolder))
+ {
+ list.Add(name);
+ if (Path.Combine(_navFolder, name + ".nav").Equals(_settings.CurrentNavPath, StringComparison.OrdinalIgnoreCase)) sel = list.Count - 1;
+ }
lock (_profileListsLock) { _navFiles.Clear(); _navFiles.AddRange(list); }
_selectedNavIdx = sel;
}
@@ -2806,6 +2814,85 @@ internal sealed partial class LegacyDashboardRenderer
private DateTime _navFolderStamp, _lootFolderStamp, _metaFolderStamp, _profileFolderStamp;
private long _nextNavFolderCheckMs;
+ // ── VirindiTank navs in the wrong folder (StrayNavs) ──────────────────
+ // Null-safe where read: the host tests build the dashboard without its constructor.
+ private List? _strayNavs = new();
+ private string? _strayNavText = string.Empty;
+ private DateTime _strayStamp;
+ private bool _strayLooked;
+ private int _strayNoticeCount; // how many the last chat line was about (a new one only for more)
+ private string? _strayChatPending = string.Empty;
+ private List? _strayFolders;
+
+ /// The folders the stray-nav check looks in (the host tests point it at scratch folders).
+ internal List StrayFolders { set => _strayFolders = value; }
+
+ private static List StrayCandidateFolders() => StrayNavs.CandidateFolders(
+ RynthCore.Install.RynthInstallPaths.CoreDir,
+ RynthCore.Install.RynthInstallPaths.SuiteDir,
+ RynthCore.Install.RynthInstallPaths.RynthAiDir,
+ Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA"),
+ Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthnav.json"));
+
+ ///
+ /// Looks again for VirindiTank navs outside NavProfiles when one of the folders worth a look
+ /// changed (or the first time). Sets the Nav panel's line and queues one chat line when there
+ /// are more than the last line was about. Plugin tick, from .
+ ///
+ private void RefreshStrayNavs(DateTime navStamp, bool force = false)
+ {
+ try
+ {
+ List folders = _strayFolders ??= StrayCandidateFolders(); // once a session
+ DateTime stamp = navStamp; // a nav copied into NavProfiles settles one too
+ foreach (string f in folders)
+ {
+ try { DateTime t = Directory.GetLastWriteTimeUtc(f); if (t > stamp) stamp = t; } // a missing folder: 1601
+ catch { }
+ }
+ if (!force && _strayLooked && stamp == _strayStamp) return;
+ _strayLooked = true;
+ _strayStamp = stamp;
+
+ _strayNavs = StrayNavs.Find(folders, _navFolder);
+ _strayNavText = StrayNavs.Notice(_strayNavs, _navFolder);
+ if (_strayNavs.Count > _strayNoticeCount)
+ {
+ _strayNoticeCount = _strayNavs.Count;
+ _strayChatPending = _strayNavText + " Nav panel: Copy them into NavProfiles (or /ra nav import).";
+ _host.Log("[RynthAi] " + _strayChatPending);
+ }
+ else if (_strayNavs.Count == 0) _strayNoticeCount = 0;
+ }
+ catch (Exception ex) { _host.Log($"[RynthAi] Stray nav check failed: {ex.Message}"); }
+ }
+
+ /// Posts the stray-navs line waiting for chat (plugin tick, in game).
+ public void DrainStrayNavNotice(Func write)
+ {
+ if (string.IsNullOrEmpty(_strayChatPending)) return;
+ if (write("[RynthAi] " + _strayChatPending)) _strayChatPending = string.Empty;
+ }
+
+ ///
+ /// /ra nav import and the Nav panel's button: copies the VirindiTank navs found outside
+ /// NavProfiles into it (never over a nav of that name; the originals stay). Returns the line
+ /// to show; false when nothing could be copied.
+ ///
+ public string CopyStrayNavs(out bool ok)
+ {
+ RefreshStrayNavs(NavFileList.Stamp(_navFolder), force: true);
+ List strays = _strayNavs ?? new List();
+ StrayCopyResult r = StrayNavs.CopyInto(strays, _navFolder, (from, to) =>
+ RynthCore.Plugin.Shared.DataWriteGuard.TrySave("the nav", to, () => File.Copy(from, to, overwrite: false), out string why, callerShows: true)
+ ? null : why);
+ ok = r.Failed == 0;
+ RefreshNavFiles();
+ RefreshStrayNavs(NavFileList.Stamp(_navFolder), force: true);
+ _strayChatPending = string.Empty;
+ return StrayNavs.CopyReply(r, _navFolder);
+ }
+
///
/// Lists a folder again when it changed since the last look (a file added, removed or renamed:
/// a route saved by RynthNav's "save as nav route", a loot profile or meta copied in, a settings
@@ -2819,7 +2906,9 @@ internal sealed partial class LegacyDashboardRenderer
long now = Environment.TickCount64;
if (now < _nextNavFolderCheckMs) return;
_nextNavFolderCheckMs = now + 3000;
- if (FolderChanged(_navFolder, ref _navFolderStamp)) RefreshNavFiles();
+ DateTime navStamp = NavFileList.Stamp(_navFolder); // NavProfiles and its subfolders
+ if (StampChanged(navStamp, ref _navFolderStamp)) RefreshNavFiles();
+ RefreshStrayNavs(navStamp);
if (FolderChanged(_lootFolder, ref _lootFolderStamp)) RefreshLootFiles();
if (FolderChanged(_metaFolder, ref _metaFolderStamp)) RefreshMetaFiles();
if (FolderChanged(_charFolder, ref _profileFolderStamp)) RefreshProfilesList();
@@ -2832,14 +2921,20 @@ internal sealed partial class LegacyDashboardRenderer
try
{
DateTime now = !string.IsNullOrEmpty(folder) && Directory.Exists(folder) ? Directory.GetLastWriteTimeUtc(folder) : DateTime.MinValue;
- if (now == stamp) return false;
- bool first = stamp == default;
- stamp = now;
- return !first;
+ return StampChanged(now, ref stamp);
}
catch { return false; }
}
+ /// FolderChanged for a time worked out by the caller (NavFileList.Stamp).
+ private static bool StampChanged(DateTime now, ref DateTime stamp)
+ {
+ if (now == stamp) return false;
+ bool first = stamp == default;
+ stamp = now;
+ return !first;
+ }
+
/// Save button and /ra nav save [name]. Returns the chat line.
public string SaveRoute(string? name)
{
@@ -2859,6 +2954,32 @@ internal sealed partial class LegacyDashboardRenderer
///
public string LoadNavByName(string name)
{
+ // A nav in a subfolder ("VirindiTank\Hunt", or just "Hunt" when only one subfolder has it):
+ // loaded from the list. A name at the top, or no such nav, goes on as before (a new one is made).
+ string typed = NewProfileFiles.Tidy(name, NewProfileFiles.NavExtensions, out _);
+ if (!File.Exists(Path.Combine(_navFolder, typed.Replace('/', '\\') + ".nav")) || typed.Contains('\\') || typed.Contains('/'))
+ {
+ RefreshNavFiles();
+ string? listed;
+ int matches;
+ List same;
+ lock (_profileListsLock)
+ {
+ listed = NavFileList.Find(_navFiles, typed, out matches);
+ same = matches > 1 ? NavFileList.SameName(_navFiles, typed) : new List();
+ }
+ if (listed != null && !listed.Equals("None", StringComparison.OrdinalIgnoreCase))
+ {
+ lock (_profileListsLock) _selectedNavIdx = _navFiles.IndexOf(listed);
+ LoadSelectedNav();
+ SaveSettings();
+ return $"[RynthAi] Loaded {listed} ({_settings.CurrentRoute.Points.Count} waypoints).";
+ }
+ if (matches > 1)
+ return $"[RynthAi] {matches} navs are named '{typed}': {string.Join(", ", same)}. /ra nav load \\ picks one.";
+ // Not listed: on as before (a name with a folder in it is refused there; nothing is made in a subfolder).
+ }
+
ProfileFileResult r = NewProfileFiles.FindOrCreateNav(_navFolder, name, out string want, out _, out string error);
if (r == ProfileFileResult.Rejected)
return $"[RynthAi] Can't use '{want}' as a nav name: {error}.";
@@ -2952,26 +3073,36 @@ internal sealed partial class LegacyDashboardRenderer
private void RefreshLootFiles()
{
- var list = new System.Collections.Generic.List { "None" };
- int idx = _settings.LootProfileIdx;
- if (Directory.Exists(_lootFolder))
- {
- var files = new System.Collections.Generic.List();
- files.AddRange(Directory.GetFiles(_lootFolder, "*.utl"));
- files.AddRange(Directory.GetFiles(_lootFolder, "*.json"));
- files.Sort(StringComparer.OrdinalIgnoreCase);
-
- foreach (string file in files)
- {
- list.Add(Path.GetFileName(file));
- if (file.Equals(_settings.CurrentLootPath, StringComparison.OrdinalIgnoreCase))
- idx = list.Count - 1;
- }
- }
+ // One list for every loot profile picker (Loot.LootProfileList).
+ List list = Loot.LootProfileList.Build(_lootFolder);
+ int idx = Loot.LootProfileList.SelectedIndex(list, _lootFolder, _settings.CurrentLootPath, _settings.LootProfileIdx);
lock (_profileListsLock) { _lootFiles.Clear(); _lootFiles.AddRange(list); }
_settings.LootProfileIdx = idx;
}
+ /// The loot profile pickers' list ("None", then LootProfiles' *.utl and *.json), a copy. Any thread.
+ public string[] LootProfileNames()
+ {
+ lock (_profileListsLock) return _lootFiles.ToArray();
+ }
+
+ ///
+ /// The Mini Remote's Loot row: picks from the list by name (the list can
+ /// change between the click and this call) through the pickers' one path, SelectProfileAtIndex.
+ /// Pump thread.
+ ///
+ public void SelectLootProfileByName(string fileName)
+ {
+ int idx;
+ lock (_profileListsLock) idx = Loot.LootProfileList.IndexOf(_lootFiles, fileName);
+ if (idx < 0)
+ {
+ _host.WriteToChat($"[RynthAi] Loot profile {fileName} is no longer in LootProfiles.", 4);
+ return;
+ }
+ SelectProfileAtIndex(1, idx);
+ }
+
private void RefreshMetaFiles()
{
var list = new List { "None" };
@@ -3118,7 +3249,7 @@ internal sealed partial class LegacyDashboardRenderer
? "None (Unsaved)"
: _settings.CurrentNavPath.StartsWith("') + " (in meta)"
- : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath),
+ : NavListName(_settings.CurrentNavPath),
NavStatusLine = _settings.NavStatusLine ?? string.Empty,
NavIsStuck = _settings.NavIsStuck,
MacroRunning = _settings.IsMacroRunning,
@@ -3134,12 +3265,31 @@ internal sealed partial class LegacyDashboardRenderer
TrailPoints = NavBreadcrumbs?.Trail.Length ?? 0,
TrailYards = NavBreadcrumbs?.TrailYards ?? 0,
EditStatus = CurrentNavEditStatus(),
+ StrayNavCount = _strayNavs?.Count ?? 0,
+ StrayNavText = _strayNavText ?? string.Empty,
};
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.NavBridgePayload);
}
catch { return "{}"; }
}
+ ///
+ /// The nav list's name for a nav file: "Folder\Name" for one in a NavProfiles subfolder (so the
+ /// Nav panel's picker shows it as the one loaded), else the file name without ".nav".
+ ///
+ private string NavListName(string path)
+ {
+ try
+ {
+ string rel = Path.GetRelativePath(_navFolder, path);
+ if (!rel.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(rel)
+ && rel.EndsWith(".nav", StringComparison.OrdinalIgnoreCase) && rel.Contains('\\'))
+ return rel[..^4];
+ }
+ catch { }
+ return Path.GetFileNameWithoutExtension(path);
+ }
+
public void HandleNavCommand(string json)
{
if (string.IsNullOrWhiteSpace(json)) return;
@@ -3152,7 +3302,7 @@ internal sealed partial class LegacyDashboardRenderer
{
case "startNav":
_settings.RearmFinishedNavRoute(); // the player's Start Navigation re-runs a finished Once route
- _settings.IsMacroRunning = true;
+ _settings.SetMacroRunning(true, "the remote's Start Navigation");
_settings.EnableNavigation = true;
if (_settings.BotAction != "Navigating")
_settings.BotAction = "Default";
@@ -3253,6 +3403,13 @@ internal sealed partial class LegacyDashboardRenderer
if (ni >= 0) { _selectedNavIdx = ni; LoadSelectedNav(); SaveSettings(); }
break;
+ case "copyStrayNavs":
+ // Nav panel: "Copy them into NavProfiles" under the stray-navs line.
+ string copied = CopyStrayNavs(out bool copyOk);
+ SetNavEditStatus(copied);
+ _host.WriteToChat("[RynthAi] " + copied, copyOk ? CommandReply.OkColor : CommandReply.FailColor);
+ break;
+
default:
// Route editor commands (multi-select edits, pause / portal steps, trail -> route).
HandleNavEditCommand(cmd);
@@ -3480,7 +3637,7 @@ internal sealed partial class LegacyDashboardRenderer
return sb.ToString();
}
- public void TogglePanelMacro() => _settings.IsMacroRunning = !_settings.IsMacroRunning;
+ public void TogglePanelMacro(string source = "the panel's macro toggle") => _settings.SetMacroRunning(!_settings.IsMacroRunning, source);
public void SetSubsystemEnabled(int id, bool enabled)
{
@@ -3533,9 +3690,14 @@ internal sealed partial class LegacyDashboardRenderer
case 1:
if (lootFile != null)
{
+ string before = _settings.CurrentLootPath ?? string.Empty;
_settings.LootProfileIdx = index;
_settings.CurrentLootPath = index == 0 ? string.Empty : Path.Combine(_lootFolder, lootFile);
SaveSettings();
+ // Every picker (Loaded files, Classic Loot tab, Settings > Looting, the Mini Remote) says
+ // what it switched to; the profile itself loads when looting next reads it.
+ if (!string.Equals(before, _settings.CurrentLootPath, StringComparison.OrdinalIgnoreCase))
+ _host.WriteToChat(Loot.LootProfileList.SwitchedLine(_settings.CurrentLootPath), 1);
}
break;
case 2:
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs
index 7809ea6..995214a 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyNavigationUi.cs
@@ -76,7 +76,7 @@ internal sealed class LegacyNavigationUi
if (ImGui.Button("Start Navigation", new Vector2(-1, 28)))
{
_settings.RearmFinishedNavRoute(); // a finished Once route runs again
- _settings.IsMacroRunning = true;
+ _settings.SetMacroRunning(true, "the Start Navigation button");
_settings.EnableNavigation = true;
if (_settings.BotAction != "Navigating")
_settings.BotAction = "Default";
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
index ff365e2..714bc05 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
@@ -18,7 +18,69 @@ public static class DashWindows
public sealed class LegacyUiSettings
{
// ── Runtime-only state — never persisted ────────────────────────────────
- [JsonIgnore] public bool IsMacroRunning;
+ // The macro switch. Every change records who made it (MacroStopSource / MacroStartSource), for the
+ // "Macro stopped" / "Macro started" log lines: a stop with no cause logged could not be told apart
+ // (the player's button, a script, a meta, the HP failsafe) (2026-11-22). A caller names itself with
+ // SetMacroRunning, or wraps its calls in MacroSource(...) (a meta's rule, a script's call); a plain
+ // write says so.
+ private bool _isMacroRunning;
+ private readonly List _macroSources = new();
+ [JsonIgnore] public bool IsMacroRunning
+ {
+ get => _isMacroRunning;
+ set => SetMacroRunning(value, null);
+ }
+ /// Who turned the macro off last ("" before the first stop).
+ [JsonIgnore] public string MacroStopSource { get; private set; } = "";
+ /// Who turned the macro on last ("" before the first start).
+ [JsonIgnore] public string MacroStartSource { get; private set; } = "";
+
+ /// Turns the macro on or off, saying who did (null: only the enclosing MacroSource scopes).
+ public void SetMacroRunning(bool on, string? source)
+ {
+ if (_isMacroRunning != on)
+ {
+ string who = DescribeMacroSource(source);
+ if (on) MacroStartSource = who; else MacroStopSource = who;
+ }
+ _isMacroRunning = on;
+ }
+
+ /// Names the caller of every macro change inside the scope (nested scopes add to it).
+ public IDisposable MacroSource(string source)
+ {
+ lock (_macroSources) _macroSources.Add(source);
+ return new MacroSourceScope(this, source);
+ }
+
+ private string DescribeMacroSource(string? source)
+ {
+ var parts = new List();
+ if (!string.IsNullOrEmpty(source)) parts.Add(source);
+ lock (_macroSources)
+ for (int i = _macroSources.Count - 1; i >= 0; i--)
+ if (!parts.Exists(p => p.Contains(_macroSources[i], StringComparison.Ordinal))) parts.Add(_macroSources[i]);
+ if (parts.Count == 0) return "a plain write (no source named)";
+ return parts.Count == 1 ? parts[0] : parts[0] + " (from " + string.Join(", from ", parts.GetRange(1, parts.Count - 1)) + ")";
+ }
+
+ private sealed class MacroSourceScope : IDisposable
+ {
+ private LegacyUiSettings? _s;
+ private readonly string _source;
+ public MacroSourceScope(LegacyUiSettings s, string source) { _s = s; _source = source; }
+ public void Dispose()
+ {
+ var s = _s;
+ if (s == null) return;
+ _s = null;
+ lock (s._macroSources)
+ {
+ int i = s._macroSources.LastIndexOf(_source);
+ if (i >= 0) s._macroSources.RemoveAt(i);
+ }
+ }
+ }
///
/// RynthSort's auto-sort is on (read from RynthSort every couple of seconds): Auto Cram stands down and
/// its checkboxes are greyed out, as the two fought over the packs (owner, 2026-11-03). Never saved.
@@ -134,6 +196,12 @@ public sealed class LegacyUiSettings
// own dialog as usual, never a No (engine API v97; MiniRemote/Crafting/CraftAutoConfirm.cs).
public bool AutoConfirmCraft = false;
public int AutoConfirmCraftPercent = 100;
+ // Make kits when low (2026-11-22; default off): with the macro on and nothing around, when fewer
+ // than MakeKitsBelow Plentiful Healing Kits are carried, make up to MakeKitsUpTo from the pack's
+ // ingredients at the Kits tab's Min chance % (MiniRemote/Crafting/KitAuto.cs, RynthAiPlugin.Kits.cs).
+ public bool MakeKitsWhenLow = false;
+ public int MakeKitsBelow = MiniRemote.Crafting.KitAuto.DefaultBelow;
+ public int MakeKitsUpTo = MiniRemote.Crafting.KitAuto.DefaultUpTo;
public bool EnableCombineSalvage = true;
public bool CombineBagsDuringSalvage = true;
// Salvage (and combine bags) by sending the 0x027D salvage request straight to the server, no
@@ -326,7 +394,8 @@ public sealed class LegacyUiSettings
public int TargetSelection;
// Target Lock: keep the picked target until it dies or goes, leaves Monster Range, or is
// blacklisted or skipped by a watchdog; a higher-priority monster in range doesn't take it
- // (2026-11-07). Off: a higher priority in range takes over at once, and it switches when
+ // (2026-11-07). With Targeting on Closest, a monster within 5 yd takes it from a target more
+ // than 6.5 m off (2026-11-22). Off: a higher priority in range takes over at once, and it switches when
// another is clearly better by Targeting. On by default; a profile saved before this setting
// loads it as on.
public bool TargetLock = true;
@@ -355,6 +424,14 @@ public sealed class LegacyUiSettings
"in through a door.\n" +
"Off: a monster behind a wall is never a melee target for being close; it is treated like any monster\n" +
"out of sight. On by default. /ra meleewalls [on|off]";
+ // Debuff every monster in range before attacking (2026-11-22, off by default, the meta option
+ // debuffallbeforeattacking, /ra debuffall): with several monsters in Monster Range, each one's own
+ // debuffs (its Monsters rule) go on all of them, nearest first, before any attack, and the pet
+ // summon waits for it. Capped per monster and in time; a monster hitting you in melee is fought
+ // first. CombatManager.DebuffPass.cs. A profile saved before this setting loads it as off.
+ public bool DebuffAllBeforeAttacking;
+ internal const string DebuffAllBeforeAttackingTip =
+ "Casts each monster's Monsters-rule debuffs on every monster in range, nearest first, before attacking any (/ra debuffall).";
public int RingRange = 5;
// Obsolete since 2026-10-20 (unused here, kept so profiles still load and carry it): the Empyrean
// Handler lethal-ring evade is Infinite Leaftide's and lives in RynthILT now (its ILT settings,
@@ -399,6 +476,10 @@ public sealed class LegacyUiSettings
public int CustomPetRange = 5;
public int PetMinMonsters = 1;
public bool PetAutoRefill = true; // auto-consume Encapsulated Spirits to recharge empty essences
+ // The element combat pets are summoned for (2026-11-22): "" = Any (the per-monster choice: the
+ // Damage-panel pick, the Monsters rule, then the monster's weakness), else Fire, Cold, ... An
+ // essence of it is summoned first unless the monster has a choice of its own (PetChoice.Order).
+ public string PetElement = string.Empty;
public bool AdvancedOptions;
public bool MineOnly = true;
public bool ShowEditor;
@@ -439,8 +520,8 @@ public sealed class LegacyUiSettings
/// on the way as usual, recover the corpse, then carry on. Off by default.
///
public bool TravelToOwnCorpse;
- /// Not read by the corpse looting (no rare-corpse check exists); kept so saved profiles
- /// round-trip. Hidden in Advanced Settings. The meta/MagTools option of that name sets Mine Only.
+ /// Loot Only Rare Corpses (2026-11-22, VTank's option): only a corpse whose description says it
+ /// generated a rare is opened (RynthAiPlugin.RareCorpses.cs). Off by default.
public bool LootOnlyRareCorpses;
///
/// Loot Mode (Loot.LootModes): 0 = Profile (the loot profile, the default), 1 = Rares and needed
@@ -1293,6 +1374,11 @@ public sealed class NavBridgePayload
public double TrailYards { get; set; }
/// Result of the last route edit ("Route reversed."), empty once it is a few seconds old.
public string EditStatus { get; set; } = string.Empty;
+ /// VirindiTank navs outside NavProfiles (StrayNavs): how many, and the line saying where
+ /// they are. The Nav panel shows it with a "Copy them into NavProfiles" button (copyStrayNavs).
+ /// 0 / empty when there are none; an engine that predates them ignores both.
+ public int StrayNavCount { get; set; }
+ public string StrayNavText { get; set; } = string.Empty;
}
/// One-shot command sent from the Avalonia NavPanel to the plugin.
@@ -1482,6 +1568,7 @@ public sealed class SettingsBridgePayload
public bool? TargetLock { get; set; }
public bool? FightSelectedTarget { get; set; }
public bool? MeleeThroughWalls { get; set; } // Melee through walls; absent (an engine without the row) = unchanged
+ public bool? DebuffAllBeforeAttacking { get; set; } // Debuff every monster in range before attacking; absent = unchanged
public int RingRange { get; set; }
public int ApproachRange { get; set; }
public double CorpseApproachRangeMax { get; set; }
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyWeaponsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyWeaponsUi.cs
index d80000f..11ae41f 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyWeaponsUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyWeaponsUi.cs
@@ -93,7 +93,8 @@ internal sealed class LegacyWeaponsUi
_host.WriteToChat($"[RynthAi] {wo.Name} is already in the list.", 1);
else
{
- string type = DetectConsumableType(wo);
+ // A server's holder of summons ("Duo Summon Gem": no "Essence" in its name) is a Pet.
+ string type = PetElements.IsHolder(_host, unchecked((uint)wo.Id), wo.Name) ? "Pet" : DetectConsumableType(wo);
_settings.ConsumableRules.Add(new ConsumableRule
{
Id = wo.Id,
@@ -128,6 +129,8 @@ internal sealed class LegacyWeaponsUi
continue;
}
string? type = PackConsumableType(wo);
+ // A server's holder of summons (PetElements: "Duo Summon Gem", no "Essence" in its name).
+ if (type == null && PetElements.IsHolder(_host, unchecked((uint)wo.Id), wo.Name)) type = "Pet";
if (type == null || _settings.ConsumableRules.Any(x => x.Id == wo.Id)) continue;
// An "...Essence" that is no combat pet device (appraised: no charges, no Summoning
// requirement, no summoning-gem icon; PetDeviceKind) is not listed as a combat pet: a
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavFileList.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavFileList.cs
new file mode 100644
index 0000000..188d517
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavFileList.cs
@@ -0,0 +1,168 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace RynthCore.Plugin.RynthAi.LegacyUi;
+
+///
+/// What the nav picker lists from NavProfiles (2026-11-22). It listed the top of the folder only,
+/// so VirindiTank navs dropped in as a folder (NavProfiles\VirindiTank\*.nav, a folder per server
+/// or per character) never showed. Now:
+/// - the top of the folder first, as before ("Hunt");
+/// - then the navs in its subfolders, as "Folder\Hunt" (up to deep),
+/// sorted. Not the Deleted folder (the profile buttons move files there), not hidden or
+/// dot folders, and not VirindiTank's "--<character>_<server>" state files, which a
+/// copied VirindiTank folder has hundreds of (nearly all empty).
+/// The names are paths relative to NavProfiles without ".nav", so Path.Combine(folder, name + ".nav")
+/// is the file for every entry. System only (the tests compile it in).
+///
+internal static class NavFileList
+{
+ /// How deep subfolders are looked into (NavProfiles\a\b\c\x.nav is the deepest).
+ public const int MaxDepth = 3;
+
+ /// Most entries listed (a whole Decal folder copied in can't flood the picker).
+ public const int MaxEntries = 2000;
+
+ /// The subfolder the profile buttons' Delete moves files into (ProfileFileOps.DeletedFolderName).
+ public const string DeletedFolder = "Deleted";
+
+ /// The navs in (see the class summary); empty when it doesn't exist.
+ public static List List(string folder)
+ {
+ var top = new List();
+ var sub = new List();
+ try
+ {
+ if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) return top;
+ foreach (string file in Directory.GetFiles(folder, "*.nav"))
+ if (IsNavFile(file)) top.Add(Path.GetFileNameWithoutExtension(file));
+ top.Sort(StringComparer.OrdinalIgnoreCase);
+ AddSubfolders(folder, folder, 1, sub);
+ sub.Sort(StringComparer.OrdinalIgnoreCase);
+ }
+ catch { /* an unreadable folder lists what was read */ }
+ top.AddRange(sub);
+ if (top.Count > MaxEntries) top.RemoveRange(MaxEntries, top.Count - MaxEntries);
+ return top;
+ }
+
+ private static void AddSubfolders(string root, string dir, int depth, List into)
+ {
+ if (depth > MaxDepth || into.Count >= MaxEntries) return;
+ string[] dirs;
+ try { dirs = Directory.GetDirectories(dir); } catch { return; }
+ foreach (string d in dirs)
+ {
+ if (!ListsFolder(d)) continue;
+ try
+ {
+ foreach (string file in Directory.GetFiles(d, "*.nav"))
+ {
+ if (!IsNavFile(file) || IsVTankStateFile(file)) continue;
+ into.Add(Path.GetRelativePath(root, file)[..^4]);
+ if (into.Count >= MaxEntries) return;
+ }
+ }
+ catch { continue; }
+ AddSubfolders(root, d, depth + 1, into);
+ }
+ }
+
+ /// A subfolder whose navs are listed: not Deleted, not hidden or a dot folder.
+ internal static bool ListsFolder(string dir)
+ {
+ string name = Path.GetFileName(dir);
+ if (name.Length == 0 || name[0] == '.') return false;
+ if (name.Equals(DeletedFolder, StringComparison.OrdinalIgnoreCase)) return false;
+ try
+ {
+ var attrs = File.GetAttributes(dir);
+ if ((attrs & (FileAttributes.Hidden | FileAttributes.System)) != 0) return false;
+ if ((attrs & FileAttributes.ReparsePoint) != 0) return false; // never follow a junction
+ }
+ catch { return false; }
+ return true;
+ }
+
+ /// A ".nav" file (the pattern alone would also take "x.nav~" on some systems).
+ private static bool IsNavFile(string file) => file.EndsWith(".nav", StringComparison.OrdinalIgnoreCase);
+
+ /// VirindiTank's own "--<character>_<server>.nav" (the route a character last had).
+ internal static bool IsVTankStateFile(string file) => Path.GetFileName(file).StartsWith("--", StringComparison.Ordinal);
+
+ ///
+ /// When or a listed subfolder last changed: the latest write time of
+ /// them. Adding a file to a subfolder changes only that subfolder's time, so the folder's own
+ /// time alone missed it. MinValue when the folder doesn't exist.
+ ///
+ public static DateTime Stamp(string folder)
+ {
+ try
+ {
+ if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) return DateTime.MinValue;
+ DateTime latest = Directory.GetLastWriteTimeUtc(folder);
+ StampSubfolders(folder, 1, ref latest);
+ return latest;
+ }
+ catch { return DateTime.MinValue; }
+ }
+
+ private static void StampSubfolders(string dir, int depth, ref DateTime latest)
+ {
+ if (depth > MaxDepth) return;
+ string[] dirs;
+ try { dirs = Directory.GetDirectories(dir); } catch { return; }
+ foreach (string d in dirs)
+ {
+ if (!ListsFolder(d)) continue;
+ try
+ {
+ DateTime t = Directory.GetLastWriteTimeUtc(d);
+ if (t > latest) latest = t;
+ }
+ catch { continue; }
+ StampSubfolders(d, depth + 1, ref latest);
+ }
+ }
+
+ ///
+ /// The entry of that /ra nav load <> means
+ /// (typed already tidied: no quotes, no ".nav"): the entry itself, any case, with \ or /; else,
+ /// for a name without a folder, the only subfolder entry with that file name. Null when there
+ /// is none; is how many subfolder entries had the name (2+: the
+ /// player has to say which).
+ ///
+ public static string? Find(IReadOnlyList names, string typed, out int matches)
+ {
+ matches = 0;
+ string want = (typed ?? string.Empty).Trim().Replace('/', '\\').Trim('\\');
+ if (want.Length == 0) return null;
+ foreach (string n in names)
+ if (n.Equals(want, StringComparison.OrdinalIgnoreCase)) { matches = 1; return n; }
+ if (want.Contains('\\')) return null;
+
+ string? found = null;
+ foreach (string n in names)
+ {
+ int slash = n.LastIndexOf('\\');
+ if (slash < 0) continue;
+ if (!n.AsSpan(slash + 1).Equals(want, StringComparison.OrdinalIgnoreCase)) continue;
+ matches++;
+ found ??= n;
+ }
+ return matches == 1 ? found : null;
+ }
+
+ /// The subfolder entries named (for the "which one?" reply).
+ public static List SameName(IReadOnlyList names, string name)
+ {
+ var list = new List();
+ foreach (string n in names)
+ {
+ int slash = n.LastIndexOf('\\');
+ if (slash >= 0 && n.AsSpan(slash + 1).Equals(name, StringComparison.OrdinalIgnoreCase)) list.Add(n);
+ }
+ return list;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs
index 9495f9c..2647b2d 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs
@@ -116,6 +116,13 @@ public sealed class NavRouteParser
///
public bool OutdoorHuntWalk { get; set; }
+ ///
+ /// The corners of a RynthNav navmesh path laid on the fly (a script's ai.GoTo outdoors, 2026-11-18):
+ /// like a hunt walk, a corner is turned early only where the navmesh shows a straight walk to the next
+ /// one (NavigationEngine's corner gate). Never set on a loaded route.
+ ///
+ public bool NavmeshCorners { get; set; }
+
///
/// Non-null if the last load hit an unknown waypoint type or a malformed
/// line. The route still holds whatever points parsed cleanly before that.
@@ -227,9 +234,9 @@ public sealed class NavRouteParser
var pt = new NavPoint
{
Type = (NavPointType)typeRaw,
- EW = double.Parse(lines[idx++], CultureInfo.InvariantCulture),
- NS = double.Parse(lines[idx++], CultureInfo.InvariantCulture),
- Z = double.Parse(lines[idx++], CultureInfo.InvariantCulture)
+ EW = ParseNumber(lines[idx++]),
+ NS = ParseNumber(lines[idx++]),
+ Z = ParseNumber(lines[idx++])
};
// Z is in nav units (metres / 240). Waypoints added from the UI before
// 2026-09-29 stored metres, so they drew hundreds of metres up; no real
@@ -253,18 +260,18 @@ public sealed class NavRouteParser
pt.TargetName = lines[idx++];
break;
case NavPointType.Jump:
- pt.JumpHeading = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
+ pt.JumpHeading = ParseNumber(lines[idx++]);
pt.JumpShift = lines[idx++].Trim().Equals("true", StringComparison.OrdinalIgnoreCase);
- pt.JumpMs = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
+ pt.JumpMs = ParseNumber(lines[idx++]);
break;
case NavPointType.PortalNPC:
case NavPointType.Npc:
pt.TargetName = lines[idx++];
pt.ObjectClass = int.Parse(lines[idx++], CultureInfo.InvariantCulture);
pt.IsTie = ParseTieFlag(lines[idx++]);
- pt.PortalExitEW = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
- pt.PortalExitNS = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
- pt.PortalExitZ = double.Parse(lines[idx++], CultureInfo.InvariantCulture);
+ pt.PortalExitEW = ParseNumber(lines[idx++]);
+ pt.PortalExitNS = ParseNumber(lines[idx++]);
+ pt.PortalExitZ = ParseNumber(lines[idx++]);
break;
}
@@ -283,6 +290,19 @@ public sealed class NavRouteParser
return route;
}
+ ///
+ /// A number line of a nav (coordinates, jump heading and power). Written by VirindiTank and
+ /// RynthAi as "12.5"; a line with a comma and no dot ("12,5", a PC set to a comma-decimal
+ /// language) is read as 12.5 (it used to read as 125: the comma was taken for a thousands
+ /// separator, and the point drew far off its place). No thousands separators.
+ ///
+ internal static double ParseNumber(string s)
+ {
+ s = (s ?? string.Empty).Trim();
+ if (s.IndexOf(',') >= 0 && s.IndexOf('.') < 0) s = s.Replace(',', '.');
+ return double.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture);
+ }
+
private static bool ParseTieFlag(string s)
{
if (bool.TryParse(s, out bool b)) return b; // "True"/"False" (VTank wire format)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/StrayNavs.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/StrayNavs.cs
new file mode 100644
index 0000000..b04115f
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/StrayNavs.cs
@@ -0,0 +1,205 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text.Json;
+
+namespace RynthCore.Plugin.RynthAi.LegacyUi;
+
+/// A VirindiTank-format nav outside NavProfiles, where the nav picker can't see it.
+internal readonly record struct StrayNav(string Path, string Folder, string Name);
+
+/// What copying the stray navs did.
+internal readonly record struct StrayCopyResult(int Copied, int AlreadyThere, int Failed, string FirstError);
+
+///
+/// Navs put in the wrong folder (2026-11-22). Players moving VirindiTank navs over put them in
+/// "the nav folder", and the one called that is RynthNav's map data folder (C:\Games\RynthCore\
+/// NavData); others land in the RynthAi or RynthSuite folder itself. RynthAi lists NavProfiles
+/// (and its subfolders) only, so they never showed and nothing said why. Here: the folders worth a
+/// look, the VirindiTank navs at the top of each that NavProfiles has no file of that name for, a
+/// line that says where they are and where they go, and the copy into NavProfiles (never moved,
+/// never over a file; the originals stay). System and System.Text.Json only (the tests compile it in).
+///
+internal static class StrayNavs
+{
+ /// RynthNav's own default for its map data folder (NavDataConfig.DefaultDir).
+ public const string DefaultNavDataDir = @"C:\Games\RynthCore\NavData";
+
+ ///
+ /// The folders to look in: RynthNav's map data folder (as RynthNav resolves it: the
+ /// RYNTHNAV_NAVDATA variable, "navDataDir" in %APPDATA%\RynthCore\rynthnav.json, else
+ /// <CoreDir>\NavData and the default), the RynthCore folder, the RynthSuite folder, RynthAi's
+ /// own folder and RynthNav's plugin folder. Never NavProfiles. Duplicates dropped.
+ ///
+ public static List CandidateFolders(string coreDir, string suiteDir, string rynthAiDir,
+ string? navDataEnv, string? rynthNavSettingsPath)
+ {
+ var list = new List();
+ void Add(string? dir)
+ {
+ if (string.IsNullOrWhiteSpace(dir) || !System.IO.Path.IsPathFullyQualified(dir)) return;
+ string full;
+ try { full = System.IO.Path.GetFullPath(dir).TrimEnd('\\', '/'); } catch { return; }
+ foreach (string have in list) if (have.Equals(full, StringComparison.OrdinalIgnoreCase)) return;
+ list.Add(full);
+ }
+ Add(navDataEnv);
+ try
+ {
+ if (!string.IsNullOrEmpty(rynthNavSettingsPath) && File.Exists(rynthNavSettingsPath))
+ Add(ReadNavDataDir(File.ReadAllText(rynthNavSettingsPath)));
+ }
+ catch { }
+ if (!string.IsNullOrEmpty(coreDir)) Add(System.IO.Path.Combine(coreDir, "NavData"));
+ Add(DefaultNavDataDir);
+ Add(coreDir);
+ Add(suiteDir);
+ Add(rynthAiDir);
+ if (!string.IsNullOrEmpty(suiteDir)) Add(System.IO.Path.Combine(suiteDir, "RynthNav"));
+ return list;
+ }
+
+ /// "navDataDir" from rynthnav.json's text (the same key RynthNav reads), or null.
+ internal static string? ReadNavDataDir(string json)
+ {
+ try
+ {
+ using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
+ if (doc.RootElement.ValueKind != JsonValueKind.Object) return null;
+ foreach (JsonProperty p in doc.RootElement.EnumerateObject())
+ if (p.Name.Equals("navDataDir", StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.String)
+ return p.Value.GetString();
+ }
+ catch (JsonException) { }
+ return null;
+ }
+
+ ///
+ /// The VirindiTank-format navs (first line "uTank2 NAV") at the top of each of
+ /// that has no file of that name for.
+ /// VirindiTank's "--" state files are left out. A folder inside NavProfiles is skipped (it's listed).
+ ///
+ public static List Find(IEnumerable folders, string navFolder)
+ {
+ var found = new List();
+ string navFull = Full(navFolder);
+ foreach (string folder in folders)
+ {
+ string f = Full(folder);
+ if (f.Length == 0 || IsSameOrInside(f, navFull)) continue;
+ string[] files;
+ try { if (!Directory.Exists(f)) continue; files = Directory.GetFiles(f, "*.nav"); }
+ catch { continue; }
+ Array.Sort(files, StringComparer.OrdinalIgnoreCase);
+ foreach (string file in files)
+ {
+ if (!file.EndsWith(".nav", StringComparison.OrdinalIgnoreCase) || NavFileList.IsVTankStateFile(file)) continue;
+ if (!IsVTankNav(file)) continue;
+ string name = System.IO.Path.GetFileNameWithoutExtension(file);
+ if (navFull.Length > 0 && File.Exists(System.IO.Path.Combine(navFull, name + ".nav"))) continue;
+ found.Add(new StrayNav(file, f, name));
+ }
+ }
+ return found;
+ }
+
+ /// True when the file's first line is a VirindiTank nav header.
+ internal static bool IsVTankNav(string file)
+ {
+ try
+ {
+ using var reader = new StreamReader(file);
+ string? first = reader.ReadLine();
+ return first != null && first.Contains("uTank2 NAV", StringComparison.OrdinalIgnoreCase);
+ }
+ catch { return false; }
+ }
+
+ ///
+ /// Copies into the top of , where the picker
+ /// lists them. A name NavProfiles already has is left alone (counted, not copied); the
+ /// originals stay where they were. does the write (DataWriteGuard in
+ /// the plugin, File.Copy in the tests).
+ ///
+ public static StrayCopyResult CopyInto(IReadOnlyList strays, string navFolder, Func? copy = null)
+ {
+ copy ??= DefaultCopy;
+ int copied = 0, there = 0, failed = 0;
+ string firstError = string.Empty;
+ var taken = new HashSet(StringComparer.OrdinalIgnoreCase);
+ try { Directory.CreateDirectory(navFolder); } catch { }
+ foreach (StrayNav s in strays)
+ {
+ string target = System.IO.Path.Combine(navFolder, s.Name + ".nav");
+ if (!taken.Add(s.Name) || File.Exists(target)) { there++; continue; }
+ string? error = copy(s.Path, target);
+ if (error == null) copied++;
+ else
+ {
+ failed++;
+ if (firstError.Length == 0) firstError = error;
+ }
+ }
+ return new StrayCopyResult(copied, there, failed, firstError);
+ }
+
+ private static string? DefaultCopy(string from, string to)
+ {
+ try { File.Copy(from, to, overwrite: false); return null; }
+ catch (Exception ex) { return ex.Message; }
+ }
+
+ ///
+ /// The line that says where the stray navs are and where they go (chat and the Nav panel), or
+ /// empty when there are none. Names the folder with the most of them; "and N more in other
+ /// folders" for the rest.
+ ///
+ public static string Notice(IReadOnlyList strays, string navFolder, string? navDataDir = null)
+ {
+ if (strays.Count == 0) return string.Empty;
+ var byFolder = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (StrayNav s in strays) byFolder[s.Folder] = byFolder.TryGetValue(s.Folder, out int n) ? n + 1 : 1;
+ string top = string.Empty; int topCount = 0;
+ foreach (var kv in byFolder) if (kv.Value > topCount) { top = kv.Key; topCount = kv.Value; }
+ bool isNavData = IsNavDataFolder(top, navDataDir);
+ string what = strays.Count == 1 ? "1 VirindiTank nav is" : $"{strays.Count} VirindiTank navs are";
+ string where = byFolder.Count == 1
+ ? $"in {top}"
+ : $"in {top} ({topCount}) and {byFolder.Count - 1} other folder{(byFolder.Count == 2 ? "" : "s")}";
+ string why = isNavData ? " (RynthNav's map data folder)" : string.Empty;
+ return $"{what} {where}{why}, so the nav list doesn't show {(strays.Count == 1 ? "it" : "them")}. "
+ + $"RynthAi's navs go in {navFolder} (subfolders are fine).";
+ }
+
+ /// The chat line after a copy (/ra nav import and the Nav panel's button).
+ public static string CopyReply(StrayCopyResult r, string navFolder)
+ {
+ if (r.Copied == 0 && r.AlreadyThere == 0 && r.Failed == 0)
+ return $"No VirindiTank navs outside NavProfiles to copy. The nav list shows {navFolder} and its subfolders.";
+ var parts = new List();
+ if (r.Copied > 0) parts.Add($"Copied {r.Copied} nav{(r.Copied == 1 ? "" : "s")} into {navFolder}; {(r.Copied == 1 ? "it is" : "they are")} in the nav list now. The originals are still where they were");
+ if (r.AlreadyThere > 0) parts.Add($"{r.AlreadyThere} left alone (NavProfiles has a nav of that name)");
+ if (r.Failed > 0) parts.Add($"{r.Failed} couldn't be copied: {r.FirstError}");
+ return string.Join("; ", parts) + ".";
+ }
+
+ private static bool IsNavDataFolder(string folder, string? navDataDir)
+ {
+ string name = System.IO.Path.GetFileName(folder.TrimEnd('\\', '/'));
+ if (name.Equals("NavData", StringComparison.OrdinalIgnoreCase)) return true;
+ return !string.IsNullOrEmpty(navDataDir) && Full(navDataDir).Equals(Full(folder), StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static string Full(string? dir)
+ {
+ if (string.IsNullOrWhiteSpace(dir)) return string.Empty;
+ try { return System.IO.Path.GetFullPath(dir).TrimEnd('\\', '/'); } catch { return string.Empty; }
+ }
+
+ private static bool IsSameOrInside(string dir, string parent)
+ {
+ if (parent.Length == 0) return false;
+ return dir.Equals(parent, StringComparison.OrdinalIgnoreCase)
+ || dir.StartsWith(parent + "\\", StringComparison.OrdinalIgnoreCase);
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs
index 78b28e3..6beea6c 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootEditorBridge.cs
@@ -73,8 +73,9 @@ internal sealed class LootEditorBridge
}
}
- // The session's revision plus the popup draft's: both only grow, so the sum moves when either does.
- private long StateRevision => _session.Revision + _draftRevision;
+ // The session's revision plus the popup draft's plus the Keep # per day counts' (each only
+ // grows), so the sum moves when any does.
+ private long StateRevision => _session.Revision + _draftRevision + Items.PerDayRevision();
public string StateJson()
{
@@ -85,6 +86,12 @@ internal sealed class LootEditorBridge
LootEditState state = _session.BuildState(inUse, ListFiles());
state.Revision = StateRevision;
state.ItemDraft = _draft;
+ for (int i = 0; i < state.Rules.Count; i++)
+ {
+ LootEditRow row = state.Rules[i];
+ if (row.Action == (int)VTankLootAction.KeepUpTo && row.PerDayHours > 0)
+ row.PerDayStatus = PerDayStatus(row.Name, i, row.PerDayHours, row.KeepCount);
+ }
return JsonSerializer.Serialize(state, LootEditJsonContext.Default.LootEditState);
}
}
@@ -94,10 +101,31 @@ internal sealed class LootEditorBridge
lock (_sync)
{
LootEditRule? rule = _session.BuildRule(index);
- return rule == null ? "{\"Index\":-1}" : JsonSerializer.Serialize(rule, LootEditJsonContext.Default.LootEditRule);
+ if (rule == null) return "{\"Index\":-1}";
+ if (rule.Action == (int)VTankLootAction.KeepUpTo && rule.PerDayHours is int h && h > 0)
+ rule.PerDayStatus = PerDayStatus(rule.Name, index, h, rule.KeepCount);
+ return JsonSerializer.Serialize(rule, LootEditJsonContext.Default.LootEditRule);
}
}
+ private string PerDayStatus(string name, int index, int hours, int cap)
+ {
+ try { return Items.PerDayStatus(LootPerDay.Key(name, index), hours, cap); }
+ catch { return string.Empty; }
+ }
+
+ /// The rule view's "Reset count": forgets the pickups of the rule at cmd.Index. Under the lock.
+ private void PerDayResetCommand(LootEditCommand cmd)
+ {
+ LootEditRule? rule = _session.BuildRule(cmd.Index);
+ if (rule == null || (cmd.Expect != null && !string.Equals(cmd.Expect, rule.Name, StringComparison.Ordinal)))
+ {
+ _session.Say("That rule is no longer there. The list has been refreshed.", ok: false);
+ return;
+ }
+ _session.Say(Items.PerDayReset(LootPerDay.Key(rule.Name, cmd.Index)), ok: true);
+ }
+
public string VocabJson() =>
_vocabJson ??= JsonSerializer.Serialize(LootRuleText.BuildVocab(), LootEditJsonContext.Default.LootEditVocab);
@@ -113,6 +141,11 @@ internal sealed class LootEditorBridge
string? saved = null;
lock (_sync)
{
+ if (cmd.Op == "perday_reset")
+ {
+ PerDayResetCommand(cmd);
+ return;
+ }
if (cmd.Op == "open")
{
string inUse = InUse;
@@ -396,6 +429,12 @@ internal sealed class LootItemHooks
/// (the looter's own classification, run as a preview), or null.
///
public Func BuiltInKeep { get; set; } = _ => null;
+ /// Keep # per day: (rule key, window hours, count) to "1 of 2 picked up in the last 24 h, ...".
+ public Func PerDayStatus { get; set; } = (_, _, _) => string.Empty;
+ /// Keep # per day: grows whenever a count changes (and each minute while any is on record).
+ public Func PerDayRevision { get; set; } = () => 0;
+ /// Keep # per day: forget a rule's pickups; the reply.
+ public Func PerDayReset { get; set; } = _ => "Not available.";
}
///
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPerDayStore.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPerDayStore.cs
new file mode 100644
index 0000000..985ce42
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootPerDayStore.cs
@@ -0,0 +1,247 @@
+// ============================================================================
+// RynthAi - Loot/LootPerDayStore.cs
+// "Keep # per day" (2026-11-22, RynthCore.Loot.LootPerDay): what this
+// character picked up for each such rule, with the time of each pickup, so a
+// rule takes at most N in any rolling window (24 h by default). Counted by
+// pickups, not by the pack: treasure maps and the like get used or sold.
+//
+// One file per character and server, beside the settings profiles:
+// SettingsProfiles\\\loot_per_day.json
+// {"version":1,"rules":{"Treasure Maps":[{"at":"2026-11-22T10:00:00Z","n":1}]}}
+// Times are UTC (no jump when the clocks change). Pickups older than a week
+// (the longest window) are dropped on load and on every pickup.
+//
+// Pure (no host): the host tests drive it with their own clock.
+// ============================================================================
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Text;
+using System.Text.Json;
+using RynthCore.Loot;
+
+namespace RynthCore.Plugin.RynthAi.Loot;
+
+internal sealed class LootPerDayStore
+{
+ public const string FileName = "loot_per_day.json";
+ public const int FileVersion = 1;
+
+ private readonly Dictionary> _rules = new(StringComparer.OrdinalIgnoreCase);
+
+ internal readonly record struct Pick(DateTime AtUtc, int Units);
+
+ /// The file (empty: kept in memory only, nothing saved).
+ public string Path { get; private set; } = string.Empty;
+
+ /// Grows on every change (the Loot Editor's revision follows it).
+ public long Revision { get; private set; }
+
+ /// The last load or save problem, or empty.
+ public string Problem { get; private set; } = string.Empty;
+
+ ///
+ /// Reads (empty: memory only). A missing file is no pickups; a
+ /// broken one is no pickups too, with set (and kept until the next
+ /// pickup overwrites it).
+ ///
+ public void Load(string path, DateTime nowUtc)
+ {
+ Path = path ?? string.Empty;
+ _rules.Clear();
+ Problem = string.Empty;
+ Revision++;
+ if (Path.Length == 0 || !File.Exists(Path)) return;
+ try
+ {
+ Parse(File.ReadAllText(Path));
+ Prune(nowUtc);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or FormatException)
+ {
+ _rules.Clear();
+ Problem = $"{Path}: {ex.Message}";
+ }
+ }
+
+ /// A pickup of (at least 1) for the rule , saved at once.
+ public void Record(string key, int units, DateTime nowUtc)
+ {
+ if (string.IsNullOrWhiteSpace(key)) return;
+ if (!_rules.TryGetValue(key, out List? list))
+ _rules[key] = list = new List();
+ list.Add(new Pick(nowUtc, Math.Max(1, units)));
+ Prune(nowUtc);
+ Revision++;
+ Save();
+ }
+
+ /// Units picked up for in the last .
+ public int Count(string key, int hours, DateTime nowUtc)
+ {
+ if (!_rules.TryGetValue(key, out List? list)) return 0;
+ DateTime from = nowUtc - TimeSpan.FromHours(hours);
+ int n = 0;
+ foreach (Pick p in list)
+ if (p.AtUtc > from) n += p.Units;
+ return n;
+ }
+
+ ///
+ /// How long until the count is under again (zero when it is now); under
+ /// the cap, how long until the oldest pickup in the window frees its place (null: none in it).
+ ///
+ public TimeSpan? NextFree(string key, int hours, int cap, DateTime nowUtc)
+ {
+ if (!_rules.TryGetValue(key, out List? list)) return null;
+ TimeSpan window = TimeSpan.FromHours(hours);
+ var inWindow = new List();
+ foreach (Pick p in list)
+ if (p.AtUtc > nowUtc - window) inWindow.Add(p);
+ if (inWindow.Count == 0) return null;
+ inWindow.Sort((a, b) => a.AtUtc.CompareTo(b.AtUtc));
+ int total = 0;
+ foreach (Pick p in inWindow) total += p.Units;
+ if (total < cap)
+ return Max0(inWindow[0].AtUtc + window - nowUtc);
+ // Drop the oldest until the rest is under the cap: that pickup's expiry is when.
+ int left = total;
+ foreach (Pick p in inWindow)
+ {
+ left -= p.Units;
+ if (left < cap) return Max0(p.AtUtc + window - nowUtc);
+ }
+ return TimeSpan.Zero;
+ }
+
+ private static TimeSpan Max0(TimeSpan t) => t < TimeSpan.Zero ? TimeSpan.Zero : t;
+
+ /// Forgets the pickups of (null: of every rule). True when there were any.
+ public bool Clear(string? key)
+ {
+ bool had = key == null ? _rules.Count > 0 : _rules.Remove(key);
+ if (key == null) _rules.Clear();
+ if (!had) return false;
+ Revision++;
+ Save();
+ return true;
+ }
+
+ /// Every rule with pickups on record, with its pickups (oldest first).
+ public IEnumerable<(string Key, IReadOnlyList Picks)> Rules()
+ {
+ var keys = new List(_rules.Keys);
+ keys.Sort(StringComparer.OrdinalIgnoreCase);
+ foreach (string k in keys)
+ {
+ var list = new List(_rules[k]);
+ list.Sort((a, b) => a.AtUtc.CompareTo(b.AtUtc));
+ yield return (k, list);
+ }
+ }
+
+ /// "1 of 2 picked up in the last 24 h, next frees in 5 h 10 min".
+ public string Status(string key, int hours, int cap, DateTime nowUtc)
+ {
+ int have = Count(key, hours, nowUtc);
+ string s = $"{have} of {cap} picked up in the last {LootPerDay.WindowText(hours)}";
+ TimeSpan? next = NextFree(key, hours, cap, nowUtc);
+ if (have > 0 && next is TimeSpan t) s += (have >= cap ? ", none until " : ", next frees in ") + Duration(t);
+ return s;
+ }
+
+ /// "5 h 10 min", "45 min", "under a minute".
+ public static string Duration(TimeSpan t)
+ {
+ long minutes = (long)Math.Ceiling(t.TotalMinutes);
+ if (minutes <= 0) return "under a minute";
+ long h = minutes / 60, m = minutes % 60;
+ if (h == 0) return m.ToString(CultureInfo.InvariantCulture) + " min";
+ return h.ToString(CultureInfo.InvariantCulture) + " h" + (m > 0 ? " " + m.ToString(CultureInfo.InvariantCulture) + " min" : string.Empty);
+ }
+
+ private void Prune(DateTime nowUtc)
+ {
+ DateTime from = nowUtc - TimeSpan.FromHours(LootPerDay.MaxHours);
+ var empty = new List();
+ foreach (var kv in _rules)
+ {
+ kv.Value.RemoveAll(p => p.AtUtc <= from);
+ if (kv.Value.Count == 0) empty.Add(kv.Key);
+ }
+ foreach (string k in empty) _rules.Remove(k);
+ }
+
+ // ── File ──────────────────────────────────────────────────────────────────
+
+ private void Save()
+ {
+ if (Path.Length == 0) return;
+ try
+ {
+ string? dir = System.IO.Path.GetDirectoryName(Path);
+ if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
+ string tmp = Path + ".tmp";
+ File.WriteAllText(tmp, Serialize());
+ File.Move(tmp, Path, overwrite: true);
+ Problem = string.Empty;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Problem = $"{Path}: {ex.Message}";
+ }
+ }
+
+ internal string Serialize()
+ {
+ using var stream = new MemoryStream();
+ using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
+ {
+ w.WriteStartObject();
+ w.WriteNumber("version", FileVersion);
+ w.WriteStartObject("rules");
+ foreach ((string key, IReadOnlyList picks) in Rules())
+ {
+ w.WriteStartArray(key);
+ foreach (Pick p in picks)
+ {
+ w.WriteStartObject();
+ w.WriteString("at", p.AtUtc.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture));
+ w.WriteNumber("n", p.Units);
+ w.WriteEndObject();
+ }
+ w.WriteEndArray();
+ }
+ w.WriteEndObject();
+ w.WriteEndObject();
+ }
+ return Encoding.UTF8.GetString(stream.ToArray());
+ }
+
+ private void Parse(string json)
+ {
+ using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
+ if (doc.RootElement.ValueKind != JsonValueKind.Object
+ || !doc.RootElement.TryGetProperty("rules", out JsonElement rules) || rules.ValueKind != JsonValueKind.Object)
+ return;
+ foreach (JsonProperty rule in rules.EnumerateObject())
+ {
+ if (rule.Value.ValueKind != JsonValueKind.Array || string.IsNullOrWhiteSpace(rule.Name)) continue;
+ var list = new List();
+ foreach (JsonElement e in rule.Value.EnumerateArray())
+ {
+ if (e.ValueKind != JsonValueKind.Object
+ || !e.TryGetProperty("at", out JsonElement at) || at.ValueKind != JsonValueKind.String
+ || !DateTime.TryParse(at.GetString(), CultureInfo.InvariantCulture,
+ DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime when))
+ continue;
+ int n = e.TryGetProperty("n", out JsonElement ne) && ne.ValueKind == JsonValueKind.Number && ne.TryGetInt32(out int v) ? v : 1;
+ list.Add(new Pick(DateTime.SpecifyKind(when, DateTimeKind.Utc), Math.Max(1, n)));
+ }
+ if (list.Count == 0) continue;
+ if (_rules.TryGetValue(rule.Name, out List? have)) have.AddRange(list); // same name, other case
+ else _rules[rule.Name] = list;
+ }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/LootProfileList.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootProfileList.cs
new file mode 100644
index 0000000..9431119
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/LootProfileList.cs
@@ -0,0 +1,90 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace RynthCore.Plugin.RynthAi.Loot;
+
+///
+/// The loot profile pickers' list and selection: the dashboard's Loaded files drawer (LOOT), the
+/// Classic look's Loot tab, Settings > Looting (the engine's and RynthAi's own) and the Mini Remote's
+/// Loot row all show this one list, built by LegacyDashboardRenderer.RefreshLootFiles (at load, and
+/// within 3 s of the LootProfiles folder changing). Pure, apart from listing the folder.
+///
+internal static class LootProfileList
+{
+ /// The first entry: no loot profile.
+ public const string None = "None";
+
+ ///
+ /// "None", then the *.utl and *.json files in (file names, sorted, any case).
+ /// No such folder: "None" alone.
+ ///
+ public static List Build(string? folder)
+ {
+ var files = new List();
+ if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder))
+ {
+ try
+ {
+ foreach (string f in Directory.GetFiles(folder, "*.utl")) files.Add(Path.GetFileName(f));
+ foreach (string f in Directory.GetFiles(folder, "*.json")) files.Add(Path.GetFileName(f));
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+ files.Sort(StringComparer.OrdinalIgnoreCase);
+ var list = new List(files.Count + 1) { None };
+ list.AddRange(files);
+ return list;
+ }
+
+ ///
+ /// The entry the pickers select for (the loot profile in use):
+ /// 0 (None) when there is none; its file's entry when it is in ; else
+ /// (a profile a meta loaded from elsewhere) , kept in the list's range.
+ ///
+ public static int SelectedIndex(IReadOnlyList list, string? folder, string? currentPath, int previous)
+ {
+ string path = (currentPath ?? string.Empty).Trim().Trim('"');
+ if (path.Length == 0 || list.Count == 0) return 0;
+ string name = Path.GetFileName(path);
+ string? dir = Path.GetDirectoryName(path);
+ if (!string.IsNullOrEmpty(folder) && SameFolder(dir, folder))
+ for (int i = 1; i < list.Count; i++)
+ if (string.Equals(list[i], name, StringComparison.OrdinalIgnoreCase)) return i;
+ return Math.Clamp(previous, 0, list.Count - 1);
+ }
+
+ /// The name a picker shows for the profile in use: its file name, or None.
+ public static string ShownName(string? currentPath)
+ {
+ string path = (currentPath ?? string.Empty).Trim().Trim('"');
+ return path.Length == 0 ? None : Path.GetFileName(path);
+ }
+
+ /// The index of in (any case), or -1.
+ public static int IndexOf(IReadOnlyList list, string? fileName)
+ {
+ if (string.IsNullOrEmpty(fileName)) return -1;
+ for (int i = 0; i < list.Count; i++)
+ if (string.Equals(list[i], fileName, StringComparison.OrdinalIgnoreCase)) return i;
+ return -1;
+ }
+
+ /// The chat line after a picker switched the loot profile (empty path: None).
+ public static string SwitchedLine(string? newPath) =>
+ string.IsNullOrWhiteSpace(newPath)
+ ? "[RynthAi] Loot profile: None (no loot profile in use)."
+ : $"[RynthAi] Loot profile: {Path.GetFileName(newPath.Trim())}.";
+
+ private static bool SameFolder(string? a, string b)
+ {
+ if (string.IsNullOrEmpty(a)) return false;
+ try
+ {
+ return string.Equals(Path.GetFullPath(a).TrimEnd('\\', '/'), Path.GetFullPath(b).TrimEnd('\\', '/'),
+ StringComparison.OrdinalIgnoreCase);
+ }
+ catch (Exception) { return false; }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs
index e79dbd1..766b91f 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/SalvageManager.cs
@@ -291,7 +291,8 @@ public sealed class SalvageManager
public void NoteLootedForSalvage(uint itemId, string? name = null)
{
if (itemId == 0) return;
- if (IsSalvageBag(name ?? _cache?[unchecked((int)itemId)]?.Name)) return;
+ string? noted = name ?? _cache?[unchecked((int)itemId)]?.Name;
+ if (IsSalvageBag(noted) || IsFoolproof(noted)) return;
Track(itemId, name);
}
@@ -314,6 +315,11 @@ public sealed class SalvageManager
if (_settings.EnableCombineSalvage) _pendingCombineScan = true;
return;
}
+ if (IsFoolproof(name))
+ {
+ Log($"[Salvage] Not salvaging 0x{itemId:X8} ({name}): {SkipFoolproof}.");
+ return;
+ }
Track(itemId, name);
QueueItem(itemId);
@@ -650,12 +656,14 @@ public sealed class SalvageManager
internal const string SkipItemsList = "on the Items list";
internal const string SkipUst = "it is the UST";
internal const string SkipBag = "already a salvage bag (the combine sweep handles bags)";
+ internal const string SkipFoolproof = "a Foolproof tinkering material (salvaging it would turn it into plain salvage)";
internal const string SkipGaveUp = "salvage failed too often";
/// Why (in the pack) must not be salvaged, or null.
private string? SkipReasonFor(uint id, WorldObject wo)
{
if (IsSalvageBag(wo.Name)) return SkipBag;
+ if (IsFoolproof(wo.Name)) return SkipFoolproof;
if (IsWornByPlayer(wo)) return SkipWorn;
if (wo.ObjectClass == AcObjectClass.Ust || IsUst(wo.Name)
|| (_host.HasGetObjectWcid && _host.TryGetObjectWcid(id, out uint wcid) && wcid == UstWcid))
@@ -1703,6 +1711,15 @@ public sealed class SalvageManager
return int.TryParse(inside, out value);
}
+ ///
+ /// A Foolproof tinkering material ("Foolproof" plus its material, a bag that can't fail; TinkerPlanner.IsFoolproof
+ /// uses the same name test). R-20261122-193822-831d: one looted from a chest matched the profile's
+ /// "(Salv) Red Garnet" rule by its material, and the batch salvaged it into 33 plain Red Garnet. It is
+ /// already the finished material: never salvaged, whatever a rule says.
+ ///
+ internal static bool IsFoolproof(string? name)
+ => !string.IsNullOrEmpty(name) && name.IndexOf("Foolproof", StringComparison.OrdinalIgnoreCase) >= 0;
+
private static bool IsSalvageBag(string? name)
{
if (string.IsNullOrEmpty(name))
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
index 33f19c3..e8f0427 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
@@ -168,6 +168,17 @@ internal sealed class UseRefusalWatch
return wasStuck ? Verdict.Recovered : Verdict.None;
}
+ ///
+ /// 's opens say nothing about the server (a wall was in the way,
+ /// RynthAiPlugin.CorpseBehindWall.cs): its pending open is dropped and its refusals are taken back.
+ ///
+ public void Forget(int corpseId)
+ {
+ if (_pending && _pendingId == corpseId) { _pending = false; _answeredAt = 0; }
+ if (_refused.Remove(corpseId) && Refusals > 0 && State == Phase.Normal) Refusals--;
+ if (LastRefusedCorpse == corpseId) LastRefusedCorpse = 0;
+ }
+
/// Back to normal: a relog, a login, a successful open.
public void Reset()
{
diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
index 9c7917b..2116712 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
@@ -253,6 +253,7 @@ public sealed partial class RynthAiPlugin
["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off
["lootchestsmacrooff"] = "LootChestsMacroOff",
["meleethroughwalls"] = "MeleeThroughWalls", // Settings > Combat > Targeting > Melee through walls
+ ["debuffallbeforeattacking"] = "DebuffAllBeforeAttacking", // Settings > Combat > Targeting > Debuff every monster in range before attacking
["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
["dooropenrange"] = "OpenDoorRange",
["autofellowmanagement"] = "AutoFellowMgmt",
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.RaNav.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.RaNav.cs
new file mode 100644
index 0000000..2ea9e88
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.RaNav.cs
@@ -0,0 +1,32 @@
+// ExpressionEngine.RaNav.cs - ranav[]: the nav route RynthAi has loaded, as one JSON line, for a script that
+// runs routes of its own (2026-11-18: a route for a Thread where the explore can't go,
+// then a second one looped from where the first ends):
+// {"name":"Pit00C1In","points":24,"index":3,"type":"Once","finished":false,"nav":true,"macro":true}
+// name is the file's name without .nav ("" for a route made on the fly: /ra dunnav-to, a GoTo, a meta's nav);
+// finished is a Once route walked to its end (the meta's "nav route empty").
+using System.Globalization;
+using System.Text;
+using System.Text.Json;
+
+namespace RynthCore.Plugin.RynthAi.Meta;
+
+internal sealed partial class ExpressionEngine
+{
+ private string EvalRaNav()
+ {
+ var s = _settings;
+ if (s == null) return "{}";
+ var route = s.CurrentRoute;
+ string path = s.CurrentNavPath ?? string.Empty;
+ string name = path.Length > 0 ? System.IO.Path.GetFileNameWithoutExtension(path) : string.Empty;
+ var sb = new StringBuilder(160);
+ sb.Append("{\"name\":\"").Append(JsonEncodedText.Encode(name).ToString()).Append('"');
+ sb.Append(",\"points\":").Append((route?.Points.Count ?? 0).ToString(CultureInfo.InvariantCulture));
+ sb.Append(",\"index\":").Append(s.ActiveNavIndex.ToString(CultureInfo.InvariantCulture));
+ sb.Append(",\"type\":\"").Append(route?.RouteType.ToString() ?? "None").Append('"');
+ sb.Append(",\"finished\":").Append(s.NavRouteFinished() ? "true" : "false");
+ sb.Append(",\"nav\":").Append(s.EnableNavigation ? "true" : "false");
+ sb.Append(",\"macro\":").Append(s.IsMacroRunning ? "true" : "false");
+ return sb.Append('}').ToString();
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
index 1328b6d..607e37e 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
@@ -234,6 +234,10 @@ internal sealed partial class ExpressionEngine
// radunexploreinfo[]: the explore as JSON (state, rooms, the shut doors and the rooms behind each, the
// lever errand, the last lever's result), "{}" before the first. For the Lua script's json.decode.
internal Func? DunExploreInfo { get; set; }
+ // rabuffsdue[seconds] (RynthAi only, 2026-11-20): how many buffs a rebuff would cast if Rebuff With were
+ // `seconds` (BuffManager.CountBuffsDue): the character's, the item spells' and the shield's. -1 with buffing
+ // off or no buff manager. A script asks it before a Thread, since Lua sees only the character's own.
+ internal Func? BuffsDue { get; set; }
// ── Backward-compat shim ──────────────────────────────────────────────────
@@ -422,6 +426,9 @@ internal sealed partial class ExpressionEngine
"radunexplorerooms" => (DunExploreStatus?.Invoke().Rooms ?? 0).ToString(CultureInfo.InvariantCulture),
"radunexplorevisited" => (DunExploreStatus?.Invoke().Visited ?? 0).ToString(CultureInfo.InvariantCulture),
"radunexploreinfo" => DunExploreInfo?.Invoke() ?? "{}",
+ "ranav" => EvalRaNav(),
+ "rabuffsdue" => (BuffsDue?.Invoke(double.TryParse(A(0), NumberStyles.Float, CultureInfo.InvariantCulture, out double dueSec)
+ ? (int)Math.Clamp(dueSec, 0, int.MaxValue) : 0) ?? -1).ToString(CultureInfo.InvariantCulture),
// ── World object queries ──────────────────────────────────────────
"wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)),
@@ -3726,6 +3733,7 @@ internal sealed partial class ExpressionEngine
["TargetLock"] = (() => B(s.TargetLock), v => s.TargetLock = ToDouble(v) != 0),
["FightSelectedTarget"] = (() => B(s.FightSelectedTarget), v => s.FightSelectedTarget = ToDouble(v) != 0),
["MeleeThroughWalls"] = (() => B(s.MeleeThroughWalls), v => s.MeleeThroughWalls = ToDouble(v) != 0),
+ ["DebuffAllBeforeAttacking"] = (() => B(s.DebuffAllBeforeAttacking), v => s.DebuffAllBeforeAttacking = ToDouble(v) != 0),
["RingRange"] = (() => I(s.RingRange), v => { if (int.TryParse(v, out int i)) s.RingRange = i; }),
["ApproachRange"] = (() => I(s.ApproachRange), v => { if (int.TryParse(v, out int i)) s.ApproachRange = i; }),
["MinRingTargets"] = (() => I(s.MinRingTargets), v => { if (int.TryParse(v, out int i)) s.MinRingTargets = i; }),
@@ -3745,6 +3753,7 @@ internal sealed partial class ExpressionEngine
["MissileAttackPower"] = (() => I(s.MissileAttackPower), v => { if (int.TryParse(v, out int i)) s.MissileAttackPower = i; }),
["CustomPetRange"] = (() => I(s.CustomPetRange), v => { if (int.TryParse(v, out int i)) s.CustomPetRange = i; }),
["PetMinMonsters"] = (() => I(s.PetMinMonsters), v => { if (int.TryParse(v, out int i)) s.PetMinMonsters = i; }),
+ ["PetElement"] = (() => s.PetElement.Length > 0 ? s.PetElement : "Any", v => s.PetElement = PetChoice.NormalizeElement(v)),
// VTank-meta migration (Phase 2): fields existed but weren't exposed here.
["CorpseApproachRangeMax"] = (() => D(s.CorpseApproachRangeMax), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMax = d; }),
["CorpseApproachRangeMin"] = (() => D(s.CorpseApproachRangeMin), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMin = d; }),
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs
index 46f08f7..5b60917 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs
@@ -66,7 +66,7 @@ internal sealed partial class MetaManager
{
DateTime now = Clock();
_settings.CurrentState = s.State;
- _settings.IsMacroRunning = s.MacroRunning;
+ _settings.SetMacroRunning(s.MacroRunning, "the meta resume after a reload");
_lastState = s.State;
_lastMacroRunning = s.MacroRunning; // no "macro started": that would re-arm every rule
_settings.MetaCallStackReset = false;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
index 7fbce4b..a0aafa8 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
@@ -384,6 +384,7 @@ internal sealed partial class MetaManager
engine.LastChestLooted = _lastChestLooted;
engine.DunExploreStatus = _dunExploreStatus;
engine.DunExploreInfo = _dunExploreInfo;
+ engine.BuffsDue = sec => _buffManager?.CountBuffsDue(sec) ?? -1; // the buff manager may come later
// vtsetsetting[] / vtgetsetting[] take VTank names and units, as '/vt opt set|get' does.
engine.VtOptionSetter = TrySetVtOption;
engine.VtOptionGetter = GetVtOption;
@@ -1001,6 +1002,8 @@ internal sealed partial class MetaManager
private void ExecuteAction(MetaRule rule)
{
_actionDepth++;
+ // A macro stop or start an action makes names the meta (LegacyUiSettings.MacroSource).
+ using var source = _settings.MacroSource($"the meta (state '{_settings.CurrentState}')");
try { ExecuteActionCore(rule); }
finally { _actionDepth--; }
}
@@ -1626,6 +1629,7 @@ internal sealed partial class MetaManager
["pickupmacrooff"] = "LootChestsMacroOff", // Settings > Looting > Pickup with macro off
["lootchestsmacrooff"] = "LootChestsMacroOff",
["meleethroughwalls"] = "MeleeThroughWalls", // Settings > Combat > Targeting > Melee through walls
+ ["debuffallbeforeattacking"] = "DebuffAllBeforeAttacking", // Settings > Combat > Targeting > Debuff every monster in range before attacking
["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
["dooropenrange"] = "OpenDoorRange",
["autofellowmanagement"] = "AutoFellowMgmt",
diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitAuto.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitAuto.cs
new file mode 100644
index 0000000..c492b04
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitAuto.cs
@@ -0,0 +1,345 @@
+// KitAuto.cs - "Make kits when low" (Mini Remote > Crafting > Kits, /ra kits auto): with the macro
+// on, a kit run starts by itself when fewer than MakeKitsBelow Plentiful Healing Kits are carried
+// and nothing needs the character. Pure (System only), so RynthCore.RynthAiTests links it; the
+// plugin side (RynthAiPlugin.Kits.cs) reads the facts each tick, holds the bot while a run goes
+// (the way it holds for buffs) and KitRunner does the combines.
+//
+// A start needs every one of: the setting on, the macro on, fewer kits than the line, nothing else
+// going (buffing or healing, a fight, looting, salvaging, a portal, a vendor, following, ...),
+// vitals over their heal lines, no monster within the safe radius (35 yd, or Monster Range when
+// that is bigger), no hit for 20 s, and the pack making one kit at the Min chance % floor with
+// Healing trained. Then the bot is held still: peace mode is asked for (combat mode is the only
+// one left from a fight), and once in peace and standing still for a second the run starts.
+//
+// A run stops at once on a monster inside the radius, a hit, a heal line, buffing, the macro off,
+// or moving (KitRunner checks the last three itself). Waits after a run:
+// - a stop for danger (monster, damage, heal, moving, leaving peace): 60 s;
+// - a run that made nothing (every combine failed, the server's chance under the floor, a
+// refusal) or the player's Stop: 10 min;
+// - a run that made kits: the next look in 30 s (the count decides then).
+// Before a start, a pack that can't make a kit (out of an ingredient, under the floor, untrained)
+// is said once per reason, then looked at again every 30 s.
+using System;
+
+namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
+
+/// Why a kit run ended (KitRunner sets it; the "when low" waits follow it).
+internal enum KitStopKind
+{
+ /// Logged out, settings gone: no wait of its own.
+ Other,
+ /// Made the count asked for, or the pack ran out.
+ Finished,
+ /// A monster, a hit, a heal line, buffing, moving, leaving peace mode.
+ Danger,
+ /// The server's chance under the floor, a refusal, no answer, AC's dialog wanting a click.
+ Refused,
+ /// The player's Stop (the button, /ra kits stop).
+ User,
+ /// The macro was turned off during a "when low" run.
+ MacroOff,
+}
+
+/// What stops a "when low" start (the first that holds, cheap ones first).
+internal enum KitBlock { None, Off, MacroOff, Enough, Busy, Vitals, Monster, Hurt, Pack }
+
+/// What the next tick does about "Make kits when low".
+internal enum KitAutoStep
+{
+ /// Nothing: the bot goes on as usual.
+ Wait,
+ /// Hold the bot still (getting ready).
+ Hold,
+ /// Hold the bot and ask for peace mode.
+ GoPeace,
+ /// Start the run now (and hold the bot while it goes).
+ Start,
+}
+
+/// One look at the character for "Make kits when low" (RynthAiPlugin.Kits.cs fills it).
+internal sealed class KitAutoFacts
+{
+ public bool Enabled;
+ public bool MacroOn;
+ /// Plentiful Healing Kits carried (main pack and side packs).
+ public int Kits;
+ /// A run starts with fewer kits than this.
+ public int Below = KitAuto.DefaultBelow;
+ /// "" when the pack makes a kit at the floor; else the planner's why (out of X, under the floor, untrained).
+ public string PackWhy = string.Empty;
+ public bool InPeace = true;
+ /// The character moved since the last tick.
+ public bool Moving;
+ /// The nearest live monster (PositiveInfinity = none known).
+ public double NearestMonsterYd = double.PositiveInfinity;
+ public double RadiusYd = KitAuto.DefaultRadiusYd;
+ /// Since health last went down (MaxValue = not this session).
+ public long SinceHurtMs = long.MaxValue;
+ /// "" when health, stamina and mana are over their lines; else which one.
+ public string VitalsWhy = string.Empty;
+ /// "" when nothing else needs the character; else what does (buffing, a fight, looting, ...).
+ public string BusyWhy = string.Empty;
+}
+
+internal sealed class KitAuto
+{
+ public const int DefaultBelow = 2;
+ public const int DefaultUpTo = 5;
+ public const int MaxBelow = 50;
+ public const int MaxUpTo = 100;
+ /// No monster this close (or within Monster Range, when that is bigger) for a start; one coming this close stops a run.
+ public const double DefaultRadiusYd = 35;
+ /// No start for this long after a hit.
+ public const long HurtQuietMs = 20_000;
+ /// The next look while something else has the character, or the kits are enough.
+ public const long CheckMs = 5_000;
+ /// The next look after the pack couldn't make a kit, and after a run that made some.
+ public const long PackCheckMs = 30_000;
+ /// The wait after a stop for danger (a monster, a hit, a heal line, moving).
+ public const long CooldownMs = 60_000;
+ /// The wait after a run that made nothing, or the player's Stop.
+ public const long BackoffMs = 600_000;
+ /// Getting ready (peace mode, standing still) gives up after this.
+ public const long ReadyTimeoutMs = 6_000;
+ /// Standing still this long in peace mode before the first combine.
+ public const long SettleMs = 1_000;
+ /// Peace mode is asked for again after this.
+ public const long PeaceResendMs = 2_000;
+
+ /// Clock (ms, monotonic); tests replace it.
+ public Func NowMs = static () => Environment.TickCount64;
+ /// A chat line for the player (a reason said once).
+ public Action? Say;
+
+ private long _nextCheckAt;
+ private string _waitWhy = string.Empty;
+ private long _readySince = -1;
+ private long _stillSince = -1;
+ private long _peaceSentAt = long.MinValue / 2;
+ private string _said = string.Empty;
+ private volatile string _status = "off";
+
+ /// What it is doing, for the Kits tab and /ra kits auto status.
+ public string Status => _status;
+ /// Getting ready for a run (the bot is held).
+ public bool Readying => _readySince >= 0;
+ /// No look before this (0 = the next tick).
+ public long NextCheckAt => _nextCheckAt;
+ /// The reason last said in chat ("" = none since the last run that made kits).
+ public string Said => _said;
+
+ // ── Rules ───────────────────────────────────────────────────────────────
+
+ /// The first thing that stops a start now (KitBlock.None and "" when it can go, peace mode aside).
+ public static (KitBlock Block, string Why) Blocker(KitAutoFacts f)
+ {
+ if (!f.Enabled) return (KitBlock.Off, "off");
+ if (!f.MacroOn) return (KitBlock.MacroOff, "the macro is off");
+ int below = Math.Clamp(f.Below, 1, MaxBelow);
+ if (f.Kits >= below) return (KitBlock.Enough, $"{KitsText(f.Kits)} carried (makes more under {below})");
+ if (f.BusyWhy.Length > 0) return (KitBlock.Busy, f.BusyWhy);
+ if (f.VitalsWhy.Length > 0) return (KitBlock.Vitals, f.VitalsWhy);
+ if (f.NearestMonsterYd <= f.RadiusYd) return (KitBlock.Monster, $"monster {f.NearestMonsterYd:0} yd away");
+ if (f.SinceHurtMs < HurtQuietMs) return (KitBlock.Hurt, $"hit {f.SinceHurtMs / 1000} s ago");
+ if (f.PackWhy.Length > 0) return (KitBlock.Pack, f.PackWhy);
+ return (KitBlock.None, string.Empty);
+ }
+
+ ///
+ /// Why a "when low" run must stop now ("" = go on): buffing or a fight, a heal line, a monster
+ /// within the radius. The macro off, moving, a hit and leaving peace mode KitRunner stops on itself.
+ ///
+ public static string StopReason(KitAutoFacts f)
+ {
+ if (f.BusyWhy.Length > 0) return f.BusyWhy;
+ if (f.VitalsWhy.Length > 0) return f.VitalsWhy;
+ if (f.NearestMonsterYd <= f.RadiusYd) return $"a monster came within {f.NearestMonsterYd:0} yd";
+ return string.Empty;
+ }
+
+ public static string KitsText(int n) => n == 1 ? "1 kit" : $"{n} kits";
+
+ // ── The tick ────────────────────────────────────────────────────────────
+
+ ///
+ /// One tick with no run going. is read only when a look is due (it walks
+ /// the pack and the world), every tick while getting ready.
+ ///
+ public KitAutoStep Decide(Func facts)
+ {
+ long now = NowMs();
+ if (_readySince < 0 && now < _nextCheckAt)
+ {
+ long left = (_nextCheckAt - now + 999) / 1000;
+ _status = (_waitWhy.Length > 0 ? "waiting: " + _waitWhy + "; " : "") + $"next check in {left} s";
+ return KitAutoStep.Wait;
+ }
+
+ KitAutoFacts f = facts();
+ var (block, why) = Blocker(f);
+ if (block != KitBlock.None)
+ {
+ bool wasReady = _readySince >= 0;
+ EndReady();
+ switch (block)
+ {
+ case KitBlock.Off:
+ _status = "off";
+ _nextCheckAt = 0;
+ break;
+ case KitBlock.MacroOff:
+ _status = "waiting: the macro is off";
+ _nextCheckAt = 0;
+ break;
+ case KitBlock.Pack:
+ // Said once per reason; not "can't read your skill" (the qualities arrive late after a login).
+ if (_said != why && !why.StartsWith("can't read", StringComparison.Ordinal))
+ {
+ _said = why;
+ SayLine($"[RynthAi] Make kits when low: {KitsText(f.Kits)} left, but none can be made now: {why}.");
+ }
+ Wait(now, PackCheckMs, why);
+ break;
+ case KitBlock.Enough:
+ Wait(now, CheckMs, why);
+ break;
+ default:
+ // Something came up while getting ready: the danger wait, as after a stopped run.
+ bool danger = block is KitBlock.Monster or KitBlock.Hurt or KitBlock.Vitals;
+ Wait(now, wasReady && danger ? CooldownMs : CheckMs, why);
+ break;
+ }
+ if (block is not (KitBlock.Off or KitBlock.MacroOff)) _status = "waiting: " + why;
+ return KitAutoStep.Wait;
+ }
+
+ // Everything clear: hold the bot, go to peace mode, stand still, then start.
+ if (_readySince < 0)
+ {
+ _readySince = now;
+ _stillSince = -1;
+ _peaceSentAt = long.MinValue / 2;
+ }
+ if (now - _readySince > ReadyTimeoutMs)
+ {
+ EndReady();
+ Wait(now, CooldownMs, f.InPeace ? "couldn't stand still" : "couldn't go to peace mode");
+ _status = "waiting: " + _waitWhy;
+ return KitAutoStep.Wait;
+ }
+ if (!f.InPeace)
+ {
+ _stillSince = -1;
+ _status = "going to peace mode";
+ if (now - _peaceSentAt >= PeaceResendMs)
+ {
+ _peaceSentAt = now;
+ return KitAutoStep.GoPeace;
+ }
+ return KitAutoStep.Hold;
+ }
+ if (f.Moving)
+ {
+ _stillSince = -1;
+ _status = "stopping to make kits";
+ return KitAutoStep.Hold;
+ }
+ if (_stillSince < 0) _stillSince = now;
+ if (now - _stillSince < SettleMs)
+ {
+ _status = "getting ready";
+ return KitAutoStep.Hold;
+ }
+ EndReady();
+ _status = "starting";
+ return KitAutoStep.Start;
+ }
+
+ /// The run went out (the Kits tab shows "running made/limit").
+ public void Running(int made, int limit) => _status = limit > 0 ? $"running {made}/{limit}" : $"running ({made} made)";
+
+ /// KitRunner refused the start after all (its own checks): look again later.
+ public void StartRefused(string why)
+ {
+ Wait(NowMs(), PackCheckMs, why);
+ _status = "waiting: " + why;
+ }
+
+ ///
+ /// A "when low" run ended: the wait that follows it. Returns what the run's summary line adds
+ /// ("" = nothing), so one line says how it went and when the next try is.
+ ///
+ public string RunEnded(KitStopKind kind, int made)
+ {
+ long now = NowMs();
+ EndReady();
+ switch (kind)
+ {
+ case KitStopKind.MacroOff:
+ case KitStopKind.Other:
+ _nextCheckAt = 0;
+ _waitWhy = string.Empty;
+ _status = kind == KitStopKind.MacroOff ? "waiting: the macro is off" : "idle";
+ if (made > 0) _said = string.Empty;
+ return string.Empty;
+ case KitStopKind.Danger:
+ if (made > 0) _said = string.Empty;
+ Wait(now, CooldownMs, "the last run was stopped");
+ return $" Next try in {CooldownMs / 1000} s at the earliest.";
+ case KitStopKind.User:
+ Wait(now, BackoffMs, "you stopped the last run");
+ return $" Next try in {BackoffMs / 60_000} min (turn Make kits when low off to stop it for good).";
+ default:
+ if (made <= 0)
+ {
+ Wait(now, BackoffMs, "the last run made nothing");
+ return $" Next try in {BackoffMs / 60_000} min.";
+ }
+ _said = string.Empty;
+ Wait(now, PackCheckMs, string.Empty);
+ return string.Empty;
+ }
+ }
+
+ /// The setting was turned on, or the player asked (/ra kits auto on): look on the next tick.
+ public void LookNow()
+ {
+ EndReady();
+ _nextCheckAt = 0;
+ _waitWhy = string.Empty;
+ _said = string.Empty;
+ }
+
+ /// The setting is off (or the character logged out).
+ public void Off()
+ {
+ EndReady();
+ _nextCheckAt = 0;
+ _waitWhy = string.Empty;
+ _status = "off";
+ }
+
+ /// Logout: nothing carries over to the next character.
+ public void Reset()
+ {
+ Off();
+ _said = string.Empty;
+ }
+
+ private void Wait(long now, long ms, string why)
+ {
+ _nextCheckAt = now + ms;
+ _waitWhy = why;
+ }
+
+ private void EndReady()
+ {
+ _readySince = -1;
+ _stillSince = -1;
+ }
+
+ private void SayLine(string line)
+ {
+ try { Say?.Invoke(line); } catch { }
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitPlanner.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitPlanner.cs
new file mode 100644
index 0000000..20a6bff
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitPlanner.cs
@@ -0,0 +1,262 @@
+// KitPlanner.cs - "Make kits": which kits the pack's ingredients make, how many, and the next
+// combine. Pure (System only), so RynthCore.RynthAiTests links it; KitRunner does the work.
+//
+// Retail data (ACE World Database v0.9.293, recipes 4022-4025; ACE RecipeManager):
+// Treated Mandrake (22448) on Treated Hyssop (22447), either way round
+// -> Combined Hyssop and Mandrake (22446) Healing, difficulty 100
+// Combined Hyssop and Mandrake (22446) on Soft Bandages (22445), either way round
+// -> Plentiful Healing Kit (22449, 100 uses) Healing, difficulty 200
+// Each combine uses one of each item, success or failure (a failure makes nothing). The chance is
+// ACE's SkillCheck.GetSkillChance(buffed skill, difficulty) = 1 - 1/(1 + e^(0.03 (skill - diff))),
+// plus the Craftsman augmentation's skill (which only raises it: our figure is the floor). An
+// untrained skill is refused by the server.
+// That is the only Plentiful kit in the retail data: there is no Plentiful mana or stamina kit to
+// make there. Another kit chain is one more KitRecipe in Retail.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
+
+/// An item a kit recipe uses or makes: its weenie class id and its name (the name is the fallback match).
+internal sealed record KitPart(uint Wcid, string Name);
+
+/// One combine: used on makes .
+internal sealed record KitCombine(
+ string Label, KitPart Source, KitPart Target, KitPart Product, int SkillId, int Difficulty,
+ string SuccessText, string FailText);
+
+/// A kit and the combines that make it (the last one makes the kit; earlier ones make its parts).
+internal sealed record KitRecipe(string Id, string Name, KitPart Product, KitCombine[] Steps)
+{
+ public KitCombine Final => Steps[^1];
+
+ /// The combine that makes , or null for an ingredient you carry.
+ public KitCombine? Producer(KitPart part) => Steps.FirstOrDefault(s => s.Product.Wcid == part.Wcid);
+
+ /// The items you carry for it (not made by an earlier step), in step order.
+ public IEnumerable Ingredients()
+ {
+ var seen = new HashSet();
+ foreach (var s in Steps)
+ foreach (var p in new[] { s.Source, s.Target })
+ if (seen.Add(p.Wcid)) yield return p;
+ }
+}
+
+/// A stack in the pack as the planner sees it (Wcid 0 = unknown: the name decides).
+internal readonly record struct KitStack(int Id, uint Wcid, string Name, int Count);
+
+/// The crafting skill: its buffed value and training (2 trained, 3 specialized); Known false when the engine can't read it.
+internal readonly record struct KitSkill(bool Known, int Buffed, int Training)
+{
+ public static readonly KitSkill Unknown = new(false, 0, 0);
+ public bool Trained => Training >= 2;
+}
+
+/// One step's chance in a plan (-1 percent = unknown).
+internal readonly record struct KitStepChance(KitCombine Step, int Percent, bool UnderFloor);
+
+/// What the pack makes of one kit.
+internal sealed class KitPlanRow
+{
+ public KitRecipe Recipe = null!;
+ /// Kits the pack makes if every combine works.
+ public int CanMake;
+ /// Each item the recipe uses (and makes on the way), with the count carried.
+ public List<(KitPart Part, int Count)> Parts = new();
+ public List Chances = new();
+ /// Why no combine can go now ("" when one can).
+ public string Blocked = string.Empty;
+}
+
+/// The next combine: the stacks to use, or why none (Step null).
+internal readonly record struct KitNext(KitCombine? Step, int SourceId, int TargetId, int Percent, string Why)
+{
+ public static KitNext None(string why) => new(null, 0, 0, -1, why);
+}
+
+internal static class KitPlanner
+{
+ public const int SkillHealing = 21;
+ /// The Min chance % a new character starts with.
+ public const int DefaultFloorPercent = 90;
+
+ public static readonly KitPart SoftBandages = new(22445, "Soft Bandages");
+ public static readonly KitPart CombinedHerbs = new(22446, "Combined Hyssop and Mandrake");
+ public static readonly KitPart TreatedHyssop = new(22447, "Treated Hyssop");
+ public static readonly KitPart TreatedMandrake = new(22448, "Treated Mandrake");
+ public static readonly KitPart PlentifulHealingKit = new(22449, "Plentiful Healing Kit");
+
+ /// The retail kit recipes (ACE World Database).
+ public static readonly KitRecipe[] Retail =
+ {
+ new("plentiful-healing", "Plentiful Healing Kit", PlentifulHealingKit, new[]
+ {
+ new KitCombine("Combine the herbs", TreatedMandrake, TreatedHyssop, CombinedHerbs, SkillHealing, 100,
+ "You crumble the dried and treated leaves together.",
+ "You crumble the leaves and they become useless."),
+ new KitCombine("Pack the kit", CombinedHerbs, SoftBandages, PlentifulHealingKit, SkillHealing, 200,
+ "You pack the bandages with the herbs. The odor is pungent and heady. The kit appears to be bulkier than any others you have seen.",
+ "The herbs spill out of the bandages onto the ground. The bandages are ruined as they unravel onto the dirt."),
+ }),
+ };
+
+ public static string SkillName(int skillId) => skillId switch
+ {
+ SkillHealing => "Healing",
+ _ => $"skill {skillId}",
+ };
+
+ // ── Chance ──────────────────────────────────────────────────────────────
+
+ /// ACE SkillCheck.GetSkillChance (factor 0.03), 0-1.
+ public static double Chance(int skill, int difficulty)
+ {
+ double c = 1.0 - 1.0 / (1.0 + Math.Exp(0.03 * (skill - difficulty)));
+ return Math.Clamp(c, 0.0, 1.0);
+ }
+
+ /// The chance as the server's prompt shows it (a rounded percent).
+ public static int Percent(int skill, int difficulty) => (int)Math.Round(Chance(skill, difficulty) * 100.0, MidpointRounding.AwayFromZero);
+
+ /// A step's percent for this skill (-1 unknown).
+ public static int StepPercent(KitCombine step, Func skill)
+ {
+ var s = skill(step.SkillId);
+ return s.Known ? Percent(s.Buffed, step.Difficulty) : -1;
+ }
+
+ // ── Counting ────────────────────────────────────────────────────────────
+
+ public static bool Matches(KitPart part, KitStack stack)
+ => stack.Wcid != 0 ? stack.Wcid == part.Wcid : string.Equals(stack.Name, part.Name, StringComparison.OrdinalIgnoreCase);
+
+ /// How many of a part the pack holds (every matching stack).
+ public static int Count(KitPart part, IReadOnlyList pack)
+ {
+ int n = 0;
+ foreach (var s in pack) if (Matches(part, s)) n += Math.Max(1, s.Count);
+ return n;
+ }
+
+ /// The first stack of a part (its object id), 0 when none.
+ public static int FirstStack(KitPart part, IReadOnlyList pack)
+ {
+ foreach (var s in pack) if (Matches(part, s)) return s.Id;
+ return 0;
+ }
+
+ /// Carried plus what the earlier steps can still make of it.
+ private static int Available(KitRecipe r, KitPart part, IReadOnlyList pack, int depth)
+ {
+ int have = Count(part, pack);
+ var producer = depth < 8 ? r.Producer(part) : null;
+ return producer == null ? have : have + Makeable(r, producer, pack, depth + 1);
+ }
+
+ /// How many times a step can go with what the pack holds and makes.
+ private static int Makeable(KitRecipe r, KitCombine step, IReadOnlyList pack, int depth = 0)
+ => Math.Min(Available(r, step.Source, pack, depth), Available(r, step.Target, pack, depth));
+
+ /// Kits the pack makes if every combine works.
+ public static int CanMake(KitRecipe r, IReadOnlyList pack) => Makeable(r, r.Final, pack);
+
+ // ── Planning ────────────────────────────────────────────────────────────
+
+ /// What the pack makes of each recipe, with the chances at this skill and floor.
+ public static List Plan(IReadOnlyList recipes, IReadOnlyList pack,
+ Func