From 759009b56965efc879336811c88591710ebdf480 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Mon, 23 Nov 2026 11:13:51 -0500 Subject: [PATCH] RynthSuite as of 2026-11-23 (internal 327a8263): release 2026.11.23.1 --- .../RynthCore.Plugin.RynthAi/BuildingMap.cs | 479 +++++++++- .../Combat/BuffCastChain.cs | 102 +- .../Combat/BuffManager.HealAnimationCap.cs | 71 ++ .../Combat/BuffManager.HpFailsafe.cs | 4 +- .../Combat/BuffManager.KitUsedUp.cs | 4 +- .../Combat/BuffManager.LegacySwap.cs | 2 +- .../Combat/BuffManager.VitalWandGate.cs | 36 + .../Combat/BuffManager.cs | 319 ++++++- .../Combat/CombatManager.Ammo.cs | 45 + .../Combat/CombatManager.DebuffPass.cs | 202 ++++ .../Combat/CombatManager.Offhand.cs | 2 +- .../Combat/CombatManager.PassedOver.cs | 1 + .../Combat/CombatManager.cs | 325 +++++-- .../Combat/DebuffPass.cs | 285 ++++++ .../Combat/DirtyFightingHeights.cs | 26 +- .../Combat/HealLatencyTracker.cs | 22 + .../Combat/PetChoice.cs | 129 ++- .../Combat/PetDeviceKind.cs | 4 + .../Combat/PetElements.cs | 186 ++++ .../Combat/PetManager.cs | 59 +- .../Combat/WorldObjectCache.cs | 82 +- .../CorpseOpenController.cs | 68 +- .../Dashboard/InstrumentDashboard.cs | 13 + .../Diagnostics/TickGuard.cs | 2 + .../DungeonGeometry.cs | 510 +++++++++- .../DungeonPathfinder.Blocked.cs | 185 +++- .../DungeonPathfinder.Explore.cs | 4 +- .../DungeonPathfinder.Holes.cs | 200 +++- .../DungeonPathfinder.Jumps.cs | 298 ++++++ .../DungeonPathfinder.Ledges.cs | 56 +- .../DungeonPathfinder.Portals.cs | 58 ++ .../DungeonPathfinder.Rooms.cs | 179 ++++ .../DungeonPathfinder.Straighten.cs | 10 +- .../DungeonPathfinder.cs | 104 ++ .../GroundLootController.cs | 2 + .../RynthCore.Plugin.RynthAi/Huds/HudState.cs | 2 + .../Huds/MiniRemoteHud.cs | 47 +- .../LegacyUi/LegacyAdvancedSettingsUi.cs | 27 +- .../LegacyUi/LegacyDashboardRenderer.cs | 226 ++++- .../LegacyUi/LegacyNavigationUi.cs | 2 +- .../LegacyUi/LegacyUiSettings.cs | 95 +- .../LegacyUi/LegacyWeaponsUi.cs | 5 +- .../LegacyUi/NavFileList.cs | 168 ++++ .../LegacyUi/NavRouteParser.cs | 36 +- .../LegacyUi/StrayNavs.cs | 205 ++++ .../Loot/LootEditorBridge.cs | 45 +- .../Loot/LootPerDayStore.cs | 247 +++++ .../Loot/LootProfileList.cs | 90 ++ .../Loot/SalvageManager.cs | 19 +- .../Loot/UseRefusalWatch.cs | 11 + .../MagToolsCommands.cs | 1 + .../Meta/ExpressionEngine.RaNav.cs | 32 + .../Meta/ExpressionEngine.cs | 9 + .../Meta/MetaManager.Resume.cs | 2 +- .../Meta/MetaManager.cs | 4 + .../MiniRemote/Crafting/KitAuto.cs | 345 +++++++ .../MiniRemote/Crafting/KitPlanner.cs | 262 ++++++ .../MiniRemote/Crafting/KitRunner.cs | 475 ++++++++++ .../MiniRemote/CraftingTab.cs | 202 +++- .../MiniRemote/MiniRemoteContext.cs | 3 + .../MiniRemote/MiniRemoteState.cs | 4 + .../MiniRemote/PetsTab.cs | 27 + .../NavBreadcrumbTracker.cs | 39 + .../RynthCore.Plugin.RynthAi/NavRecovery.cs | 180 +++- .../NavigationEngine.cs | 261 +++++- .../RynthCore.Plugin.RynthAi/OutdoorHunt.cs | 133 ++- .../RynthCore.Plugin.RynthAi/PlacedSolid.cs | 734 +++++++++++++++ .../Raycasting/BoundingVolume.cs | 3 + .../Raycasting/DungeonLOS.cs | 7 + .../Raycasting/GeometryLoader.cs | 887 ++++++++++++++---- .../Raycasting/LandblockStructs.cs | 105 ++- .../Raycasting/TargetingFSM.cs | 48 + .../RynthAiCommands.cs | 139 ++- .../RynthAiPlugin.BoostLootFirst.cs | 36 + .../RynthAiPlugin.ChestLoot.cs | 10 +- .../RynthAiPlugin.CorpseBehindWall.cs | 82 ++ .../RynthAiPlugin.Dashboard.cs | 1 + .../RynthAiPlugin.DataFolders.cs | 2 + .../RynthAiPlugin.DeathWait.cs | 63 ++ .../RynthAiPlugin.DirtyFighting.cs | 3 +- .../RynthAiPlugin.DunExplore.cs | 10 +- .../RynthAiPlugin.HuntFence.cs | 153 +++ .../RynthAiPlugin.Kits.cs | 422 +++++++++ .../RynthAiPlugin.LootPerDay.cs | 251 +++++ .../RynthAiPlugin.LowComponents.cs | 2 +- .../RynthAiPlugin.MacroStopWho.cs | 46 + .../RynthAiPlugin.OutdoorHunt.cs | 60 +- .../RynthAiPlugin.PetElement.cs | 70 ++ .../RynthAiPlugin.RareCorpses.cs | 38 + .../RynthAiPlugin.Safety.cs | 6 +- .../RynthAiPlugin.TimedCommands.cs | 3 +- .../RynthAiPlugin.VTankHotkeys.cs | 29 + .../RynthAiPlugin.VTankYield.cs | 2 +- .../RynthCore.Plugin.RynthAi/RynthAiPlugin.cs | 46 +- .../ScriptInterface.cs | 117 ++- .../RynthCore.Plugin.RynthAi/VTankYield.cs | 2 +- .../RynthCore.Plugin.RynthChat/ChatBuffer.cs | 96 +- .../ChatClassifier.cs | 41 + .../PluginExports.cs | 13 + .../RynthChatPlugin.cs | 4 +- .../RynthCore.Plugin.RynthNav/AutoRunGate.cs | 3 + Plugins/RynthCore.Plugin.RynthNav/Entrance.cs | 6 +- .../RynthCore.Plugin.RynthNav/NavCoarse.cs | 8 +- .../RynthCore.Plugin.RynthNav/NavPathQuery.cs | 97 +- Plugins/RynthCore.Plugin.RynthNav/RealWalk.cs | 96 ++ .../RecallPlanner.cs | 8 +- .../RynthNavPlugin.Avoid.cs | 4 +- .../RynthNavPlugin.Blocked.cs | 7 +- .../RynthNavPlugin.Panel.cs | 17 +- .../RynthNavPlugin.PathApi.cs | 2 +- .../RynthNavPlugin.Pause.cs | 79 ++ .../RynthNavPlugin.PortalAim.cs | 21 +- .../RynthNavPlugin.Settle.cs | 9 + .../RynthNavPlugin.TownNet.cs | 30 +- .../RynthNavPlugin.Travel.cs | 45 +- .../RynthNavPlugin.TripTime.cs | 104 ++ .../RynthNavPlugin.Ways.cs | 411 ++++++++ .../RynthNavPlugin.cs | 176 +++- Plugins/RynthCore.Plugin.RynthNav/TownNet.cs | 37 +- .../RynthCore.Plugin.RynthNav/TravelPlan.cs | 57 +- .../RynthCore.Plugin.RynthNav/TripClock.cs | 111 +++ .../RynthNetPlugin.cs | 37 +- .../Transport/FlapBackoff.cs | 19 + .../Transport/NetNode.cs | 20 + Plugins/Shared/EngineServerState.cs | 58 ++ Plugins/Shared/RynthServerProfileApi.cs | 8 + Plugins/Shared/RynthUi/RynthIcons.cs | 2 + .../Editing/LootEditSession.cs | 11 +- .../RynthCore.LootSdk/Editing/LootEditWire.cs | 19 +- Shared/RynthCore.LootSdk/LootModel.cs | 8 +- Shared/RynthCore.LootSdk/LootPerDay.cs | 60 ++ .../VTank/VTankLootParser.cs | 43 +- .../VTank/VTankLootProfile.cs | 8 + .../VTank/VTankLootWriter.cs | 30 + Tools/RynthCore.LootEditor/MainViewModel.cs | 3 + .../RynthCore.LootSdkTests/LootPerDayTests.cs | 301 ++++++ Tools/RynthCore.LootSdkTests/Program.cs | 1 + Tools/RynthCore.LosProof/Program.cs | 93 +- Tools/RynthCore.RynthAiHostTests/Program.cs | 17 + .../Tests/AmmoTests.cs | 38 +- .../Tests/BlankLoadTests.cs | 85 ++ .../Tests/BlockedDoorwayTests.cs | 30 +- .../Tests/BuffChainTests.cs | 191 ++++ .../Tests/BuildingFurnitureTests.cs | 499 ++++++++++ .../Tests/ChestLootTests.cs | 22 + .../Tests/CommandReplyTests.cs | 15 + .../Tests/DebuffPassTests.cs | 403 ++++++++ .../Tests/HandSwapTests.cs | 43 + .../Tests/HealGraceTests.cs | 9 +- .../Tests/HealUpSpeedTests.cs | 252 +++++ .../Tests/HuntBuildingTests.cs | 81 ++ .../Tests/JumpDownTests.cs | 230 +++++ .../Tests/KitAutoPluginTests.cs | 339 +++++++ .../Tests/KitRunnerTests.cs | 447 +++++++++ .../Tests/LootCorpseTests.cs | 118 ++- .../Tests/LootPerDayTests.cs | 367 ++++++++ .../Tests/LootProfilePickerTests.cs | 148 +++ .../Tests/LootSalvageTests.cs | 13 +- .../Tests/MacroStopSourceTests.cs | 70 ++ .../Tests/NavEngineTests.cs | 19 + .../Tests/NavJumpStepTests.cs | 138 +++ .../Tests/ObstacleMergeTests.cs | 80 ++ .../Tests/OutdoorHuntTests.cs | 266 ++++++ .../Tests/PetElementTests.cs | 383 ++++++++ .../Tests/PlacedBandTests.cs | 284 ++++++ .../Tests/PlacedObjectTests.cs | 156 +++ .../Tests/PlannerObjectTests.cs | 619 ++++++++++++ .../Tests/RebuffWhenIdleTests.cs | 102 +- .../Tests/StaticCollisionTests.cs | 352 +++++++ .../Tests/StraightenTests.cs | 54 ++ .../Tests/StuckLogAndCornerTests.cs | 616 ++++++++++++ .../Tests/TargetingTests.cs | 56 ++ .../Tests/UseRefusalTests.cs | 72 ++ .../Tests/VTankHotkeyTests.cs | 2 +- .../Tests/VitalWandGateTests.cs | 45 +- .../Tests/VitalsTests.cs | 55 +- Tools/RynthCore.RynthAiTests/Program.cs | 3 + .../RynthCore.RynthAiTests.csproj | 10 + .../Tests/ChatClassifierTests.cs | 112 +++ .../Tests/DirtyFightingHeightTests.cs | 29 +- .../Tests/KitAutoTests.cs | 330 +++++++ .../Tests/KitPlannerTests.cs | 192 ++++ .../Tests/NavFolderTests.cs | 228 +++++ .../Tests/NavFormatTests.cs | 9 +- Tools/RynthNav.GraphTests/PortalFloorTests.cs | 71 ++ Tools/RynthNav.GraphTests/Program.cs | 56 ++ Tools/RynthNav.PortalGraph/PortalRoute.cs | 833 ++++++++++++---- Tools/RynthNav.RouteTests/ArrivalTests.cs | 101 ++ Tools/RynthNav.RouteTests/Program.cs | 4 + Tools/RynthNav.RouteTests/RealWalkTests.cs | 171 ++++ .../RynthNav.RouteTests.csproj | 1 + Tools/RynthNav.RouteTests/TripTimeTests.cs | 116 +++ Tools/RynthNav.RouteTests/WaysTests.cs | 239 +++++ Tools/RynthNet.Tests/FlapTests.cs | 20 + Tools/RynthNet.Tests/Program.cs | 1 + Tools/RynthNet.Tests/RynthNet.Tests.csproj | 1 + 196 files changed, 21073 insertions(+), 1028 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.HealAnimationCap.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.DebuffPass.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/DebuffPass.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Combat/PetElements.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/DungeonPathfinder.Jumps.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavFileList.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/LegacyUi/StrayNavs.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/LootPerDayStore.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Loot/LootProfileList.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.RaNav.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitAuto.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitPlanner.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitRunner.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/PlacedSolid.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.BoostLootFirst.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.CorpseBehindWall.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HuntFence.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Kits.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootPerDay.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MacroStopWho.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PetElement.cs create mode 100644 Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.RareCorpses.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RealWalk.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Pause.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TripTime.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Ways.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNav/TripClock.cs create mode 100644 Plugins/RynthCore.Plugin.RynthNet/Transport/FlapBackoff.cs create mode 100644 Shared/RynthCore.LootSdk/LootPerDay.cs create mode 100644 Tools/RynthCore.LootSdkTests/LootPerDayTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/BuildingFurnitureTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/DebuffPassTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/HealUpSpeedTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/JumpDownTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/KitAutoPluginTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/KitRunnerTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/LootPerDayTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/LootProfilePickerTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/MacroStopSourceTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/NavJumpStepTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/ObstacleMergeTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/PetElementTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/PlacedBandTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/PlacedObjectTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/PlannerObjectTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/StaticCollisionTests.cs create mode 100644 Tools/RynthCore.RynthAiHostTests/Tests/StuckLogAndCornerTests.cs create mode 100644 Tools/RynthCore.RynthAiTests/Tests/KitAutoTests.cs create mode 100644 Tools/RynthCore.RynthAiTests/Tests/KitPlannerTests.cs create mode 100644 Tools/RynthCore.RynthAiTests/Tests/NavFolderTests.cs create mode 100644 Tools/RynthNav.GraphTests/PortalFloorTests.cs create mode 100644 Tools/RynthNav.RouteTests/ArrivalTests.cs create mode 100644 Tools/RynthNav.RouteTests/RealWalkTests.cs create mode 100644 Tools/RynthNav.RouteTests/TripTimeTests.cs create mode 100644 Tools/RynthNav.RouteTests/WaysTests.cs create mode 100644 Tools/RynthNet.Tests/FlapTests.cs 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 skill, int floorPercent) + { + var rows = new List(); + foreach (var r in recipes) + { + var row = new KitPlanRow { Recipe = r, CanMake = CanMake(r, pack) }; + foreach (var p in r.Ingredients()) row.Parts.Add((p, Count(p, pack))); + foreach (var st in r.Steps) + { + int pct = StepPercent(st, skill); + row.Chances.Add(new KitStepChance(st, pct, pct >= 0 && pct < floorPercent)); + } + var next = Next(r, pack, skill, floorPercent); + row.Blocked = next.Step == null ? next.Why : string.Empty; + rows.Add(row); + } + return rows; + } + + /// + /// The next combine for : the kit itself when its two parts are carried, else + /// the earlier step that makes the missing part. Nothing is combined that the kit can't use (no + /// herbs without bandages), and nothing when a step it needs is under the floor, untrained, or + /// its chance can't be read with a floor set. + /// + public static KitNext Next(KitRecipe r, IReadOnlyList pack, Func skill, int floorPercent) + => Next(r, r.Final, pack, skill, Math.Clamp(floorPercent, 0, 100), 0); + + private static KitNext Next(KitRecipe r, KitCombine step, IReadOnlyList pack, Func skill, int floor, int depth) + { + if (Makeable(r, step, pack) <= 0) + return KitNext.None("out of " + Missing(r, step, pack)); + + var s = skill(step.SkillId); + string skillName = SkillName(step.SkillId); + if (s.Known && !s.Trained) + return KitNext.None($"{skillName} isn't trained (the server refuses the combine)"); + int pct = s.Known ? Percent(s.Buffed, step.Difficulty) : -1; + if (pct < 0 && floor > 0) + return KitNext.None($"can't read your {skillName} skill to check the {floor}% floor (set Min chance to 0 to go without it)"); + if (pct >= 0 && pct < floor) + return KitNext.None($"{step.Label}: {pct}% at {skillName} {s.Buffed} is under your {floor}% floor"); + + int src = FirstStack(step.Source, pack), tgt = FirstStack(step.Target, pack); + if (src != 0 && tgt != 0) + return new KitNext(step, src, tgt, pct, string.Empty); + + // A part has to be made first. + var missing = src == 0 ? step.Source : step.Target; + var producer = depth < 8 ? r.Producer(missing) : null; + if (producer == null) return KitNext.None("out of " + missing.Name); + return Next(r, producer, pack, skill, floor, depth + 1); + } + + /// The first item that runs out for a step (an ingredient you carry, not a part made on the way). + private static string Missing(KitRecipe r, KitCombine step, IReadOnlyList pack, int depth = 0) + { + foreach (var part in new[] { step.Source, step.Target }) + { + if (Available(r, part, pack, depth) > 0) continue; + var producer = depth < 8 ? r.Producer(part) : null; + return producer == null ? part.Name : Missing(r, producer, pack, depth + 1); + } + return step.Source.Name; + } + + // ── Text ──────────────────────────────────────────────────────────────── + + /// "Soft Bandages 3, Treated Hyssop 5, ..." (what the pack holds for a row). + public static string PartsText(KitPlanRow row) + => string.Join(", ", row.Parts.Select(p => $"{p.Part.Name} {p.Count}")); + + /// "Combine the herbs 99%, Pack the kit 95%" ("?" when the skill can't be read). + public static string ChancesText(KitPlanRow row) + => string.Join(", ", row.Chances.Select(c => $"{c.Step.Label} {(c.Percent >= 0 ? c.Percent + "%" : "?")}")); + + /// One chat line for a row (/ra kits). + public static string Line(KitPlanRow row) + { + string make = row.CanMake == 1 ? "1 kit" : $"{row.CanMake} kits"; + string tail = row.Blocked.Length > 0 && row.CanMake > 0 ? $" - can't start: {row.Blocked}" : ""; + return $"{row.Recipe.Name}: {make} ({PartsText(row)}; chance {ChancesText(row)}){tail}"; + } + + /// The run's closing line. + public static string Summary(string kitName, int made, int failed, IReadOnlyDictionary lost, string why) + { + string madeText = made == 1 ? $"made 1 {kitName}" : $"made {made} {kitName}s"; + string failText = failed == 0 ? "no combine failed" + : (failed == 1 ? "1 combine failed" : $"{failed} combines failed") + + (lost.Count > 0 ? " (lost " + string.Join(", ", lost.Select(kv => $"{kv.Value} {kv.Key}")) + ")" : ""); + return $"{madeText}, {failText}. Stopped: {why}."; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitRunner.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitRunner.cs new file mode 100644 index 0000000..9f67738 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/Crafting/KitRunner.cs @@ -0,0 +1,475 @@ +// KitRunner.cs - "Make kits" (the Crafting tab's Kits sub-tab, /ra kits): makes Plentiful Healing +// Kits from their ingredients, one combine at a time. KitPlanner picks each combine from a fresh +// look at the pack; this does it and waits for the server. +// +// Pump thread only (the tab's Render reads the volatile snapshots and posts Start/Stop). +// Only while the macro is OFF: Start refuses with the macro on, and turning it on stops the run +// (the macro's own heals, buffs and fights would race the combines). Each step: +// 1. stop checks: the macro turned on, out of peace mode, health dropped (something hit you), or +// the character moved from where the run started; +// 2. gates: not busy, ActionPacer; +// 3. KitPlanner.Next over the pack (the floor: Min chance %, checked ahead from the buffed skill); +// 4. arm the engine's one-shot answer for AC's chance prompt (v85: Yes at the floor, else No; +// it goes before the Auto-confirm crafting arm) and UseObjectOn(source, target); +// 5. wait for the result: the recipe's chat line, the product showing up or the parts going, a +// declined prompt, "cannot be used on", or a WeenieError (YoureTooBusy retries). +// The server only asks when the character option "show the chance of success dialog" is on; +// without it the combine just happens, so the floor is checked here first, every step. +// Ends with one plain chat line: made, failed, lost, and why it stopped. +// +// "Make kits when low" (KitAuto, RynthAiPlugin.Kits.cs) starts runs with StartAuto: the same +// combines, only while the macro is ON (it holds the bot meanwhile); the macro turning off stops it, +// AC's own craft dialog stops it (nobody is there to click), and each stop says what kind it was +// (KitStopKind) so the waits after it follow. Start (the button, /ra kits make) is unchanged. +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting; + +internal sealed class KitRunner +{ + private const uint ErrorYoureTooBusy = 0x1D; + private const long StepTimeoutMs = 15_000; + /// The player answers AC's own dialog: give them time. + private const long ManualTimeoutMs = 60_000; + private const long RetryDelayMs = 1_500; + private const long StepGapMs = 600; + /// After the parts went, how long to wait for the product (or the result line) before calling it a failure. + private const long ProductGraceMs = 1_500; + private const int MaxRetries = 3; + /// Moving more than this from the start (same cell) stops the run. + public const float MoveTolerance = 1.5f; + /// The plan the tab shows is refreshed this often while the tab is drawn. + private const long PlanRefreshMs = 1_000; + private const long ViewedWindowMs = 2_500; + + private readonly MiniRemoteContext _ctx; + private readonly IReadOnlyList _recipes; + + // Job (pump thread) + private KitRecipe? _recipe; + private int _limit; + private int _made, _failed, _retries; + private readonly Dictionary _lost = new(StringComparer.Ordinal); + private bool _waiting, _manual; + private KitCombine? _step; + private int _confSeq, _errSeq; + private long _stepAt, _nextAt, _partsGoneAt; + private int _srcBefore, _tgtBefore, _productBefore; + private bool _havePose; + private uint _startCell; + private float _startX, _startY, _startZ; + private uint _startHealth; + /// A "Make kits when low" run (StartAuto); its end goes to . + private bool _auto; + private Func? _autoEnded; + + // Render snapshots + private volatile bool _active; + private volatile string _status = "idle"; + private volatile string _lastSummary = string.Empty; + private volatile KitPlanRow[] _plan = Array.Empty(); + private long _planAt = long.MinValue / 2; + private long _viewedAt = long.MinValue / 2; + + public KitRunner(MiniRemoteContext ctx, IReadOnlyList? recipes = null) + { + _ctx = ctx; + _recipes = recipes ?? KitPlanner.Retail; + } + + public bool Running => _active; + public string Status => _status; + /// The last run's closing line ("" before one ends). + public string LastSummary => _lastSummary; + /// What the pack makes (refreshed while the tab is drawn, and by /ra kits). + public KitPlanRow[] Plan => _plan; + public IReadOnlyList Recipes => _recipes; + public KitRecipe? Recipe => _recipe; + public int MadeCount => _made; + public int FailedCount => _failed; + /// The run going was started by "Make kits when low" (StartAuto). + public bool Auto => _active && _auto; + /// The run's count (0 = as many as the pack makes). + public int Limit => _limit; + /// How the last run ended. + public KitStopKind LastStopKind { get; private set; } = KitStopKind.Other; + + private RynthCoreHost Host => _ctx.Host; + private MiniRemoteInventory Inv => _ctx.Inventory; + private CraftingTabState C => _ctx.State.Crafting; + public int Floor => Math.Clamp(C.KitMinChancePercent, 0, 100); + + /// The tab was drawn (render thread): keep the plan fresh. + public void MarkViewed(long nowMs) => System.Threading.Volatile.Write(ref _viewedAt, nowMs); + + // ── Pack and skill ────────────────────────────────────────────────────── + + /// The pack's stacks of anything a recipe uses or makes (equipped items left out). + public List Pack() + { + var wanted = new HashSet(); + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var r in _recipes) + foreach (var st in r.Steps) + foreach (var p in new[] { st.Source, st.Target, st.Product }) + { + wanted.Add(p.Wcid); + names.Add(p.Name); + } + var list = new List(); + foreach (var wo in Inv.Items()) + { + string name = wo.Name ?? string.Empty; + uint wcid = Inv.Wcid(wo); + if (wcid != 0 ? !wanted.Contains(wcid) : !names.Contains(name)) continue; + if (Inv.IsEquipped(wo)) continue; + list.Add(new KitStack(wo.Id, wcid, name, Inv.StackSize(wo))); + } + return list; + } + + /// The player's buffed skill and training (Unknown when the engine can't read it). + public KitSkill Skill(int skillId) + { + if (!Host.HasGetObjectSkill) return KitSkill.Unknown; + if (!Host.TryGetObjectSkill(Inv.PlayerId, unchecked((uint)skillId), out int buffed, out int training)) return KitSkill.Unknown; + // The engine reads 0 for a trained skill before the qualities arrive: unknown, not "can't". + if (training >= 2 && buffed <= 0) return KitSkill.Unknown; + return new KitSkill(true, buffed, training); + } + + /// Re-reads the pack into (pump thread). + public KitPlanRow[] RefreshPlan() + { + var rows = KitPlanner.Plan(_recipes, Pack(), Skill, Floor).ToArray(); + _plan = rows; + _planAt = Environment.TickCount64; + return rows; + } + + public KitRecipe? Find(string? id) + { + if (string.IsNullOrWhiteSpace(id)) return _recipes.FirstOrDefault(); + string t = id.Trim(); + return _recipes.FirstOrDefault(r => r.Id.Equals(t, StringComparison.OrdinalIgnoreCase) + || r.Name.Equals(t, StringComparison.OrdinalIgnoreCase)); + } + + // ── Job control ───────────────────────────────────────────────────────── + + /// + /// Why a run can't start now ("" when it can): the macro is on, not in the world, not in + /// peace mode, or the pack makes none. + /// + public string CanStart(KitRecipe recipe) + { + if (Running) return "a kit run is already going (Stop it first)"; + var s = _ctx.Settings; + if (s == null) return "not ready yet (log in first)"; + if (s.IsMacroRunning) return "turn the macro off first (kits are made only while it is off)"; + if (Inv.PlayerId == 0) return "not in the world yet"; + if (!Inv.InPeaceMode) return "go to peace mode first"; + var next = KitPlanner.Next(recipe, Pack(), Skill, Floor); + return next.Step == null ? next.Why : string.Empty; + } + + /// Starts making (limit 0 = as many as the pack makes). Returns "" or why not. Pump thread. + public string Start(KitRecipe recipe, int limit) + { + string why = CanStart(recipe); + if (why.Length > 0) { _status = why; return why; } + Begin(recipe, limit, auto: false, ended: null); + return string.Empty; + } + + /// + /// Why a "when low" run can't start now ("" when it can): another run is going, the macro is off, + /// not in the world, not in peace mode, or the pack makes none at the floor. + /// + public string CanStartAuto(KitRecipe recipe) + { + if (Running) return "a kit run is already going"; + var s = _ctx.Settings; + if (s == null) return "not ready yet (log in first)"; + if (!s.IsMacroRunning) return "the macro is off"; + if (Inv.PlayerId == 0) return "not in the world yet"; + if (!Inv.InPeaceMode) return "not in peace mode"; + var next = KitPlanner.Next(recipe, Pack(), Skill, Floor); + return next.Step == null ? next.Why : string.Empty; + } + + /// + /// "Make kits when low": starts a run with the macro on (up to kits). + /// hears how it ended and the kits made, and returns what the summary + /// line adds (the next try). Returns "" or why not. Pump thread. + /// + public string StartAuto(KitRecipe recipe, int limit, Func? ended) + { + string why = CanStartAuto(recipe); + if (why.Length > 0) return why; + Begin(recipe, limit, auto: true, ended: ended); + return string.Empty; + } + + private void Begin(KitRecipe recipe, int limit, bool auto, Func? ended) + { + _auto = auto; + _autoEnded = ended; + _recipe = recipe; + _limit = Math.Max(0, limit); + _made = _failed = _retries = 0; + _lineOwedUntil = 0; + _lost.Clear(); + _waiting = false; + _nextAt = 0; + _havePose = Host.TryGetPlayerPose(out _startCell, out _startX, out _startY, out _startZ, out _, out _, out _, out _); + _startHealth = Inv.PlayerHealth().Cur; + _active = true; + int can = KitPlanner.CanMake(recipe, Pack()); + int target = _limit > 0 ? Math.Min(_limit, can) : can; + _status = $"making {target} {recipe.Name}(s)" + (auto ? " (Make kits when low)" : ""); + RynthLog.Write(LogCat.Crafting, $"[Kits] start{(auto ? " (when low)" : "")}: {recipe.Name}, up to {target} (pack makes {can}), floor {Floor}%"); + } + + /// + /// Ends the run and prints the summary (pump thread). No-op when idle. : + /// how it ended (the player's Stop unless said), for the "when low" waits. + /// + public void Stop(string why, KitStopKind kind = KitStopKind.User) + { + if (!_active) { _status = why; return; } + if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + _waiting = false; + _active = false; + LastStopKind = kind; + bool auto = _auto; + var ended = _autoEnded; + _auto = false; + _autoEnded = null; + string tail = string.Empty; + if (auto && ended != null) + { + try { tail = ended(kind, _made) ?? string.Empty; } + catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "Make kits when low: the end of a run"); } + } + string name = _recipe?.Name ?? "kit"; + string line = KitPlanner.Summary(name, _made, _failed, _lost, why) + tail; + _lastSummary = line; + _status = "idle - " + why; + _ctx.Chat((auto ? "[RynthAi] Make kits when low: " : "[RynthAi] Make kits: ") + line); + RynthLog.Write(LogCat.Crafting, "[Kits] " + (auto ? "(when low) " : "") + line); + RefreshPlan(); + } + + public void OnLogout() + { + Stop("logged out", KitStopKind.Other); + _plan = Array.Empty(); + _status = "idle"; + } + + // ── Tick (pump thread) ────────────────────────────────────────────────── + + /// The last tick's clock (the result handlers time the next step from it). + private long _now; + + public void Tick(long nowMs) + { + _now = nowMs; + if (!Running) + { + long viewed = System.Threading.Volatile.Read(ref _viewedAt); + if (nowMs - viewed < ViewedWindowMs && nowMs - _planAt >= PlanRefreshMs) RefreshPlan(); + return; + } + + var (stop, stopKind) = StopReason(); + if (stop.Length > 0) { Stop(stop, stopKind); return; } + + if (_waiting) { Wait(nowMs); return; } + if (nowMs < _nextAt) return; + if (Inv.IsBusy) return; + if (!ActionPacer.MayStart(Host, "Kits", HealNeed.None, out string pace)) { _status = "waiting: " + pace; return; } + + var recipe = _recipe!; + if (_limit > 0 && _made >= _limit) { Stop($"made the {_limit} asked for", KitStopKind.Finished); return; } + + var pack = Pack(); + var next = KitPlanner.Next(recipe, pack, Skill, Floor); + if (next.Step == null) { Stop(next.Why, KitStopKind.Finished); return; } + var step = next.Step; + + int floor = Floor; + _manual = !(Host.HasConfirmationAnswers + && Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, floor, (int)StepTimeoutMs) == 1); + _confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0; + _errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0; + _srcBefore = KitPlanner.Count(step.Source, pack); + _tgtBefore = KitPlanner.Count(step.Target, pack); + _productBefore = KitPlanner.Count(step.Product, pack); + + string pct = next.Percent >= 0 ? $" ~{next.Percent}%" : ""; + if (!Host.UseOnFor(unchecked((uint)next.SourceId), unchecked((uint)next.TargetId), "Kits", + $"{step.Label}: {step.Source.Name} on {step.Target.Name}{pct}" + (_auto ? " (Make kits when low)" : ""), + _auto ? UseKind.Auto : UseKind.Asked)) + { + if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0); + Retry(nowMs, "the use request didn't go out"); + return; + } + _step = step; + _waiting = true; + _stepAt = nowMs; + _partsGoneAt = 0; + string ask = _manual && !_auto ? " - click Yes if AC asks" : ""; + _status = $"{step.Label}{pct} ({_made} made){ask}"; + } + + /// + /// Why the run must stop now ("" to go on), and what kind of stop: the macro (on for a run by + /// hand, off for a "when low" one), combat mode, damage, moving. + /// + private (string Why, KitStopKind Kind) StopReason() + { + var s = _ctx.Settings; + if (s == null) return ("settings went away", KitStopKind.Other); + if (_auto) + { + if (!s.IsMacroRunning) return ("the macro turned off", KitStopKind.MacroOff); + } + else if (s.IsMacroRunning) return ("the macro turned on", KitStopKind.Other); + if (!Inv.InPeaceMode) return ("you left peace mode", KitStopKind.Danger); + uint hp = Inv.PlayerHealth().Cur; + if (_startHealth > 0 && hp > 0 && hp < _startHealth) return ("you took damage", KitStopKind.Danger); + if (hp > _startHealth) _startHealth = hp; // healed up: the new level is the line + if (_havePose && Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _)) + { + float dx = x - _startX, dy = y - _startY, dz = z - _startZ; + if (cell != _startCell || dx * dx + dy * dy + dz * dz > MoveTolerance * MoveTolerance) return ("you moved", KitStopKind.Danger); + } + return (string.Empty, KitStopKind.Other); + } + + private void Retry(long nowMs, string why) + { + _waiting = false; + if (++_retries > MaxRetries) { Stop("gave up: " + why, KitStopKind.Refused); return; } + _nextAt = nowMs + RetryDelayMs; + _status = $"{why} - retrying ({_retries}/{MaxRetries})"; + } + + /// A result the counts showed before its chat line: that line, when it comes, is the old step's. + private const long LineOwedMs = 3_000; + private long _lineOwedUntil; + + private void Succeeded(bool byLine) + { + var step = _step!; + _lineOwedUntil = byLine ? 0 : _now + LineOwedMs; + _waiting = false; + _retries = 0; + _nextAt = _now + StepGapMs; + bool kit = ReferenceEquals(step, _recipe!.Final); + if (kit) _made++; + _status = kit ? $"made {_made} {_recipe.Name}(s)" : $"{step.Product.Name} made"; + RynthLog.Write(LogCat.Crafting, $"[Kits] {step.Label}: ok ({_made} made)"); + } + + private void Failed(bool byLine) + { + var step = _step!; + _lineOwedUntil = byLine ? 0 : _now + LineOwedMs; + _waiting = false; + _retries = 0; + _nextAt = _now + StepGapMs; + _failed++; + foreach (var p in new[] { step.Source, step.Target }) + _lost[p.Name] = (_lost.TryGetValue(p.Name, out int n) ? n : 0) + 1; + _status = $"{step.Label} failed ({_failed} failed so far)"; + RynthLog.Write(LogCat.Crafting, $"[Kits] {step.Label}: failed, lost 1 {step.Source.Name} + 1 {step.Target.Name}"); + } + + private void Wait(long nowMs) + { + var step = _step!; + // Engine answer: a No (the server's own percent under the floor) uses nothing. + if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _) + && seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction) + { + _confSeq = seq; + if (outcome == RynthCoreHost.ConfirmationOutcome.Declined) + { + _waiting = false; + Stop($"the server's chance for {step.Label} is {pct}%, under your {Floor}% floor", KitStopKind.Refused); + return; + } + if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed) + { + if (_auto) + { + // Nobody is there to click it: a "when low" run never waits on AC's dialog. + _waiting = false; + Stop("AC's craft dialog came up and needs a click (Yes makes this one)", KitStopKind.Refused); + return; + } + _manual = true; + _status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})"; + } + } + + if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq) + { + _errSeq = es; + if (error == ErrorYoureTooBusy) { Retry(nowMs, "server says busy"); return; } + _waiting = false; + Stop($"the server refused {step.Label} (error 0x{error:X})", KitStopKind.Refused); + return; + } + + // Counts: the product showing up is a success; both parts going without it is a failure. + var pack = Pack(); + if (KitPlanner.Count(step.Product, pack) > _productBefore) { Succeeded(byLine: false); return; } + bool partsGone = KitPlanner.Count(step.Source, pack) < _srcBefore && KitPlanner.Count(step.Target, pack) < _tgtBefore; + if (partsGone) + { + if (_partsGoneAt == 0) _partsGoneAt = nowMs; + else if (nowMs - _partsGoneAt >= ProductGraceMs) { Failed(byLine: false); return; } + } + + // A "when low" run has no one to answer AC's dialog: the plain timeout, then retries. + bool waitForPlayer = _manual && !_auto; + if (nowMs - _stepAt > (waitForPlayer ? ManualTimeoutMs : StepTimeoutMs)) + { + if (waitForPlayer) { _waiting = false; Stop("no answer to AC's craft dialog", KitStopKind.Refused); } + else Retry(nowMs, "no result from the server"); + } + } + + /// The recipe's result lines and "cannot be used on" (never hidden). + public void OnChat(string text) + { + if (!_active || string.IsNullOrEmpty(text)) return; + string t = text.Trim(); + if (_lineOwedUntil != 0 && IsResultLine(t)) + { + bool owed = _now < _lineOwedUntil; + _lineOwedUntil = 0; + if (owed) return; // the step the counts already finished + } + if (!_waiting || _step == null) return; + if (t.Equals(_step.SuccessText, StringComparison.Ordinal)) { Succeeded(byLine: true); return; } + if (t.Equals(_step.FailText, StringComparison.Ordinal)) { Failed(byLine: true); return; } + if (t.StartsWith("The ", StringComparison.Ordinal) && t.Contains(" cannot be used on the ", StringComparison.Ordinal)) + { + _waiting = false; + Stop($"this server has no such recipe ({_step.Source.Name} on {_step.Target.Name})", KitStopKind.Refused); + } + } + + private bool IsResultLine(string t) + => _recipe != null && _recipe.Steps.Any(st => t.Equals(st.SuccessText, StringComparison.Ordinal) || t.Equals(st.FailText, StringComparison.Ordinal)); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/CraftingTab.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/CraftingTab.cs index 1330cc6..cab748c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/CraftingTab.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/CraftingTab.cs @@ -12,6 +12,10 @@ // One TinkerRunner works one tab's scan at a time. // Above the benches: "Auto-confirm crafting" (CraftAutoConfirm), Yes to the server's chance prompt // at the chosen percent for crafts the player starts by hand. +// The Kits sub-tab: "Make kits" (KitRunner / KitPlanner) makes Plentiful Healing Kits from their +// ingredients, one combine at a time, only while the macro is off (also /ra kits). Under it, +// "Make kits when low" (KitAuto; the macro side is RynthAiPlugin.Kits.cs) does the same by itself +// while the macro runs, when the kits carried fall under the line and nothing is around. using System; using System.Collections.Generic; using System.Linq; @@ -31,6 +35,17 @@ internal sealed class CraftingTab /// Auto-confirm crafting (the sticky engine answer for hand-made crafts). public CraftAutoConfirm AutoConfirm { get; } + /// Make kits (the Kits sub-tab, /ra kits). + public KitRunner Kits { get; } + + /// Make kits when low: when a run may start with the macro on, and the waits (ticked by RynthAiPlugin.Kits.cs). + public KitAuto AutoKits { get; } + + /// A command asked for the Kits sub-tab (the next frame selects it). + private volatile bool _selectKits; + public void SelectKitsTab() => _selectKits = true; + private static readonly byte[] KitsTabLabel = System.Text.Encoding.UTF8.GetBytes("Kits\0"); + // Custom-row editor (render thread only) private int _newMaterial = TinkerCatalog.Steel; private int _newKind; @@ -45,6 +60,8 @@ internal sealed class CraftingTab _ctx = ctx; Runner = new TinkerRunner(ctx, RowsFor, SettingsFor); AutoConfirm = new CraftAutoConfirm(() => ctx.Host, () => ctx.Settings, ctx.Chat); + Kits = new KitRunner(ctx); + AutoKits = new KitAuto { Say = ctx.Chat }; } private CraftingTabState C => _ctx.State.Crafting; @@ -88,13 +105,20 @@ internal sealed class CraftingTab { Runner.Tick(nowMs); AutoConfirm.Tick(nowMs); + Kits.Tick(nowMs); } - public void OnChat(string text) => Runner.OnChat(text); + public void OnChat(string text) + { + Runner.OnChat(text); + Kits.OnChat(text); + } public void OnLogout() { Runner.OnLogout(); + Kits.OnLogout(); + AutoKits.Reset(); AutoConfirm.Release(); } @@ -119,9 +143,185 @@ internal sealed class CraftingTab if (ImGui.BeginTabItem("Jewelry")) { RenderBench(TinkerBench.Jewelry); ImGui.EndTabItem(); } if (ImGui.BeginTabItem("Trinkets")) { RenderBench(TinkerBench.Trinkets); ImGui.EndTabItem(); } if (ImGui.BeginTabItem("Items")) { RenderBench(TinkerBench.Items); ImGui.EndTabItem(); } + bool selectKits = _selectKits; + _selectKits = false; + if (BeginTab(KitsTabLabel, selectKits ? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None)) { RenderKits(); ImGui.EndTabItem(); } ImGui.EndTabBar(); } + /// BeginTabItem with flags and no close button (ImGui.NET only wraps flags with p_open). + private static unsafe bool BeginTab(byte[] labelUtf8Z, ImGuiTabItemFlags flags) + { + fixed (byte* label = labelUtf8Z) + return ImGuiNative.igBeginTabItem(label, null, flags) != 0; + } + + // ── Kits (render thread) ──────────────────────────────────────────────── + + /// The Kits sub-tab: what the pack makes, the floor and count, Make kits / Stop. + private void RenderKits() + { + var k = Kits; + k.MarkViewed(MiniRemoteContext.NowMs); + SafeImGui.TextWrapped("Makes kits from their ingredients, one combine at a time, waiting for each result. " + + "Every combine uses your Healing skill and can fail: a failure destroys one of each item. " + + "Runs only while the macro is off, and stops if you move, leave peace mode or take damage."); + ImGui.Spacing(); + + int floor = Math.Clamp(C.KitMinChancePercent, 0, 100); + ImGui.SetNextItemWidth(90); + if (ImGui.InputInt("Min chance %##kitfloor", ref floor, 5)) + { + int value = Math.Clamp(floor, 0, 100); + _ctx.Post(() => C.KitMinChancePercent = value); + } + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("Never try a combine whose chance is under this (0 = any chance).\n" + + "Worked out from your buffed Healing skill before every combine; when AC asks,\n" + + "RynthAi also says No to a lower server percent. Also /ra kits floor <0-100>."); + ImGui.SameLine(); + int count = Math.Max(0, C.KitMakeCount); + ImGui.SetNextItemWidth(90); + if (ImGui.InputInt("Kits to make##kitcount", ref count, 1)) + { + int value = Math.Clamp(count, 0, 1000); + _ctx.Post(() => C.KitMakeCount = value); + } + if (ImGui.IsItemHovered()) ImGui.SetTooltip("How many kits one run makes (0 = as many as the pack makes)."); + + var plan = k.Plan; + if (plan.Length == 0) + { + SafeImGui.TextDisabled("Reading your pack..."); + } + else if (ImGui.BeginTable("##kits", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp)) + { + ImGui.TableSetupColumn("Kit", ImGuiTableColumnFlags.WidthFixed, 150); + ImGui.TableSetupColumn("Can make", ImGuiTableColumnFlags.WidthFixed, 65); + ImGui.TableSetupColumn("In your pack"); + ImGui.TableSetupColumn("Chance"); + ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed, 80); + ImGui.TableHeadersRow(); + bool macroOn = _ctx.Settings?.IsMacroRunning == true; + foreach (var row in plan) + { + ImGui.PushID(row.Recipe.Id); + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(row.Recipe.Name); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(row.CanMake.ToString()); + ImGui.TableNextColumn(); + SafeImGui.TextWrapped(KitPlanner.PartsText(row)); + ImGui.TableNextColumn(); + foreach (var c in row.Chances) + { + string text = $"{c.Step.Label}: {(c.Percent >= 0 ? c.Percent + "%" : "?")}"; + if (c.UnderFloor) SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, text + " (under the floor)"); + else SafeImGui.TextDisabled(text); + } + ImGui.TableNextColumn(); + string why = macroOn ? "Turn the macro off first: kits are made only while it is off." + : k.Running ? "A kit run is going." + : row.Blocked; + ImGui.BeginDisabled(why.Length > 0); + if (ImGui.SmallButton("Make kits")) + { + var recipe = row.Recipe; + int ask = Math.Max(0, C.KitMakeCount); + int n = ask > 0 ? Math.Min(ask, row.CanMake) : row.CanMake; + int fl = Math.Clamp(C.KitMinChancePercent, 0, 100); + _ctx.Confirm("Make kits", + $"Make up to {n} {recipe.Name}(s)?\n\nChance: {KitPlanner.ChancesText(row)} (floor {fl}%).\n" + + "A failed combine destroys one of each item it used.\n" + + "It stops if you move, leave peace mode, take damage or turn the macro on.", + () => + { + string refused = Kits.Start(recipe, ask); + if (refused.Length > 0) _ctx.Chat("[RynthAi] Make kits: can't start - " + refused + "."); + }, "Make kits"); + } + ImGui.EndDisabled(); + if (why.Length > 0 && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) SafeImGui.SetTooltip(why); + ImGui.PopID(); + } + ImGui.EndTable(); + } + + ImGui.BeginDisabled(!k.Running); + if (ImGui.Button("Stop##kitstop")) _ctx.Post(() => Kits.Stop("stopped by you")); + ImGui.EndDisabled(); + ImGui.SameLine(); + SafeImGui.TextDisabled(k.Status); + if (k.LastSummary.Length > 0) SafeImGui.TextWrapped("Last run: " + k.LastSummary); + RenderAutoKits(); + SafeImGui.TextDisabled("Ingredients: Soft Bandages, Treated Hyssop and Treated Mandrake (Healing must be trained). Also /ra kits."); + } + + /// Make kits when low: the checkbox, the two numbers and what it is doing. + private void RenderAutoKits() + { + var settings = _ctx.Settings; + if (settings == null) return; + ImGui.Separator(); + bool on = settings.MakeKitsWhenLow; + if (ImGui.Checkbox("Make kits when low##kitauto", ref on)) + { + bool value = on; + _ctx.Post(() => + { + settings.MakeKitsWhenLow = value; + if (value) AutoKits.LookNow(); + else + { + if (Kits.Auto) Kits.Stop("Make kits when low turned off", KitStopKind.Other); + AutoKits.Off(); + } + _ctx.SaveCombatSettings?.Invoke(); + }); + } + if (ImGui.IsItemHovered()) + SafeImGui.SetTooltip("While the macro runs: when you carry fewer Plentiful Healing Kits than the first number,\n" + + "make up to the second number from your pack, at the Min chance % above.\n" + + $"Only when nothing is around: no monster within {KitAuto.DefaultRadiusYd:0} yd (or your Monster Range, if bigger),\n" + + $"no hit for {KitAuto.HurtQuietMs / 1000} s, no healing, buffing, looting or fight. The macro waits meanwhile;\n" + + "a monster, a hit, a heal or moving stops it at once. Also /ra kits auto on|off."); + ImGui.SameLine(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted("when fewer than"); + ImGui.SameLine(); + int below = Math.Clamp(settings.MakeKitsBelow, 1, KitAuto.MaxBelow); + ImGui.SetNextItemWidth(80); + if (ImGui.InputInt("##kitbelow", ref below, 1)) + { + int value = Math.Clamp(below, 1, KitAuto.MaxBelow); + _ctx.Post(() => { settings.MakeKitsBelow = value; _ctx.SaveCombatSettings?.Invoke(); }); + } + if (ImGui.IsItemHovered()) ImGui.SetTooltip($"A run starts when you carry fewer kits than this (1-{KitAuto.MaxBelow}). Also /ra kits auto below N."); + ImGui.SameLine(); + ImGui.TextUnformatted("kits, make up to"); + ImGui.SameLine(); + int upTo = Math.Clamp(settings.MakeKitsUpTo, 1, KitAuto.MaxUpTo); + ImGui.SetNextItemWidth(80); + if (ImGui.InputInt("##kitupto", ref upTo, 1)) + { + int value = Math.Clamp(upTo, 1, KitAuto.MaxUpTo); + _ctx.Post(() => { settings.MakeKitsUpTo = value; _ctx.SaveCombatSettings?.Invoke(); }); + } + if (ImGui.IsItemHovered()) ImGui.SetTooltip($"The most kits one run makes (1-{KitAuto.MaxUpTo}); fewer when the pack runs out. Also /ra kits auto upto M."); + if (!settings.MakeKitsWhenLow) SafeImGui.TextDisabled("Make kits when low is off."); + else SafeImGui.TextDisabled("Make kits when low: " + AutoStatusText(settings)); + } + + /// What Make kits when low is doing ("running 2/5", "waiting: monster 22 yd away; next check in 4 s", ...). + public string AutoStatusText(LegacyUiSettings settings) + { + if (!settings.MakeKitsWhenLow) return "off"; + if (Kits.Auto) return $"running {Kits.MadeCount}/{Math.Max(1, Kits.Limit)}"; + if (!settings.IsMacroRunning) return "waiting: the macro is off"; + return AutoKits.Status; + } + /// Auto-confirm crafting: the checkbox, the percent and what it has done. private void RenderAutoConfirm() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteContext.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteContext.cs index 69600e2..33f631e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteContext.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteContext.cs @@ -95,6 +95,8 @@ internal sealed class MiniRemoteContext EngineServerState? st = _server.State; string name = st != null && st.HasActive ? st.ActiveName : string.Empty; _serverView = new ServerView(name, ServerSalvageView.ParseList(_server.ProfileJson), ServerTrinketRule.Parse(_server.ProfileJson)); + // The server's own summon items that hold other summons (the combat summoner and the Pets tab). + PetElements.ServerSummons = ServerSummonView.ParseList(_server.ProfileJson); } /// Logout: forget the server; the next login polls fresh. @@ -103,6 +105,7 @@ internal sealed class MiniRemoteContext _server.Clear(); _serverRevision = -1; _serverView = ServerView.None; + PetElements.ServerSummons = Array.Empty(); } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs index 9d527d8..6b523a4 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/MiniRemoteState.cs @@ -48,6 +48,10 @@ public sealed class CraftingTabState public int TrinketTier; /// Prepare a raw bag on the tier's Ammunition when no prepared bag is carried. public bool TrinketPrep; + /// Kits sub-tab ("Make kits"): never try a combine whose chance is under this percent (0 = any). + public int KitMinChancePercent = Crafting.KitPlanner.DefaultFloorPercent; + /// Kits sub-tab: how many kits one run makes (0 = as many as the pack makes). + public int KitMakeCount; // "RingRuns" (the Rings chain, now left to RynthILT) may still be in older files: it is ignored. } diff --git a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs index bd11a79..a55b30c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/MiniRemote/PetsTab.cs @@ -120,6 +120,7 @@ internal sealed class PetsTab if (w is >= 78780001 and <= 78780012) return false; // capture devices if (w is >= 787802001 and <= 787802072) return false; // summoned combat pet creatures if (w is >= 787801001 and <= 787801072) return true; // combat essence block + if (PetElements.IsHolder(_ctx.Host, unchecked((uint)wo.Id), wo.Name)) return true; // a server's holder of summons if (HasSummonGemUnderlay(wo)) return true; if (RequiresSummoning(wo)) return true; @@ -661,6 +662,7 @@ internal sealed class PetsTab } var s = PetStatsReader.Read(_ctx.Host, _ctx.Inventory, wo, unixNow); + ShowElements(s, wo); s.Kind = kind.Value; s.KindAssigned = assigned; int pri = rules.FindIndex(r => r.Id == wo.Id || r.Name.Equals(wo.Name, StringComparison.OrdinalIgnoreCase)); @@ -680,6 +682,21 @@ internal sealed class PetsTab _pets = rows.ToArray(); } + /// + /// The row's element(s) when the server sent no damage type: "Fire", or "Fire+Cold" for a holder + /// of two summons (PetElements), with "holds 1 of 2" for one that can't summon yet. + /// + private void ShowElements(PetStats s, WorldObject wo) + { + var info = PetElements.Describe(_ctx.Host, unchecked((uint)wo.Id), wo.Name); + string text = s.DamageType.Length > 0 ? s.DamageType : info.ElementText; + if (info.IsHolder && !info.Ready) + text = (text.Length > 0 ? text + ", " : "") + $"holds {info.Held.Count} of {info.Slots}"; + if (text == s.DamageType) return; + s.DamageType = text; + PetStatsReader.FormatLines(s); + } + // ── UI (render thread) ────────────────────────────────────────────────── /// Set from any thread: the sub-tab the next frame opens ("/ra hub open breeding"); null = none. @@ -840,6 +857,16 @@ internal sealed class PetsTab if (ImGui.InputInt("Min monsters", ref minMobs)) _ctx.Post(() => { settings.PetMinMonsters = Math.Max(1, minMobs); _ctx.SaveCombatSettings?.Invoke(); }); bool refill = settings.PetAutoRefill; if (ImGui.Checkbox("Refill empty essences with Encapsulated Spirit", ref refill)) _ctx.Post(() => { settings.PetAutoRefill = refill; _ctx.SaveCombatSettings?.Invoke(); }); + ImGui.TextUnformatted("Pet element"); + ImGui.SameLine(); + ImGui.SetNextItemWidth(110); + int petElem = PetChoice.SettingIndex(settings.PetElement); + if (ImGui.Combo("##petelement", ref petElem, PetChoice.SettingChoices, PetChoice.SettingChoices.Length)) + { + string chosen = PetChoice.SettingValue(petElem); + _ctx.Post(() => { settings.PetElement = chosen; _ctx.SaveCombatSettings?.Invoke(); }); + } + if (ImGui.IsItemHovered()) ImGui.SetTooltip(PetChoice.SettingTooltip); ImGui.TextDisabled("Tick pets to add them to the summon list; with Sort = Priority the arrows set the order."); break; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavBreadcrumbTracker.cs b/Plugins/RynthCore.Plugin.RynthAi/NavBreadcrumbTracker.cs index 98cbc26..a1a4a2f 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavBreadcrumbTracker.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavBreadcrumbTracker.cs @@ -50,6 +50,43 @@ internal sealed class NavBreadcrumbTracker private int _recAdded, _recSinceSave; private (string Name, int Cls, double NS, double EW, double NavZ, long At)? _portalCandidate; + // ── A jump step added while recording (/ra nav addjump) ── + /// After a jump step, no point is recorded for at least this long (you are in the air). + internal const long JumpHoldMinMs = 1200; + /// Nor until your height has held still this long (landed), or this much time has gone by. + internal const long JumpLandStillMs = 500, JumpHoldMaxMs = 6000; + /// Height change per tick under this is "still", metres. + internal const float JumpLandStillM = 0.05f; + private long _jumpAt = -1, _jumpStillSince; + private float _jumpLastZ; + + /// + /// A Jump step went onto the route here (tick thread, from /ra nav addjump): the recording holds its next + /// point until you have jumped and landed, so no point is laid in the air or on the edge you jumped from. + /// + public void JumpAdded() + { + _jumpAt = Environment.TickCount64; + _jumpStillSince = 0; + _jumpLastZ = float.NaN; + } + + /// True while a jump just added holds the recording (see ). + internal bool HoldingForJump(float z, long now) + { + if (_jumpAt < 0) return false; + long since = now - _jumpAt; + bool still = !float.IsNaN(_jumpLastZ) && Math.Abs(z - _jumpLastZ) < JumpLandStillM; + _jumpLastZ = z; + if (!still) _jumpStillSince = 0; + else if (_jumpStillSince == 0) _jumpStillSince = now; + bool landed = since >= JumpHoldMinMs && _jumpStillSince != 0 && now - _jumpStillSince >= JumpLandStillMs; + if (!landed && since < JumpHoldMaxMs) return true; + _jumpAt = -1; + _recNS = double.NaN; // the landing spot is recorded straight away + return false; + } + public NavBreadcrumbTracker(RynthCoreHost host, LegacyUiSettings settings, Func describePortal, Action chat) { @@ -224,6 +261,8 @@ internal sealed class NavBreadcrumbTracker _recNS = double.NaN; } + if (HoldingForJump(z, Environment.TickCount64)) return; + if (!double.IsNaN(_recNS) && NavRouteEditing.DistanceYards(_recNS, _recEW, ns, ew) < o.RecordSpacingYards) return; diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs b/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs index a0f1d0a..459cd67 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavRecovery.cs @@ -42,6 +42,12 @@ internal sealed class NavRecoveryPlan public string Planner = string.Empty; /// Doorways (dungeon portals) the path goes through. public int Doorways; + /// The points are RynthNav navmesh corners: the engine turns a corner early only where the + /// navmesh shows a straight walk to the next one (NavigationEngine's corner gate). + public bool NavmeshCorners; + /// The route waypoint stands inside something placed (a statue's middle): the last point is the nearest + /// spot clear of it, and reaching that reaches the waypoint (nobody gets nearer). + public bool TargetMoved; } /// Result of . @@ -76,6 +82,8 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner // when it is this close to one of its cells. internal const double AreaCellReachYd = 60.0; private const int MaxNavmeshCorners = 128; + // A partial navmesh way must end at least this far from the character to be worth walking. + private const double PartialMinGainYd = 2.0; private readonly RynthCoreHost _host; private readonly Func _raycast; @@ -181,7 +189,18 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner applicable = true; uint start = graph.ContainsKey(playerCell) ? playerCell : DungeonPathfinder.NearestCell(graph, pNs, pEw, pz); if (start == 0) { why = "can't place you on the dungeon map"; return null; } - if (start == goal) { why = "already in the waypoint's room, the map has no way around"; return null; } + var geo = DungeonPathfinder.GetGeometry(lb, cellDat, _raycast()?.GeometryLoader?.DungeonLOS); + if (start == goal) + { + // The same cell: what it stuck on is in the room with it (a table, a statue), and the cell graph has + // nothing to say. The dungeon map walks round it. + string roomWhy = string.Empty; + var inRoom = geo != null ? PlanInRoom(geo, pNs, pEw, pz, tNs, tEw, tz, out roomWhy) : null; + if (inRoom != null) return inRoom; + why = geo == null ? "already in the waypoint's room, the map has no way around" + : $"already in the waypoint's room, the map has no way around ({roomWhy})"; + return null; + } var path = DungeonPathfinder.FindPath(start, goal, graph, _hazards()); if (path.Count < 2) { why = "no walkable way on the dungeon map"; return null; } @@ -190,7 +209,6 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner // every narrow opening (flagged, so the engine goes through straight), rooms crossed // directly. Without the map geometry, cell-centre midpoints. var plan = new NavRecoveryPlan { Planner = "dungeon map" }; - var geo = DungeonPathfinder.GetGeometry(lb, cellDat, _raycast()?.GeometryLoader?.DungeonLOS); plan.Points = DungeonPathfinder.BuildPathPoints(path, graph, geo, _hazards(), pNs, pEw, pz, tNs, tEw, tz, out int doorways); plan.Doorways = doorways; if (plan.Points.Count == 0) { why = "empty path"; return null; } @@ -198,6 +216,125 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner return plan; } + // ── In one room (2026-11-18) ──────────────────────────────────────────── + // 9 of the 29 logged "no plan" recoveries were "already in the waypoint's room": the character and the + // waypoint in one cell, with a table (0x0190 room 88, 0x020002FB), a statue (0x00C1 room 81, 0x020014A3: the + // waypoint in its middle), an altar (0x000A) or a slab (0x01F5) between them, and the stuck escapes ran blind + // until they gave up (about 3 minutes in 0x00C1). The dungeon map knows those objects now. + + /// A waypoint inside something placed is moved out to this much room ... + internal const double InRoomTargetClearance = 1.0; + /// ... at most this far (0x00C1's statue is 9 x 9 m: its waypoint came 2.5 m out). + internal const double InRoomTargetPushMax = 8.0; + + /// + /// The walk from the character (pNs, pEw, pz) to the waypoint (tNs, tEw, tz) within one room, on the dungeon map: + /// a waypoint inside a placed object is moved out of it first (PushClear to InRoomTargetClearance, at most + /// InRoomTargetPushMax), then the straight walk is walked round the placed objects on the floor + /// (DungeonPathfinder.WalkRoundHoles, objects only). A "dungeon map (room)" plan when that put points in (the + /// moved waypoint is its last point, and is set); null, with + /// , when the straight walk is clear (the snag isn't on the map) or there is no way round. + /// Only an obstacle's waypoint is moved: one up on something placed (at its own height ), or in a + /// step-over or a connector, gets no plan. + /// + internal static NavRecoveryPlan? PlanInRoom(DungeonGeometry geo, double pNs, double pEw, double pz, + double tNs, double tEw, double tz, out string why) + { + why = string.Empty; + double px = DungeonGeometry.NavToWorld(pEw), py = DungeonGeometry.NavToWorld(pNs); + double tx = DungeonGeometry.NavToWorld(tEw), ty = DungeonGeometry.NavToWorld(tNs); + if (!geo.TryFloorHeight(px, py, pz, 3.0, out double ph)) ph = pz; + if (!geo.TryFloorHeight(tx, ty, tz, 3.0, out double th)) th = tz; + + bool moved = false; + if (geo.InsidePlaced(tx, ty, th)) + { + // Inside it at the map's floor is not inside it for a waypoint up on it: one recorded on a dais's top, half way + // up a ramp or on a platform. Moved down beside the object and taken as reached (TargetMoved), it was skipped, + // and the next waypoint, up there too, ran the character into the object's side again, stuck after stuck. Nor + // is a step or a ramp (a step-over, a connector) something to move a waypoint out of: it is the way on. Both are + // left to the escapes, as before the room planner (review of wf/obst-int). + if (geo.OnTopOfPlaced(tx, ty, tz, th)) + { + why = "the waypoint is up on something placed (the map has no floor on its top)"; + return null; + } + if (geo.InsidePlaced(tx, ty, Math.Max(th, tz), c => c is PlacedClass.StepOver or PlacedClass.Connector)) + { + why = "the waypoint is in a step or a ramp placed there (climbed, not walked round)"; + return null; + } + double ox = tx, oy = ty; + geo.PushClear(ref tx, ref ty, th, InRoomTargetClearance, InRoomTargetPushMax); + if (geo.InsidePlaced(tx, ty, th) || !geo.OnWalkableFloor(tx, ty, th)) + { + why = "the waypoint is inside something placed, with no floor clear of it within " + InRoomTargetPushMax.ToString("0", System.Globalization.CultureInfo.InvariantCulture) + " m"; + return null; + } + moved = Math.Abs(tx - ox) > 1e-6 || Math.Abs(ty - oy) > 1e-6; + } + + var target = new NavPoint { Type = NavPointType.Point, NS = DungeonGeometry.WorldToNav(ty), EW = DungeonGeometry.WorldToNav(tx), Z = th / 240.0 }; + var pts = new List + { + new NavPoint { Type = NavPointType.Point, NS = pNs, EW = pEw, Z = ph / 240.0 }, + target, + }; + using var count = DungeonPathfinder.CountHoles(); + int left0 = DungeonPathfinder.HolesLeft; + int round = DungeonPathfinder.WalkRoundHoles(pts, geo, objectsOnly: true); + if (round == 0 && DungeonPathfinder.HolesLeft > left0) { why = "no way round what is placed there"; return null; } + if (round == 0 && !moved) { why = "the straight walk is clear on the map (the snag isn't on it)"; return null; } + + var plan = new NavRecoveryPlan { Planner = moved ? "dungeon map (room, waypoint moved out of an object)" : "dungeon map (room)", TargetMoved = moved }; + // The character's own spot is not walked to; the waypoint is the engine's, unless it was moved. + for (int i = 1; i < pts.Count; i++) + if (i + 1 < pts.Count || moved) plan.Points.Add(pts[i]); + plan.LengthYd = PathLengthYd(pNs, pEw, plan.Points, tNs, tEw); + return plan; + } + + /// + /// NavigationEngine.EscapeRoom: on the dungeon map, how far (metres, up to 2) the character at (wx, wy, wz) (world + /// metres, in ) gets along a compass heading (0 north, clockwise) before it runs into + /// something; NaN outside a dungeon's cell, without the map, or with no floor under the character on it. + /// + internal double EscapeRoom(uint cell, double wx, double wy, double wz, double headingDeg) + { + try + { + if ((cell & 0xFFFF) < 0x0100) return double.NaN; + var cellDat = CellDat; + if (cellDat == null || !IsDungeonLandblock(cell >> 16, cellDat)) return double.NaN; + var geo = DungeonPathfinder.GetGeometry(cell >> 16, cellDat, _raycast()?.GeometryLoader?.DungeonLOS); + return geo == null ? double.NaN : EscapeRoomOn(geo, wx, wy, wz, headingDeg); + } + catch { return double.NaN; } + } + + /// Along an escape heading, the character has run into something where it comes this near a wall, a floor's + /// edge or something placed (half its 0.48 m body over it): a burst sliding along a face it stuck on gets on, one + /// head-on into it doesn't. + internal const double EscapeTouchMeters = 0.25; + internal const double EscapeLookMeters = 2.0; + + /// The map half of : looked at every 0.1 m, following the floor. + internal static double EscapeRoomOn(DungeonGeometry geo, double wx, double wy, double wz, double headingDeg) + { + if (!geo.TryFloorHeight(wx, wy, wz, 3.0, out double h)) return double.NaN; + double a = headingDeg * Math.PI / 180.0, ux = Math.Sin(a), uy = Math.Cos(a); + const double step = 0.1; + for (double d = step; d <= EscapeLookMeters + 1e-9; d += step) + { + double x = wx + ux * d, y = wy + uy * d; + if (!geo.TryFloorHeight(x, y, h, 0.6, out double hh) || !geo.OnWalkableFloor(x, y, hh) + || geo.ClearanceMemo(x, y, hh, EscapeTouchMeters + 0.1) < EscapeTouchMeters) + return d - step; + h = hh; + } + return EscapeLookMeters; + } + private NavRecoveryPlan? PlanOutdoor(uint cell, float lx, float ly, float lz, double tNs, double tEw, float tz, out string why) { @@ -212,10 +349,11 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner int result; int count = 0; double[] buf = new double[MaxNavmeshCorners * 3]; + double[] info = new double[RynthNavPathApiV1.InfoLength]; + bool ex; unsafe { // Resolved on every call: RynthNav may be missing, or reloaded since last time. - // Version 1 (FindPath is all this needs): a RynthNav from before v2 answers it too. IntPtr p = _host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, 1); var t = (RynthNavPathApiV1*)p; if (t == null || t->Version < 1 || t->StructSize < RynthNavPathApiV1.SizeV1 || t->FindPath == null) @@ -223,16 +361,42 @@ internal sealed class NavRecoveryPlanner : INavRecoveryPlanner why = "RynthNav isn't loaded"; return null; } + // Version 2: FindPathEx with the Outdoor Hunt's flags, so the way back keeps out of portals and + // 1 m off the walls as the hunt's walks do (v1 FindPath does neither: a detour could run along a + // building's wall or through a portal's circle). No PathStartOutdoors: the start is where the + // character stands, so from inside a building RynthNav refuses it as before. A RynthNav from + // before v2: FindPath. + ex = t->Version >= 2 && t->StructSize >= (uint)sizeof(RynthNavPathApiV1) && t->FindPathEx != null; fixed (double* pts = buf) - result = t->FindPath(sx, sy, lz, gx, gy, tz, pts, MaxNavmeshCorners, &count); + fixed (double* inf = info) + result = ex + ? t->FindPathEx(sx, sy, lz, gx, gy, tz, RynthAiPlugin.HuntPathFlags, 0, pts, MaxNavmeshCorners, &count, inf) + : t->FindPath(sx, sy, lz, gx, gy, tz, pts, MaxNavmeshCorners, &count); } if (result == RynthNavPathApiV1.ResultNoMesh) { why = "no RynthNav navmesh here"; return null; } - if (result != RynthNavPathApiV1.ResultOk || count < 2) { why = "RynthNav found no walkable way"; return null; } + // A partial way (the waypoint off the mesh, or past a seam between two tiles that don't link) ends at + // the reachable point nearest the waypoint: that point is walked to as well, then the route's own leg + // from there, as RynthNav's own walks push straight on over a seam. + bool partial = ex && result == RynthNavPathApiV1.ResultPartial; + if ((result != RynthNavPathApiV1.ResultOk && !partial) || count < 2) { why = "RynthNav found no walkable way"; return null; } + // A partial way that ends where the character stands gets it nowhere: no detour, the escapes (as v1 said). + double endX = buf[(count - 1) * 3] - sx, endY = buf[(count - 1) * 3 + 1] - sy; + if (partial && endX * endX + endY * endY < PartialMinGainYd * PartialMinGainYd) + { + why = "RynthNav's way ends where you stand (the waypoint isn't reachable on its map)"; + return null; + } - var plan = new NavRecoveryPlan { Planner = "RynthNav navmesh" }; - // Corners 1..count-2 are the turns; the first is our position and the last the waypoint. - for (int i = 1; i < count - 1; i++) + var plan = new NavRecoveryPlan + { + Planner = partial ? string.Create(System.Globalization.CultureInfo.InvariantCulture, $"RynthNav navmesh (partial, ends {info[5]:F0}yd short)") : "RynthNav navmesh", + NavmeshCorners = true, + }; + // Corners 1..count-2 are the turns; the first is our position and the last the waypoint (for a + // partial way the last is where it ends, a point of the detour too). + int last = partial ? count : count - 1; + for (int i = 1; i < last; i++) { double wx = buf[i * 3], wy = buf[i * 3 + 1], wz = buf[i * 3 + 2]; plan.Points.Add(new NavPoint diff --git a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs index 5a32fe1..cd098f3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/NavigationEngine.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; +using System.Text; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.PluginSdk; using RynthCore.Plugin.Shared; @@ -131,6 +133,9 @@ internal sealed class NavigationEngine // ── Stuck watchdog ─────────────────────────────────────────────────────── private double _watchdogNs = double.NaN; private double _watchdogEw = double.NaN; + private long _watchdogAt; // when _watchdogNs/Ew were taken + private double _watchdogMovedYd = double.NaN; // moved in the last watchdog window, for the stuck lines + private double _watchdogWindowMs; private long _watchdogNext; private int _stuckCount; private bool _inRecovery; @@ -155,6 +160,8 @@ internal sealed class NavigationEngine public int Number; // session recovery counter, for the log public string Reason = string.Empty; public string Planner = string.Empty; + public bool Navmesh; // RynthNav navmesh corners: the corner gate applies (NavmeshRaycast) + public bool TargetMoved; // the rejoin waypoint is inside something placed: the last point stands in for it public List Points = new(); public int Index; // next detour point to reach public int StartIdx; // ActiveNavIndex when it began (a change cancels it) @@ -193,8 +200,14 @@ internal sealed class NavigationEngine /// Every detour for the current waypoint has been tried and the character is still stuck there /// (only the escapes are left, for as long as it takes): the dungeon explore takes this as a way it can't - /// get through, something the map doesn't have standing in it (a spider web spawned in a doorway). - public bool DetoursUsedUpAndStuck => _detour == null && _detourAttempts >= MaxDetourAttempts && _stuckCount >= 2; + /// get through, something the map doesn't have standing in it (a spider web spawned in a doorway). + /// Only on the route walked when that was found: a route put in since (the explore laid again round that + /// way) clears it when navigation next runs, and until then it is not yet stuck at all. Navigation doesn't + /// run while buffing: 2026-11-17, a DreamWeave Thread in 0x0278, the explore laid its walk again five times in + /// 2.4 s during a rebuff, each time "stuck for good" on the walk before, closing a real opening or spot each + /// time until the walk from the start reached nothing and the explore ended as done. + public bool DetoursUsedUpAndStuck => _detour == null && _detourAttempts >= MaxDetourAttempts && _stuckCount >= 2 + && ReferenceEquals(_settings.CurrentRoute, _lastRoute); private INavRecoveryPlanner? _planner; private Detour? _detour; @@ -239,6 +252,9 @@ internal sealed class NavigationEngine // ── Observability (GetStateSnapshot / /ra navstate) ────────────────────── private double _lastDistYd = double.NaN; private double _lastHeadingErr = double.NaN; + // The heading the steering last aimed at (0 = north, clockwise; NaN = not steered yet), kept from + // HeadingErrorTo / SteerToWaypoint for the stuck lines. + private double _lastDesiredDeg = double.NaN; private long _lastSteerAt; // ── Derived thresholds (from settings) ────────────────────────────────── @@ -273,8 +289,12 @@ internal sealed class NavigationEngine // half a metre of its centre line, at under 15 degrees. The lookahead is off at them too. internal const double DoorwayReachYd = 1.0; // NavMarkerRenderer draws doorway rings at this size private const double DoorwaySweepMult = 1.5; - private double ReachFor(NavPoint p) => p.Doorway ? Math.Min(ArrivalYards, DoorwayReachYd) : ArrivalYards; - private double SweepFor(NavPoint p) => ReachFor(p) * (p.Doorway ? Math.Min(SweepMult, DoorwaySweepMult) : SweepMult); + // A Jump step is reached as tightly as a doorway, from a file too (Doorway is never saved): it stands at + // the edge it was laid or recorded at (/ra nav addjump, 2026-11-18), and a jump a yard or two short of a + // ledge or a stepping stone falls short. + private static bool Tight(NavPoint p) => p.Doorway || p.Type == NavPointType.Jump; + private double ReachFor(NavPoint p) => Tight(p) ? Math.Min(ArrivalYards, DoorwayReachYd) : ArrivalYards; + private double SweepFor(NavPoint p) => ReachFor(p) * (Tight(p) ? Math.Min(SweepMult, DoorwaySweepMult) : SweepMult); // Lookahead (corner rounding): within this distance of a waypoint, blend the aim point // toward the next one so corners are rounded. It used to be the Lookahead setting alone @@ -291,15 +311,57 @@ internal sealed class NavigationEngine => Math.Clamp(CornerRoundPerReachYd * (reachYd - CornerRoundFreeReachYd), 0.0, Math.Max(0.0, lookaheadSetting)); private double LookaheadYards => CornerLookaheadYards(_settings.NavLookaheadYards, ArrivalYards); + // Corner gate (2026-11-18). A hunt walk is RynthNav's path, laid 1 m off the walls; nav turned toward the + // next corner at the nav point reach (1.5 yd) without looking, and the cut across the inside of the corner + // left the mesh's safe corridor for the building corner the path went round. A walk simulation on the live + // tiles (0x7D64, 0xA9B4, 0x32D9, 0x64D5, 0x238E, 1,309 walks) had the centre line through baked collision on + // 157 walks at reach 1.5, and on 10 with this gate (the body's sides, 0.48 m out, touching it: 343 to 167). + // So on walks along RynthNav's corners (a hunt walk, a planned GoTo, a navmesh detour) a corner is reached at + // the nav point reach, or blended toward the next one, only while RynthNav's raycast from the character to the + // next corner is clear (RynthNav's own walker does the same: PathFollow.Advance); otherwise as tightly as a + // doorway point (DoorwayReachYd). Meta, VTank and saved routes are never gated and keep their reach exactly. + + /// RynthNav's navmesh raycast (RynthNav.Path v2) from (x, y, z) to (x, y, z), world units: RayClear (1) + /// when a straight walk stays on the mesh. Set by the plugin (RynthAiPlugin.HuntRaycast); null: no corner gate. + public Func? NavmeshRaycast { get; set; } + + private bool CornerGated(NavRouteParser route) => NavmeshRaycast != null && (route.OutdoorHuntWalk || route.NavmeshCorners); + private double TightReachYd => Math.Min(ArrivalYards, DoorwayReachYd); + private int _cornerHeldIdx = -1; // the route waypoint whose turn the gate has held (for the arrival line) + + /// + /// False when the walk may not turn the corner at yet: a gated walk, the character inside + /// the reach (or the lookahead blend) but outside the tight reach, a corner after it, and no straight walk to + /// that corner on the navmesh. True everywhere the answer changes nothing, so the raycast is asked only there. + /// + private bool CornerOpen(NavPoint pt, NavPoint? next, double dist, double blendYd) + { + if (Tight(pt) || dist < TightReachYd || dist >= Math.Max(ReachFor(pt), blendYd)) return true; + if (next == null || !IsWalkTarget(next.Type)) return true; // the walk's end: no corner to turn + return NavmeshStraightTo(next); + } + + /// The navmesh raycast from the character to is clear. + private bool NavmeshStraightTo(NavPoint p) + { + var ray = NavmeshRaycast; + if (ray == null) return true; + if (!_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) || cell == 0) + return false; + double ax = ((cell >> 24) & 0xFF) * 192.0 + lx, ay = ((cell >> 16) & 0xFF) * 192.0 + ly; + double bz = p.Z != 0.0 ? p.Z * 240.0 : lz; // 0: not recorded + return ray(ax, ay, lz, NavToWorld(p.EW), NavToWorld(p.NS), bz) == RynthNavPathApiV1.RayClear; + } + // Pass-through: a plain waypoint the character has gone past (it is beyond the point along // the way it came, and no farther to the side than the sweep radius) counts as reached, // so nav doesn't turn round to walk back to it. "Beyond along the way it came" means the // point is behind the character: a corner cut toward the next point never qualifies. - // Doorway points keep their own tight reach and sweep and never use it. + // Doorway and Jump points keep their own tight reach and sweep and never use it. private const double PassMinLegYd = 1.0; // shorter approach: no reliable direction private bool PassedThrough(NavPoint pt, double ns, double ew) { - if (pt.Doorway || double.IsNaN(_legStartNs)) return false; + if (Tight(pt) || double.IsNaN(_legStartNs)) return false; double ux = (pt.NS - _legStartNs) * 240.0, uy = (pt.EW - _legStartEw) * 240.0; double len = Math.Sqrt(ux * ux + uy * uy); if (len < PassMinLegYd) return false; @@ -484,6 +546,7 @@ internal sealed class NavigationEngine _lastRoute = route; _inPause = false; _closestDist = double.MaxValue; + _cornerHeldIdx = -1; _linearDir = 1; if (!sameWalk) { @@ -662,10 +725,20 @@ internal sealed class NavigationEngine } _campHoldAnnounced = false; - // Arrival check - if (dist < ReachFor(pt)) + // Corner gate (see NavmeshRaycast): on a walk along RynthNav's corners the turn waits for a clear raycast. + bool cornerOpen = true; + if (CornerGated(route)) { - _host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing"); + int ni = PeekNext(idx, route); + cornerOpen = CornerOpen(pt, ni >= 0 ? route.Points[ni] : null, dist, LookaheadYards); + if (!cornerOpen) _cornerHeldIdx = idx; + } + + // Arrival check + if (dist < (cornerOpen ? ReachFor(pt) : TightReachYd)) + { + string held = _cornerHeldIdx == idx ? $" (corner held to {TightReachYd:F1}yd: no straight walk to the next on the navmesh)" : ""; + _host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing{held}"); _closestDist = double.MaxValue; UpdateStatusLine(idx, dist, route, 0.0); // Advance before the jump: the Jumper pauses nav and later restores what it @@ -703,7 +776,7 @@ internal sealed class NavigationEngine } _closestDist = Math.Min(_closestDist, dist); - SteerToWaypoint(idx, pt, route, ns, ew, dist); + SteerToWaypoint(idx, pt, route, ns, ew, dist, cornerOpen); } public void Stop() @@ -1083,14 +1156,15 @@ internal sealed class NavigationEngine private void SteerToWaypoint(int idx, NavPoint pt, NavRouteParser route, - double ns, double ew, double dist) + double ns, double ew, double dist, bool cornerOpen = true) { - _steerDoorway = pt.Doorway; + _steerDoorway = Tight(pt); // ── Lookahead blend ────────────────────────────────────────────────── double tNS = pt.NS, tEW = pt.EW; // Never at a doorway point: blending toward the next point there is exactly the corner - // cut that meets a narrow opening at an angle. - if (dist < LookaheadYards && !pt.Doorway) + // cut that meets a narrow opening at an angle. Nor at a corner the gate holds (no straight + // walk to the next one on the navmesh). + if (dist < LookaheadYards && !Tight(pt) && cornerOpen) { int ni = PeekNext(idx, route); // Only blend toward the NEXT waypoint when it is a real travel target @@ -1112,6 +1186,7 @@ internal sealed class NavigationEngine // ── Desired heading (0=North, clockwise) ──────────────────────────── double desiredDeg = Math.Atan2(tEW - ew, tNS - ns) * (180.0 / Math.PI); if (desiredDeg < 0) desiredDeg += 360.0; + _lastDesiredDeg = desiredDeg; // ── Current heading from quaternion (always reliable) ─────────────── double currentDeg; @@ -1141,6 +1216,7 @@ internal sealed class NavigationEngine { double desiredDeg = Math.Atan2(tEW - ew, tNS - ns) * (180.0 / Math.PI); if (desiredDeg < 0) desiredDeg += 360.0; + _lastDesiredDeg = desiredDeg; if (TryGetQuaternionHeading(out float qHeading)) { @@ -1365,6 +1441,7 @@ internal sealed class NavigationEngine { int oldIdx = _settings.ActiveNavIndex; _closestDist = double.MaxValue; + _cornerHeldIdx = -1; _portalState = PortalState.None; // Reaching a waypoint is progress: the next snag gets a fresh detour budget. _detourAttempts = 0; @@ -2379,6 +2456,8 @@ internal sealed class NavigationEngine { double dN = ns - _watchdogNs, dE = ew - _watchdogEw; double moved = Math.Sqrt(dN * dN + dE * dE) * 240.0; + _watchdogMovedYd = moved; + _watchdogWindowMs = Now - _watchdogAt; if (moved < StuckYd) { _stuckCount++; @@ -2391,6 +2470,7 @@ internal sealed class NavigationEngine } _watchdogNs = ns; _watchdogEw = ew; + _watchdogAt = Now; } // ── Escapes and portals (2026-11-15) ──────────────────────────────────── @@ -2430,6 +2510,55 @@ internal sealed class NavigationEngine return EscapeOffsetClear(px, py, lz, curDeg, near, ref offset, out note); } + // ── Room for a burst on the dungeon map (2026-11-18) ──────────────────────────────────────── + // The bursts are blind: +75, -75, then 165 degrees off the heading, whatever is there. In a dungeon the map knows + // the walls and what the cells place, so a burst that would run head-on into one (a side step into the wall of a + // corner, a crate beside the altar it stuck on) is turned to the side that has room. A burst sliding along the + // face it stuck on gets on, so it is kept: the rungs still try their different sides in turn. + + /// The dungeon map's room for an escape burst: how far (metres, up to 2) the character (cell, world x, y, z) + /// gets along a compass heading (0 north, clockwise) before it runs into something; NaN where the map doesn't say. + /// RynthAiPlugin sets it (NavRecoveryPlanner.EscapeRoom). + public Func? EscapeRoom { get; set; } + /// A burst that gets less than this far runs head-on into something: another heading is looked for. + internal const double EscapeRoomTight = 0.5; + /// The other heading is taken when it gets this much farther. + internal const double EscapeRoomBetter = 0.5; + private static readonly double[] EscapeRoomDeg = { +SideStepDeg, -SideStepDeg, BackOutDeg, -BackOutDeg }; + + private bool RoomiestEscapeOffset(double curDeg, ref double offset, out string? note) + { + note = null; + var room = EscapeRoom; + if (room == null || !_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) || cell == 0) return false; + double px = ((cell >> 24) & 0xFF) * 192.0 + lx, py = ((cell >> 16) & 0xFF) * 192.0 + ly; + return PickRoomiestEscape(curDeg, ref offset, h => room(cell, px, py, lz, h), out note); + } + + /// The pure half of : the rung's offset when it has EscapeRoomTight ahead + /// (or the map doesn't say), else the side-step or back-out offset with the most room, when that is EscapeRoomBetter + /// more. True (note says so) when it turned the burst. + internal static bool PickRoomiestEscape(double curDeg, ref double offset, Func roomAt, out string? note) + { + note = null; + double first = offset, own = roomAt(Wrap360(curDeg + first)); + if (double.IsNaN(own) || own >= EscapeRoomTight) return false; + double pick = first, pickRoom = double.NegativeInfinity; + foreach (double off in EscapeRoomDeg) + { + if (Math.Abs(off - first) < 0.01) continue; + double r = roomAt(Wrap360(curDeg + off)); + if (!double.IsNaN(r) && r > pickRoom) { pick = off; pickRoom = r; } + } + if (Math.Abs(pick - first) < 0.01 || !(pickRoom > own + EscapeRoomBetter)) return false; + note = string.Create(CultureInfo.InvariantCulture, + $"escape burst turned {pick:+0;-0}° instead of {first:+0;-0}° for room on the dungeon map ({pickRoom:F1} m clear ahead, {own:F1} m that way)"); + offset = pick; + return true; + } + + private static double Wrap360(double deg) { deg %= 360.0; return deg < 0 ? deg + 360.0 : deg; } + /// The pure half of (world position given). internal static bool EscapeOffsetClear(double px, double py, double pz, double curDeg, IReadOnlyList<(double X, double Y, double Z)> portals, ref double offset, out string? note) @@ -2483,6 +2612,11 @@ internal sealed class NavigationEngine } _settings.NavIsStuck = true; + // Where, before anything moves the character: every stuck line ends with it. + string where = StuckWhere(route); + _lastStuckWhere = where; + _lastStuckAt = Now; + _lastStuckCount = _stuckCount; StopMovement(); // Escalation ladder, keyed on how many consecutive watchdog windows have @@ -2492,7 +2626,7 @@ internal sealed class NavigationEngine { // Nothing shook us loose. Waypoints are never skipped (2026-09-28): // start the ladder over (jump, side-steps, back-out) on the same one. - _host.Log($"Nav: stuck x{_stuckCount} at [{_settings.ActiveNavIndex}] — still stuck, retrying the escapes."); + _host.Log($"Nav: stuck x{_stuckCount} at [{_settings.ActiveNavIndex}] — still stuck, retrying the escapes | {where}"); _stuckCount = 1; } @@ -2503,13 +2637,17 @@ internal sealed class NavigationEngine if (_detour != null) EndDetour("stuck on the detour", success: false); else if (TryStuckDetour(route)) + { + _host.Log($"Nav: stuck x{_stuckCount} — detour, recovery #{_recoveryNumber} | {where}"); return; + } // Rungs 2+ need a heading we can command. Without TurnToHeading the only // primitive we have is the jump, so stay on rung 1 rather than autorunning // blindly into whatever we happen to be facing. if (_stuckCount <= 1 || !_host.HasTurnToHeading || !TryGetQuaternionHeading(out float curDeg)) { + _host.Log($"Nav: stuck x{_stuckCount} — jump | {where}"); _recoveryKind = RecoveryKind.Jump; _recoveryUntil = Now + (long)RecoveryMs; _inRecovery = true; @@ -2524,23 +2662,26 @@ internal sealed class NavigationEngine _ => BackOutDeg, }; + // In a dungeon, a burst heading straight into a wall or something placed is turned to where the map has room. + if (RoomiestEscapeOffset(curDeg, ref offset, out string? roomNote)) _host.Log($"Nav: stuck x{_stuckCount} — {roomNote} | {where}"); + // A burst must not run the character into a portal (it fires on touch): the rung's heading if // it keeps away from every portal near, else the nearest one that does; none: the jump instead. if (!PortalSafeEscapeOffset(curDeg, ref offset, out string? portalNote)) { - _host.Log($"Nav: stuck x{_stuckCount} — every escape heading runs at a portal ({portalNote}): jumping instead."); + _host.Log($"Nav: stuck x{_stuckCount} — every escape heading runs at a portal ({portalNote}): jumping instead | {where}"); _recoveryKind = RecoveryKind.Jump; _recoveryUntil = Now + (long)RecoveryMs; _inRecovery = true; _host.JumpNonAutonomous(0.5f); return; } - if (portalNote != null) _host.Log($"Nav: stuck x{_stuckCount} — {portalNote}."); + if (portalNote != null) _host.Log($"Nav: stuck x{_stuckCount} — {portalNote} | {where}"); double escapeHeading = curDeg + offset; if (escapeHeading >= 360.0) escapeHeading -= 360.0; else if (escapeHeading < 0.0) escapeHeading += 360.0; - _host.Log($"Nav: stuck x{_stuckCount} — escape burst {offset:+0;-0}° for {RecoveryBurstMs:F0}ms."); + _host.Log($"Nav: stuck x{_stuckCount} — escape burst {offset:+0;-0}° for {RecoveryBurstMs:F0}ms | {where}"); _host.TurnToHeadingBy("Nav", (float)escapeHeading); StartForward(); _recoveryKind = RecoveryKind.Escape; @@ -2959,9 +3100,68 @@ internal sealed class NavigationEngine // ── Starting / ending a detour ─────────────────────────────────────────── + /// Stucks at the latest stuck spot (within StuckSpotYards of each other), for the outdoor hunt: at + /// StuckSpotRepeatHits it leaves the monster it walks to and keeps its walks off the spot. StuckSpotSeq: every stuck noted. + internal int StuckSpotHits => _stuckSpotHits; + internal int StuckSpotSeq { get; private set; } + internal const int StuckSpotRepeatHits = StuckSpotRepeat; + + // ── Where a stuck happened (2026-11-18) ────────────────────────────────── + // Only 2 of the logged dungeon stucks had a position, and the 0x01F5 and A9B4 replays failed for want of z. + // Every "Nav: stuck xN" line ends with " | " and the spot as key=value words, on the one line: + // cell=0x019001A2 at=(262.00,38.00,-12.00) heading=271 desired=268 target=[5] to=(263.10,38.20,-12.00) 1.1m + // moved=0.42m/5.0s walk=Circular + // at/to are local to the character's landblock (a dungeon's coordinates); heading is where it faces, desired + // where nav last steered it (0 = north, clockwise); target is the route index, "[5]/detour#3:2/4" on a detour + // (its point 2 of 4); moved is the stuck watchdog's window; walk is hunt, navmesh (a planned GoTo) or the + // route's type. + private string _lastStuckWhere = string.Empty; + private long _lastStuckAt; + private int _lastStuckCount; + + /// The last stuck's spot (the words after " | " on its stuck line); empty before the first stuck. + internal string LastStuckWhere => _lastStuckWhere; + + /// "; last nav stuck x2 4.1s ago: cell=..." for a line about the same trouble logged later (the explore's + /// stuck for good); empty when nav hasn't been stuck. + internal string LastStuckNote() + => _lastStuckWhere.Length == 0 ? string.Empty + : string.Create(CultureInfo.InvariantCulture, $"; last nav stuck x{_lastStuckCount} {(Now - _lastStuckAt) / 1000.0:F1}s ago: {_lastStuckWhere}"); + + private string StuckWhere(NavRouteParser route) + { + var inv = CultureInfo.InvariantCulture; + var sb = new StringBuilder(200); + bool pose = _host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz, out _, out _, out _, out _) && cell != 0; + if (pose) sb.Append(inv, $"cell=0x{cell:X8} at=({lx:F2},{ly:F2},{lz:F2})"); + else sb.Append("cell=? at=?"); + sb.Append(TryGetQuaternionHeading(out float heading) ? string.Create(inv, $" heading={heading:F0}") : " heading=?"); + sb.Append(double.IsNaN(_lastDesiredDeg) ? " desired=?" : string.Create(inv, $" desired={_lastDesiredDeg:F0}")); + + // The point it was heading for: a detour's when one is walked, else the route's. + int idx = _settings.ActiveNavIndex; + NavPoint? t = null; + string which = $"[{idx}]"; + var d = _detour; + if (d != null && d.Index < d.Points.Count) { t = d.Points[d.Index]; which = $"[{idx}]/detour#{d.Number}:{d.Index + 1}/{d.Points.Count}"; } + else if (IndexValid(idx, route)) t = route.Points[idx]; + sb.Append(" target=").Append(which); + if (t != null && pose) + { + double ox = ((cell >> 24) & 0xFF) * 192.0, oy = ((cell >> 16) & 0xFF) * 192.0; + double tx = NavToWorld(t.EW) - ox, ty = NavToWorld(t.NS) - oy, tz = t.Z * 240.0; + double off = Math.Sqrt((tx - lx) * (tx - lx) + (ty - ly) * (ty - ly)); + sb.Append(inv, $" to=({tx:F2},{ty:F2},{tz:F2}) {off:F1}m"); + } + sb.Append(double.IsNaN(_watchdogMovedYd) ? " moved=?" : string.Create(inv, $" moved={_watchdogMovedYd:F2}m/{_watchdogWindowMs / 1000.0:F1}s")); + sb.Append(" walk=").Append(route.OutdoorHuntWalk ? "hunt" : route.NavmeshCorners ? "navmesh" : route.RouteType.ToString()); + return sb.ToString(); + } + private void NoteStuckSpot() { if (!TryGetPos(out double ns, out double ew)) return; + StuckSpotSeq++; if (!double.IsNaN(_stuckSpotNs) && NavYd(ns - _stuckSpotNs, ew - _stuckSpotEw) <= StuckSpotYards) { _stuckSpotHits++; @@ -3018,6 +3218,8 @@ internal sealed class NavigationEngine Number = number, Reason = reason, Planner = plan.Planner, + Navmesh = plan.NavmeshCorners, + TargetMoved = plan.TargetMoved && plan.Points.Count > 0, Points = plan.Points, StartIdx = idx, RejoinIdx = rejoin, @@ -3105,7 +3307,11 @@ internal sealed class NavigationEngine var p = d.Points[d.Index]; double dist = NavYd(p.NS - ns, p.EW - ew); - if (dist < ReachFor(p) || (d.ClosestDist < SweepFor(p) && dist > d.ClosestDist + 0.3)) + double look = Math.Min(LookaheadYards, 2.0); + var next = d.Index + 1 < d.Points.Count ? d.Points[d.Index + 1] : route.Points[d.RejoinIdx]; + // A navmesh detour is RynthNav's path too: its corners wait for a clear raycast (the corner gate). + bool cornerOpen = !d.Navmesh || NavmeshRaycast == null || CornerOpen(p, next, dist, look); + if (dist < (cornerOpen ? ReachFor(p) : TightReachYd) || (d.ClosestDist < SweepFor(p) && dist > d.ClosestDist + 0.3)) { d.Index++; d.ClosestDist = double.MaxValue; @@ -3113,6 +3319,15 @@ internal sealed class NavigationEngine { // Back on the route: resume at the rejoin waypoint; normal nav walks the last leg. _settings.ActiveNavIndex = d.RejoinIdx; + if (d.TargetMoved) + { + // The waypoint is inside something placed (0x00C1 room 81: a statue's middle) and the detour's last + // point is the nearest spot clear of it: that is reaching it. Walking on at it ran into the + // statue again, stuck after stuck, until the detours were used up. + Advance(route); + EndDetour($"reached the spot nearest [{d.RejoinIdx}] (it is inside something placed), on to [{_settings.ActiveNavIndex}]", success: true); + return; + } EndDetour($"rejoined the route at [{d.RejoinIdx}]", success: true); } return; @@ -3120,12 +3335,10 @@ internal sealed class NavigationEngine d.ClosestDist = Math.Min(d.ClosestDist, dist); // Aim point: blend toward the following point near arrival, but less than the - // route does (doorways are narrow). + // route does (doorways are narrow), and not at a corner the gate holds. double tNS = p.NS, tEW = p.EW; - double look = Math.Min(LookaheadYards, 2.0); - if (look > 0.0 && dist < look && !p.Doorway) + if (look > 0.0 && dist < look && !p.Doorway && cornerOpen) { - var next = d.Index + 1 < d.Points.Count ? d.Points[d.Index + 1] : route.Points[d.RejoinIdx]; double t = 1.0 - dist / look; tNS = Lerp(p.NS, next.NS, t); tEW = Lerp(p.EW, next.EW, t); @@ -3154,6 +3367,8 @@ internal sealed class NavigationEngine d.Points = plan.Points; d.Index = 0; d.Planner = plan.Planner; + d.Navmesh = plan.NavmeshCorners; + d.TargetMoved = plan.TargetMoved && plan.Points.Count > 0; d.LengthYd = plan.LengthYd; d.Doorways = plan.Doorways; d.DoorRequests.Clear(); diff --git a/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs index 823b47d..cda18c9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/OutdoorHunt.cs @@ -224,6 +224,8 @@ internal sealed class OutdoorHunt Anchor = at; TargetId = 0; _skip.Clear(); + _skipCells.Clear(); + _snags.Clear(); _lastPlan = _lastPick = _arrivedSince = DateTime.MinValue; Note = $"started at {at.X:0},{at.Y:0}"; } @@ -239,6 +241,24 @@ internal sealed class OutdoorHunt /// Left out of the hunt for a while (no way to it, or combat gave up on it). public void Skip(int id, DateTime now, double sec = -1) => _skip[id] = now.AddSeconds(sec < 0 ? SkipSec : sec); + /// A building's cell a walk ended a floor under: every monster in it is left out this long. + public double SkipCellSec { get; set; } = 600; + private readonly Dictionary _skipCells = new(); + /// Under the monster being walked to (this near, a floor apart) this long in all: the walk can't get up there. + public double UnderItSec { get; set; } = 3; + public double UnderItYd { get; set; } = 4; + private double _underSec; // time under the target so far (UnderItSec) + private DateTime _underLast = DateTime.MinValue; // the last tick under it (MinValue: not under it) + private void NewTarget() { _underSec = 0; _underLast = DateTime.MinValue; } + + internal bool CellSkipped(uint cell, DateTime now) + { + if (cell == 0 || !_skipCells.TryGetValue(cell, out var until)) return false; + if (now < until) return true; + _skipCells.Remove(cell); + return false; + } + public bool IsSkipped(int id, DateTime now) { if (!_skip.TryGetValue(id, out var until)) return false; @@ -292,16 +312,31 @@ internal sealed class OutdoorHunt // rooms" to one on the floor above went to the spot under it; it moved about up there, so each walk // planned again ended a yard or two off, and it was walked again every half second for 20 s; nav's // points count as reached by the flat distance). - bool floorApart = t is Candidate under && routeDone && !IsSkipped(under.Id, now) - && me.FlatDistanceTo(_plannedTo) <= ReachYd && Math.Abs(under.Pos.Z - me.Z) > ReachRiseYd; + // Or, walk over or not, it has been under the monster (a floor apart) for UnderItSec in all: the + // monster moving about up there made each walk planned again a fresh one, so the walk never ran + // out and the character circled under it (2026-11-17 10:55:43, Thread E74E, 16 s: "doing circles"). + if (t is Candidate near && me.FlatDistanceTo(near.Pos) <= UnderItYd && Math.Abs(near.Pos.Z - me.Z) > ReachRiseYd) + { + if (_underLast != DateTime.MinValue) _underSec += Math.Min(1.0, (now - _underLast).TotalSeconds); + _underLast = now; + } + else _underLast = DateTime.MinValue; + bool floorApart = t is Candidate under && !IsSkipped(under.Id, now) && Math.Abs(under.Pos.Z - me.Z) > ReachRiseYd + && ((routeDone && me.FlatDistanceTo(_plannedTo) <= ReachYd) || _underSec >= UnderItSec); if (floorApart) { var u = t!.Value; Skip(u.Id, now); + // The spot too (a building's cell): the others up there are no nearer (2026-11-17, Thread + // E74E: a Tormentor, a Reaver and an Excruciator on one platform were walked under one after + // another, 10:15 to 10:17, and each again 120 s later). + bool spot = IsIndoorCell(u.Cell); + if (spot) _skipCells[u.Cell] = now.AddSeconds(SkipCellSec); Note = $"'{u.Name}': the walk to it ended {Math.Abs(u.Pos.Z - me.Z):0} yd {(u.Pos.Z > me.Z ? "below" : "above")} it " - + $"(another floor, no way there found): left out for {SkipSec:0} s"; + + $"(another floor, no way there found): left out for {SkipSec:0} s" + + (spot ? $", and every monster in its cell {u.Cell & 0xFFFF:X4} for {SkipCellSec / 60:0} min" : ""); } - else if (t is Candidate target && InArea(target.Pos) && !IsSkipped(target.Id, now) && Plannable(target)) + else if (t is Candidate target && InArea(target.Pos) && !IsSkipped(target.Id, now) && !CellSkipped(target.Cell, now) && Plannable(target)) { double since = (now - _lastPlan).TotalSeconds; bool moved = target.Pos.DistanceTo(_plannedTo) > ReplanMovedYd && since >= ReplanMinSec; @@ -334,6 +369,7 @@ internal sealed class OutdoorHunt } TargetId = 0; _arrivedSince = DateTime.MinValue; + NewTarget(); } // Choosing (at most once every PickEverySec): the few nearest, by the walk to them. @@ -347,7 +383,7 @@ internal sealed class OutdoorHunt { if (asked >= PickCandidates) break; if (c.Distance > RangeYd) break; // nearest first - if (!InArea(c.Pos) || IsSkipped(c.Id, now) || !Plannable(c)) continue; + if (!InArea(c.Pos) || IsSkipped(c.Id, now) || CellSkipped(c.Cell, now) || !Plannable(c)) continue; asked++; var w = PlanWalk(me, meCell, c.Pos, c.Cell); var p = w.P; @@ -377,7 +413,9 @@ internal sealed class OutdoorHunt /// The chosen monster becomes the target: walked to, or stood by when the walk's end is already here. private Decision Go(DateTime now, Candidate c, HuntWalk w, string pack = "") { + if (TargetId != c.Id) NewTarget(); TargetId = c.Id; + _targetName = c.Name; _plannedTo = c.Pos; _lastPlan = now; Note = NextNote(c, w, pack); @@ -393,7 +431,7 @@ internal sealed class OutdoorHunt /// Nothing to hunt: wait where it is (no walk back to the start: Tom 10-23, "it shouldn't bother"). private Decision Waiting() { - string wait = $"nothing within Hunt Range ({RangeYd:0} yd){(RadiusYd > 0 ? $" inside Hunt Radius ({RadiusYd:0} yd)" : "")}: waiting here"; + string wait = $"nothing within Hunt Range ({RangeYd:0} yd){(RadiusYd > 0 ? $" inside Hunt Radius ({RadiusYd:0} yd)" : "")}{(Fence != null ? " inside the fence" : "")}: waiting here"; if (_note != wait) Note = wait; return new Decision(Act.Idle); } @@ -415,7 +453,7 @@ internal sealed class OutdoorHunt foreach (var c in candidates) { if (c.Distance > RangeYd) break; // nearest first - if (!InArea(c.Pos) || IsSkipped(c.Id, now) || !Plannable(c)) continue; + if (!InArea(c.Pos) || IsSkipped(c.Id, now) || CellSkipped(c.Cell, now) || !Plannable(c)) continue; _eligible.Add(c); if (_eligible.Count >= MaxPackCandidates) break; } @@ -621,7 +659,10 @@ internal sealed class OutdoorHunt return new Decision(Act.Walk, way, TargetId, Note); } - private bool InArea(Vec p) => RadiusYd <= 0 || p.FlatDistanceTo(Anchor) <= RadiusYd; + private bool InArea(Vec p) => (RadiusYd <= 0 || p.FlatDistanceTo(Anchor) <= RadiusYd) && (Fence == null || Fence(p)); + + /// The hunt fence (RynthAiPlugin.HuntFence.cs): a monster it says no to is left out of the picks. Null: no fence. + public Func? Fence { get; set; } /// /// The walk ends where the character stands already (within ArrivedYd, across): nothing to walk, whatever @@ -632,7 +673,75 @@ internal sealed class OutdoorHunt private bool Reaches(PathResult p, Vec goal) => p.Corners.Count > 0 && (p.Status == PathStatus.Ok || (p.Status == PathStatus.Partial && p.Gap <= ReachYd)) - && p.Length <= RangeYd * MaxWalkFactor && Math.Abs(EndRise(p, goal)) <= ReachRiseYd; + && p.Length <= RangeYd * MaxWalkFactor && !TooFarRound(p, goal) && Math.Abs(EndRise(p, goal)) <= ReachRiseYd + && WalkInFence(p) && !BySnag(p); + + /// + /// A walk longer than DetourFactor times the straight line to the monster, plus DetourSlackYd, is too far + /// round for it. 2026-11-17 11:13:58, the fort Thread 3073: a Threadbound Rynthid Slayer 68 yd away got a + /// 425 yd walk, up onto the fort's wall, where the character stuck on a piece of wall for 90 s and then died + /// ("It's running into a small piece of fort wall, it did climb the wall to find a monster"). + /// + public double DetourFactor { get; set; } = 3; + public double DetourSlackYd { get; set; } = 60; + private bool TooFarRound(PathResult p, Vec goal) => p.Length > DetourFactor * _meNow.DistanceTo(goal) + DetourSlackYd; + + // ── Snags: where navigation stuck on a hunt walk again and again ─────────────────────────────── + // RynthNav's map doesn't hold every obstacle (a piece of the fort wall in Thread 3073: "RynthNav sees a + // clear straight line (the snag isn't on its map)"), and the hunt planned the same walk through it again + // every 8 s while navigation's stuck escapes went round for 90 s. The plugin tells the hunt (Snagged) when + // a spot has stuck the walk StuckSpotRepeat times: the monster walked to is left out, and no walk passes + // within SnagYd of the spot for SnagSec. + + public double SnagYd { get; set; } = 4; + public double SnagSec { get; set; } = 600; + private readonly List<(Vec At, DateTime Until)> _snags = new(); + private string _targetName = ""; + internal int SnagCount => _snags.Count; + + /// Navigation stuck at again and again on the hunt's walk. + public void Snagged(DateTime now, Vec at) + { + _snags.RemoveAll(s => s.Until <= now); + int i = _snags.FindIndex(s => s.At.FlatDistanceTo(at) <= SnagYd && Math.Abs(s.At.Z - at.Z) <= ReachRiseYd); + if (i >= 0) _snags[i] = (_snags[i].At, now.AddSeconds(SnagSec)); + else _snags.Add((at, now.AddSeconds(SnagSec))); + if (TargetId == 0) return; + Skip(TargetId, now); + Note = $"stuck at {at.X:0},{at.Y:0} again and again on the walk to '{_targetName}': it is left out for {SkipSec:0} s, " + + $"and no walk goes by that spot for {SnagSec / 60:0} min"; + TargetId = 0; + _arrivedSince = DateTime.MinValue; + NewTarget(); + } + + /// + /// The walk passes within SnagYd of a snag (at its height). Not one at the walk's start: standing at a + /// snag, every walk would start "by" it, and the hunt would stand there. + /// + private bool BySnag(PathResult p) + { + if (_snags.Count == 0) return false; + Vec a = _meNow; + foreach (var b in p.Corners) + { + foreach (var (s, until) in _snags) + { + if (until <= _now || s.FlatDistanceTo(_meNow) <= SnagYd) continue; + double dx = b.X - a.X, dy = b.Y - a.Y, l2 = dx * dx + dy * dy; + double t = l2 < 1e-9 ? 0 : Math.Clamp(((s.X - a.X) * dx + (s.Y - a.Y) * dy) / l2, 0, 1); + var q = new Vec(a.X + dx * t, a.Y + dy * t, a.Z + (b.Z - a.Z) * t); + if (q.FlatDistanceTo(s) <= SnagYd && Math.Abs(q.Z - s.Z) <= ReachRiseYd) return true; + } + a = b; + } + return false; + } + + /// The hunt fence's walk test (RynthAiPlugin.HuntFence.cs): false when the walk's corners go out past + /// what it allows (a monster inside the fence with the way to it round the outside). Null: any walk. + public Func, bool>? WalkFence { get; set; } + private bool WalkInFence(PathResult p) => WalkFence == null || WalkFence(_meNow, p.Corners); /// How far the monster is above (+) or below (-) the walk's end. private static double EndRise(PathResult p, Vec goal) => p.Corners.Count > 0 ? goal.Z - p.Corners[^1].Z : 0; @@ -645,6 +754,12 @@ internal sealed class OutdoorHunt : $"{-EndRise(p, goal):0} yd below the walk's end", _ when p.Corners.Count > 0 && p.Length > RangeYd * MaxWalkFactor && (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => $"a {p.Length:0} yd walk, too far round", + _ when p.Corners.Count > 0 && TooFarRound(p, goal) + && (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => $"a {p.Length:0} yd walk, too far round for one {_meNow.DistanceTo(goal):0} yd away", + _ when p.Corners.Count > 0 && !WalkInFence(p) + && (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => "the walk goes out past the fence", + _ when p.Corners.Count > 0 && BySnag(p) + && (p.Status == PathStatus.Ok || p.Status == PathStatus.Partial) => "the walk goes by a spot it got stuck at", _ when why.Length > 0 => why, PathStatus.Partial => $"the walk ends {p.Gap:0} yd short", PathStatus.NoPath => "no walkable way", diff --git a/Plugins/RynthCore.Plugin.RynthAi/PlacedSolid.cs b/Plugins/RynthCore.Plugin.RynthAi/PlacedSolid.cs new file mode 100644 index 0000000..9811caf --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/PlacedSolid.cs @@ -0,0 +1,734 @@ +// PlacedSolid: the space a placed object fills, column by column (2026-11-18). +// +// The dungeon map's placed objects (an altar, a table, a statue: the EnvCells' stabs, as physics triangles) +// were cut at three heights over their floor (0.5, 1.0 and 1.5 m). What lay between or above the cuts was +// missed: the tops of the 0x01003694 tables (1.5 of their 2.4 m2), the 0x020003B3 rails at 0.79-0.92 m, +// beams between 1.5 m and the body's top. And a cut that came out as an open line (a lone plane, a fence, a +// web) read as filled on one side: 0x02001A58 was 31.5 m2 inside against an 11.3 m2 real footprint. +// +// This is the object as solid columns instead: the ground under it in 0.1 m squares, each square with the +// height ranges where something is. They come from +// - a cross-section every 0.1 m up the object: a closed one (a box's sides cut round) is filled, an open +// one (a plane, a web's strands) counts as its line only and is never filled; +// - every sloped or flat polygon at its own height over each square it covers (a table top, a ramp). +// Something is in a body's way where its column has anything between the body's feet + 0.45 and its top. +// +// A model is made once per setup and kept: the same object placed again, turned about the vertical and moved, +// is the same solid in its own frame, so later copies only turn a query point into that frame. A copy that is +// tilted or scaled otherwise (the triangles don't match once turned) gets a model of its own. +// +// Any triangle set is taken, closed or open; the frame's axes follow the object's own edges (the commonest +// edge direction), so a box's sides fall along the columns however it is turned in the world. + +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.Raycasting; + +namespace RynthCore.Plugin.RynthAi; + +/// One object's solid model, in its own frame (metres from its first vertex, turned by ). +internal sealed class PlacedSolid +{ + /// Column size and cross-section spacing (metres). + internal const double Res = 0.1; + // Bigger objects than this many columns (50 x 50 m) get coarser columns; taller than this many sections, coarser sections. + private const int MaxColumns = 250_000, MaxLevels = 1200; + // A copy is the same model when every vertex is within this of the model's, once turned and moved. + private const double MatchTolerance = 0.02; + // A walkable face (WalkableNz either way up) is exposed when nothing of the object is this far over it. + private const double ExposedFrom = 0.15, ExposedTo = 0.6; + + /// The frame's turn from world east, for the copy it was made from (radians). + public readonly double Yaw; + /// Column size ( unless the object is huge). + public readonly double Step; + /// The raster's corner in the model frame, and its size in columns (with one empty column round). + public readonly double U0, V0; + public readonly int NU, NV; + /// Its lowest and highest point (model frame: height over the first vertex). + public readonly double MinW, MaxW; + /// A walkable face at its top (a bench's seat, a dais), for the step-over class. + public readonly bool WalkableTop; + + private readonly int[] _start; // per column, its first range in _ranges (NU * NV + 1) + private readonly float[] _ranges; // lo, hi pairs, model frame + private readonly float[] _ref; // the triangles' vertices in the model frame (u, v, w), to match a copy + private readonly int _far; // the vertex farthest from the first, across: sets a copy's turn + private readonly int[] _walkFaces; // exposed walkable faces (triangle index) + private readonly float[] _walkArea; + private readonly Dictionary _bands = new(); + + public int VertexCount => _ref.Length / 3; + public int WalkFaceCount => _walkFaces.Length; + internal double WalkFaceArea(int k) => _walkArea[k]; + + /// Roughly what the model holds in memory (bytes). + public long Bytes => 160 + 4L * (_start.Length + _ranges.Length + _ref.Length + _walkFaces.Length + _walkArea.Length); + + // ── Cache ─────────────────────────────────────────────────────────────── + + private static readonly Dictionary> _cache = new(); + private static long _cacheBytes; + // Past this the cache starts again (a long session through many dungeons): the maps made keep their models. + private const long CacheBytesMax = 64L << 20; + + internal static int CachedModels { get { lock (_cache) { int n = 0; foreach (var l in _cache.Values) n += l.Count; return n; } } } + internal static long CachedBytes { get { lock (_cache) return _cacheBytes; } } + internal static void ClearCache() { lock (_cache) { _cache.Clear(); _cacheBytes = 0; } } + + /// + /// The object as placed: its triangles (world metres, three vertices a triangle) as a + /// model turned and moved into place, the model made now or taken from the cache. Null for fewer than one triangle. + /// + internal static PlacedShape? Place(uint setup, Vector3[] tris) + { + if (tris == null || tris.Length < 3) return null; + int n = tris.Length - tris.Length % 3; + double ax = tris[0].X, ay = tris[0].Y, az = tris[0].Z; + 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; + } + PlacedSolid? model = null; + double yaw = 0; + lock (_cache) + { + if (_cache.TryGetValue(setup, out var list)) + foreach (var m in list) + if (m.VertexCount == n && m.Match(tris, n, ax, ay, az, out yaw)) { model = m; break; } + } + if (model == null) + { + model = Build(tris, n, ax, ay, az); + yaw = model.Yaw; + lock (_cache) + { + if (_cacheBytes + model.Bytes > CacheBytesMax) { _cache.Clear(); _cacheBytes = 0; } + if (!_cache.TryGetValue(setup, out var list)) _cache[setup] = list = new List(1); + list.Add(model); + _cacheBytes += model.Bytes; + } + } + return new PlacedShape(model, ax, ay, az, yaw, minX, minY, minZ, maxX, maxY, maxZ); + } + + // The copy's turn from the far vertex, then every vertex checked. + private bool Match(Vector3[] t, int n, double ax, double ay, double az, out double yaw) + { + double rx = t[_far].X - ax, ry = t[_far].Y - ay; + double fu = _ref[3 * _far], fv = _ref[3 * _far + 1]; + yaw = fu * fu + fv * fv > 0.0025 && rx * rx + ry * ry > 0.0025 ? Math.Atan2(ry, rx) - Math.Atan2(fv, fu) : Yaw; + double c = Math.Cos(yaw), s = Math.Sin(yaw); + for (int k = 0; k < n; k++) + { + double dx = t[k].X - ax, dy = t[k].Y - ay; + if (Math.Abs(dx * c + dy * s - _ref[3 * k]) > MatchTolerance + || Math.Abs(-dx * s + dy * c - _ref[3 * k + 1]) > MatchTolerance + || Math.Abs(t[k].Z - az - _ref[3 * k + 2]) > MatchTolerance) return false; + } + return true; + } + + private static PlacedSolid Build(Vector3[] t, int n, double ax, double ay, double az) + { + // The frame follows the commonest horizontal edge direction (mod 90 degrees): a box's sides along the columns. + double cs = 0, sn = 0; + for (int i = 0; i + 2 < n; i += 3) + for (int e = 0; e < 3; e++) + { + var p = t[i + e]; var q = t[i + (e + 1) % 3]; + double dx = q.X - p.X, dy = q.Y - p.Y, h = Math.Sqrt(dx * dx + dy * dy); + if (h < 1e-4) continue; + double c = dx / h, s = dy / h, c2 = c * c - s * s, s2 = 2 * c * s; + cs += h * (c2 * c2 - s2 * s2); + sn += h * 2 * c2 * s2; + } + double yaw = cs * cs + sn * sn > 1e-12 ? Math.Atan2(sn, cs) / 4 : 0; + double co = Math.Cos(yaw), si = Math.Sin(yaw); + var refv = new float[n * 3]; + for (int k = 0; k < n; k++) + { + double dx = t[k].X - ax, dy = t[k].Y - ay; + refv[3 * k] = (float)(dx * co + dy * si); + refv[3 * k + 1] = (float)(-dx * si + dy * co); + refv[3 * k + 2] = (float)(t[k].Z - az); + } + return new PlacedSolid(refv, yaw); + } + + // ── Making the columns ────────────────────────────────────────────────── + + private readonly struct Piece : IComparable + { + public readonly int Col; public readonly float Lo, Hi; + public Piece(int col, float lo, float hi) { Col = col; Lo = lo; Hi = hi; } + public int CompareTo(Piece o) => Col != o.Col ? Col.CompareTo(o.Col) : Lo.CompareTo(o.Lo); + } + + private PlacedSolid(float[] refv, double yaw) + { + _ref = refv; + Yaw = yaw; + int nv = refv.Length / 3, nt = nv / 3; + double minU = double.MaxValue, minV = double.MaxValue, minW = double.MaxValue, maxU = double.MinValue, maxV = double.MinValue, maxW = double.MinValue, far = -1; + for (int k = 0; k < nv; k++) + { + double u = refv[3 * k], v = refv[3 * k + 1], w = refv[3 * k + 2]; + minU = Math.Min(minU, u); maxU = Math.Max(maxU, u); + minV = Math.Min(minV, v); maxV = Math.Max(maxV, v); + minW = Math.Min(minW, w); maxW = Math.Max(maxW, w); + if (u * u + v * v > far) { far = u * u + v * v; _far = k; } + } + MinW = minW; MaxW = maxW; + double step = Res; + while (((maxU - minU) / step + 3) * ((maxV - minV) / step + 3) > MaxColumns) step *= 2; + Step = step; + U0 = Math.Floor(minU / step) * step - step; + V0 = Math.Floor(minV / step) * step - step; + NU = (int)Math.Floor((maxU - U0) / step) + 2; + NV = (int)Math.Floor((maxV - V0) / step) + 2; + int ncol = NU * NV; + var pieces = new List(); + + // Cross-sections at z_k = (k + 0.5) * lstep, the ones with a vertex under and one at or over them. + double lstep = step; + if ((maxW - minW) / lstep > MaxLevels) lstep = (maxW - minW) / MaxLevels; + int kFirst = (int)Math.Floor(minW / lstep - 0.5) + 1, kLast = (int)Math.Floor(maxW / lstep - 0.5); + int nl = Math.Max(0, kLast - kFirst + 1); + if (nl > 0) + { + var off = new int[nl + 1]; + void Span(int tri, out int k0, out int k1) + { + double z0 = Math.Min(refv[9 * tri + 2], Math.Min(refv[9 * tri + 5], refv[9 * tri + 8])); + double z1 = Math.Max(refv[9 * tri + 2], Math.Max(refv[9 * tri + 5], refv[9 * tri + 8])); + k0 = Math.Max(kFirst, (int)Math.Floor(z0 / lstep - 0.5) + 1); + k1 = Math.Min(kLast, (int)Math.Floor(z1 / lstep - 0.5)); + } + for (int tri = 0; tri < nt; tri++) + { + Span(tri, out int k0, out int k1); + for (int k = k0; k <= k1; k++) off[k - kFirst + 1]++; + } + for (int l = 0; l < nl; l++) off[l + 1] += off[l]; + var byLevel = new int[off[nl]]; + var fillAt = (int[])off.Clone(); + for (int tri = 0; tri < nt; tri++) + { + Span(tri, out int k0, out int k1); + for (int k = k0; k <= k1; k++) byLevel[fillAt[k - kFirst]++] = tri; + } + + var runLo = new float[ncol]; + var runHi = new float[ncol]; + for (int c = 0; c < ncol; c++) runHi[c] = float.NaN; + var stamp = new int[ncol]; + var marked = new List(); + var section = new Section(this); + for (int l = 0; l < nl; l++) + { + double z = (kFirst + l + 0.5) * lstep; + section.Begin(l + 1, stamp, marked); + for (int q = off[l]; q < off[l + 1]; q++) section.Cut(refv, byLevel[q], z); + section.Mark(); + float zf = (float)z; + foreach (int c in marked) + { + if (!float.IsNaN(runHi[c]) && zf - runHi[c] <= lstep * 1.01) { runHi[c] = zf; continue; } + if (!float.IsNaN(runHi[c])) pieces.Add(new Piece(c, runLo[c], runHi[c])); + runLo[c] = runHi[c] = zf; + } + } + for (int c = 0; c < ncol; c++) + if (!float.IsNaN(runHi[c])) pieces.Add(new Piece(c, runLo[c], runHi[c])); + } + + // Sloped and flat polygons at their own height over every column centre they cover. + for (int tri = 0; tri < nt; tri++) + { + double au = refv[9 * tri], av = refv[9 * tri + 1], aw = refv[9 * tri + 2]; + double bu = refv[9 * tri + 3], bv = refv[9 * tri + 4], bw = refv[9 * tri + 5]; + double cu = refv[9 * tri + 6], cv = refv[9 * tri + 7], cw = refv[9 * tri + 8]; + double d = (bv - cv) * (au - cu) + (cu - bu) * (av - cv); + if (Math.Abs(d) < 1e-9) continue; // upright: its cross-sections have it + int i0 = Math.Max(0, (int)Math.Ceiling((Math.Min(au, Math.Min(bu, cu)) - U0) / step - 0.5)); + int i1 = Math.Min(NU - 1, (int)Math.Floor((Math.Max(au, Math.Max(bu, cu)) - U0) / step - 0.5)); + int j0 = Math.Max(0, (int)Math.Ceiling((Math.Min(av, Math.Min(bv, cv)) - V0) / step - 0.5)); + int j1 = Math.Min(NV - 1, (int)Math.Floor((Math.Max(av, Math.Max(bv, cv)) - V0) / step - 0.5)); + for (int j = j0; j <= j1; j++) + { + double y = V0 + (j + 0.5) * step; + for (int i = i0; i <= i1; i++) + { + double x = U0 + (i + 0.5) * step; + double l1 = ((bv - cv) * (x - cu) + (cu - bu) * (y - cv)) / d; + double l2 = ((cv - av) * (x - cu) + (au - cu) * (y - cv)) / d; + double l3 = 1 - l1 - l2; + if (l1 < -1e-9 || l2 < -1e-9 || l3 < -1e-9) continue; + float w = (float)(l1 * aw + l2 * bw + l3 * cw); + pieces.Add(new Piece(j * NU + i, w, w)); + } + } + } + + // Each column's pieces sorted and joined where less than a section apart (a body can't be between). + pieces.Sort(); + _start = new int[ncol + 1]; + var ranges = new List(pieces.Count); + double gap = lstep * 1.01 + 1e-4; + int at = 0; + for (int c = 0; c < ncol; c++) + { + _start[c] = ranges.Count / 2; + if (at >= pieces.Count || pieces[at].Col != c) continue; + float lo = pieces[at].Lo, hi = pieces[at].Hi; + for (at++; at < pieces.Count && pieces[at].Col == c; at++) + { + if (pieces[at].Lo <= hi + gap) { if (pieces[at].Hi > hi) hi = pieces[at].Hi; continue; } + ranges.Add(lo); ranges.Add(hi); + lo = pieces[at].Lo; hi = pieces[at].Hi; + } + ranges.Add(lo); ranges.Add(hi); + } + _start[ncol] = ranges.Count / 2; + _ranges = ranges.ToArray(); + + // Walkable faces (steep enough to stand on, either way up) with nothing of the object just over them. + var walk = new List(); + var walkArea = new List(); + double topArea = 0; + for (int tri = 0; tri < nt; tri++) + { + double au = refv[9 * tri], av = refv[9 * tri + 1], aw = refv[9 * tri + 2]; + double bu = refv[9 * tri + 3] - au, bv = refv[9 * tri + 4] - av, bw = refv[9 * tri + 5] - aw; + double cu = refv[9 * tri + 6] - au, cv = refv[9 * tri + 7] - av, cw = refv[9 * tri + 8] - aw; + double nx = bv * cw - bw * cv, ny = bw * cu - bu * cw, nz = bu * cv - bv * cu; + double len = Math.Sqrt(nx * nx + ny * ny + nz * nz); + if (len < 1e-9 || Math.Abs(nz) / len < DungeonGeometry.WalkableNz) continue; + double mu = au + (bu + cu) / 3, mv = av + (bv + cv) / 3, mw = aw + (bw + cw) / 3; + if (SolidAt(mu, mv, mw + ExposedFrom, mw + ExposedTo)) continue; + walk.Add(tri); + walkArea.Add((float)(Math.Abs(nz) / 2)); + double top = Math.Max(aw, Math.Max(aw + bw, aw + cw)); + if (top >= maxW - 0.1) topArea += Math.Abs(nz) / 2; + } + _walkFaces = walk.ToArray(); + _walkArea = walkArea.ToArray(); + WalkableTop = topArea >= 0.05; + } + + // One cross-section: its segments, which of them close round (filled) and which are open lines. + private sealed class Section + { + private readonly PlacedSolid _m; + private readonly List _seg = new(); // u0, v0, u1, v1 per segment + private readonly List _segNode = new(); // the two node ids per segment + private readonly Dictionary _nodeAt = new(); + private readonly List _nodeU = new(), _nodeV = new(); + private readonly List _parent = new(), _degree = new(); + private readonly List _cross = new(); + private int _stampValue; + private int[] _stamp = null!; + private List _marked = null!; + private const double NodeSnap = 1e-3; // ends this close are one point (a T-joint's rounding) + + public Section(PlacedSolid m) { _m = m; } + + public void Begin(int stampValue, int[] stamp, List marked) + { + _stampValue = stampValue; _stamp = stamp; _marked = marked; + marked.Clear(); + _seg.Clear(); _segNode.Clear(); _nodeAt.Clear(); _nodeU.Clear(); _nodeV.Clear(); _parent.Clear(); _degree.Clear(); + } + + // Where triangle `tri` crosses z (a vertex at z counts as over it). Each edge is interpolated from its lower + // end, so the two triangles sharing an edge meet at the very same point. + public void Cut(float[] r, int tri, double z) + { + double au = 0, av = 0, bu = 0, bv = 0; + int n = 0; + for (int e = 0; e < 3; e++) + { + int p = 9 * tri + 3 * e, q = 9 * tri + 3 * ((e + 1) % 3); + bool pUp = r[p + 2] >= z, qUp = r[q + 2] >= z; + if (pUp == qUp) continue; + if (pUp) (p, q) = (q, p); + double t = (z - r[p + 2]) / (r[q + 2] - r[p + 2]); + double u = r[p] + (r[q] - r[p]) * t, v = r[p + 1] + (r[q + 1] - r[p + 1]) * t; + if (n == 0) { au = u; av = v; } else { bu = u; bv = v; } + n++; + } + if (n != 2 || (au - bu) * (au - bu) + (av - bv) * (av - bv) < 1e-10) return; + int a = Node(au, av), b = Node(bu, bv); + if (a == b) return; + _seg.Add(au); _seg.Add(av); _seg.Add(bu); _seg.Add(bv); + _segNode.Add(a); _segNode.Add(b); + _degree[a]++; _degree[b]++; + Union(a, b); + } + + private int Node(double u, double v) + { + long qu = (long)Math.Floor(u / NodeSnap), qv = (long)Math.Floor(v / NodeSnap); + for (long du = -1; du <= 1; du++) + for (long dv = -1; dv <= 1; dv++) + if (_nodeAt.TryGetValue(Key(qu + du, qv + dv), out int id) + && Math.Abs(_nodeU[id] - u) <= NodeSnap && Math.Abs(_nodeV[id] - v) <= NodeSnap) return id; + int nid = _nodeU.Count; + _nodeU.Add(u); _nodeV.Add(v); _parent.Add(nid); _degree.Add(0); + _nodeAt[Key(qu, qv)] = nid; + return nid; + } + + private static long Key(long a, long b) => (a << 32) ^ (b & 0xFFFFFFFFL); + + private int Find(int a) + { + while (_parent[a] != a) { _parent[a] = _parent[_parent[a]]; a = _parent[a]; } + return a; + } + + private void Union(int a, int b) { int ra = Find(a), rb = Find(b); if (ra != rb) _parent[ra] = rb; } + + // Closed pieces filled (each on its own, so two overlapping parts don't cancel out), open ones drawn as lines. + public void Mark() + { + int ns = _segNode.Count / 2; + if (ns == 0) return; + var open = new HashSet(); + for (int i = 0; i < _degree.Count; i++) if ((_degree[i] & 1) != 0) open.Add(Find(i)); + var byComp = new Dictionary>(); + for (int s = 0; s < ns; s++) + { + int root = Find(_segNode[2 * s]); + if (!byComp.TryGetValue(root, out var l)) byComp[root] = l = new List(); + l.Add(s); + } + foreach (var (root, segs) in byComp) + { + if (open.Contains(root)) { foreach (int s in segs) Line(s); continue; } + double u0 = double.MaxValue, v0 = double.MaxValue, u1 = double.MinValue, v1 = double.MinValue; + foreach (int s in segs) + { + u0 = Math.Min(u0, Math.Min(_seg[4 * s], _seg[4 * s + 2])); u1 = Math.Max(u1, Math.Max(_seg[4 * s], _seg[4 * s + 2])); + v0 = Math.Min(v0, Math.Min(_seg[4 * s + 1], _seg[4 * s + 3])); v1 = Math.Max(v1, Math.Max(_seg[4 * s + 1], _seg[4 * s + 3])); + } + int filled = Fill(segs, v0, v1); + // A closed piece thinner than two columns (a rail, a thin slab's edge) may cover no column centre: its line too. + if (filled == 0 || Math.Min(u1 - u0, v1 - v0) < 2 * _m.Step) foreach (int s in segs) Line(s); + } + } + + // Even-odd over the piece's own segments, by column centre; how many centres are inside. + private int Fill(List segs, double vMin, double vMax) + { + var m = _m; + int count = 0; + int j0 = Math.Max(0, (int)Math.Ceiling((vMin - m.V0) / m.Step - 0.5)), j1 = Math.Min(m.NV - 1, (int)Math.Floor((vMax - m.V0) / m.Step - 0.5)); + for (int j = j0; j <= j1; j++) + { + double vc = m.V0 + (j + 0.5) * m.Step; + _cross.Clear(); + foreach (int s in segs) + { + double sv0 = _seg[4 * s + 1], sv1 = _seg[4 * s + 3]; + if ((sv0 > vc) == (sv1 > vc)) continue; + double su0 = _seg[4 * s], su1 = _seg[4 * s + 2]; + _cross.Add(su0 + (vc - sv0) * (su1 - su0) / (sv1 - sv0)); + } + if (_cross.Count < 2) continue; + _cross.Sort(); + for (int c = 0; c + 1 < _cross.Count; c += 2) + { + int i0 = Math.Max(0, (int)Math.Ceiling((_cross[c] - m.U0) / m.Step - 0.5)); + int i1 = Math.Min(m.NU - 1, (int)Math.Floor((_cross[c + 1] - m.U0) / m.Step - 0.5)); + for (int i = i0; i <= i1; i++) { Mark(j * m.NU + i); count++; } + } + } + return count; + } + + // Every column the segment passes through (sampled at a quarter column). + private void Line(int s) + { + var m = _m; + double u0 = _seg[4 * s], v0 = _seg[4 * s + 1], u1 = _seg[4 * s + 2], v1 = _seg[4 * s + 3]; + double len = Math.Sqrt((u1 - u0) * (u1 - u0) + (v1 - v0) * (v1 - v0)); + int n = Math.Max(1, (int)Math.Ceiling(len / (m.Step * 0.25))); + for (int k = 0; k <= n; k++) + { + double u = u0 + (u1 - u0) * k / n, v = v0 + (v1 - v0) * k / n; + int i = Math.Clamp((int)Math.Floor((u - m.U0) / m.Step), 0, m.NU - 1), j = Math.Clamp((int)Math.Floor((v - m.V0) / m.Step), 0, m.NV - 1); + Mark(j * m.NU + i); + } + } + + private void Mark(int c) + { + if (_stamp[c] == _stampValue) return; + _stamp[c] = _stampValue; + _marked.Add(c); + } + } + + // ── Queries (model frame) ─────────────────────────────────────────────── + + /// The column holding (u, v), or -1 off the raster. + public int ColumnAt(double u, double v) + { + int i = (int)Math.Floor((u - U0) / Step), j = (int)Math.Floor((v - V0) / Step); + return i < 0 || j < 0 || i >= NU || j >= NV ? -1 : j * NU + i; + } + + /// Something solid in the column at (u, v) between heights lo and hi (model frame). + public bool SolidAt(double u, double v, double lo, double hi) + { + int c = ColumnAt(u, v); + return c >= 0 && SolidIn(c, lo, hi); + } + + private bool SolidIn(int c, double lo, double hi) + { + for (int r = _start[c]; r < _start[c + 1]; r++) + if (_ranges[2 * r] <= hi && _ranges[2 * r + 1] >= lo) return true; + return false; + } + + /// The highest top of something solid in the column at (u, v) that is no higher than wMax (model + /// frame), or -infinity: what a body could stand on there. + public double TopAtMost(double u, double v, double wMax) + { + int c = ColumnAt(u, v); + double best = double.NegativeInfinity; + if (c < 0) return best; + for (int r = _start[c]; r < _start[c + 1]; r++) + if (_ranges[2 * r + 1] <= wMax && _ranges[2 * r + 1] > best) best = _ranges[2 * r + 1]; + return best; + } + + /// The centre of column c (model frame). + public void ColumnCentre(int c, out double u, out double v) + { + u = U0 + (c % NU + 0.5) * Step; + v = V0 + (c / NU + 0.5) * Step; + } + + /// Walkable face k's three corners (model frame). + public void WalkFace(int k, out double au, out double av, out double aw, out double bu, out double bv, out double bw, out double cu, out double cv, out double cw) + { + int t = 9 * _walkFaces[k]; + au = _ref[t]; av = _ref[t + 1]; aw = _ref[t + 2]; + bu = _ref[t + 3]; bv = _ref[t + 4]; bw = _ref[t + 5]; + cu = _ref[t + 6]; cv = _ref[t + 7]; cw = _ref[t + 8]; + } + + /// + /// What is in a body's way between heights lo and hi (model frame): the columns, and their outline as + /// segments (model frame) round every filled patch. Remembered per band (copies on like floors share it). + /// + public PlacedBand Band(double lo, double hi) + { + long key = ((long)Math.Round(lo * 100) << 32) ^ (uint)(int)Math.Round(hi * 100); + lock (_bands) if (_bands.TryGetValue(key, out var have)) return have; + int ncol = NU * NV; + var mask = new bool[ncol]; + var cells = new List(); + for (int c = 0; c < ncol; c++) + if (SolidIn(c, lo, hi)) { mask[c] = true; cells.Add(c); } + var band = new PlacedBand(cells.ToArray(), cells.Count == 0 ? Array.Empty() : Outline(mask), cells.Count * Step * Step); + lock (_bands) if (_bands.Count < 32) _bands[key] = band; + return band; + } + + // Marching squares over the column centres (each filled patch's edge runs half way between a filled centre and + // an empty one: the patch's own side), chained into loops and thinned to within 0.4 of a column. + private double[] Outline(bool[] mask) + { + int nu = NU; + bool M(int i, int j) => mask[j * nu + i]; + int H(int i, int j) => 2 * (j * nu + i); // the edge between centres (i, j) and (i + 1, j) + int Vt(int i, int j) => 2 * (j * nu + i) + 1; // between (i, j) and (i, j + 1) + var link = new Dictionary(); + void Link(int a, int b) + { + link[a] = link.TryGetValue(a, out var la) ? (la.A, b) : (b, -1); + link[b] = link.TryGetValue(b, out var lb) ? (lb.A, a) : (a, -1); + } + for (int j = 0; j + 1 < NV; j++) + for (int i = 0; i + 1 < NU; i++) + { + int code = (M(i, j) ? 1 : 0) | (M(i + 1, j) ? 2 : 0) | (M(i + 1, j + 1) ? 4 : 0) | (M(i, j + 1) ? 8 : 0); + if (code == 0 || code == 15) continue; + int b = H(i, j), r = Vt(i + 1, j), t = H(i, j + 1), l = Vt(i, j); + switch (code) + { + case 1: case 14: Link(l, b); break; + case 2: case 13: Link(b, r); break; + case 3: case 12: Link(l, r); break; + case 4: case 11: Link(r, t); break; + case 6: case 9: Link(b, t); break; + case 7: case 8: Link(t, l); break; + case 5: Link(l, b); Link(r, t); break; // two corners apart: each its own loop + case 10: Link(b, r); Link(t, l); break; + } + } + void At(int id, out double u, out double v) + { + int idx = id >> 1, i = idx % nu, j = idx / nu; + if ((id & 1) == 0) { u = U0 + (i + 1) * Step; v = V0 + (j + 0.5) * Step; } + else { u = U0 + (i + 0.5) * Step; v = V0 + (j + 1) * Step; } + } + var outSegs = new List(); + var done = new HashSet(); + var loopU = new List(); var loopV = new List(); + foreach (int start in link.Keys) + { + if (done.Contains(start)) continue; + loopU.Clear(); loopV.Clear(); + int prev = -1, cur = start; + while (true) + { + done.Add(cur); + At(cur, out double u, out double v); + loopU.Add(u); loopV.Add(v); + var (a, b) = link[cur]; + int next = a != prev ? a : b; + if (next < 0 || next == start || done.Contains(next)) break; + prev = cur; cur = next; + } + Thin(loopU, loopV, 0.4 * Step, outSegs); + } + return outSegs.ToArray(); + } + + // A closed loop thinned (Douglas-Peucker on its two halves) and added as segments. + private static void Thin(List u, List v, double tol, List outSegs) + { + int n = u.Count; + if (n < 2) return; + if (n <= 3) + { + for (int i = 0; i < n; i++) { int k = (i + 1) % n; outSegs.Add(u[i]); outSegs.Add(v[i]); outSegs.Add(u[k]); outSegs.Add(v[k]); } + return; + } + int far = 0; double best = -1; + for (int i = 1; i < n; i++) { double d = (u[i] - u[0]) * (u[i] - u[0]) + (v[i] - v[0]) * (v[i] - v[0]); if (d > best) { best = d; far = i; } } + var keep = new bool[n]; + keep[0] = keep[far] = true; + void Dp(int a, int b) // indices along the loop, b > a (b may be n: the start again) + { + if (b - a < 2) return; + double ax = u[a % n], ay = v[a % n], bx = u[b % n], by = v[b % n]; + double dx = bx - ax, dy = by - ay, len = Math.Sqrt(dx * dx + dy * dy); + int at = -1; double worst = tol; + for (int i = a + 1; i < b; i++) + { + double px = u[i % n] - ax, py = v[i % n] - ay; + double d = len < 1e-12 ? Math.Sqrt(px * px + py * py) : Math.Abs(px * dy - py * dx) / len; + if (d > worst) { worst = d; at = i; } + } + if (at < 0) return; + keep[at % n] = true; + Dp(a, at); Dp(at, b); + } + Dp(0, far); Dp(far, n); + int first = -1, last = -1; + for (int i = 0; i < n; i++) + { + if (!keep[i]) continue; + if (first < 0) first = i; + if (last >= 0) { outSegs.Add(u[last]); outSegs.Add(v[last]); outSegs.Add(u[i]); outSegs.Add(v[i]); } + last = i; + } + if (first >= 0 && last != first) { outSegs.Add(u[last]); outSegs.Add(v[last]); outSegs.Add(u[first]); outSegs.Add(v[first]); } + } +} + +/// What of an object is in a body's way at one band: its columns, outline (u0, v0, u1, v1 per +/// segment, model frame) and area. +internal sealed class PlacedBand +{ + public readonly int[] Cells; + public readonly double[] Outline; + public readonly double Area; + public PlacedBand(int[] cells, double[] outline, double area) { Cells = cells; Outline = outline; Area = area; } + public bool Empty => Cells.Length == 0; +} + +/// One placed copy of a : the model turned by its yaw and moved to its first +/// vertex, with the world box of its triangles. +internal sealed class PlacedShape +{ + public readonly PlacedSolid Model; + public readonly double Ox, Oy, Oz, Yaw, Cos, Sin; + public readonly double MinX, MinY, MinZ, MaxX, MaxY, MaxZ; + + public PlacedShape(PlacedSolid model, double ox, double oy, double oz, double yaw, + double minX, double minY, double minZ, double maxX, double maxY, double maxZ) + { + Model = model; Ox = ox; Oy = oy; Oz = oz; Yaw = yaw; Cos = Math.Cos(yaw); Sin = Math.Sin(yaw); + MinX = minX; MinY = minY; MinZ = minZ; MaxX = maxX; MaxY = maxY; MaxZ = maxZ; + } + + public void ToModel(double x, double y, out double u, out double v) + { + double dx = x - Ox, dy = y - Oy; + u = dx * Cos + dy * Sin; + v = -dx * Sin + dy * Cos; + } + + public void ToWorld(double u, double v, out double x, out double y) + { + x = Ox + u * Cos - v * Sin; + y = Oy + u * Sin + v * Cos; + } + + /// Something of it at (x, y) between world heights zLo and zHi. + public bool SolidIn(double x, double y, double zLo, double zHi) + { + if (x < MinX - 0.1 || x > MaxX + 0.1 || y < MinY - 0.1 || y > MaxY + 0.1 || zHi < MinZ || zLo > MaxZ) return false; + ToModel(x, y, out double u, out double v); + return Model.SolidAt(u, v, zLo - Oz, zHi - Oz); + } + + /// The highest top of it at (x, y) no higher than world height zMax, or -infinity. + public double TopAtMost(double x, double y, double zMax) + { + if (x < MinX - 0.1 || x > MaxX + 0.1 || y < MinY - 0.1 || y > MaxY + 0.1 || zMax < MinZ) return double.NegativeInfinity; + ToModel(x, y, out double u, out double v); + return Model.TopAtMost(u, v, zMax - Oz) + Oz; + } + + /// What of it is in the way between world heights zLo and zHi. + public PlacedBand Band(double zLo, double zHi) => Model.Band(zLo - Oz, zHi - Oz); + + public void CellCentre(int c, out double x, out double y) + { + Model.ColumnCentre(c, out double u, out double v); + ToWorld(u, v, out x, out y); + } + + /// Walkable face k: its world box and height range. + public void WalkFace(int k, out double minX, out double minY, out double maxX, out double maxY, out double z0, out double z1) + { + Model.WalkFace(k, out double au, out double av, out double aw, out double bu, out double bv, out double bw, out double cu, out double cv, out double cw); + ToWorld(au, av, out double ax, out double ay); + ToWorld(bu, bv, out double bx, out double by); + ToWorld(cu, cv, out double cx, out double cy); + minX = Math.Min(ax, Math.Min(bx, cx)); maxX = Math.Max(ax, Math.Max(bx, cx)); + minY = Math.Min(ay, Math.Min(by, cy)); maxY = Math.Max(ay, Math.Max(by, cy)); + z0 = Oz + Math.Min(aw, Math.Min(bw, cw)); z1 = Oz + Math.Max(aw, Math.Max(bw, cw)); + } + + /// Walkable face k's centre (world). + public void WalkFaceCentre(int k, out double x, out double y, out double z) + { + Model.WalkFace(k, out double au, out double av, out double aw, out double bu, out double bv, out double bw, out double cu, out double cv, out double cw); + ToWorld((au + bu + cu) / 3, (av + bv + cv) / 3, out x, out y); + z = Oz + (aw + bw + cw) / 3; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/BoundingVolume.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/BoundingVolume.cs index ae796bc..13f65af 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/BoundingVolume.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/BoundingVolume.cs @@ -36,6 +36,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting public Vector3 Max { get; set; } // Maximum bounds public bool IsDoor { get; set; } // Whether this is a door (passable) public bool NoAabbFallback { get; set; } // If true, only count actual triangle hits (no AABB fallback) + // A cylinder's or a sphere's solid the loader made (GeometryLoader.PlaceCollision), not a model's own polygons: + // round, so never a stair, whatever its ring faces look like (BuildingMap.FurnitureFilter). + public bool Round { get; set; } public BoundingVolume() { diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs index de48911..336fea7 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/DungeonLOS.cs @@ -226,6 +226,13 @@ namespace RynthCore.Plugin.RynthAi.Raycasting foreach (var poly in cellGeo.Polygons) { if (poly.Vertices.Count < 3) continue; + // A portal is an opening, never floor. Only the render-polygon fallback has any + // (a cell with no physics polygons keeps its render ones, portals tagged): an + // open-air cell, all openings. DreamWeave Thread 0x0169's 20 m shaft is four such + // cells (0159/015A/015F/0160, open on every side, a floor portal at 0 down to the + // cave 9-12 m below). Its floor portals read as floor, so the map walked straight + // over the shaft and never saw the drop (2026-11-17). + if (poly.IsPortal) continue; var worldVerts = new Vector3[poly.Vertices.Count]; for (int i = 0; i < poly.Vertices.Count; i++) worldVerts[i] = TransformVertex(poly.Vertices[i], envCell, gx, gy); diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs index 4a89b6a..d4df177 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs @@ -633,105 +633,20 @@ namespace RynthCore.Plugin.RynthAi.Raycasting } /// - /// Loads static objects from dungeon/interior cells in cell.dat. - /// Indoor cells are numbered 0xXXYY0100 through 0xXXYYFFFD. - /// Uses ACE's EnvCell format for correct parsing. + /// Adds the static objects of a landblock's dungeon/interior cells (0xXXYY0100 and up) to the LOS + /// volumes: GetStaticCollision's cell stabs, as AC collides with them. /// private void LoadIndoorCells(uint landblockKey, List volumes) { - float globalOffsetX = ((landblockKey >> 8) & 0xFF) * 192.0f; - float globalOffsetY = (landblockKey & 0xFF) * 192.0f; - - // Use dat index to find ALL cells — no sequential scan with gap cutoff - var cellIds = _cellDat.GetLandblockCellIds(landblockKey); - - foreach (uint cellId in cellIds) - { - byte[] data = _cellDat.GetFileData(cellId); - if (data == null || data.Length < 20) continue; - - try - { - using (var ms = new MemoryStream(data)) - using (var reader = new BinaryReader(ms)) - { - uint id = reader.ReadUInt32(); - uint flags = reader.ReadUInt32(); - reader.ReadUInt32(); // duplicate CellId - - byte numSurfaces = reader.ReadByte(); - byte numPortals = reader.ReadByte(); - ushort numVisibleCells = reader.ReadUInt16(); - - // Skip surfaces - for (int i = 0; i < numSurfaces; i++) - reader.ReadUInt16(); - - ushort envId = reader.ReadUInt16(); - ushort cellStructure = reader.ReadUInt16(); - - // Cell Position (Frame) - float cellX = reader.ReadSingle(); - float cellY = reader.ReadSingle(); - float cellZ = reader.ReadSingle(); - reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); reader.ReadSingle(); // rotation - - // Skip portals (8 bytes each) - for (int i = 0; i < numPortals; i++) - { - if (ms.Position + 8 > ms.Length) break; - reader.ReadUInt64(); // 4 × ushort - } - - // Skip visible cells - for (int i = 0; i < numVisibleCells; i++) - { - if (ms.Position + 2 > ms.Length) break; - reader.ReadUInt16(); - } - - // Read static objects if present (flag 0x02 = HasStaticObjs) - if ((flags & 0x02) != 0 && ms.Position + 4 <= ms.Length) - { - uint numStabs = reader.ReadUInt32(); - if (numStabs > 500) numStabs = 500; - - for (uint i = 0; i < numStabs; i++) - { - if (ms.Position + 32 > ms.Length) break; - - uint setupId = reader.ReadUInt32(); - float px = reader.ReadSingle(); - float py = reader.ReadSingle(); - float pz = reader.ReadSingle(); - float rw = reader.ReadSingle(); - float rx = reader.ReadSingle(); - float ry = reader.ReadSingle(); - float rz = reader.ReadSingle(); - - var frame = new Frame - { - // Static object position is in cell-local space - // Cell position is already in landblock-local space - OriginX = px + cellX, - OriginY = py + cellY, - OriginZ = pz + cellZ, - RotW = rw, RotX = rx, RotY = ry, RotZ = rz - }; - - var objVolumes = GetSetupBoundingVolumes(setupId); - foreach (var vol in objVolumes) - { - var transformed = TransformVolume(vol, frame, globalOffsetX, globalOffsetY); - if (transformed != null) - volumes.Add(transformed); - } - } - } - } - } - catch { } - } + // A stab's frame is already in the landblock's space; this added its cell's origin to it, so + // combat LOS had nothing at 0x0190's table, 0x00C1's statue or 0x000A's altar, and blockers a + // cell's offset away from where anything stands (2026-11-18). The volumes are now the shapes AC + // collides with (physics polygons, else cylinders, else spheres, triangle hits only), not a + // bounding sphere or box round the model: a shot over a 0.9 m table is clear, and a light or a + // banner with no collision at all no longer stops one. + foreach (var s in GetStaticCollision(landblockKey)) + if (s.Source == StaticSource.CellStab) + volumes.AddRange(s.Parts); } /// @@ -1017,7 +932,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting foreach (var face in mesh.Faces) { - TriangulateAndTransform(face, mesh.Vertices, setup.PartFrames[i], triangles); + TriangulateAndTransform(face, mesh.Vertices, setup, i, triangles); if (triangles.Count / 3 >= MAX_BUILDING_TRIANGLES) break; } meshParts++; @@ -1080,7 +995,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting foreach (var corner in corners) { - Vector3 t = setup.PartFrames[i].TransformPoint(corner); + Vector3 t = setup.PartToSetup(i, corner); if (t.X < cMinX) cMinX = t.X; if (t.X > cMaxX) cMaxX = t.X; if (t.Y < cMinY) cMinY = t.Y; if (t.Y > cMaxY) cMaxY = t.Y; if (t.Z < cMinZ) cMinZ = t.Z; if (t.Z > cMaxZ) cMaxZ = t.Z; @@ -1115,6 +1030,18 @@ namespace RynthCore.Plugin.RynthAi.Raycasting if ((modelId & 0xFF000000) == 0x01000000) { var gfxVol = GetGfxObjBounds(modelId); + // A big GfxObj placed on its own (Neftet's rock spires and mesas, R-20261120-203229-771e): + // its sorting sphere, 9-75 m round, is its render bound. A character and a monster 50 m + // apart both stood inside one, so the line between them crossed no surface and read as + // clear, and every cast went into the rock. Its physics polygons are what AC collides with; + // with none (no HasPhysics) nothing stops a spell there. As a setup's part spheres are + // (GetSetupCollision: a GfxObj on its own is one part at the object's origin, size 1). + if (gfxVol != null && gfxVol.Type == BoundingVolume.VolumeType.Sphere && gfxVol.Dimensions.X > LargePartSphereRadius) + { + var collision = GetSetupCollision(modelId); + if (collision.Kind == StaticCollisionKind.Polygons) { result.Add(MeshOf(collision.Triangles)); return result; } + if (GfxObjDrawingOnly(modelId)) return result; + } if (gfxVol != null) { result.Add(gfxVol); @@ -1172,7 +1099,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting // Even if parse failed, try GfxObj from Parts if we got them if (setup.PartIds != null && setup.PartIds.Length > 0) { - var gfxVol = GetGfxObjBounds(setup.PartIds[0]); + var gfxVol = GetPartBounds(setup, 0); if (gfxVol != null) result.Add(gfxVol); } @@ -1276,7 +1203,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting // Priority 5: Fall back to GfxObj bounding data from first part if (setup.PartIds != null && setup.PartIds.Length > 0) { - var gfxVol = GetGfxObjBounds(setup.PartIds[0]); + var gfxVol = GetPartBounds(setup, 0); // A big object's first-part sphere is its render bound, not a wall (R-20261119-114214-b9ed, // landblock 0xB64A): wall panel 0x02001C33 is 24 x 0.4 m but its part sphere 28 m round, // and 0x02001C39 (29 parts, not one with physics polygons) got a 13 m sphere. They stand @@ -1288,9 +1215,10 @@ namespace RynthCore.Plugin.RynthAi.Raycasting // Tools/RynthCore.LosProof checks this spot. if (gfxVol != null && gfxVol.Type == BoundingVolume.VolumeType.Sphere && gfxVol.Dimensions.X > LargePartSphereRadius) { - var mesh = PartsPhysicsMesh(setup, out bool drawingOnly); - if (mesh != null) { result.Add(mesh); return result; } - if (drawingOnly) return result; + // GetSetupCollision: the parts' physics polygons, posed and scaled as AC places them. + var collision = GetSetupCollision(modelId); + if (collision.Kind == StaticCollisionKind.Polygons) { result.Add(MeshOf(collision.Triangles)); return result; } + if (NoPartHasPhysics(setup)) return result; } if (gfxVol != null) result.Add(gfxVol); @@ -1299,70 +1227,71 @@ namespace RynthCore.Plugin.RynthAi.Raycasting return result; } - /// Past this radius a part's sorting sphere is too coarse to stand for the object (meters). - internal const float LargePartSphereRadius = 4.0f; - - /// - /// The physics polygons of every part of , placed by its part frames, as one - /// triangle mesh (null when there are none or a part couldn't be read). : - /// every part was read and none has physics polygons (the GfxObj's HasPhysics flag, 0x01), so nothing - /// in the object collides. - /// - private BoundingVolume PartsPhysicsMesh(SetupInfo setup, out bool drawingOnly) + // A part's GfxObj bounds where the setup puts that part: scaled by its DefaultScale and posed by its + // frame in the Resting/Default placement (SetupInfo.PartToSetup). They were the GfxObj's own, + // as if every part sat at the setup's origin at size 1. + private BoundingVolume GetPartBounds(SetupInfo setup, int part) { - drawingOnly = false; - int count = setup.PartIds.Length; - bool anyPhysics = false, allRead = true; - for (int i = 0; i < count; i++) + var vol = GetGfxObjBounds(setup.PartIds[part]); + if (vol == null || (setup.PartFrames == null && setup.DefaultScale == null)) return vol; + if (vol.Type == BoundingVolume.VolumeType.Sphere) { - byte[] head = _portalDat.GetFileData(setup.PartIds[i]); - if (head == null || head.Length < 8) { allRead = false; continue; } - if ((BitConverter.ToUInt32(head, 4) & 0x01) != 0) anyPhysics = true; - } - if (!anyPhysics) - { - drawingOnly = allRead; - return null; - } - if (setup.PartFrames == null || setup.PartFrames.Length < count) return null; - - var triangles = new List(); - for (int i = 0; i < count && triangles.Count / 3 < MAX_BUILDING_TRIANGLES; i++) - { - if (setup.PartFrames[i] == null) return null; - var mesh = LoadGfxObjMesh(setup.PartIds[i]); - if (mesh == null) continue; // a drawing-only part (or unreadable: the rest still stand) - foreach (var face in mesh.Faces) + var sc = setup.PartScale(part); + float r = vol.Dimensions.X * Math.Max(Math.Abs(sc.X), Math.Max(Math.Abs(sc.Y), Math.Abs(sc.Z))); + var c = setup.PartToSetup(part, vol.Center); + return new BoundingVolume { - TriangulateAndTransform(face, mesh.Vertices, setup.PartFrames[i], triangles); - if (triangles.Count / 3 >= MAX_BUILDING_TRIANGLES) break; - } + Type = BoundingVolume.VolumeType.Sphere, + Center = c, + Dimensions = new Vector3(r, r, r), + Min = c - new Vector3(r, r, r), + Max = c + new Vector3(r, r, r), + IsDoor = vol.IsDoor + }; } - if (triangles.Count < 3) return null; - - float minX = float.MaxValue, minY = float.MaxValue, minZ = float.MaxValue; - float maxX = float.MinValue, maxY = float.MinValue, maxZ = float.MinValue; - foreach (var v in triangles) + Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue); + for (int k = 0; k < 8; k++) { - if (v.X < minX) minX = v.X; if (v.X > maxX) maxX = v.X; - if (v.Y < minY) minY = v.Y; if (v.Y > maxY) maxY = v.Y; - if (v.Z < minZ) minZ = v.Z; if (v.Z > maxZ) maxZ = v.Z; + var corner = new Vector3((k & 1) == 0 ? vol.Min.X : vol.Max.X, (k & 2) == 0 ? vol.Min.Y : vol.Max.Y, (k & 4) == 0 ? vol.Min.Z : vol.Max.Z); + var t = setup.PartToSetup(part, corner); + min = Vector3.Min(min, t); + max = Vector3.Max(max, t); } return new BoundingVolume { - Type = BoundingVolume.VolumeType.TriangleMesh, - Center = new Vector3((minX + maxX) * 0.5f, (minY + maxY) * 0.5f, (minZ + maxZ) * 0.5f), - Dimensions = new Vector3(maxX - minX, maxY - minY, maxZ - minZ), - Min = new Vector3(minX, minY, minZ), - Max = new Vector3(maxX, maxY, maxZ), - MeshTriangles = triangles.ToArray(), - IsDoor = false, - // Physics polygons only, so no box stands in for missing walls (and a thin panel turned - // on the landblock would make a big one). - NoAabbFallback = true + Type = BoundingVolume.VolumeType.AxisAlignedBox, + Center = (min + max) * 0.5f, + Dimensions = max - min, + Min = min, + Max = max, + IsDoor = vol.IsDoor }; } + /// Past this radius a part's sorting sphere is too coarse to stand for the object (meters). + internal const float LargePartSphereRadius = 4.0f; + + /// Every part of was read and none has physics polygons (the GfxObj's + /// HasPhysics flag, 0x01): nothing in the object collides. False when a part couldn't be read. + private bool NoPartHasPhysics(SetupInfo setup) + { + foreach (uint part in setup.PartIds) + { + byte[] head = _portalDat.GetFileData(part); + if (head == null || head.Length < 8) return false; + if ((BitConverter.ToUInt32(head, 4) & 0x01) != 0) return false; + } + return true; + } + + /// The GfxObj was read and has no physics polygons (no HasPhysics flag, 0x01). + private bool GfxObjDrawingOnly(uint gfxObjId) + { + byte[] head = _portalDat.GetFileData(gfxObjId); + return head != null && head.Length >= 8 && (BitConverter.ToUInt32(head, 4) & 0x01) == 0; + } + // ── Triangle mesh loading ─────────────────────────────────────────── /// @@ -1568,6 +1497,31 @@ namespace RynthCore.Plugin.RynthAi.Raycasting /// by the given frame, appending the resulting triangles to the output list. /// Returns the number of triangles added. /// + // A setup's part: its GfxObj's vertices scaled by the part's DefaultScale, then posed by its frame + // (SetupInfo.PartToSetup), as ACE PartArray poses the parts of a placed object. + private static int TriangulateAndTransform( + int[] faceIndices, + Dictionary vertices, + SetupInfo setup, + int part, + List outTriangles) + { + if (faceIndices.Length < 3) return 0; + if (!vertices.TryGetValue(faceIndices[0], out var v0)) return 0; + Vector3 tv0 = setup.PartToSetup(part, v0); + int added = 0; + for (int i = 1; i < faceIndices.Length - 1; i++) + { + if (!vertices.TryGetValue(faceIndices[i], out var v1)) continue; + if (!vertices.TryGetValue(faceIndices[i + 1], out var v2)) continue; + outTriangles.Add(tv0); + outTriangles.Add(setup.PartToSetup(part, v1)); + outTriangles.Add(setup.PartToSetup(part, v2)); + added++; + } + return added; + } + private static int TriangulateAndTransform( int[] faceIndices, Dictionary vertices, @@ -1632,17 +1586,121 @@ namespace RynthCore.Plugin.RynthAi.Raycasting }; } + // ── Static collision: what AC itself collides with ───────────────────────────────────────────── + // + // AC's rule for a placed object (ACE PhysicsObj.FindObjCollisions, Physics/PhysicsObj.cs:412-450, and + // PartArray.CacheHasPhysicsBSP): when any of its parts has physics polygons, those, posed by the + // Resting placement and scaled by DefaultScale (SetupInfo.PartToSetup); else its CylSpheres; else its + // Spheres; else nothing at all (lights, banners, decals). This kept the polygons only, so 60,289 + // cylinder and sphere objects at body height in the dungeons were nowhere on the map: 0x6346's + // pillars (0x0200028D), 0x0190's round tables (0x020000CE), 0x00FE's 0x02001055 (2026-11-18 survey). + // The map, the blocked-doorway rays and combat LOS all take triangles, so cylinders and spheres are + // handed over as closed solids (AppendCylinderSolid, AppendSphereSolid) and every consumer sees them + // as it sees a statue. No box stands for anything (NoAabbFallback): + // the box round an arch, a web or 0x039B's spiral stair is no wall, and the fallback reported 4,172 + // hits where no triangle was in 54,000 fan rays. + + /// The most physics triangles one placed object keeps (a sanity bound, not a cut: the + /// largest setup any cell or landblock places has far fewer). Buildings keep MAX_BUILDING_TRIANGLES. + internal const int MAX_STATIC_TRIANGLES = 200000; + private const int MAX_STATIC_CACHE = 12; + private const int MAX_COLLISION_CACHE = 4000; + + // The body band over a floor: the dungeon map's ClearWallLow (0.45 m) up to the top of AC's human + // (setup 0x02000001: spheres at 0.475 and 1.35 m, radius 0.48, so 1.83 m). + private const float BodyBandLow = 0.45f, BodyBandHigh = 1.83f; + + // A setup's (or GfxObj's) collision in its own space, as AC picks it. + private sealed class SetupCollision + { + public StaticCollisionKind Kind; + public Vector3[] Triangles = Array.Empty(); + public CollisionCylinder[] Cylinders = Array.Empty(); + public CollisionSphere[] Spheres = Array.Empty(); + public int TriangleCount; // physics triangles found (before MAX_STATIC_TRIANGLES) + public bool Capped; + } + + private readonly Dictionary _collisionCache = new Dictionary(); + private readonly Dictionary _staticCache = new Dictionary(); + private readonly List _staticOrder = new List(); + /// - /// The physics polygons of every static object a dungeon's cells place (the EnvCells' stabs: a spider - /// web across a doorway, a pillar), in world metres, one TriangleMesh each. A stab's frame is in the - /// landblock's space (its z is the floor's: DreamWeave Thread 0x5456's webs stand at z -24 on a -24 - /// floor). Objects with no physics polygons (nothing to walk into) are left out. + /// Every placed static of that AC collides with, in world metres: each + /// EnvCell's stabs (a web, an altar, a pillar, a table), and the landblock's own objects (0xXXYYFFFE, + /// not its buildings) that stand over an EnvCell's floor at body height (tagged with that cell). + /// Built once per landblock and kept (two threads asking at once get the same list); the list and its + /// meshes are shared, so callers read them and never change them. + /// + public IReadOnlyList GetStaticCollision(uint landblockKey) + { + lock (_cacheGate) + { + if (_staticCache.TryGetValue(landblockKey, out var have)) return have; + } + var built = BuildStaticCollision(landblockKey); + lock (_cacheGate) + { + // Another thread built it meanwhile: everyone keeps the first one. + if (_staticCache.TryGetValue(landblockKey, out var first)) return first; + if (_staticCache.Count >= MAX_STATIC_CACHE && _staticOrder.Count > 0) + { + _staticCache.Remove(_staticOrder[0]); + _staticOrder.RemoveAt(0); + } + _staticCache[landblockKey] = built; + _staticOrder.Add(landblockKey); + } + return built; + } + + /// + /// The placed statics of a landblock (GetStaticCollision) as (model, cell, mesh), in world metres, triangle + /// hits only: physics polygons, or each cylinder and sphere as a closed solid of its own. A stab's frame is in + /// the landblock's space (its z is the floor's: DreamWeave Thread 0x5456's webs stand at z -24 on a -24 + /// floor). Objects AC doesn't collide with are left out. A new list each call over the shared meshes. /// public List<(uint SetupId, uint CellId, BoundingVolume Mesh)> GetDungeonStaticMeshes(uint landblockKey) { - var list = new List<(uint, uint, BoundingVolume)>(); - if (_cellDat == null) return list; + var all = GetStaticCollision(landblockKey); + var list = new List<(uint, uint, BoundingVolume)>(all.Count); + foreach (var s in all) + foreach (var part in s.Parts) list.Add((s.SetupId, s.CellId, part)); + return list; + } + + private StaticCollision[] BuildStaticCollision(uint landblockKey) + { + var list = new List(); + if (_cellDat == null || _portalDat == null) return list.ToArray(); + var sw = System.Diagnostics.Stopwatch.StartNew(); float gx = ((landblockKey >> 8) & 0xFF) * 192.0f, gy = (landblockKey & 0xFF) * 192.0f; + int stabs = 0; + foreach (var (cellId, setupId, frame) in ReadCellStabs(landblockKey)) + { + stabs++; + var c = GetSetupCollision(setupId); + if (c.Kind == StaticCollisionKind.None) continue; + list.Add(PlaceCollision(setupId, cellId, StaticSource.CellStab, c, frame, gx, gy)); + } + int fromCells = list.Count; + AddLandblockObjectsOnFloors(landblockKey, gx, gy, list); + int poly = 0, cyl = 0, sph = 0; + foreach (var s in list) + { + if (s.Kind == StaticCollisionKind.Polygons) poly++; + else if (s.Kind == StaticCollisionKind.Cylinders) cyl++; + else if (s.Kind == StaticCollisionKind.Spheres) sph++; + } + Log($"Statics 0x{landblockKey:X4}: {stabs} cell stabs, {fromCells} collide; {list.Count - fromCells} landblock objects over a cell's floor; " + + $"{poly} polygons, {cyl} cylinders, {sph} spheres in all, {sw.Elapsed.TotalMilliseconds:F1} ms"); + return list.ToArray(); + } + + // Every EnvCell stab of the landblock: (cell, model, frame in the landblock's space). + private List<(uint CellId, uint SetupId, Frame Frame)> ReadCellStabs(uint landblockKey) + { + var list = new List<(uint, uint, Frame)>(); foreach (uint cellId in _cellDat.GetLandblockCellIds(landblockKey)) { byte[] data = _cellDat.GetFileData(cellId); @@ -1667,17 +1725,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting for (uint i = 0; i < numStabs && ms.Position + 32 <= ms.Length; i++) { uint setupId = reader.ReadUInt32(); - var frame = new Frame - { - OriginX = reader.ReadSingle(), OriginY = reader.ReadSingle(), OriginZ = reader.ReadSingle(), - RotW = reader.ReadSingle(), RotX = reader.ReadSingle(), RotY = reader.ReadSingle(), RotZ = reader.ReadSingle() - }; - foreach (var vol in GetBuildingCompositeVolumes(setupId)) - { - if (vol.Type != BoundingVolume.VolumeType.TriangleMesh) continue; - var placed = TransformVolume(vol, frame, gx, gy); - if (placed != null) list.Add((setupId, cellId, placed)); - } + var frame = new Frame(); + frame.Unpack(reader); + list.Add((cellId, setupId, frame)); } } catch (Exception) { } @@ -1685,6 +1735,402 @@ namespace RynthCore.Plugin.RynthAi.Raycasting return list; } + // The landblock's own objects (LandBlockInfo 0xXXYYFFFE's stab list; its buildings are not looked at) + // that collide and stand over an EnvCell's floor with something in the body band above it: chairs + // the outdoor list puts on a building's upper floor (0x7D64 at z 15.6, two at A9B4: 581 such objects + // stand on building floors world-wide, 133 with physics). Each is filed under the cell whose floor + // it overlaps most. + private void AddLandblockObjectsOnFloors(uint landblockKey, float gx, float gy, List into) + { + byte[] info = _cellDat.GetFileData((landblockKey << 16) | 0xFFFE); + if (info == null || info.Length < 12) return; + uint n = Math.Min(BitConverter.ToUInt32(info, 8), 5000u); + var placed = new List(); + using (var ms = new MemoryStream(info)) + using (var reader = new BinaryReader(ms)) + { + ms.Position = 12; + for (uint i = 0; i < n && ms.Position + 32 <= ms.Length; i++) + { + uint setupId = reader.ReadUInt32(); + var frame = new Frame(); + frame.Unpack(reader); + if (float.IsNaN(frame.OriginX) || Math.Abs(frame.OriginX) > 50000) continue; + var c = GetSetupCollision(setupId); + if (c.Kind == StaticCollisionKind.None) continue; + placed.Add(PlaceCollision(setupId, 0, StaticSource.LandblockObject, c, frame, gx, gy)); + } + } + if (placed.Count == 0 || _dungeonLOS == null) return; + var floors = _dungeonLOS.GetDungeonMapFloorPolygons(landblockKey); + if (floors == null || floors.Count == 0) return; + + var boxes = new (float MinX, float MinY, float MinZ, float MaxX, float MaxY, float MaxZ)[floors.Count]; + for (int f = 0; f < floors.Count; f++) + { + float x0 = float.MaxValue, y0 = float.MaxValue, z0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue, z1 = float.MinValue; + foreach (var p in floors[f].Vertices) + { + x0 = Math.Min(x0, p.X); y0 = Math.Min(y0, p.Y); z0 = Math.Min(z0, p.Z); + x1 = Math.Max(x1, p.X); y1 = Math.Max(y1, p.Y); z1 = Math.Max(z1, p.Z); + } + boxes[f] = (x0, y0, z0, x1, y1, z1); + } + foreach (var s in placed) + { + Vector3 mMin = s.Min, mMax = s.Max; + uint bestCell = 0; + double bestArea = 0.01; // m2: a sliver along a wall's foot doesn't count + for (int f = 0; f < floors.Count; f++) + { + var b = boxes[f]; + if (b.MaxX < mMin.X || b.MinX > mMax.X || b.MaxY < mMin.Y || b.MinY > mMax.Y) continue; + // Something of it in the body band over this floor (a fence on the ground under a floor + // 5 m up, or a beam over a walker's head, isn't in this cell's way). + if (mMax.Z <= b.MinZ + BodyBandLow || mMin.Z >= b.MaxZ + BodyBandHigh) continue; + double area = ClippedArea(floors[f].Vertices, mMin.X, mMin.Y, mMax.X, mMax.Y); + if (area > bestArea) { bestArea = area; bestCell = floors[f].CellId; } + } + if (bestCell == 0) continue; + s.CellId = bestCell; + into.Add(s); + } + } + + // The area of a polygon (its x, y) inside the box [x0, x1] x [y0, y1]: Sutherland-Hodgman against + // the box's four sides (right for a concave floor too, as the box is convex). + internal static double ClippedArea(Vector3[] poly, double x0, double y0, double x1, double y1) + { + var pts = new List<(double X, double Y)>(poly.Length); + foreach (var p in poly) pts.Add((p.X, p.Y)); + for (int side = 0; side < 4 && pts.Count >= 3; side++) + { + var outPts = new List<(double X, double Y)>(pts.Count + 4); + for (int i = 0; i < pts.Count; i++) + { + var cur = pts[i]; + var prev = pts[(i + pts.Count - 1) % pts.Count]; + bool ci = InsideSide(side, cur, x0, y0, x1, y1), pi = InsideSide(side, prev, x0, y0, x1, y1); + if (ci) + { + if (!pi) outPts.Add(CrossSide(side, prev, cur, x0, y0, x1, y1)); + outPts.Add(cur); + } + else if (pi) outPts.Add(CrossSide(side, prev, cur, x0, y0, x1, y1)); + } + pts = outPts; + } + if (pts.Count < 3) return 0; + double a2 = 0; + for (int i = 0; i < pts.Count; i++) + { + var p = pts[i]; + var q = pts[(i + 1) % pts.Count]; + a2 += p.X * q.Y - q.X * p.Y; + } + return Math.Abs(a2) / 2; + } + + private static bool InsideSide(int side, (double X, double Y) q, double x0, double y0, double x1, double y1) => + side switch { 0 => q.X >= x0, 1 => q.X <= x1, 2 => q.Y >= y0, _ => q.Y <= y1 }; + + private static (double X, double Y) CrossSide(int side, (double X, double Y) a, (double X, double Y) b, double x0, double y0, double x1, double y1) + { + double t = side switch + { + 0 => (x0 - a.X) / (b.X - a.X), + 1 => (x1 - a.X) / (b.X - a.X), + 2 => (y0 - a.Y) / (b.Y - a.Y), + _ => (y1 - a.Y) / (b.Y - a.Y), + }; + return (a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t); + } + + // A setup, read once and kept (shared, never changed). Null when portal.dat has no such file or + // even the fallback parse found no parts. + private SetupInfo GetSetupInfo(uint modelId) + { + lock (_cacheGate) + { + if (_setupCache.TryGetValue(modelId, out var have)) return have; + } + byte[] data = _portalDat.GetFileData(modelId); + if (data == null) return null; + var setup = new SetupInfo(); + setup.Unpack(data); + if (setup.PartIds == null) return null; + lock (_cacheGate) + { + if (_setupCache.Count >= MAX_SETUP_CACHE) _setupCache.Clear(); + _setupCache[modelId] = setup; + } + return setup; + } + + private SetupCollision GetSetupCollision(uint modelId) + { + lock (_cacheGate) + { + if (_collisionCache.TryGetValue(modelId, out var have)) return have; + } + var c = BuildSetupCollision(modelId); + lock (_cacheGate) + { + if (_collisionCache.Count >= MAX_COLLISION_CACHE) _collisionCache.Clear(); + _collisionCache[modelId] = c; + } + return c; + } + + private SetupCollision BuildSetupCollision(uint modelId) + { + var c = new SetupCollision(); + var tris = new List(); + uint kind = modelId & 0xFF000000; + if (kind == 0x01000000) + { + // A GfxObj placed on its own: one part at the object's origin, size 1. Cylinders and spheres + // belong to setups, so with no physics polygons AC has nothing to collide with. (This fell back + // to a box under 3 triangles or on a failed parse, and the box was then dropped; a one- or + // two-triangle panel is kept now.) + var mesh = LoadGfxObjMesh(modelId); + if (mesh != null) c.TriangleCount += AddFaces(mesh, null, 0, tris, ref c.Capped); + } + else if (kind == 0x02000000) + { + var setup = GetSetupInfo(modelId); + if (setup == null) return c; + for (int i = 0; i < setup.PartIds.Length; i++) + { + var mesh = LoadGfxObjMesh(setup.PartIds[i]); + if (mesh != null) c.TriangleCount += AddFaces(mesh, setup, i, tris, ref c.Capped); + } + if (tris.Count == 0) + { + c.Cylinders = setup.Cylinders.ToArray(); + c.Spheres = setup.Spheres.ToArray(); + } + } + if (tris.Count >= 3) + { + c.Kind = StaticCollisionKind.Polygons; + c.Triangles = tris.ToArray(); + c.Cylinders = Array.Empty(); + c.Spheres = Array.Empty(); + } + else if (c.Cylinders.Length > 0) + { + c.Kind = StaticCollisionKind.Cylinders; + c.Spheres = Array.Empty(); + } + else if (c.Spheres.Length > 0) c.Kind = StaticCollisionKind.Spheres; + if (c.Capped) Log($"[STATIC] 0x{modelId:X8}: {c.TriangleCount} physics triangles, kept {MAX_STATIC_TRIANGLES}"); + return c; + } + + // One part's physics polygons as triangles in its setup's space (no setup: as they are). Returns + // how many triangles the part has, kept or not. + private static int AddFaces(GfxObjMeshData mesh, SetupInfo setup, int part, List into, ref bool capped) + { + int count = 0; + var identity = new Frame(); + foreach (var face in mesh.Faces) + { + if (into.Count / 3 >= MAX_STATIC_TRIANGLES) + { + capped = true; + count += Math.Max(0, face.Length - 2); + continue; + } + count += setup != null ? TriangulateAndTransform(face, mesh.Vertices, setup, part, into) + : TriangulateAndTransform(face, mesh.Vertices, identity, into); + } + return count; + } + + // A setup's collision placed by a stab's frame, in world metres. Cylinders stay upright (AC moves + // only a CylSphere's low point with the object: ACE CylSphere.IntersectsSphere). Each cylinder and + // sphere is a closed piece of its own: where two of an object's spheres overlap (0x0200104E's pair, + // 5,447 placed), one mesh of both would read the overlap as outside to an even-odd inside test, and + // a ray only looks at the triangles of the pieces whose box it crosses. + private static StaticCollision PlaceCollision(uint setupId, uint cellId, StaticSource source, SetupCollision c, Frame f, float gx, float gy) + { + Vector3 W(Vector3 local) + { + var w = f.TransformPoint(local); + return new Vector3(w.X + gx, w.Y + gy, w.Z); + } + var parts = new List(); + var cyls = Array.Empty<(Vector3 Low, float Radius, float Height)>(); + var sphs = Array.Empty<(Vector3 Center, float Radius)>(); + if (c.Kind == StaticCollisionKind.Polygons) + { + var tris = new Vector3[c.Triangles.Length]; + for (int i = 0; i < tris.Length; i++) tris[i] = W(c.Triangles[i]); + parts.Add(MeshOf(tris)); + } + else if (c.Kind == StaticCollisionKind.Cylinders) + { + cyls = new (Vector3, float, float)[c.Cylinders.Length]; + for (int i = 0; i < cyls.Length; i++) + { + var low = W(c.Cylinders[i].BottomCenter); + cyls[i] = (low, c.Cylinders[i].Radius, c.Cylinders[i].Height); + var list = new List(SolidSlices * 12); + AppendCylinderSolid(list, low, c.Cylinders[i].Radius, c.Cylinders[i].Height); + if (list.Count > 0) parts.Add(RoundMesh(list)); + } + } + else if (c.Kind == StaticCollisionKind.Spheres) + { + sphs = new (Vector3, float)[c.Spheres.Length]; + for (int i = 0; i < sphs.Length; i++) + { + var centre = W(c.Spheres[i].Center); + sphs[i] = (centre, c.Spheres[i].Radius); + var list = new List(SolidSlices * SphereStacks * 6); + AppendSphereSolid(list, centre, c.Spheres[i].Radius); + if (list.Count > 0) parts.Add(RoundMesh(list)); + } + } + if (parts.Count == 0) parts.Add(MeshOf(new[] { W(new Vector3(0, 0, 0)) })); + return new StaticCollision(setupId, cellId, source, c.Kind, parts.ToArray(), cyls, sphs, c.TriangleCount, c.Capped); + } + + // A cylinder's or a sphere's solid as a mesh, marked round: its ring faces are walkable at many heights, and the + // building map's stair test took a 1 m ball chained to a dais for steps (8090012A's 0x0200035E: off the map). + private static BoundingVolume RoundMesh(List tris) + { + var m = MeshOf(tris.ToArray()); + m.Round = true; + return m; + } + + // A world-space triangle list as a mesh volume: its box is the triangles' own, and only real triangle + // hits count. + internal static BoundingVolume MeshOf(Vector3[] tris) + { + var min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); + var max = new Vector3(float.MinValue, float.MinValue, float.MinValue); + foreach (var v in tris) + { + min = Vector3.Min(min, v); + max = Vector3.Max(max, v); + } + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.TriangleMesh, + Center = (min + max) * 0.5f, + Dimensions = max - min, + Min = min, + Max = max, + MeshTriangles = tris, + IsDoor = false, + NoAabbFallback = true + }; + } + + /// For offline checks: which shapes AC collides with for a model, and how many physics + /// triangles, cylinders and spheres it has (triangles before MAX_STATIC_TRIANGLES). + internal StaticCollisionKind DescribeCollision(uint modelId, out int triangles, out int cylinders, out int spheres) + { + var c = GetSetupCollision(modelId); + triangles = c.TriangleCount; + cylinders = c.Cylinders.Length; + spheres = c.Spheres.Length; + return c.Kind; + } + + /// For offline checks: a model's physics triangles in its own space, posed and scaled as AC + /// places it (a copy; empty unless its kind is Polygons). + internal Vector3[] SetupCollisionTriangles(uint modelId) => (Vector3[])GetSetupCollision(modelId).Triangles.Clone(); + + // ── Closed solids for cylinders and spheres ──────────────────────────────────────────────────── + // Everything downstream cuts the triangles level (the map's walls) or casts rays at them, so a + // CylSphere becomes a 12-sided prism over its height and a Sphere a 12-slice, 8-stack closed solid. + // Their corners sit out by PolyAreaScale, so a level cut has the circle's area (its mid-edges 1.2 % + // inside the radius, its corners 2.3 % outside); a sphere's rings are pushed out by SphereRingScale + // so its side straddles the true surface (within 1 % of the radius both ways). A level cut through + // the sphere up to 0.9 of the radius from its middle is within 1 % of the radius of the true circle + // there (5 % at the very top and bottom). A sphere under SmallSphereRadius (a cup or a candle on a + // table: 0x8804 has some 600 of 0.1 m) is 8 x 4, 48 triangles not 168, within 6 mm of its surface. + internal const int SolidSlices = 12, SphereStacks = 8; + internal const int SmallSphereSlices = 8, SmallSphereStacks = 4; + internal const float SmallSphereRadius = 0.25f; + internal static readonly double PolyAreaScale = AreaScale(SolidSlices); + internal static readonly double SphereRingScale = RingScale(SphereStacks); + + // An n-gon's corner radius over the radius of the circle with its area. + internal static double AreaScale(int n) => Math.Sqrt(Math.PI / (n / 2.0 * Math.Sin(2 * Math.PI / n))); + // How far out a sphere's rings go so its side's chords straddle the true surface. + internal static double RingScale(int stacks) => 2 / (1 + Math.Cos(Math.PI / (2 * stacks))); + + /// A closed upright prism round (low, radius, height), as triangles appended to . + internal static void AppendCylinderSolid(List into, Vector3 low, float radius, float height) + { + if (!(radius > 0.001f) || !(height > 0.001f)) return; + int n = SolidSlices; + double r = radius * PolyAreaScale; + var bot = new Vector3[n]; + var top = new Vector3[n]; + for (int k = 0; k < n; k++) + { + double a = 2 * Math.PI * k / n; + float x = (float)(low.X + r * Math.Cos(a)), y = (float)(low.Y + r * Math.Sin(a)); + bot[k] = new Vector3(x, y, low.Z); + top[k] = new Vector3(x, y, low.Z + height); + } + for (int k = 0; k < n; k++) + { + int k1 = (k + 1) % n; + into.Add(bot[k]); into.Add(bot[k1]); into.Add(top[k1]); + into.Add(bot[k]); into.Add(top[k1]); into.Add(top[k]); + } + for (int k = 1; k + 1 < n; k++) + { + into.Add(bot[0]); into.Add(bot[k + 1]); into.Add(bot[k]); + into.Add(top[0]); into.Add(top[k]); into.Add(top[k + 1]); + } + } + + /// A closed solid round the sphere (centre, radius), as triangles appended to . + internal static void AppendSphereSolid(List into, Vector3 centre, float radius) + { + if (!(radius > 0.001f)) return; + bool small = radius < SmallSphereRadius; + int n = small ? SmallSphereSlices : SolidSlices, stacks = small ? SmallSphereStacks : SphereStacks; + double rr = radius * RingScale(stacks), areaScale = AreaScale(n); + var rings = new Vector3[stacks - 1][]; + for (int j = 1; j < stacks; j++) + { + double phi = -Math.PI / 2 + Math.PI * j / stacks; + double rho = rr * Math.Cos(phi) * areaScale; + float z = (float)(centre.Z + rr * Math.Sin(phi)); + var ring = new Vector3[n]; + for (int k = 0; k < n; k++) + { + double a = 2 * Math.PI * k / n; + ring[k] = new Vector3((float)(centre.X + rho * Math.Cos(a)), (float)(centre.Y + rho * Math.Sin(a)), z); + } + rings[j - 1] = ring; + } + var south = new Vector3(centre.X, centre.Y, (float)(centre.Z - rr)); + var north = new Vector3(centre.X, centre.Y, (float)(centre.Z + rr)); + for (int k = 0; k < n; k++) + { + int k1 = (k + 1) % n; + into.Add(south); into.Add(rings[0][k1]); into.Add(rings[0][k]); + for (int j = 0; j + 1 < rings.Length; j++) + { + var lo = rings[j]; + var hi = rings[j + 1]; + into.Add(lo[k]); into.Add(lo[k1]); into.Add(hi[k1]); + into.Add(lo[k]); into.Add(hi[k1]); into.Add(hi[k]); + } + into.Add(north); into.Add(rings[rings.Length - 1][k]); into.Add(rings[rings.Length - 1][k1]); + } + } + /// /// Transforms a local-space bounding volume by a placement frame, /// producing a world-space AABB for raycasting. @@ -1758,7 +2204,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting Max = worldMax, MeshTriangles = tris, IsDoor = localVol.IsDoor, - NoAabbFallback = localVol.NoAabbFallback // a parts mesh (PartsPhysicsMesh): its triangles are all of it + NoAabbFallback = localVol.NoAabbFallback // a collision mesh (MeshOf): its triangles are all of it }; } @@ -1892,6 +2338,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting { _landblockCache.Clear(); _setupCache.Clear(); + _collisionCache.Clear(); + _staticCache.Clear(); + _staticOrder.Clear(); } Log("All caches flushed"); } @@ -1902,6 +2351,8 @@ namespace RynthCore.Plugin.RynthAi.Raycasting { _landblockCache.Remove(landblockKey); _landblockCache.Remove(landblockKey | 0x80000000u); + _staticCache.Remove(landblockKey); + _staticOrder.Remove(landblockKey); } } @@ -1913,6 +2364,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting { _landblockCache.Clear(); _setupCache.Clear(); + _collisionCache.Clear(); + _staticCache.Clear(); + _staticOrder.Clear(); } _initialized = false; } @@ -1922,7 +2376,90 @@ namespace RynthCore.Plugin.RynthAi.Raycasting string line = $"[GeoLoader] {msg}"; System.Diagnostics.Debug.WriteLine(line); RynthLog.Trace(LogCat.Raycast, line); // visible via /ra trace raycast - if (DiagLog.Count < 200) DiagLog.Add(msg); + // Statics can be built on more than one thread (the tick's map, a UI inspect). + lock (DiagLog) + { + if (DiagLog.Count < 200) DiagLog.Add(msg); + } } } + + /// Which of a placed object's collision shapes AC collides with (ACE PhysicsObj.FindObjCollisions): + /// its parts' physics polygons when any part has some, else its CylSpheres, else its Spheres, else none. + public enum StaticCollisionKind { None = 0, Polygons = 1, Cylinders = 2, Spheres = 3 } + + /// Where a placed static comes from. + public enum StaticSource + { + /// An EnvCell's stab list (a dungeon's or a building's cells). + CellStab = 0, + /// The landblock's own object list (LandBlockInfo 0xXXYYFFFE), standing over a cell's floor. + LandblockObject = 1, + } + + /// One placed static object as AC collides with it, in world metres (GeometryLoader.GetStaticCollision). + /// Shared between callers: read it, never change it. + public sealed class StaticCollision + { + private BoundingVolume _union; + + internal StaticCollision(uint setupId, uint cellId, StaticSource source, StaticCollisionKind kind, BoundingVolume[] parts, + IReadOnlyList<(Vector3 Low, float Radius, float Height)> cylinders, IReadOnlyList<(Vector3 Center, float Radius)> spheres, + int triangleCount, bool capped) + { + SetupId = setupId; + CellId = cellId; + Source = source; + Kind = kind; + Parts = parts; + Cylinders = cylinders; + Spheres = spheres; + PhysicsTriangles = triangleCount; + Capped = capped; + var min = parts[0].Min; + var max = parts[0].Max; + foreach (var p in parts) + { + min = Vector3.Min(min, p.Min); + max = Vector3.Max(max, p.Max); + } + Min = min; + Max = max; + } + + /// The model (a 0x02 setup or a 0x01 GfxObj). + public uint SetupId { get; } + /// The EnvCell it stands in: its stab's cell, or for a landblock object the cell whose floor it is over most. + public uint CellId { get; internal set; } + public StaticSource Source { get; } + public StaticCollisionKind Kind { get; } + /// Its closed pieces as triangle meshes, world metres, triangle hits only: the physics polygons as one, + /// or each cylinder and sphere as a solid of its own. + public IReadOnlyList Parts { get; } + /// The box round all its pieces. + public Vector3 Min { get; } + public Vector3 Max { get; } + /// All of it as one mesh (its only piece, or the pieces' triangles together, made when first asked). + public BoundingVolume Mesh + { + get + { + if (Parts.Count == 1) return Parts[0]; + var u = System.Threading.Volatile.Read(ref _union); + if (u != null) return u; + var all = new List(); + foreach (var p in Parts) all.AddRange(p.MeshTriangles); + u = GeometryLoader.MeshOf(all.ToArray()); + return System.Threading.Interlocked.CompareExchange(ref _union, u, null) ?? u; + } + } + /// Kind Cylinders: each upright cylinder, its low point in world metres. + public IReadOnlyList<(Vector3 Low, float Radius, float Height)> Cylinders { get; } + /// Kind Spheres: each sphere, its centre in world metres. + public IReadOnlyList<(Vector3 Center, float Radius)> Spheres { get; } + /// Kind Polygons: how many physics triangles the model has. + public int PhysicsTriangles { get; } + /// The model has more than GeometryLoader.MAX_STATIC_TRIANGLES physics triangles (not all kept). + public bool Capped { get; } + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs index b58f84e..9945b44 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs @@ -340,12 +340,66 @@ namespace RynthCore.Plugin.RynthAi.Raycasting // Collision cylinders public List Cylinders = new List(); - // Default pose part frames (from first placement in Setup) - // Used to compute composite building bounding volumes. + /// Every placement in the file (the parts' frames for one pose), by key: 0 Default, + /// 0x65 Resting, and the animation poses. + public Dictionary Placements = new Dictionary(); + + /// The key of the placement is, or -1 when the file has none. + public int PartFramesKey = -1; + + /// The key of the first placement in the file. + public int FirstPlacementKey; + + // The parts' frames in the pose AC puts a placed object in: Resting (0x65) when the setup has it, + // else Default (0), else the first in the file (ACE PartArray.SetPlacementFrame: the server and + // client both ask for 0x65 when they make a static). This was the first placement in the file: + // all 5,935 setups of today's portal.dat have a Default pose, 2,629 also have a Resting one and it + // is never the first, so 0x0200016C's parts stood 0.41 m too low (z -0.41..0.41, AC 0..0.82) and + // 0x02000183's a metre off (measured 2026-11-18). public Frame[] PartFrames; + /// Each part's DefaultScale (applied to its GfxObj before its frame, as ACE PartArray + /// does), or null when the setup has none (scale 1). 330 setups have one. + public Vector3[] DefaultScale; + + public float StepUpHeight, StepDownHeight; + + /// A placement carried animation hooks, which this reader can't step over: placements after + /// it and the collision volumes come from the fallback parse. None in today's portal.dat. + public bool PlacementHooks; + public bool HasBounds; + /// Part 's scale (1, 1, 1 when the setup has none). + public Vector3 PartScale(int part) + { + if (DefaultScale == null || part < 0 || part >= DefaultScale.Length) return new Vector3(1, 1, 1); + return DefaultScale[part]; + } + + /// A point of part 's GfxObj in the setup's space: scaled by the + /// part's DefaultScale, then posed by its frame in . + public Vector3 PartToSetup(int part, Vector3 local) + { + var s = PartScale(part); + var scaled = new Vector3(local.X * s.X, local.Y * s.Y, local.Z * s.Z); + var f = PartFrames != null && part >= 0 && part < PartFrames.Length ? PartFrames[part] : null; + return f != null ? f.TransformPoint(scaled) : scaled; + } + + // Resting (0x65), else Default (0), else the first in the file. + private void ChoosePartFrames() + { + if (PartFrames != null) return; + foreach (int key in new[] { 0x65, 0, FirstPlacementKey }) + if (Placements.TryGetValue(key, out var frames)) + { + PartFrames = frames; + PartFramesKey = key; + return; + } + } + public bool Unpack(byte[] data) { if (data == null || data.Length < 16) @@ -373,9 +427,15 @@ namespace RynthCore.Plugin.RynthAi.Raycasting if ((Flags & 0x01) != 0) ms.Seek(numParts * 4, SeekOrigin.Current); - // HasDefaultScale = 0x02 + // HasDefaultScale = 0x02: one Vector3 per part (setups such as 0x0200187B and + // 0x02000D96 shrink or stretch parts with it; skipping it left them at size 1) if ((Flags & 0x02) != 0) - ms.Seek(numParts * 12, SeekOrigin.Current); // Vector3 = 12 bytes + { + if (ms.Position + numParts * 12 > ms.Length) return TryFallbackParse(data); + DefaultScale = new Vector3[numParts]; + for (int i = 0; i < numParts; i++) + DefaultScale[i] = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + } // --- Skip HoldingLocations: uint32 count + count × (key(4) + PartId(4) + Frame(28)) --- if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data); @@ -383,41 +443,39 @@ namespace RynthCore.Plugin.RynthAi.Raycasting // --- Skip ConnectionPoints: same format --- if (!SkipHashTable(reader, ms, 36)) return TryFallbackParse(data); - // --- Skip PlacementFrames --- + // --- PlacementFrames: every one kept by its key --- if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); int placementsCount = reader.ReadInt32(); if (placementsCount < 0 || placementsCount > 100) return TryFallbackParse(data); for (int p = 0; p < placementsCount; p++) { - if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); - reader.ReadInt32(); // key + if (ms.Position + 4 > ms.Length) { ChoosePartFrames(); return TryFallbackParse(data); } + int key = reader.ReadInt32(); + if (p == 0) FirstPlacementKey = key; // AnimationFrame: numParts × Frame(28 bytes) + uint32 numHooks + if (ms.Position + numParts * 28L > ms.Length) { ChoosePartFrames(); return TryFallbackParse(data); } + var frames = new Frame[numParts]; for (int part = 0; part < numParts; part++) { - if (ms.Position + 28 > ms.Length) return TryFallbackParse(data); - if (p == 0) // Store default pose part frames for composite bounds - { - if (PartFrames == null) PartFrames = new Frame[numParts]; - PartFrames[part] = new Frame(); - PartFrames[part].Unpack(reader); - } - else - { - ms.Seek(28, SeekOrigin.Current); - } + frames[part] = new Frame(); + frames[part].Unpack(reader); } + Placements[key] = frames; - if (ms.Position + 4 > ms.Length) return TryFallbackParse(data); + if (ms.Position + 4 > ms.Length) { ChoosePartFrames(); return TryFallbackParse(data); } uint numHooks = reader.ReadUInt32(); if (numHooks > 0) { - // AnimationHooks are variable-size; can't easily skip - // But we already stored PartFrames from the default placement above + // AnimationHooks are variable-size and this reader can't step over them: the + // placements read so far are kept, the volumes come from the fallback. + PlacementHooks = true; + ChoosePartFrames(); return TryFallbackParse(data); } } + ChoosePartFrames(); // --- NOW we're at the good stuff! --- return ReadBoundsData(reader, ms, data); @@ -425,6 +483,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting } catch { + ChoosePartFrames(); return TryFallbackParse(data); } } @@ -471,8 +530,8 @@ namespace RynthCore.Plugin.RynthAi.Raycasting if (ms.Position + 16 > ms.Length) return false; Height = reader.ReadSingle(); Radius = reader.ReadSingle(); - float stepUp = reader.ReadSingle(); - float stepDown = reader.ReadSingle(); + StepUpHeight = reader.ReadSingle(); + StepDownHeight = reader.ReadSingle(); // SortingSphere: Vector3 center + float radius if (ms.Position + 16 > ms.Length) return false; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs index 9afa120..92b7884 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/TargetingFSM.cs @@ -76,6 +76,40 @@ namespace RynthCore.Plugin.RynthAi.Raycasting public bool LineBlocked; public bool ArcChecked; public RaycastEngine.ArcLosResult Arc; + public bool TerrainBlocked; // outdoors: the ground rises above the path (a hill between) + public float TerrainAlong; // where along the path, in meters from the shooter + } + + // ── Hills (2026-11-22, R-20261122-203611-ff3d) ───────────────────────────────────────── + // The verdict tested objects and buildings only, never the ground: on the Withered Tumerok + // hills a caster 56-68 m below its targets (11 m lower) cast Blade Arc after Blade Arc into + // the hillside ("stopped short of the target"), three no-damage casts and a blacklist per + // monster, round the whole group. Outdoors the path is now sampled every TerrainStepMeters + // against the landscape: the ground above it by TerrainClearance anywhere past the first and + // before the last TerrainEndSkipMeters (the slopes the two stand on) blocks the shot. + private const float TerrainStepMeters = 1.5f, TerrainEndSkipMeters = 2.0f, TerrainClearance = 0.25f; + + /// + /// Outdoors, whether the ground rises above the path from to + /// (chest heights, global meters); with > 0 the path bows up by that much at + /// its middle (an arc). : where, in meters from . + /// + public bool TerrainBetween(Vector3 a, Vector3 b, float sag, out float along) + { + along = 0f; + float dx = b.X - a.X, dy = b.Y - a.Y; + float flat = (float)Math.Sqrt(dx * dx + dy * dy); + if (flat <= 2 * TerrainEndSkipMeters) return false; + for (float s = TerrainEndSkipMeters; s <= flat - TerrainEndSkipMeters; s += TerrainStepMeters) + { + float f = s / flat; + float x = a.X + dx * f, y = a.Y + dy * f; + float ground = _geoLoader.GetTerrainZWorld(x, y); + if (float.IsNaN(ground)) continue; + float pathZ = a.Z + (b.Z - a.Z) * f + (sag > 0 ? 4f * sag * f * (1f - f) : 0f); + if (ground > pathZ + TerrainClearance) { along = s; return true; } + } + return false; } private static bool IsMissileArc(AttackType t) => @@ -259,6 +293,20 @@ namespace RynthCore.Plugin.RynthAi.Raycasting arcHeadroom = arc.ApexAboveLaunch + (launch.Z - origin.Z) + Math.Max(0f, MissileArcClearance) + 0.5f; } + // Outdoors: a hill between (TerrainBetween). Before the pre-filter below, which only + // knows objects: open hillsides have none near the path. + if (!isDungeon) + { + float sag = missileArc && arc.Valid ? arc.MaxRiseAboveChord : 0f; + if (TerrainBetween(missileArc ? launch : origin, targetPos, sag, out float along)) + { + detail.Checked = true; + detail.TerrainBlocked = true; + detail.TerrainAlong = along; + return true; + } + } + // Pre-filter: skip full ray test if no geometry near the path float margin = Math.Min(flatDist * 0.3f, 15.0f); margin = Math.Max(margin, 3.0f); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs index dd67f0e..e87c82a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiCommands.cs @@ -74,6 +74,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra power <0-100|auto> — set attack power (auto = recklessness-aware)"); ChatLine("[RynthAi] /ra dfheight [on|off|status|window] — Dirty Fighting rotation: attack heights by the effects on the target"); ChatLine("[RynthAi] /ra meleewalls [on|off] — Melee through walls: melee reaches a monster within 4 m behind a wall (not a building's)"); + ChatLine("[RynthAi] /ra debuffall [on|off] — Debuff every monster in range before attacking (toggle)"); ChatLine("[RynthAi] /ra cast — cast spell on current target"); ChatLine("[RynthAi] /ra buffs — show active buff timers"); ChatLine("[RynthAi] /ra buffitems [list|allow|block|add|addselected|remove|repeat|open] — the buff items RynthAi may use"); @@ -117,6 +118,9 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra items fill — add weapons, healing kits, lockpicks and pet essences from your pack"); ChatLine("[RynthAi] /ra aetheria [status|unbox|on|off] — unbox Coalesced Aetheria with an Aetheria Mana Stone (Unbox Aetheria When Idle)"); ChatLine("[RynthAi] /ra autoconfirm [status|on|off|<50-100>] — Yes to the craft-chance prompt at that % or better (Mini Remote > Crafting)"); + ChatLine("[RynthAi] /ra kits [status|make [N]|stop|floor <0-100>|show] — make Plentiful Healing Kits from their ingredients, macro off (Mini Remote > Crafting > Kits)"); + ChatLine("[RynthAi] /ra kits auto [status|on|off|below N|upto M] — Make kits when low: with the macro on and nothing around, make kits when fewer than N are carried"); + ChatLine("[RynthAi] /ra petelement [status|any|fire|cold|acid|lightning|nether|slash|pierce|bludgeon] — the element combat pets are summoned for (Mini Remote > Pets)"); ChatLine("[RynthAi] /ra offhand [auto|shield|weapon|none] [rule] — the off hand (shield / dual wield), global or for a Monsters rule; dual on|off"); ChatLine("[RynthAi] /ra dunnav — navigate to NS/EW coords through dungeon (no nav file needed)"); ChatLine("[RynthAi] /ra dunnav-to — walk to an object in this dungeon, any floor (a monster, say)"); @@ -141,6 +145,7 @@ public sealed partial class RynthAiPlugin ChatLine("[RynthAi] /ra chests — Loot Nearby Chests: on or off, what it is doing, and the chests it is leaving alone and why"); ChatLine("[RynthAi] /ra loot why — which loot rule takes the selected item, and why the rules above it didn't"); ChatLine("[RynthAi] /ra loot mode [profile|rares] — loot by the loot profile, or rares and needed mana stones only"); + ChatLine("[RynthAi] /ra loot today — Keep # per day rules: what this character picked up in each one's window (clear |all)"); ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item"); ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)"); ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot"); @@ -1302,6 +1307,14 @@ public sealed partial class RynthAiPlugin var names = _dashboard.NavFileNames(); ChatLine(names.Count == 0 ? "[RynthAi] No navs in NavProfiles." : $"[RynthAi] Navs ({names.Count}): {string.Join(", ", names)}"); break; + case "import": + { + // VirindiTank navs put in another folder (RynthNav's NavData, the RynthAi folder...): + // copied into NavProfiles, as the Nav panel's button does. + string msg = _dashboard.CopyStrayNavs(out bool ok); + if (ok) ReplyOk("[RynthAi] " + msg); else ReplyFail("[RynthAi] " + msg); + break; + } case "new": case "saveas": case "rename": @@ -1310,6 +1323,9 @@ public sealed partial class RynthAiPlugin // The Loaded files drawer's NAV buttons (RynthAiPlugin.ProfileFiles.cs). TryProfileVerb(ProfileKind.Nav, sub, rest, NavUsage); break; + case "addjump": + AddJumpHere(rest); + break; case "restart": { // Stopping and starting the macro keeps the route where it was (a finished Once @@ -1335,7 +1351,48 @@ public sealed partial class RynthAiPlugin } private const string NavUsage = - "/ra nav save [name] | /ra nav load | /ra nav new | /ra nav saveas | /ra nav rename | /ra nav delete | /ra nav folder | /ra nav list | /ra nav restart"; + "/ra nav save [name] | /ra nav load | /ra nav new | /ra nav saveas | /ra nav rename | /ra nav delete | /ra nav folder | /ra nav list | /ra nav import | /ra nav restart | /ra nav addjump [ms] [shift]"; + + /// The hold a recorded jump gets when none is given: the dungeon walk's own hop. + internal const int AddJumpDefaultMs = DungeonPathfinder.JumpHoldMs; + + /// + /// /ra nav addjump [ms] [shift]: a Jump step where you stand, facing the way you face, added to the end of + /// the loaded route (and saved to its file). Recording doesn't see a jump (the client tells a plugin + /// nothing of one), and some places can only be reached by one: 2026-11-18, Thread 0x00C1's pit, where the + /// fighting is, is dropped into from a ledge. ms is how long the jump is held (0-1000, the power; 300 by + /// default), shift a walking jump. While recording, the next point waits until you have landed. + /// + private void AddJumpHere(string args) + { + var settings = _dashboard?.Settings; + if (settings == null) { ReplyFail("[RynthAi] Settings not ready."); return; } + int ms = AddJumpDefaultMs; + bool shift = false; + foreach (string word in args.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + if (word.Equals("shift", StringComparison.OrdinalIgnoreCase)) shift = true; + else if (int.TryParse(word, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int n)) ms = Math.Clamp(n, 0, 1000); + else { ReplyFail("[RynthAi] Usage: /ra nav addjump [ms] [shift] (ms: 0-1000, how long the jump is held)"); return; } + } + if (!NavCoordinateHelper.TryGetNavPosition(Host, out double ns, out double ew, out double z) + || !PlayerCompass.TryGet(Host, out float heading)) + { + ReplyFail("[RynthAi] Could not read your position and heading."); + return; + } + var pt = new NavPoint + { + Type = NavPointType.Jump, NS = ns, EW = ew, Z = z, + JumpHeading = Math.Round(heading, 1), JumpMs = ms, JumpShift = shift, + }; + NavRouteEditing.Apply(settings, list => { list.Add(pt); return list; }); + if (settings.IsRecordingNav) _navBreadcrumbs?.JumpAdded(); + _dashboard?.AutoSaveRoute(); + string navName = string.IsNullOrEmpty(settings.CurrentNavPath) ? "(unsaved)" : System.IO.Path.GetFileName(settings.CurrentNavPath); + ReplyOk($"[RynthAi] Added a jump [{settings.CurrentRoute.Points.Count - 1}] facing {heading:F0}°, held {ms} ms{(shift ? ", walking" : "")}, to {navName}" + + (settings.IsRecordingNav ? ": jump now; recording goes on once you land." : ".")); + } private const string MetaUsage = "/ra meta load | new | save | saveas | rename | delete | folder | list | repair"; private const string SettingsUsage = @@ -1692,6 +1749,9 @@ public sealed partial class RynthAiPlugin FirstMatchNative = FirstLootRuleFor, Added = OnLootRuleAdded, BuiltInKeep = LootBuiltInKeepFor, + PerDayStatus = PerDayStatusFor, + PerDayRevision = PerDayRevision, + PerDayReset = PerDayReset, }, }; @@ -1858,6 +1918,11 @@ public sealed partial class RynthAiPlugin HandleLootModeCommand(parts); return; } + if (sub == "today") + { + HandleLootTodayCommand(parts); // Keep # per day (RynthAiPlugin.LootPerDay.cs) + return; + } // The Loaded files drawer's LOOT buttons (RynthAiPlugin.ProfileFiles.cs). if (TryProfileVerb(ProfileKind.Loot, sub, parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : string.Empty, LootFileUsage)) return; @@ -1865,6 +1930,7 @@ public sealed partial class RynthAiPlugin { ChatLine("[RynthAi] /ra loot mode [profile|rares] — what is looted: the loot profile, or rares and needed mana stones only"); ChatLine("[RynthAi] /ra loot why [window] — which loot rule takes the selected item, and why the rules above it didn't (window: in the Loot why window)"); + ChatLine("[RynthAi] /ra loot today [clear |clear all] — Keep # per day rules: what this character picked up in each one's window"); ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [t11] [preview] — add a loot rule for the selected item to the loot profile in use"); ChatLine("[RynthAi] " + LootFileUsage + " — the loot profile's file: a new one in the Loot Editor, a copy, rename, move to Deleted, its folder, the editor"); ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. t11 = also require its T11 tier, grade and modifiers (at least this good). preview = show it, add nothing."); @@ -2340,11 +2406,14 @@ public sealed partial class RynthAiPlugin /// had this via TogglePanelMacro). Routed through the same TogglePanelMacro the /// button and the remote use, so there's still one write path for the flag. /// - private void HandleMacroRunCommand(string verb, string[] parts) + private void HandleMacroRunCommand(string verb, string[] parts, string? source = null) { var dash = _dashboard; if (dash == null) { ReplyFail("[RynthAi] Settings not ready."); return; } bool running = dash.Settings.IsMacroRunning; + source ??= "the command /ra " + verb + (MetaCommandActive ? $" from the meta (state '{dash.Settings.CurrentState}')" + : Reply.FromScript ? " from a script, a route or a timed command" + : " (typed, or a hotkey or alias)"); switch (verb) { @@ -2353,14 +2422,14 @@ public sealed partial class RynthAiPlugin _macroResumeAt = 0; if (running) { ReplyOk("[RynthAi] Macro already RUNNING."); return; } if (RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge) - dash.TogglePanelMacro(); + dash.TogglePanelMacro(source); ReplyOk("[RynthAi] Macro STARTED."); return; case "stop": _macroResumeAt = 0; if (!running) { ReplyOk("[RynthAi] Macro already STOPPED."); return; } - dash.TogglePanelMacro(); + dash.TogglePanelMacro(source); // Kill autorun now rather than waiting out the nav engine's stop // debounce — a /ra stop is usually issued because the box is // running somewhere you don't want it to. @@ -2375,7 +2444,7 @@ public sealed partial class RynthAiPlugin sec = Math.Clamp(parsed, 1, 3600); if (running) { - dash.TogglePanelMacro(); + dash.TogglePanelMacro(source); _navigationEngine?.Stop(); } _macroResumeAt = CorpseNowMs + sec * 1000L; @@ -3172,14 +3241,16 @@ public sealed partial class RynthAiPlugin : $"[RynthAi] No items in inventory matched profile '{System.IO.Path.GetFileName(profilePath)}'"); } - internal const string DunNavToUsage ="[RynthAi] Usage: /ra dunnav-to — walk to an object in this dungeon (any floor), e.g. a monster: /ra dunnav-to 0x80123456"; + internal const string DunNavToUsage = "[RynthAi] Usage: /ra dunnav-to [jump] — walk to an object in this dungeon (any floor), e.g. a monster: /ra dunnav-to 0x80123456; with jump, a jump down a ledge may be taken when there's no walk (one way: no climbing back)"; /// - /// /ra dunnav-to <object id> (2026-11-15): walks to an object in the dungeon the character is in, - /// by the dungeon map (ledges closed: DungeonPathfinder.Ledges.cs), from the player's cell to the + /// /ra dunnav-to <object id> [jump] (2026-11-15): walks to an object in the dungeon the character is + /// in, by the dungeon map (ledges closed: DungeonPathfinder.Ledges.cs), from the player's cell to the /// object's own cell, so another floor works too (/ra dunnav aims at the player's floor). For /// a script: after an explore, the monsters still to be killed are walked to one by /// one; the fight is RynthAi's, as on any route. The macro goes on; the route is a Once walk. + /// With "jump" (2026-11-17), when there's no walk the path may jump down ledges + /// (DungeonPathfinder.Jumps.cs): a Jump point at each edge. One way, so only on request. /// private void HandleDunNavToCommand(string[] parts) { @@ -3225,20 +3296,41 @@ public sealed partial class RynthAiPlugin var hazards = _objectCache?.GetHazardCells(); var path = startCell != 0 && goalCell != 0 ? DungeonPathfinder.FindPath(startCell, goalCell, graph, hazards) : new List(); Host.TryGetObjectName(target, out string name); + bool mayJump = parts.Skip(3).Any(p => p.Trim().Equals("jump", StringComparison.OrdinalIgnoreCase)); + NavRouteParser route; + string how; if (path.Count == 0) { - ReplyFail($"[RynthAi] DunNav-To: no walk from {startCell:X8} to '{name}' 0x{target:X8} in {goalCell:X8} on the dungeon map (behind a ledge or a hazard?)."); - return; + // No walk: with "jump", down a ledge (or several) if that gets there. + var jumpPath = mayJump && geo != null && startCell != 0 && goalCell != 0 + ? DungeonPathfinder.FindPathWithJumps(startCell, goalCell, graph, DungeonPathfinder.FindJumps(graph, geo), hazards) + : new List<(uint Cell, DungeonJump? Jump)>(); + if (jumpPath.Count == 0) + { + ReplyFail($"[RynthAi] DunNav-To: no walk from {startCell:X8} to '{name}' 0x{target:X8} in {goalCell:X8} on the dungeon map (behind a ledge or a hazard?)" + + (mayJump ? ", and no jump down gets there either." : ".")); + return; + } + route = new NavRouteParser { RouteType = NavRouteType.Once }; + route.Points.AddRange(DungeonPathfinder.BuildJumpPathPoints(jumpPath, graph, geo, hazards, playerNS, playerEW, playerZ, destNS, destEW, oz, out int jumps)); + route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = destNS, EW = destEW, Z = oz / 240.0 }); + var first = jumpPath.First(p => p.Jump != null).Jump!.Value; + how = $"{jumpPath.Count} cells, {jumps} jump{(jumps == 1 ? "" : "s")} down (the first {first.Drop:F1} m off {first.From:X8} into {first.Land:X8})"; + Host.Log($"[RynthAi] DunNav-To: no walk to 0x{target:X8}; jumping down: {how}."); + } + else + { + route = DungeonPathfinder.BuildNavRoute(path, graph, destNS, destEW, geo, hazards, playerNS, playerEW, playerZ, oz); + how = $"{path.Count} cells"; } - var route = DungeonPathfinder.BuildNavRoute(path, graph, destNS, destEW, geo, hazards, playerNS, playerEW, playerZ, oz); if (route.Points.Count == 0) { ReplyFail($"[RynthAi] DunNav-To: no walk laid to '{name}' 0x{target:X8}."); return; } if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge) - settings.IsMacroRunning = true; + settings.SetMacroRunning(true, "/ra dunnav-to"); settings.CurrentRoute = route; settings.ActiveNavIndex = 0; settings.EnableNavigation = true; - ReplyOk($"[RynthAi] DunNav-To: '{name}' 0x{target:X8} in {goalCell:X8}: {path.Count} cells, {route.Points.Count} points → walking there"); + ReplyOk($"[RynthAi] DunNav-To: '{name}' 0x{target:X8} in {goalCell:X8}: {how}, {route.Points.Count} points → walking there"); } /// @@ -3302,7 +3394,7 @@ public sealed partial class RynthAiPlugin } if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge) - settings.IsMacroRunning = true; + settings.SetMacroRunning(true, "/ra dunnav"); settings.CurrentRoute = route; settings.ActiveNavIndex = 0; settings.EnableNavigation = true; @@ -3667,7 +3759,7 @@ public sealed partial class RynthAiPlugin // "patrol immediately runs into a wall on login" failure mode. (From where the character // walks out of a portal's circle to, when it stands in one.) // (The explore only looks a few points ahead: past those it would skip rooms, a loop comes round again.) - int startIdx = FindFirstLineOfSightWaypoint(route, losCell, losX, losY, losZ, explore != null ? ExploreSightLookahead : int.MaxValue); + int startIdx = FindFirstLineOfSightWaypoint(route, losCell, losX, losY, losZ, explore != null ? ExploreSightLookahead : int.MaxValue, walkMap: geometry); // The way to that waypoint: out of a portal's circle first, round any portal in between. if (portals.Count > 0 && route.Points.Count > 0) { @@ -3738,7 +3830,7 @@ public sealed partial class RynthAiPlugin _dunPatrolActive = false; return; } - settings.IsMacroRunning = true; + settings.SetMacroRunning(true, "the dungeon patrol"); // The patrol picked its own start (the first waypoint in sight). Starting the macro // here must not also trigger the macro-start "nearest waypoint" pick on the next // tick: on a loop that is often a waypoint near the END (it comes back to the start), @@ -4298,10 +4390,13 @@ public sealed partial class RynthAiPlugin /// world position has clear line of sight from the player. Returns 0 if no LOS check /// is possible (no raycast subsystem / no geometry) or if no waypoint clears — at /// worst we behave like the old "always start at 0" code, so this is a strict win. + /// (the dungeon map, in a dungeon): a waypoint in sight is taken only when the straight + /// walk to it passes at a body's height too (DungeonPathfinder.StraightWalkClear). In sight at chest height, a + /// later waypoint skipped the corners laid round an altar or a table, and the first leg went through it (2026-11-18). /// private int FindFirstLineOfSightWaypoint(NavRouteParser route, uint playerCell, float playerLocalX, float playerLocalY, float playerZ, - int lookahead = int.MaxValue) + int lookahead = int.MaxValue, DungeonGeometry? walkMap = null) { if (route?.Points == null || route.Points.Count == 0) return 0; var geo = _raycast?.GeometryLoader; @@ -4316,6 +4411,11 @@ public sealed partial class RynthAiPlugin var origin = new Vector3(pBlockX * 192f + playerLocalX, pBlockY * 192f + playerLocalY, playerZ + 1.0f); + // The walk test only where the map has a floor under the character (in a dungeon's cell). + NavPoint? from = null; + if (walkMap != null && (playerCell & 0xFFFF) >= 0x0100 + && walkMap.TryFloorHeight(origin.X, origin.Y, playerZ, 3.0, out _)) + from = new NavPoint { Type = NavPointType.Point, EW = DungeonGeometry.WorldToNav(origin.X), NS = DungeonGeometry.WorldToNav(origin.Y), Z = playerZ / 240.0 }; for (int i = 0; i < route.Points.Count && i < lookahead; i++) { @@ -4333,8 +4433,9 @@ public sealed partial class RynthAiPlugin // multiRay=true matches dungeon LOS used elsewhere (TargetingFSM) so thin // corner walls don't slip between the center ray. - if (!RaycastEngine.IsLinearPathBlocked(origin, target, geometry, multiRay: true)) - return i; + if (RaycastEngine.IsLinearPathBlocked(origin, target, geometry, multiRay: true)) continue; + if (from != null && !DungeonPathfinder.StraightWalkClear(walkMap!, from, p)) continue; + return i; } return 0; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.BoostLootFirst.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.BoostLootFirst.cs new file mode 100644 index 0000000..a5c84e7 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.BoostLootFirst.cs @@ -0,0 +1,36 @@ +// ============================================================================ +// RynthSuite - RynthAiPlugin.BoostLootFirst.cs +// Boost Loot Priority: corpses first, then the hunt (2026-11-22: "boost loot should loot any +// new corpse available and hunt after looting is complete"). +// +// R-20261122-010831-9488 (Shadowfang Keep, Conquest): fast spawns, and Boost Loot "is not looting +// every corpse before moving along to the next". It gave way to any monster within 5 yd twice over: +// the arbiter gave Looting the tick only while combat wasn't engaged (a target locked, or a monster +// within CloseAttackYards), and combat's hold on its next target (BoostLootHoldsNewTarget) ended the +// moment a monster came that close. In a room that refills at once one always is, so the next +// monster was locked 1 ms after each kill and the corpses waited for a lull that rarely came. +// +// Now, with Boost Loot on, while there is loot work (a corpse claimed, open, lootable in range, or +// the kill's corpse still forming) neither gives way to a close monster: the corpses are looted, +// then the fight and the hunt go on. One exception kept for safety: with health under Heal At (the +// line a fight heals at) a monster on you is fought as before, so looting never stands still while +// the character is being killed. +// ============================================================================ + +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// + /// Boost Loot Priority puts corpses ahead of a monster that is close or already fought: Boost Loot + /// can run, and health is at or above Heal At (or not known yet). + /// + private bool BoostLootFirst(LegacyUiSettings settings) + => BoostLootCanRun(settings) && (_vitals.MaxHealth == 0 || _vitals.HealthPct >= settings.HealAt); + + /// CombatManager.HoldNewTargetThroughThreat: the hold on the next target applies with a monster close. + private bool BoostLootHoldsThroughThreat() + => _dashboard?.Settings is { } s && BoostLootFirst(s); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs index 404e4be..d20f6c0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs @@ -240,7 +240,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(); _targetCorpseId = id; _corpseTargetSince = now; _lastCorpseOpenAttemptAt = 0; @@ -261,7 +261,11 @@ public sealed partial class RynthAiPlugin if (why == "completed") _lastChestLootedId = unchecked((uint)chestId); // ralastchestlooted[] // Pickup with macro off > Leave the chest open: a chest the player opened stays open, and chat says so. - bool leaveOpen = close && chestId == _manualChestLootId && (_dashboard?.Settings?.LootChestsMacroOffLeaveOpen ?? false); + // So does one the pickup took nothing from (R-20261120-173459-ea5d): it was closed about 1 ms after + // the player opened it, before they could take what the profile leaves, and some chests lock on close. + bool manual = chestId == _manualChestLootId; + bool leaveOpen = close && manual + && ((_dashboard?.Settings?.LootChestsMacroOffLeaveOpen ?? false) || _corpseItemsLooted == 0); if (chestId == _manualChestLootId) _manualChestLootId = 0; if (close && !leaveOpen) @@ -281,7 +285,7 @@ public sealed partial class RynthAiPlugin _processedCorpseItems.Clear(); _corpseItemAttempts.Clear(); - _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); + _pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear(); _pendingPerDay.Clear(); _corpseIdsRequested = false; ResetCurrentLootItem(); if (_openedContainerId == chestId) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.CorpseBehindWall.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.CorpseBehindWall.cs new file mode 100644 index 0000000..2c876b5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.CorpseBehindWall.cs @@ -0,0 +1,82 @@ +// ============================================================================ +// RynthSuite - RynthAiPlugin.CorpseBehindWall.cs +// A corpse behind a wall (2026-11-21, R-20261121-190950-ee4e, 2026.11.19.1): "I keep trying to loot +// through walls" in a dungeon (Shadowfang Keep, 0x005A). Corpses 3.4-3.7 m away on the far side of a +// wall: every open came back UseDone 0 and nothing opened (the server walks the character straight +// at the corpse, and the wall stops it). Each one cost about 11 s (four opens, the use check's clean +// stop, a jump and its pause), then came back 30 s later for two more rounds, while other corpses +// waited, and the stops and jumps read as the character fighting the wall. +// +// Now an open that is about to be re-sent for a corpse that didn't open checks the straight line to +// it (the raycast's single chest-height ray, as melee uses): a wall in the way sets the corpse aside +// instead. Set aside is not an abandon (it never counts toward the three), its failed open is not a +// use refusal, and it gets another look every CorpseWallRecheckMs: once the line is clear (the +// character moved, the hunt walked round) it is a corpse like any other. Only a failed open leads +// here, so a corpse the ray reads behind a wall that still opens is looted as before. +// ============================================================================ + +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.Raycasting; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// A corpse set aside behind a wall is looked at again this often. + internal const long CorpseWallRecheckMs = 3000; + + private readonly HashSet _corpsesBehindWall = new(); + + /// Tests: whether a wall stands between the character and the corpse (else the raycast decides). + internal System.Func? CorpseWallOverride { get; set; } + + /// The straight line to crosses a wall. False when the raycast can't say. + private bool CorpseBehindWall(int corpseId) + { + if (CorpseWallOverride != null) return CorpseWallOverride(corpseId); + var raycast = _raycastReady; + if (raycast == null || !raycast.IsInitialized) return false; + try { return raycast.IsTargetBlocked(Host, unchecked((uint)corpseId), TargetingFSM.AttackType.Melee); } + catch { return false; } + } + + /// + /// Before an open is re-sent for (one already went out and nothing + /// opened): true when it was set aside behind a wall instead, and nothing is sent. + /// + private bool SetAsideBehindWall(int corpseId, long now) + { + if (corpseId == 0 || _lastOpenAttemptCorpseId != corpseId || _openedContainerId == corpseId) return false; + if (!CorpseBehindWall(corpseId)) return false; + _useRefusals.Forget(corpseId); + if (_corpsesBehindWall.Count >= 256) _corpsesBehindWall.Clear(); // a bound: corpses go in minutes + _corpsesBehindWall.Add(corpseId); + _corpseCooldownUntil[corpseId] = now + CorpseWallRecheckMs; + string name = _objectCache?[corpseId]?.Name ?? $"0x{(uint)corpseId:X8}"; + double d = _objectCache?.Distance(unchecked((int)_playerId), corpseId) ?? double.MaxValue; + LootDiag($"[RynthAi] Corpse loot: 0x{(uint)corpseId:X8} '{name}'{(d < 1000 ? $" ({d:0.0} m)" : "")} didn't open and a wall " + + "stands between: set aside (not a refusal or an abandon) until the line to it is clear."); + StopCorpseMovement(); + ResetCorpseTarget(); + _lastOpenAttemptCorpseId = 0; + _lastCorpseOpenAttemptAt = 0; + return true; + } + + /// + /// HasUnlootedCorpsesInRange, for a corpse set aside behind a wall whose look-again time came: + /// true while the wall is still there (it waits another CorpseWallRecheckMs). + /// + private bool StillBehindWall(int corpseId, long now) + { + if (!_corpsesBehindWall.Contains(corpseId)) return false; + if (CorpseBehindWall(corpseId)) + { + _corpseCooldownUntil[corpseId] = now + CorpseWallRecheckMs; + return true; + } + _corpsesBehindWall.Remove(corpseId); + LootDiag($"[RynthAi] Corpse loot: the line to 0x{(uint)corpseId:X8} is clear now: it can be looted."); + return false; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs index f09ab72..5fbcb4e 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Dashboard.cs @@ -321,6 +321,7 @@ internal sealed class DashboardBridge : IDashboardHost public int AutoSort => _p.DashAutoSort; public bool AutoSortMoving => _p.DashSortMoving; public bool FightSelectedTarget => _p.DashboardRenderer?.Settings.FightSelectedTarget == true; + public bool DebuffAllBeforeAttacking => _p.DashboardRenderer?.Settings.DebuffAllBeforeAttacking == true; public void SetAutoSort(bool on) => Queue(() => _p.SetDashAutoSort(on)); public void ToggleSortWindow() => Queue(() => _p.SendSortCommand(string.Empty)); public void StartPatrol() => Queue(_p.HandleDungeonNavPatrol); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DataFolders.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DataFolders.cs index 4c221d5..cb34aa8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DataFolders.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DataFolders.cs @@ -39,6 +39,8 @@ public sealed partial class RynthAiPlugin { // A meta file that lost data (CallState rules with no target): its load warning. _dashboard?.DrainMetaNotices(line => Host.WriteToChat(line, CommandReply.FailColor)); + // VirindiTank navs in a folder the nav list doesn't show (LegacyUi/StrayNavs.cs): where they go. + _dashboard?.DrainStrayNavNotice(line => Host.WriteToChat(line, CommandReply.FailColor)); if (DataWriteGuard.PendingCount == 0) return; DataWriteGuard.DrainChat(line => Host.WriteToChat(line, 2)); } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs index 9d0c90a..ad42ca8 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DeathWait.cs @@ -27,8 +27,16 @@ // when it has targets, so the hold could only ever wait on a looter that waits for the fight. The corpse // is looted after the fight, as every corpse is with Boost Loot off; the wait still keeps nav and the // hunt from walking off when no fight is left (the owner's case: running off from the last kill). +// +// No corpse here (2026-11-20): "in threads it shouldn't wait for the death animation since mobs don't have +// corpses, it needs to move as fast as possible". DreamWeave's Thread monsters leave no corpse, so every kill there +// stood the character still for the whole wait ("no corpse came in 3.5 s, carrying on"). Learned in the session, +// per dungeon landblock and per monster: after NoCorpseSkipAfter kills in a row with no corpse, a kill there (or of +// that monster anywhere) starts no wait. A corpse of a kill near the character puts its landblock and its monster +// back to waiting. // Pump thread throughout. using System; +using System.Collections.Generic; using RynthCore.Plugin.RynthAi.LegacyUi; using RynthCore.Plugin.RynthAi.Loot; using RynthCore.Plugin.RynthAi.MonsterStats; @@ -57,6 +65,48 @@ public sealed partial class RynthAiPlugin private int _deathCorpseId; // its corpse, once it came private long _deathCorpseAt; private bool _deathWaitHeld; // HasLootWork's answer this tick (the arbiter's DeathWait input) + private uint _deathWaitLandblock; // the dungeon landblock of the kill being waited for (0 outdoors) + + /// Kills in a row with no corpse after which a landblock or a monster gets no corpse wait. + internal const int NoCorpseSkipAfter = 2; + private readonly Dictionary _noCorpseByLandblock = new(); + private readonly Dictionary _noCorpseByName = new(StringComparer.OrdinalIgnoreCase); + + /// The kills here (a dungeon landblock), or of this monster, have left no corpse lately: no wait. + private bool NoCorpseExpected(uint landblock, string name, out string because) + { + if (landblock != 0 && _noCorpseByLandblock.TryGetValue(landblock, out int n) && n >= NoCorpseSkipAfter) + { + because = $"the last {n} kills in landblock 0x{landblock:X4} left no corpse"; + return true; + } + if (name.Length > 0 && _noCorpseByName.TryGetValue(name, out int m) && m >= NoCorpseSkipAfter) + { + because = $"its last {m} kills left no corpse"; + return true; + } + because = ""; + return false; + } + + /// The waited-for kill left no corpse: counted for its landblock and its monster (one line when either stops waiting). + private void NoteNoCorpse() + { + if (_deathWaitLandblock != 0) + { + int n = _noCorpseByLandblock.TryGetValue(_deathWaitLandblock, out int was) ? was + 1 : 1; + _noCorpseByLandblock[_deathWaitLandblock] = n; + if (n == NoCorpseSkipAfter) + Host.Log($"[RynthAi] Kill: {n} kills in a row in landblock 0x{_deathWaitLandblock:X4} left no corpse: no corpse wait here until one does."); + } + if (_deathWaitName.Length > 0) + { + int m = _noCorpseByName.TryGetValue(_deathWaitName, out int was) ? was + 1 : 1; + _noCorpseByName[_deathWaitName] = m; + if (m == NoCorpseSkipAfter) + Host.Log($"[RynthAi] Kill: '{_deathWaitName}' left no corpse {m} times in a row: no corpse wait for it until one comes."); + } + } /// The death wait can run: the macro and Looting on, and the looter able to loot now. private bool DeathWaitCanRun(LegacyUiSettings settings) @@ -73,6 +123,14 @@ public sealed partial class RynthAiPlugin { var s = _dashboard?.Settings; if (s == null || !DeathWaitCanRun(s)) return; + uint landblock = CurrentLandblockOrZero(); + string trimmed = name?.Trim() ?? ""; + if (NoCorpseExpected(landblock, trimmed, out string because)) + { + Host.Log($"[RynthAi] Kill: no wait for the corpse of {(trimmed.Length > 0 ? $"'{trimmed}'" : "the kill")}: {because}."); + return; + } + _deathWaitLandblock = landblock; double? learned = string.IsNullOrWhiteSpace(name) ? null : _xpTable.DeathMs(name); long death = learned is double d ? (long)Math.Round(Math.Clamp(d, 0, DeathWaitMaxDeathMs)) : DeathWaitDefaultMs; _deathWaitMs = death + DeathWaitExtraMs; @@ -114,6 +172,7 @@ public sealed partial class RynthAiPlugin if (_deathCorpseId == 0) { if (since < _deathWaitMs) return true; + NoteNoCorpse(); EndDeathWait($"no corpse came in {_deathWaitMs / 1000.0:0.0} s, carrying on"); return false; } @@ -156,6 +215,10 @@ public sealed partial class RynthAiPlugin if (!Host.HasGetObjectName || !Host.TryGetObjectName(objectId, out string name)) return; string? killed = CorpseTimer.KilledName(name); if (killed == null || !CorpseNearMe(objectId)) return; + // Corpses come here after all: this landblock and this monster wait for them again. + uint landblock = CurrentLandblockOrZero(); + if (landblock != 0) _noCorpseByLandblock.Remove(landblock); + _noCorpseByName.Remove(killed); if (_corpseTimer.OnCorpse(name, CorpseNowMs) is var (who, ms) && ms <= DeathWaitMaxDeathMs) { _monsterStats.OnCorpseTime(who, ms, DateTime.UtcNow); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DirtyFighting.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DirtyFighting.cs index 42f8d5a..54a65bd 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DirtyFighting.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DirtyFighting.cs @@ -121,7 +121,8 @@ public sealed partial class RynthAiPlugin if (ImGui.Combo("Then attack##dfdefault", ref defIdx, DfDefaultLabels, DfDefaultLabels.Length)) s.DfDefaultHeight = defIdx - 1; if (!s.DfHeightRotation) ImGui.EndDisabled(); - Wrapped("Once all three are on, attacks use the Then attack height (Attack Height setting: the Melee " + Wrapped("An order with one or two heights puts on just those effects. " + + "Once the effects in the order are on, attacks use the Then attack height (Attack Height setting: the Melee " + "or Missile Attack Height), and go back to an effect about 5 seconds before it runs out. " + "Each effect lands on up to 1 hit in 4 and lasts 20 seconds; RynthAi sees it land from the " + "\"Dirty Fighting! ...\" combat line.", Ui.Mute); diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunExplore.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunExplore.cs index b118ac6..973fed9 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunExplore.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.DunExplore.cs @@ -363,7 +363,7 @@ public sealed partial class RynthAiPlugin if (!isRebuild) { if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) return false; // one bot per client (Decal bridge) - settings.IsMacroRunning = true; + settings.SetMacroRunning(true, "the dungeon explore"); // As the patrol: the explore picked its own start; the macro-start "nearest waypoint" pick // on the next tick must not move it (on a walk that ends it would skip rooms). _macroWasRunning = true; @@ -700,7 +700,7 @@ public sealed partial class RynthAiPlugin if (!settings.IsMacroRunning) { if (RefuseMacroStartForVTank()) return; - settings.IsMacroRunning = true; + settings.SetMacroRunning(true, "the dungeon explore"); _macroWasRunning = true; } settings.CurrentNavPath = string.Empty; @@ -1002,7 +1002,7 @@ public sealed partial class RynthAiPlugin if (toward == 0) { if (geo != null && StuckSpot(route, at, from, wx, wy, z, label, lx, ly, "with the next points in its cell too", out spot, out note)) return true; - Host.Log($"[RynthAi] {label}: stuck in cell {from:X8} with the next {StuckLookAheadPoints} points in it too: nothing to close"); + Host.Log($"[RynthAi] {label}: stuck in cell {from:X8} with the next {StuckLookAheadPoints} points in it too: nothing to close{_navigationEngine?.LastStuckNote()}"); return false; } var open = closed.Count > 0 ? DungeonPathfinder.WithoutOpenings(graph, new HashSet(closed), from) : graph; @@ -1028,7 +1028,7 @@ public sealed partial class RynthAiPlugin string twins = keys.Count > 1 ? $" and {keys.Count - 1} more cell pair(s) through the same opening" : ""; string seen = geo != null && geo.TryGetDoorway(a, b, out var dw) ? ThingsInDoorway(landblock, dw, inDoorway) : ""; Host.Log($"[RynthAi] {label}: stuck for good at ({lx:F1},{ly:F1},{z:F1}) heading for waypoint {at} (cell {toward:X8}): " - + $"closing the opening between {note}{twins} ({stuckCount + 1} closed){seen}"); + + $"closing the opening between {note}{twins} ({stuckCount + 1} closed){seen}{_navigationEngine?.LastStuckNote()}"); return true; } @@ -1051,7 +1051,7 @@ public sealed partial class RynthAiPlugin }; note = $"a spot in cell {cell:X8}"; Host.Log($"[RynthAi] {label}: stuck for good at ({lx:F1},{ly:F1},{z:F1}) heading for waypoint {at}, {where}: " - + $"walking round the spot ({spot.X:F1},{spot.Y:F1}) {StuckSpotRadius:F1} m round it"); + + $"walking round the spot ({spot.X:F1},{spot.Y:F1}) {StuckSpotRadius:F1} m round it{_navigationEngine?.LastStuckNote()}"); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HuntFence.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HuntFence.cs new file mode 100644 index 0000000..c16991c --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HuntFence.cs @@ -0,0 +1,153 @@ +// The hunt fence (2026-11-17): a circle the outdoor hunt picks its monsters inside and combat fights inside. +// +// DreamWeave's open-world Threads are a circle: 15 m inside its edge the server warns ("The Thread thins +// here. Turn back toward its heart."), outside it the Unraveling hurts more every second, and the Thread's +// monsters are held to the circle (a hit from a player outside it is refused). The hunt picked monsters by +// distance alone and walked out past the edge after them ("In outdoor threads he is going outside of +// the thread boundary"). A script reads the circle off the ring of wisps the server sets on its edge and +// fences the hunt a margin inside it: /ra hunt fence (global metres: landblock x * 192 + +// local x, as the hunt's own positions), /ra hunt fence off. Not saved: a script sets it for the place it +// is in, and clears it when it leaves. +// +// A walk is fenced too (same day: "here and there nav takes him outside of the thread boundary"): to a +// monster inside the fence, the way round a building can swing out past the edge. An optional fourth number +// is how far out a walk may go (default the fence and 15 m); a walk whose corners go out past it, farther +// out than where the character stands, is no walk (the monster is left out a while, as one with no way to it). +// From outside it a walk back in is still a walk. +// +// The hunt (OutdoorHunt.Fence) leaves a monster outside the fence out of its picks; combat +// (CombatManager.SkipTarget) leaves one out of its targets, unless it is the one +// being fought or the player's own target lock. + +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// The fence (centre and radius, global metres), or null: none. + internal (double X, double Y, double R)? HuntFence { get; private set; } + /// How far from the fence's centre a walk may go (metres). + internal double HuntFenceWalkR { get; private set; } + + /// A walk may go this much past the fence when the fence is given without its walk radius. + internal const double HuntFenceWalkDefaultM = 15.0; + + internal const string HuntFenceUsage = "[RynthAi] Usage: /ra hunt fence [walk radius] (global metres: landblock x * 192 + local x) or /ra hunt fence off"; + + /// OutdoorHunt.WalkFence: no corner out past the walk radius farther out than where it starts (me). + internal bool WalkInHuntFence(OutdoorHunt.Vec me, IReadOnlyList corners) + { + if (FenceHere() is not { } f || corners.Count == 0) return true; + double Out(OutdoorHunt.Vec v) => Math.Sqrt((v.X - f.X) * (v.X - f.X) + (v.Y - f.Y) * (v.Y - f.Y)); + double start = Out(me); + foreach (var c in corners) + { + double d = Out(c); + if (d > HuntFenceWalkR && d > start + 2.0) return false; + } + return true; + } + + /// True when (x, y) (global metres) is inside the fence, or there is none (or it was for another place). + internal bool InHuntFence(double x, double y) + => FenceHere() is not { } f || (x - f.X) * (x - f.X) + (y - f.Y) * (y - f.Y) <= f.R * f.R; + + /// A monster this near the character is fought, fence or not. + internal const double FenceFightNearM = 10.0; + /// Outside the fence, a monster no more than this farther from its middle than the character (up to the walk radius) is fought. + internal const double FenceFightOutM = 5.0; + /// The character this far past the walk radius: the fence was for another place, and is lifted. + internal const double FenceForgetM = 300.0; + + /// + /// CombatManager.SkipTarget's fence half: a monster outside the fence is left alone, unless it is near + /// the character or no farther out than the character stands (FenceFightOutM, up to the walk radius). + /// 2026-11-17 16:40, DreamWeave Thread 32D9: the character stood 127 m from the middle of a 124 m fence, + /// among the Thread's monsters, all outside it; combat took none of them ("possible=0"), and it stood + /// there being hit until it died ("he's just standing there not attacking"). + /// + internal bool FenceSkipsTarget(int id) + { + if (FenceHere() is not { } f) return false; + if (!Host.TryGetObjectPosition(unchecked((uint)id), out uint c, out float x, out float y, out _)) return false; + double gx = ((c >> 24) & 0xFF) * 192.0 + x, gy = ((c >> 16) & 0xFF) * 192.0 + y; + bool hasMe = TryHuntPosition(out _, out var me); + return FenceSkips(f, HuntFenceWalkR, gx, gy, hasMe, me.X, me.Y); + } + + /// The pure half of . + internal static bool FenceSkips((double X, double Y, double R) f, double walkR, double gx, double gy, bool hasMe, double mx, double my) + { + double dMon = Math.Sqrt((gx - f.X) * (gx - f.X) + (gy - f.Y) * (gy - f.Y)); + if (dMon <= f.R) return false; + if (!hasMe) return true; + if (Math.Sqrt((gx - mx) * (gx - mx) + (gy - my) * (gy - my)) <= FenceFightNearM) return false; + double dMe = Math.Sqrt((mx - f.X) * (mx - f.X) + (my - f.Y) * (my - f.Y)); + return dMon > Math.Min(dMe + FenceFightOutM, Math.Max(walkR, f.R)); + } + + private long _fenceCheckedAt; + + /// + /// The fence, for where the character is: null when there is none, and lifted when the character is in a + /// dungeon or far past it (FenceForgetM). 2026-11-17 16:42, the fence of Thread 32D9 outlived the Thread + /// (the script lost it with the Thread at a death): in the next Thread, a dungeon, every monster was + /// outside it, and combat fought none ("he died because he isn't fighting"). + /// + internal (double X, double Y, double R)? FenceHere() + { + if (HuntFence is not { } f) return null; + long now = Environment.TickCount64; + if (now - _fenceCheckedAt < 500) return f; + _fenceCheckedAt = now; + if (!TryHuntPosition(out uint cell, out var me)) return f; + double d = Math.Sqrt((me.X - f.X) * (me.X - f.X) + (me.Y - f.Y) * (me.Y - f.Y)); + bool dungeon = OutdoorHunt.IsIndoorCell(cell) && InDungeon(cell); + if (!dungeon && d <= Math.Max(HuntFenceWalkR, f.R) + FenceForgetM) return f; + HuntFence = null; + HuntFenceWalkR = 0; + Host.Log(string.Format(CultureInfo.InvariantCulture, "[RynthAi] Hunt fence: lifted ({0}): it was for another place.", + dungeon ? "in a dungeon" : $"{d:0} m from its middle")); + return null; + } + + /// /ra hunt fence <x> <y> <radius> | off (parts[3..]). + private void SetHuntFence(string[] parts) + { + string a = parts.Length > 3 ? parts[3].Trim().ToLowerInvariant() : ""; + if (a is "off" or "none" or "clear") + { + bool had = HuntFence != null; + HuntFence = null; + HuntFenceWalkR = 0; + ChatLine(had ? "[RynthAi] Hunt fence: off." : "[RynthAi] Hunt fence: there was none."); + return; + } + var inv = CultureInfo.InvariantCulture; + if (parts.Length < 6 + || !double.TryParse(parts[3], NumberStyles.Float, inv, out double x) + || !double.TryParse(parts[4], NumberStyles.Float, inv, out double y) + || !double.TryParse(parts[5], NumberStyles.Float, inv, out double r) + || double.IsNaN(x) || double.IsNaN(y) || double.IsNaN(r) || r <= 0) + { + ChatLine(a == "" && HuntFence is { } f + ? string.Format(inv, "[RynthAi] Hunt fence: {0:0.0} m round {1:0.0}, {2:0.0}.", f.R, f.X, f.Y) + : HuntFenceUsage); + return; + } + double walk = r + HuntFenceWalkDefaultM; + if (parts.Length > 6 && double.TryParse(parts[6], NumberStyles.Float, inv, out double w) && w >= r) walk = w; + HuntFence = (x, y, r); + HuntFenceWalkR = walk; + string where = ""; + if (TryHuntPosition(out _, out var me)) + { + double d = Math.Sqrt((me.X - x) * (me.X - x) + (me.Y - y) * (me.Y - y)); + where = string.Format(inv, "; you are {0:0} m from its middle{1}", d, d > r ? " (outside it)" : ""); + } + ChatLine(string.Format(inv, "[RynthAi] Hunt fence: {0:0.0} m round {1:0.0}, {2:0.0}, walks to {3:0.0} m{4}.", r, x, y, walk, where)); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Kits.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Kits.cs new file mode 100644 index 0000000..c91a2f8 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Kits.cs @@ -0,0 +1,422 @@ +using System; +using System.Globalization; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.RynthAi.MiniRemote; +using RynthCore.Plugin.RynthAi.MiniRemote.Crafting; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; + +namespace RynthCore.Plugin.RynthAi; + +// Make kits (a players' request, 2026-11-22): /ra kits [status|make [N]|stop|floor <0-100>|show]. +// The work is MiniRemote/Crafting/KitRunner.cs (ticked by the Crafting tab); the main path is the +// Mini Remote's Crafting tab, Kits sub-tab, "Make kits". Kits are made by hand only while the macro is off. +// +// Make kits when low (MakeKitsWhenLow, off by default; /ra kits auto ...): with the macro on, the +// Crafting tab's KitAuto decides when a run may start (MiniRemote/Crafting/KitAuto.cs) from the +// facts read here, and while one gets ready or goes the rest of the tick waits, as it does for buffs +// (TickAutoKits, right after the Buffing hold). Right after the arbiter's decision, ahead of every +// hold, CheckAutoKitsDanger stops a run at once on a monster within the safe radius, buffing or a +// heal line, a fight, a portal; KitRunner itself stops on a hit, moving, leaving peace or the macro off. +public sealed partial class RynthAiPlugin +{ + internal const string KitsUsage = "Usage: /ra kits [status | make [count] | stop | floor <0-100> | show | auto [on|off|status|below N|upto M]]"; + internal const string KitsAutoUsage = "Usage: /ra kits auto [status | on | off | below <1-50> | upto <1-100>]"; + + /// /ra kits: status (the default), make [count], stop, floor <percent>, show (the Kits tab), auto .... + private void HandleKitsCommand(string[] parts) + { + string verb = parts.Length > 2 ? parts[2].Trim().ToLowerInvariant() : "status"; + if (verb is not ("status" or "make" or "stop" or "floor" or "show" or "auto")) + { + ReplyFail($"[RynthAi] Make kits: unknown option '{parts[2]}'. {KitsUsage}"); + return; + } + if (verb == "auto") { HandleKitsAutoCommand(parts); return; } + var remote = _miniRemote; + if (remote == null) { ReplyFail("[RynthAi] Make kits: not ready yet (log in first)."); return; } + var tab = remote.Crafting; + var kits = tab.Kits; + + switch (verb) + { + case "status": + { + var rows = kits.RefreshPlan(); + foreach (var row in rows) ChatLine("[RynthAi] Make kits: " + KitPlanner.Line(row)); + ChatLine($"[RynthAi] Make kits: {(kits.Running ? kits.Status : "not running")}; floor {kits.Floor}%. " + + "Mini Remote > Crafting > Kits, or /ra kits make."); + ChatLine(KitsAutoStatusLine()); + break; + } + case "make": + { + int count = 0; + if (parts.Length > 3 && !parts[3].Equals("all", StringComparison.OrdinalIgnoreCase) + && (!int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out count) || count < 1)) + { + ReplyFail($"[RynthAi] Make kits: the count must be a number of 1 or more, or 'all' (got '{parts[3]}'). {KitsUsage}"); + break; + } + var recipe = kits.Find(null); + if (recipe == null) { ReplyFail("[RynthAi] Make kits: no kit recipe is known."); break; } + int can = KitPlanner.CanMake(recipe, kits.Pack()); + string why = kits.Start(recipe, count); + if (why.Length > 0) { ReplyFail($"[RynthAi] Make kits: can't start - {why}."); break; } + int target = count > 0 ? Math.Min(count, can) : can; + ReplyOk($"[RynthAi] Make kits: making up to {target} {recipe.Name}(s), floor {kits.Floor}%. /ra kits stop to stop."); + break; + } + case "stop": + if (!kits.Running) { ReplyOk("[RynthAi] Make kits: nothing is running."); break; } + kits.Stop("stopped by you"); + Reply.Answered(); // Stop printed the summary line + break; + case "floor": + { + if (parts.Length < 4) + { + ReplyOk($"[RynthAi] Make kits: the floor is {kits.Floor}% (no combine under it is tried). {KitsUsage}"); + break; + } + string text = parts[3].Trim().TrimEnd('%'); + if (!int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int pct) || pct < 0 || pct > 100) + { + ReplyFail($"[RynthAi] Make kits: the floor must be 0-100 (got '{parts[3]}'). {KitsUsage}"); + break; + } + remote.State.Crafting.KitMinChancePercent = pct; + ReplyOk($"[RynthAi] Make kits: floor set to {pct}%" + (pct == 0 ? " (any chance)." : ".")); + break; + } + case "show": + { + tab.SelectKitsTab(); + string? reply = remote.MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Crafting, "show"); + if (reply == null) ReplyFail("[RynthAi] Make kits: the Mini Remote isn't available yet."); + else ReplyOk("[RynthAi] Make kits: " + reply); + break; + } + } + } + + // ── /ra kits auto ─────────────────────────────────────────────────────── + + /// /ra kits auto [status | on | off | below N | upto M]: Make kits when low (a profile setting). + private void HandleKitsAutoCommand(string[] parts) + { + var settings = _dashboard?.Settings; + if (settings == null) { ReplyFail("[RynthAi] Make kits when low: not ready yet (log in first)."); return; } + string verb = parts.Length > 3 ? parts[3].Trim().ToLowerInvariant() : "status"; + var auto = _miniRemote?.Crafting.AutoKits; + switch (verb) + { + case "status": + ChatLine(KitsAutoStatusLine()); // the status asked for + break; + case "on": + case "off": + { + bool on = verb == "on"; + settings.MakeKitsWhenLow = on; + _dashboard?.SaveSettings(); + if (on) auto?.LookNow(); + else + { + var kits = _miniRemote?.Crafting.Kits; + if (kits != null && kits.Auto) kits.Stop("Make kits when low turned off", KitStopKind.Other); + auto?.Off(); + } + ReplyOk($"[RynthAi] Make kits when low: {verb} (under {Below(settings)} kits, make up to {UpTo(settings)})" + + (on && !settings.IsMacroRunning ? "; it works while the macro runs." : ".")); + break; + } + case "below": + case "upto": + { + int max = verb == "below" ? KitAuto.MaxBelow : KitAuto.MaxUpTo; + if (parts.Length < 5) + { + ReplyOk($"[RynthAi] Make kits when low: {(verb == "below" ? $"starts under {Below(settings)} kits" : $"makes up to {UpTo(settings)} kits a run")}. {KitsAutoUsage}"); + break; + } + if (!int.TryParse(parts[4].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1 || n > max) + { + ReplyFail($"[RynthAi] Make kits when low: {verb} must be a number from 1 to {max} (got '{parts[4]}'). {KitsAutoUsage}"); + break; + } + if (verb == "below") settings.MakeKitsBelow = n; else settings.MakeKitsUpTo = n; + _dashboard?.SaveSettings(); + auto?.LookNow(); + ReplyOk(verb == "below" + ? $"[RynthAi] Make kits when low: starts when you carry fewer than {n} kits{(settings.MakeKitsWhenLow ? "." : " (it is off: /ra kits auto on).")}" + : $"[RynthAi] Make kits when low: makes up to {n} kits a run{(settings.MakeKitsWhenLow ? "." : " (it is off: /ra kits auto on).")}"); + break; + } + default: + ReplyFail($"[RynthAi] Make kits when low: unknown option '{parts[3]}'. {KitsAutoUsage}"); + break; + } + } + + private static int Below(LegacyUiSettings s) => Math.Clamp(s.MakeKitsBelow, 1, KitAuto.MaxBelow); + private static int UpTo(LegacyUiSettings s) => Math.Clamp(s.MakeKitsUpTo, 1, KitAuto.MaxUpTo); + + /// One line: the setting, its numbers, the radius and what it is doing. + private string KitsAutoStatusLine() + { + var s = _dashboard?.Settings; + if (s == null) return "[RynthAi] Make kits when low: not ready yet (log in first)."; + string state = !s.MakeKitsWhenLow ? "off" : "on"; + string doing = ""; + var tab = _miniRemote?.Crafting; + if (s.MakeKitsWhenLow && tab != null) doing = "; " + tab.AutoStatusText(s); + return $"[RynthAi] Make kits when low: {state}, under {Below(s)} kits make up to {UpTo(s)}, " + + $"no monster within {KitSafeRadiusYd(s):0} yd{doing}. Mini Remote > Crafting > Kits, /ra kits auto on|off."; + } + + // ── Make kits when low: the macro side ────────────────────────────────── + + /// No monster this close for a start, and one coming this close stops a run: 35 yd, or Monster Range when bigger. + internal static double KitSafeRadiusYd(LegacyUiSettings s) => Math.Max(KitAuto.DefaultRadiusYd, s.MonsterRange); + + /// The world walk for monsters is this far apart while nothing is going (the scan list is read every time). + private const long KitMonsterWalkMs = 500; + private long _kitMonsterWalkAt = long.MinValue / 2; + private double _kitMonsterWalkYd = double.PositiveInfinity; + private uint _kitLastHealth; + private long _kitHurtAt = long.MinValue / 2; + private bool _kitPoseKnown; + private uint _kitPoseCell; + private float _kitPoseX, _kitPoseY, _kitPoseZ; + private bool _kitMoving; + /// Moving more than this between two ticks counts as moving (KitRunner stops past 1.5 m from the start). + private const float KitMoveEpsilon = 0.15f; + + private long KitNow() => _miniRemote?.Crafting.AutoKits.NowMs() ?? Environment.TickCount64; + + /// + /// Every in-world tick, right after the arbiter's decision and ahead of every hold: notes a hit and + /// a move, and stops a "when low" run at once when a monster comes within the radius, buffing or a + /// heal is wanted, a fight starts or a portal is taken. + /// + private void CheckAutoKitsDanger(LegacyUiSettings s) + { + long now = KitNow(); + TrackKitHurtAndMove(now); + var kits = _miniRemote?.Crafting.Kits; + if (kits == null || !kits.Auto) return; + var f = new KitAutoFacts + { + Enabled = true, + MacroOn = s.IsMacroRunning, + BusyWhy = KitBusyWhy(s, starting: false), + VitalsWhy = KitVitalsWhy(s), + RadiusYd = KitSafeRadiusYd(s), + }; + // The combat scan (kept fresh by the hold) is read every tick; the world walk past it every half second. + if (f.BusyWhy.Length == 0 && f.VitalsWhy.Length == 0) f.NearestMonsterYd = NearestMonsterYards(f.RadiusYd, now, force: false); + string why = KitAuto.StopReason(f); + if (why.Length > 0) kits.Stop(why, KitStopKind.Danger); + } + + /// + /// Make kits when low, after the Buffing hold: true while a run gets ready or goes, and the rest of + /// the tick (combat, looting, navigation, item chores) waits, as it does for buffs. + /// + private bool TickAutoKits(LegacyUiSettings s) + { + var tab = _miniRemote?.Crafting; + if (tab == null) return false; + var kits = tab.Kits; + var auto = tab.AutoKits; + if (kits.Running) + { + if (!kits.Auto) return false; // a run by hand (the macro is off then) + auto.Running(kits.MadeCount, kits.Limit); + return s.IsMacroRunning; + } + if (!s.MakeKitsWhenLow) { if (auto.Status != "off") auto.Off(); return false; } + + long now = auto.NowMs(); + KitAutoStep step = auto.Decide(() => KitStartFacts(s, kits, now, readying: auto.Readying)); + switch (step) + { + case KitAutoStep.GoPeace: + Host.ChangeCombatModeFor(CombatMode.NonCombat, "Kits", "peace mode for Make kits when low"); + return true; + case KitAutoStep.Hold: + return true; + case KitAutoStep.Start: + { + var recipe = kits.Find(null); + if (recipe == null) { auto.StartRefused("no kit recipe is known"); return false; } + string why = kits.StartAuto(recipe, UpTo(s), (kind, made) => auto.RunEnded(kind, made)); + if (why.Length > 0) { auto.StartRefused(why); return false; } + auto.Running(0, UpTo(s)); + return true; + } + default: + return false; + } + } + + /// One full look for a start (KitAuto reads it only when a look is due). + private KitAutoFacts KitStartFacts(LegacyUiSettings s, KitRunner kits, long now, bool readying) + { + var f = new KitAutoFacts + { + Enabled = s.MakeKitsWhenLow, + MacroOn = s.IsMacroRunning, + Below = Below(s), + RadiusYd = KitSafeRadiusYd(s), + }; + if (!f.Enabled || !f.MacroOn) return f; + var pack = kits.Pack(); + f.Kits = KitPlanner.Count(KitPlanner.PlentifulHealingKit, pack); + if (f.Kits >= f.Below) return f; + // Getting ready, the client is busy with our own peace-mode switch: not a reason to give up. + f.BusyWhy = KitBusyWhy(s, starting: true, clientBusyCounts: !readying); + f.VitalsWhy = KitVitalsWhy(s); + f.NearestMonsterYd = NearestMonsterYards(f.RadiusYd, now, force: false); + f.SinceHurtMs = _kitHurtAt <= long.MinValue / 4 ? long.MaxValue : Math.Max(0, now - _kitHurtAt); + var recipe = kits.Find(null); + if (recipe == null) f.PackWhy = "no kit recipe is known"; + else + { + var next = KitPlanner.Next(recipe, pack, kits.Skill, kits.Floor); + f.PackWhy = next.Step == null ? next.Why : string.Empty; + } + try { f.InPeace = !Host.HasGetCurrentCombatMode || Host.GetCurrentCombatMode() == CombatMode.NonCombat; } + catch { f.InPeace = false; } + f.Moving = _kitMoving; + return f; + } + + /// + /// What else has the character ("" = nothing): buffing or healing, a fight, a portal, a vendor or + /// trade; for a start also looting, salvaging, other item work, following, travelling back to the + /// corpse, or a busy client. + /// + private string KitBusyWhy(LegacyUiSettings s, bool starting, bool clientBusyCounts = true) + { + if (_activity == BotActivity.Buffing || (_buffManager != null && _buffManager.PendingSpellId != 0)) return "buffing or healing"; + var combat = _combatManager; + if (_activity == BotActivity.Combat || FightIsOn(s) || (combat != null && (combat.IsActivelyEngaged || combat.IsUnderCloseAttack))) return "a fight"; + try { if (Host.HasIsPortaling && Host.IsPortaling()) return "in portal space"; } catch { } + if (_navigationEngine?.IsInPortalAction == true) return "taking a portal"; + if (_autoVendor?.HoldsBot == true || _autoTrade?.HoldsBot == true) return "at a vendor or a trade"; + if (!starting) return string.Empty; + if (_activity == BotActivity.Looting || _lastWantLoot || _openedContainerId != 0 || _targetCorpseId != 0) return "looting"; + if (_activity == BotActivity.Salvaging || _salvageManager?.IsBusy == true) return "salvaging"; + if (_missileCraftingManager?.IsCrafting == true) return "crafting ammunition"; + if (_aetheriaUnboxer?.IsUnboxing == true) return "unboxing aetheria"; + if (_scrollLearner?.IsReading == true) return "reading a scroll"; + if (IsFollowActive(s)) return "following"; + if (OwnCorpseTravelHoldsNav) return "travelling back to your corpse"; + if (clientBusyCounts && PacedBusy > 0) return "busy"; + return string.Empty; + } + + /// "" when health, stamina and mana are over their lines (and no heal or recharge is wanted); else which. + private string KitVitalsWhy(LegacyUiSettings s) + { + if (_buffManager?.WantsVitalRecharge == true) return "healing or restoring vitals"; + uint h = 0, mh = 0, st = 0, mst = 0, m = 0, mm = 0; + try { if (!Host.HasGetPlayerVitals || !Host.TryGetPlayerVitals(out h, out mh, out st, out mst, out m, out mm)) return string.Empty; } + catch { return string.Empty; } + if (mh > 0) + { + int hp = (int)(h * 100UL / mh); + int line = Math.Max(s.HealAt, Math.Max(s.EmergencyHealAt, s.StaminaToHealthAt)); + if (hp <= line) return $"health {hp}% (Heal At {line}%)"; + } + if (mst > 0) + { + int sp = (int)(st * 100UL / mst); + if (sp <= s.RestamAt) return $"stamina {sp}% (Re-stam At {s.RestamAt}%)"; + } + if (mm > 0) + { + int mp = (int)(m * 100UL / mm); + if (mp <= s.GetManaAt) return $"mana {mp}% (Get Mana At {s.GetManaAt}%)"; + } + return string.Empty; + } + + /// + /// The nearest live monster: the combat scan (within Monster Range, a clear line) and, at most every + /// half second unless , the world cache (any line, past Monster Range). + /// PositiveInfinity when none is known. + /// + private double NearestMonsterYards(double within, long now, bool force) + { + double best = double.PositiveInfinity; + var combat = _combatManager; + if (combat != null) + { + var scanned = combat.ScannedTargets; + for (int i = 0; i < scanned.Count; i++) + if (scanned[i].Distance < best) best = scanned[i].Distance; + if (best > within && combat.HasCloseThreat(within)) best = within; // a predicted kill still alive + } + if (force || now - _kitMonsterWalkAt >= KitMonsterWalkMs) + { + _kitMonsterWalkAt = now; + _kitMonsterWalkYd = WorldMonsterYards(); + } + return Math.Min(best, _kitMonsterWalkYd); + } + + /// The nearest live, fightable monster in the world cache (PositiveInfinity = none). + private double WorldMonsterYards() + { + var cache = _objectCache; + uint me = _playerId; + if (cache == null || me == 0) return double.PositiveInfinity; + double best = double.PositiveInfinity; + foreach (var wo in cache.GetLandscapeObjects()) + { + if (wo.ObjectClass != AcObjectClass.Monster) continue; + if (cache.GetHealthRatio(wo.Id) == 0f) continue; // dead + double d = cache.Distance(unchecked((int)me), wo.Id); + if (!(d < best)) continue; + if (!IsFightableCreature(unchecked((uint)wo.Id))) continue; + best = d; + } + return best; + } + + /// Health going down is a hit (for "no hit for 20 s"); the pose changing between ticks is moving. + private void TrackKitHurtAndMove(long now) + { + try + { + if (Host.HasGetPlayerVitals && Host.TryGetPlayerVitals(out uint h, out _, out _, out _, out _, out _)) + { + if (_kitLastHealth > 0 && h > 0 && h < _kitLastHealth) _kitHurtAt = now; + _kitLastHealth = h; + } + if (Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _)) + { + float dx = x - _kitPoseX, dy = y - _kitPoseY, dz = z - _kitPoseZ; + _kitMoving = _kitPoseKnown && (cell != _kitPoseCell || dx * dx + dy * dy + dz * dz > KitMoveEpsilon * KitMoveEpsilon); + _kitPoseKnown = true; + _kitPoseCell = cell; + _kitPoseX = x; _kitPoseY = y; _kitPoseZ = z; + } + } + catch { } + } + + /// Logout: this character's hit and pose notes go. + private void ResetKitTracking() + { + _kitLastHealth = 0; + _kitHurtAt = long.MinValue / 2; + _kitPoseKnown = false; + _kitMoving = false; + _kitMonsterWalkAt = long.MinValue / 2; + _kitMonsterWalkYd = double.PositiveInfinity; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootPerDay.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootPerDay.cs new file mode 100644 index 0000000..6e2c2e2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LootPerDay.cs @@ -0,0 +1,251 @@ +// ============================================================================ +// RynthAi - RynthAiPlugin.LootPerDay.cs +// "Keep # per day" (2026-11-22, RynthCore.Loot.LootPerDay): a Keep # rule with +// a window (24 h by default) takes at most its count of matching items picked +// up in any such window, counted by what this character picked up, not by +// what the pack holds (treasure maps get used or sold). An item over the count +// is left like any item no rule wants. +// +// Flow: the classifier approves an item while the window's pickups plus the +// items approved and not landed yet are under the count (_pendingPerDay); +// the send moves it to _perDayInFlight; the landing (the pickup confirmed, a +// late landing, a ground pickup) records it in the character's +// LootPerDayStore (Loot/LootPerDayStore.cs), saved at once, so the count +// survives reloads and relogs. +// +// Shown: the Loot Editor's rule view (option, help line, today's count, a +// reset button) and /ra loot today [clear |clear all]. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.IO; +using RynthCore.Loot; +using RynthCore.Loot.VTank; +using RynthCore.Plugin.RynthAi.Loot; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// The time pickups are stamped with (UTC). Host tests move it. + internal static Func PerDayClock = static () => DateTime.UtcNow; + + // Approved this corpse (or ground scan), not sent yet: counted while fresh. + private readonly Dictionary _pendingPerDay = new(); + // Sent: counted until it lands (recorded) or the late-landing watch gives up on it. + private readonly Dictionary _perDayInFlight = new(); + private const long PerDayPendingMs = 120_000; + private const long PerDayInFlightMs = 120_000; + + private LootPerDayStore? _lootPerDay; + private string _lootPerDayFolder = string.Empty; + + /// + /// The store of the character logged in (SettingsProfiles\<server>\<character>\loot_per_day.json), + /// loaded on first use and again when the character changes. Before login: an in-memory one. + /// + internal LootPerDayStore PerDayStore() + { + string folder = _dashboard?.CharFolder ?? string.Empty; + if (_lootPerDay != null && string.Equals(folder, _lootPerDayFolder, StringComparison.OrdinalIgnoreCase)) + return _lootPerDay; + _lootPerDay ??= new LootPerDayStore(); + _lootPerDayFolder = folder; + _lootPerDay.Load(folder.Length == 0 ? string.Empty : Path.Combine(folder, LootPerDayStore.FileName), PerDayClock()); + if (_lootPerDay.Problem.Length > 0) + Host.Log($"[RynthAi] Keep # per day: could not read the pickup counts ({_lootPerDay.Problem}); starting from none."); + return _lootPerDay; + } + + /// + /// Keep # per day: true while fewer than units were picked up for + /// in the last , counting items approved or on + /// their way that haven't landed yet. At the count the item is left (and said, once per item). + /// + private bool UnderDailyCap(string key, string ruleLabel, WorldObject item, int cap, int hours, bool preview = false) + { + long nowMs = CorpseNowMs; + if (_pendingPerDay.TryGetValue(item.Id, out var mine) && nowMs - mine.At < PerDayPendingMs) return true; + if (_perDayInFlight.ContainsKey(item.Id)) return true; + + DateTime now = PerDayClock(); + LootPerDayStore store = PerDayStore(); + int have = store.Count(key, hours, now) + NotLandedYet(key, item.Id, nowMs); + if (preview) return LootKeepCap.UnderCap(have, cap); + string window = LootPerDay.WindowText(hours); + if (!LootKeepCap.UnderCap(have, cap)) + { + _corpseCappedIds.Add(item.Id); + TimeSpan? next = store.NextFree(key, hours, cap, now); + ChatLine($"[RynthAi] Keep # per day '{ruleLabel}': {have}/{cap} picked up in the last {window}" + + (next is TimeSpan t && t > TimeSpan.Zero ? $" (the next in {LootPerDayStore.Duration(t)})" : string.Empty) + + $" — leaving {item.Name}."); + return false; + } + int stack = LootKeepCap.StackOf(item); + _pendingPerDay[item.Id] = (key, stack, nowMs); + ChatLine($"[RynthAi] Keep # per day '{ruleLabel}': {have}/{cap} picked up in the last {window} — looting {item.Name}{(stack > 1 ? " x" + stack : "")}."); + return true; + } + + /// Units for approved (still fresh) or on their way, other than . + private int NotLandedYet(string key, int exceptId, long nowMs) + { + int n = 0; + foreach (var kv in _perDayInFlight) + if (kv.Key != exceptId && string.Equals(kv.Value.Key, key, StringComparison.OrdinalIgnoreCase) && nowMs < kv.Value.Until) + n += kv.Value.Units; + foreach (var kv in _pendingPerDay) + if (kv.Key != exceptId && !_perDayInFlight.ContainsKey(kv.Key) + && string.Equals(kv.Value.Key, key, StringComparison.OrdinalIgnoreCase) && nowMs - kv.Value.At < PerDayPendingMs) + n += kv.Value.Units; + return n; + } + + /// The pickup of was sent: an approved Keep # per day item is now on its way. + private void NotePerDaySent(int itemId) + { + if (!_pendingPerDay.TryGetValue(itemId, out var p)) return; + _perDayInFlight[itemId] = (p.Key, p.Units, CorpseNowMs + PerDayInFlightMs); + } + + /// + /// left the corpse or the ground into the pack: if a Keep # per day + /// rule took it, it counts now (once). + /// + private void NotePerDayPickedUp(int itemId) + { + string key; + int units; + if (_perDayInFlight.Remove(itemId, out var f)) { key = f.Key; units = f.Units; } + else if (_pendingPerDay.TryGetValue(itemId, out var p)) { key = p.Key; units = p.Units; } + else return; + _pendingPerDay.Remove(itemId); + LootPerDayStore store = PerDayStore(); + store.Record(key, units, PerDayClock()); + if (store.Problem.Length > 0) + Host.Log($"[RynthAi] Keep # per day: the pickup of '{key}' is counted but could not be saved ({store.Problem})."); + } + + /// Drops sends whose landing never came (the late-landing watch is over). Each corpse tick. + private void PrunePerDay() + { + if (_perDayInFlight.Count == 0 && _pendingPerDay.Count == 0) return; + long nowMs = CorpseNowMs; + List? gone = null; + foreach (var kv in _perDayInFlight) + if (nowMs >= kv.Value.Until) (gone ??= new()).Add(kv.Key); + if (gone != null) foreach (int id in gone) _perDayInFlight.Remove(id); + gone = null; + foreach (var kv in _pendingPerDay) + if (nowMs - kv.Value.At >= PerDayPendingMs && !_perDayInFlight.ContainsKey(kv.Key)) (gone ??= new()).Add(kv.Key); + if (gone != null) foreach (int id in gone) _pendingPerDay.Remove(id); + } + + /// The Loot Editor's line for a Keep # per day rule (LootEditorBridge). + internal string PerDayStatusFor(string key, int hours, int cap) => + PerDayStore().Status(key, hours, cap, PerDayClock()); + + /// + /// The Loot Editor's revision part: the store's changes plus the minute, while any pickup is on + /// record, so "next frees in" stays current. + /// + internal long PerDayRevision() + { + LootPerDayStore s = PerDayStore(); + long minute = 0; + foreach (var _ in s.Rules()) { minute = (long)(PerDayClock() - DateTime.UnixEpoch).TotalMinutes; break; } + return s.Revision * 1_000_000_000L + minute; + } + + /// The Loot Editor's "Reset count": forgets the rule's pickups. The reply for the editor's message line. + internal string PerDayReset(string key) + { + bool had = PerDayStore().Clear(key); + return had ? $"Keep # per day '{key}': pickups forgotten; it counts from 0 again." : $"Keep # per day '{key}': no pickups on record."; + } + + /// + /// /ra loot today [clear <rule>|clear all]: each Keep # per day rule of the loot profile in use, + /// with what was picked up in its window, and any other rule with pickups on record. + /// + private void HandleLootTodayCommand(string[] parts) + { + LootPerDayStore store = PerDayStore(); + DateTime now = PerDayClock(); + if (parts.Length >= 4) + { + if (!string.Equals(parts[3], "clear", StringComparison.OrdinalIgnoreCase)) + { + ReplyFail($"[RynthAi] loot today: '{parts[3]}'? Usage: /ra loot today [clear |clear all]"); + return; + } + string what = parts.Length > 4 ? string.Join(" ", parts, 4, parts.Length - 4).Trim() : string.Empty; + if (what.Length == 0) + { + ReplyFail("[RynthAi] loot today clear: which rule? Usage: /ra loot today clear |all"); + return; + } + bool all = string.Equals(what, "all", StringComparison.OrdinalIgnoreCase); + bool had = store.Clear(all ? null : what); + if (had) ReplyOk(all ? "[RynthAi] Keep # per day: every rule's pickups forgotten." : $"[RynthAi] Keep # per day '{what}': pickups forgotten; it counts from 0 again."); + else ReplyFail(all ? "[RynthAi] Keep # per day: no pickups on record." : $"[RynthAi] Keep # per day: no pickups on record for '{what}'. /ra loot today lists them."); + return; + } + + var lines = new List(); + var shown = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach ((string key, int cap, int hours) in PerDayRulesInUse()) + { + if (!shown.Add(key)) continue; + lines.Add($"[RynthAi] '{key}': {store.Status(key, hours, cap, now)}"); + } + foreach ((string key, IReadOnlyList picks) in store.Rules()) + { + if (shown.Contains(key)) continue; + int units = 0; + foreach (var p in picks) if (p.AtUtc > now.AddHours(-LootPerDay.DefaultHours)) units += p.Units; + lines.Add($"[RynthAi] '{key}' (not a Keep # per day rule of this profile): {units} picked up in the last 24 h"); + } + if (lines.Count == 0) + { + ReplyOk("[RynthAi] Keep # per day: the loot profile in use has no such rule and no pickups are on record. " + + "Turn it on for a Keep # rule in the Loot Editor (rule view: Per day)."); + return; + } + ReplyOk($"[RynthAi] Keep # per day ({lines.Count} rule{(lines.Count == 1 ? "" : "s")}), counted for this character:"); + foreach (string l in lines) ChatLine(l); + if (store.Problem.Length > 0) ChatLine("[RynthAi] (" + store.Problem + ")"); + } + + /// The loot profile in use's Keep # per day rules: key, count, window. + private List<(string Key, int Cap, int Hours)> PerDayRulesInUse() + { + var list = new List<(string, int, int)>(); + try + { + string path = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"'); + if (path.Length == 0 || !File.Exists(path)) return list; + if (TryLoadNativeLootProfile(out LootProfile native, out _)) + { + for (int i = 0; i < native.Rules.Count; i++) + { + LootRule r = native.Rules[i]; + int h = LootPerDay.Clamp(r.PerDayHours); + if (r.Action == LootAction.KeepUpTo && h > 0) list.Add((LootPerDay.Key(r.Name, i), r.KeepCount, h)); + } + } + else if (TryLoadLootProfile(string.Empty, out VTankLootProfile utl, out _)) + { + for (int i = 0; i < utl.Rules.Count; i++) + { + VTankLootRule r = utl.Rules[i]; + int h = LootPerDay.Clamp(r.PerDayHours); + if (r.Action == VTankLootAction.KeepUpTo && h > 0) list.Add((LootPerDay.Key(r.Name, i), r.KeepCount ?? 0, h)); + } + } + } + catch { } + return list; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LowComponents.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LowComponents.cs index fe13b70..785b452 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LowComponents.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.LowComponents.cs @@ -50,7 +50,7 @@ public sealed partial class RynthAiPlugin if (low == null) return; _lowCompsFired = true; - HandleMacroRunCommand("stop", Array.Empty()); + HandleMacroRunCommand("stop", Array.Empty(), "Low Components Recall"); bool recalled = Host.HasInvokeChatParser; if (recalled) Host.InvokeChatParser("/lifestone"); string line = $"Low on components ({low}): macro stopped" + (recalled ? ", recalling to the lifestone" : "") + diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MacroStopWho.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MacroStopWho.cs new file mode 100644 index 0000000..5d2d0e5 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.MacroStopWho.cs @@ -0,0 +1,46 @@ +// ============================================================================ +// RynthSuite - RynthAiPlugin.MacroStopWho.cs +// The "Macro stopped" line says who stopped it, and the health at that moment. +// +// The stop is seen at the next tick (the macro switch went false), so the line used to say only what +// the stop did. Who did it (the panel's button, a typed /ra stop, a meta, a Lua script, the HP failsafe, +// Stop Macro On Death...) is recorded where the switch is written (LegacyUiSettings.SetMacroRunning, +// MacroSource) and said here. With health under a heal line nothing heals while the macro is off: said +// too, and flagged when the stop came from a script, a meta, a route or a remote rather than the player. +// ============================================================================ + +using System; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + private string MacroStopWho(LegacyUiSettings settings) + { + string line = ""; + int hp = 0, lineValue = 0; + try { line = _buffManager?.HealLineNow(out hp, out lineValue) ?? ""; } + catch { line = ""; } + return DescribeMacroStop(settings.MacroStopSource, hp, line, lineValue); + } + + /// The tail of the "Macro stopped" line (internal for the host tests). + internal static string DescribeMacroStop(string source, int healthPct, string healLine, int lineValue) + { + string who = string.IsNullOrEmpty(source) ? "a plain write (no source named)" : source; + string text = $"Stopped by {who}"; + if (healLine.Length == 0) return text + "."; + text += $"; health {healthPct}% is under {healLine} {lineValue}%: no heal goes while the macro is off"; + if (!StopIsThePlayers(who)) text += ". FLAG: stopped by a script, meta, route or remote with a heal due"; + return text + "."; + } + + /// The player's own hands: the panel, the Mini Remote, a typed command, Stop Macro On Death. + internal static bool StopIsThePlayers(string who) => + who.StartsWith("the panel", StringComparison.Ordinal) + || who.StartsWith("the Mini Remote", StringComparison.Ordinal) + || who.Contains("(typed", StringComparison.Ordinal) + || who.StartsWith("Stop Macro On Death", StringComparison.Ordinal) + || who.StartsWith("the character session ending", StringComparison.Ordinal); +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs index d450189..97581bb 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.OutdoorHunt.cs @@ -21,16 +21,20 @@ namespace RynthCore.Plugin.RynthAi; public sealed partial class RynthAiPlugin { private readonly OutdoorHunt _hunt = new(); + private bool _huntFenceHooked; private readonly List _huntCandidates = new(); private NavRouteParser? _huntRoute; // the route the hunt installed; another one loaded ends the hunt private NavRecoveryPlanner? _huntDungeonCheck; + private int _huntStuckSeq; // NavigationEngine.StuckSpotSeq last looked at private BuildingMap? _huntBuildings; private long _huntPortalsAt; private string _huntNoteLogged = ""; private bool _huntOnLoginPending; // Hunt On Login: read at login, run once by TickLoginAutoStart private const int HuntMaxCorners = 128; - private const int HuntPathFlags = RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance - | RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet; + // Also the stuck recovery's outdoor detours (NavRecovery.PlanOutdoor) and a script's GoTo: one set of rules for every + // walk RynthAi lays on RynthNav's map. + internal const int HuntPathFlags = RynthNavPathApiV1.PathAvoidPortals | RynthNavPathApiV1.PathWallClearance + | RynthNavPathApiV1.PathAllowPartial | RynthNavPathApiV1.PathQuiet; private const uint HuntItemTypePortal = 0x00010000; private const long HuntPortalRefreshMs = 1000; @@ -56,6 +60,9 @@ public sealed partial class RynthAiPlugin case "radius": SetHuntSetting(arg, parts.Length > 3 ? parts[3] : ""); break; + case "fence": + SetHuntFence(parts); + break; case "pick": SetHuntPick(parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : ""); break; @@ -74,7 +81,7 @@ public sealed partial class RynthAiPlugin if (_hunt.Active) StopHunt("stopped", say: true); else StartHunt(); break; default: - ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range | /ra hunt radius | " + HuntPickUsage + " | " + HuntLoginUsage + " | " + KeepHuntingUsage); + ChatLine("[RynthAi] /ra hunt [start|stop|status|panel] | /ra hunt range | /ra hunt radius | /ra hunt fence | off | " + HuntPickUsage + " | " + HuntLoginUsage + " | " + KeepHuntingUsage); break; } } @@ -302,7 +309,7 @@ public sealed partial class RynthAiPlugin s.EnableNavigation = true; if (!s.IsMacroRunning) { - s.IsMacroRunning = true; + s.SetMacroRunning(true, "the outdoor hunt"); _macroWasRunning = true; // no macro-start "nearest waypoint" pick: the hunt plans its own walks } ChatLine((onLogin ? "[RynthAi] Hunt On Login: outdoor hunt on: " @@ -417,6 +424,21 @@ public sealed partial class RynthAiPlugin } if (!TryHuntPosition(out uint cell, out var me)) return; if (InDungeon(cell)) { StopHunt("went into a dungeon", say: true); return; } + // Navigation stuck at one spot again and again on the hunt's walk (a snag RynthNav's map doesn't hold): + // the hunt leaves that monster and keeps its walks off the spot (OutdoorHunt.Snagged). 2026-11-17 11:14, + // the fort Thread 3073: the same walk was planned through a piece of wall every 8 s for 90 s. + var navE = _navigationEngine; + if (navE != null && navE.StuckSpotSeq != _huntStuckSeq) + { + _huntStuckSeq = navE.StuckSpotSeq; + if (navE.StuckSpotHits >= NavigationEngine.StuckSpotRepeatHits && s.CurrentRoute.Points.Count > 0) + { + // Where the snag is, on one line with the stuck line's words (cell, local x/y/z, headings, the walk's + // target, metres moved): the snags in the logs had x,y only, and the A9B4 replays failed for want of z. + Host.Log($"[RynthAi] Hunt: snag x{navE.StuckSpotHits} on the walk to 0x{(uint)_hunt.TargetId:X8} | {navE.LastStuckWhere}"); + _hunt.Snagged(RynthClock.Now, me); + } + } // A building's rooms (InDungeon said it isn't a dungeon): off RynthNav's landscape map. The way in // is kept on every tick, a fight's chase included, for the walk back out of a building whose // doors aren't known. @@ -486,6 +508,7 @@ public sealed partial class RynthAiPlugin _hunt.RangeYd = Math.Clamp(s.OutdoorHuntRange, OutdoorHuntRangeMin, OutdoorHuntRangeMax); _hunt.RadiusYd = Math.Clamp(s.OutdoorHuntRadius, 0, OutdoorHuntRadiusMax); _hunt.Pick = (OutdoorHunt.PickMode)Math.Clamp(s.OutdoorHuntPick, 0, 2); + if (!_huntFenceHooked) { _hunt.Fence = p => InHuntFence(p.X, p.Y); _hunt.WalkFence = WalkInHuntFence; _huntFenceHooked = true; } _hunt.XpLookup ??= XpPerKill; // the learned XP per kill (MonsterXpTable), for Most XP } @@ -522,7 +545,11 @@ public sealed partial class RynthAiPlugin { _huntDungeonCheck ??= new NavRecoveryPlanner(Host, () => _raycast, () => _objectCache?.GetHazardCells()); var check = _huntDungeonCheck; - _huntBuildings = new BuildingMap(cellDat, () => _raycast?.GeometryLoader?.DungeonLOS, lb => check.IsDungeonLandblock(lb, cellDat)); + // The cells' furniture too (the stairs left out): walks round tables and chairs, not through them. + // The ground's height too: an opening whose foot is a step over it and over the room's floor is a window. + _huntBuildings = new BuildingMap(cellDat, () => _raycast?.GeometryLoader?.DungeonLOS, lb => check.IsDungeonLandblock(lb, cellDat), + lb => _raycast?.GeometryLoader?.GetDungeonStaticMeshes(lb), + (x, y) => _raycast?.GeometryLoader is { } gl ? gl.GetTerrainZWorld((float)x, (float)y) : double.NaN); } return _huntBuildings; } @@ -610,4 +637,27 @@ public sealed partial class RynthAiPlugin corners.Add(new OutdoorHunt.Vec(buf[i * 3], buf[i * 3 + 1], buf[i * 3 + 2])); return new OutdoorHunt.PathResult(status, corners, info[0], info[5]); } + + /// HuntRaycast's answer when RynthNav (v2 or later) isn't loaded. + internal const int HuntRayUnavailable = -2; + + /// + /// RynthNav's raycast (RynthNav.Path v2): RayClear when walking straight from (ax, ay, az) to (bx, by, bz), world + /// units, stays on the navmesh (the agent radius from every wall it knows), RayBlocked when a wall, building, drop + /// or the mesh's edge is in the way, ResultNoMesh off the landscape mesh (a building's cells, a dungeon), or + /// . The navigation engine's corner gate asks it on hunt walks, planned GoTo + /// walks and navmesh detours (NavigationEngine.NavmeshRaycast), as RynthNav's own walker does (PathFollow.Advance). + /// + internal int HuntRaycast(double ax, double ay, double az, double bx, double by, double bz) + { + if (!Host.HasGetPluginInterface) return HuntRayUnavailable; + unsafe + { + // Resolved on every call, as HuntPath. + var t = (RynthNavPathApiV1*)Host.GetPluginInterface(RynthNavPathApiV1.PluginName, RynthNavPathApiV1.InterfaceName, 2); + if (t == null || t->Version < 2 || t->StructSize < (uint)sizeof(RynthNavPathApiV1) || t->Raycast == null) + return HuntRayUnavailable; + return t->Raycast(ax, ay, az, bx, by, bz); + } + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PetElement.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PetElement.cs new file mode 100644 index 0000000..df40205 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.PetElement.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using RynthCore.Plugin.RynthAi.LegacyUi; + +namespace RynthCore.Plugin.RynthAi; + +// Pet element (a players' request, 2026-11-22): /ra petelement [status|any|fire|cold|...]. +// The main path is the Mini Remote's Pets tab, Combat type, "Pet element". The pick itself is +// PetChoice.Order; what each summoning item deals (two elements for a server's holder of two +// summons) is PetElements. +public sealed partial class RynthAiPlugin +{ + internal const string PetElementUsage = + "Usage: /ra petelement [status | any | fire | cold | acid | lightning | nether | slash | pierce | bludgeon]"; + + /// /ra petelement: status (the default) or the element combat pets are summoned for. + private void HandlePetElementCommand(string[] parts) + { + var settings = _dashboard?.Settings; + if (settings == null) { ReplyFail("[RynthAi] Pet element: not ready yet (log in first)."); return; } + + string arg = parts.Length > 2 ? parts[2].Trim() : "status"; + if (arg.Equals("status", StringComparison.OrdinalIgnoreCase)) + { + ChatLine(PetElementStatusLine(settings)); + foreach (string line in ListedPetElementLines(settings)) ChatLine(line); + return; + } + + string elem = arg.Equals("any", StringComparison.OrdinalIgnoreCase) || arg.Equals("auto", StringComparison.OrdinalIgnoreCase) + ? "" : PetChoice.NormalizeElement(arg.Equals("frost", StringComparison.OrdinalIgnoreCase) ? "Cold" : arg); + if (elem.Length == 0 && !arg.Equals("any", StringComparison.OrdinalIgnoreCase) && !arg.Equals("auto", StringComparison.OrdinalIgnoreCase)) + { + ReplyFail($"[RynthAi] Pet element: unknown element '{arg}'. {PetElementUsage}"); + return; + } + settings.PetElement = elem; + _dashboard?.SaveSettings(); + ReplyOk(elem.Length == 0 + ? "[RynthAi] Pet element: Any (each monster's own choice: Damage-panel pick, Monsters rule, then its weakness)." + : $"[RynthAi] Pet element: {elem}. A {elem} essence is summoned first unless the monster has a pick or a rule of its own."); + } + + private static string PetElementStatusLine(LegacyUiSettings settings) + { + string e = PetChoice.NormalizeElement(settings.PetElement); + return e.Length == 0 + ? "[RynthAi] Pet element: Any (each monster's own choice). /ra petelement , or Mini Remote > Pets > Combat." + : $"[RynthAi] Pet element: {e}. /ra petelement any to go back, or Mini Remote > Pets > Combat."; + } + + /// One line per listed combat pet item: what it deals ("Fire+Cold" for a holder of two summons). + private List ListedPetElementLines(LegacyUiSettings settings) + { + var lines = new List(); + foreach (var rule in settings.ConsumableRules) + { + if (!rule.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)) continue; + string name = _objectCache?[rule.Id]?.Name ?? rule.Name; + var info = PetElements.Describe(Host, unchecked((uint)rule.Id), name); + string elems = info.ElementText.Length > 0 ? info.ElementText : "element unknown"; + string extra = !info.IsHolder ? "" + : info.Ready ? $", holds {Math.Max(info.Held.Count, info.Slots)} summons" + (info.Held.Count > 0 ? ": " + string.Join(", ", info.Held) : "") + : $", holds {info.Held.Count} of {info.Slots} (can't summon yet)"; + lines.Add($"[RynthAi] {name}: {elems}{extra}"); + } + if (lines.Count == 0) lines.Add("[RynthAi] No pet essences listed (Mini Remote > Pets: tick them, or /ra items fill)."); + return lines; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.RareCorpses.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.RareCorpses.cs new file mode 100644 index 0000000..6d1cb7b --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.RareCorpses.cs @@ -0,0 +1,38 @@ +// ============================================================================ +// RynthSuite - RynthAiPlugin.RareCorpses.cs +// Loot Only Rare Corpses (2026-11-22: "we should know whether it's a rare corpse... vtank does +// somehow"). Asked for on Discord for rare farming on Conquest: Rares loot mode opened every corpse, +// and kills per hour went down. The setting was kept only so profiles round-trip, read by nothing. +// +// How a corpse says it holds a rare: ACE (Corpse.TryGenerateRare, the same in DreamWeave's fork) +// appends " This corpse generated a rare item!" to the corpse's long description, the text whose +// "Killed by ." the ownership rules already read once the corpse is identified (the looter +// asks for that ID for every corpse in range). It also broadcasts " has discovered the +// !", but the description is on the corpse, so it holds for a corpse seen after a relog too. +// +// With the setting on, a corpse is opened only when its description has that sentence. One whose +// description hasn't arrived yet waits for it, as Mine Only does. Your own death corpse +// (Recover My Corpse) is decided before this, so it is always recovered. +// ============================================================================ + +using System; + +namespace RynthCore.Plugin.RynthAi; + +public sealed partial class RynthAiPlugin +{ + /// The sentence ACE adds to a corpse that generated a rare (Corpse.TryGenerateRare). + internal const string RareCorpseText = "This corpse generated a rare item"; + + /// The corpse's long description says it generated a rare. + internal static bool IsRareCorpse(string? longDesc) + => !string.IsNullOrEmpty(longDesc) && longDesc.IndexOf(RareCorpseText, StringComparison.OrdinalIgnoreCase) >= 0; + + /// Why Loot Only Rare Corpses leaves a corpse closed, or null when it is a rare corpse. + internal static string? RareCorpseRefusal(string? longDesc) + { + if (string.IsNullOrWhiteSpace(longDesc)) + return "Loot Only Rare Corpses: waiting for its description (the ID) to see whether it generated a rare."; + return IsRareCorpse(longDesc) ? null : "Loot Only Rare Corpses: it didn't generate a rare."; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs index 7a5a7b1..5dc1df0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Safety.cs @@ -34,7 +34,7 @@ public sealed partial class RynthAiPlugin ArmDeathRecall(s); // before Stop Macro On Death: it reads whether the macro ran if (s.StopMacroOnDeath && s.IsMacroRunning) { - HandleMacroRunCommand("stop", Array.Empty()); + HandleMacroRunCommand("stop", Array.Empty(), "Stop Macro On Death"); ChatLine("[RynthAi] You died — macro stopped (Stop Macro On Death is on)."); } } @@ -153,7 +153,7 @@ public sealed partial class RynthAiPlugin if (_noComponentFails.Count < NoComponentFailsToStop) return; _noComponentFails.Clear(); - HandleMacroRunCommand("stop", Array.Empty()); + HandleMacroRunCommand("stop", Array.Empty(), "Stop Macro On No Components"); ChatLine("[RynthAi] Out of spell components — macro stopped (Stop Macro On No Components is on)."); } @@ -179,7 +179,7 @@ public sealed partial class RynthAiPlugin var s = _dashboard?.Settings; if (s != null && s.StopMacroWhenPackFull && s.IsMacroRunning) { - HandleMacroRunCommand("stop", Array.Empty()); + HandleMacroRunCommand("stop", Array.Empty(), "Stop Macro When Pack Full"); ChatLine("[RynthAi] Your packs are full — macro stopped (Stop Macro When Pack Full is on)."); } else diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.TimedCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.TimedCommands.cs index e33bf87..d2f812c 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.TimedCommands.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.TimedCommands.cs @@ -59,7 +59,8 @@ public sealed partial class RynthAiPlugin { Host.Log($"[RynthAi] Timed command ({TimedCommandSet.ScopeName(scope)}, {why}): {command}"); // As a script's line (a nav route's chat waypoint does the same): quiet when it works. - Reply.AsScript(() => { HandleRynthChatSubmit(command); return true; }); + using (_dashboard?.Settings.MacroSource($"the timed command '{command}'")) + Reply.AsScript(() => { HandleRynthChatSubmit(command); return true; }); } private void SaveTimedCommands() diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs index 12cff58..8052dad 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankHotkeys.cs @@ -13,6 +13,7 @@ namespace RynthCore.Plugin.RynthAi; // /ra targetlock [off] Target lock attack the selected monster (again / off: release) // /ra fightselected [on|off] Fight the monster I select (no argument: toggle) // /ra meleewalls [on|off] Melee through walls (no argument: toggle) +// /ra debuffall [on|off] Debuff every monster in range before attacking (no argument: toggle) // /ra meleelow|meleemid|meleehigh melee attack height // /ra navaddpt NavAddPt waypoint at your position (same as /ra addnavpt) // /ra testitem TestItem the selected item against the loot profile @@ -58,6 +59,8 @@ public sealed partial class RynthAiPlugin case "fightselect": HandleFightSelectedCommand(parts); return true; case "meleewalls": case "meleethroughwalls": HandleMeleeWallsCommand(parts); return true; + case "debuffall": + case "debuffallfirst": HandleDebuffAllCommand(parts); return true; case "meleelow": SetMeleeAttackHeight(0); return true; case "meleemid": case "meleemedium": SetMeleeAttackHeight(1); return true; @@ -234,6 +237,32 @@ public sealed partial class RynthAiPlugin : "[RynthAi] Melee through walls: off (a monster behind a wall is never a melee target for being close)."); } + // ── Debuff every monster in range before attacking ─────────────────────── + + private void HandleDebuffAllCommand(string[] parts) + { + var dash = _dashboard; + var s = dash?.Settings; + if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; } + string arg = parts.Length >= 3 ? parts[2].ToLowerInvariant() : ""; + bool? set = arg switch + { + "" or "toggle" => !s.DebuffAllBeforeAttacking, + "on" or "1" or "true" => true, + "off" or "0" or "false" => false, + _ => null, + }; + if (set is not bool on) + { + ReplyFail($"[RynthAi] Debuff every monster before attacking: unknown '{arg}'. Usage: /ra debuffall [on|off] (now {(s.DebuffAllBeforeAttacking ? "on" : "off")})."); + return; + } + s.DebuffAllBeforeAttacking = on; + dash!.SaveSettings(); + ReplyOk(on ? "[RynthAi] Debuff every monster before attacking: on (each monster in range gets its Monsters-rule debuffs, nearest first, before any attack)." + : "[RynthAi] Debuff every monster before attacking: off (only the target is debuffed before it is attacked)."); + } + // ── Melee attack height ────────────────────────────────────────────────── private void SetMeleeAttackHeight(int height) diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankYield.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankYield.cs index 9af6308..be63cb0 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankYield.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.VTankYield.cs @@ -41,7 +41,7 @@ public sealed partial class RynthAiPlugin _vtankRefusalPending = true; return; } - dash.TogglePanelMacro(); + dash.TogglePanelMacro("the panel's Run/Stop button"); } /// diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index cc9a6b3..aaa1607 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -521,6 +521,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _scrollLearner = null; _aetheriaUnboxer?.Reset(); _aetheriaUnboxer = null; + ResetKitTracking(); // Make kits when low (RynthAiPlugin.Kits.cs) _manaStoneManager = null; _petManager = null; _buffManager?.Dispose(); @@ -611,7 +612,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _navigationEngine = new NavigationEngine(Host, _dashboard.Settings) { // A route's chat waypoint answers as a script's line: quiet when it works (CommandReply.cs). - ChatSubmit = line => Reply.AsScript(() => { HandleRynthChatSubmit(line); return true; }), + ChatSubmit = line => { using (_dashboard?.Settings.MacroSource($"a route's chat waypoint '{line}'")) Reply.AsScript(() => { HandleRynthChatSubmit(line); return true; }); }, // Jump waypoints go through the UB-style jumper (turn, charge, jump, then // it hands navigation back). Forward jump; shift = walking jump. Jump = (heading, shift, ms) => _jumper?.Start(shift ? "ws" : "w", heading, ms), @@ -630,12 +631,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase KeepWaypointAfterPause = () => _dunPatrolActive, // Stuck escapes keep out of portals (RynthAiPlugin.PatrolPortals.cs). EscapePortals = EscapePortalsNear, + // Hunt walks, GoTo walks and navmesh detours turn a corner early only where RynthNav's mesh + // shows a straight walk to the next one (RynthAiPlugin.OutdoorHunt.cs). + NavmeshRaycast = HuntRaycast, }; // Plans the detours: the dungeon cell graph indoors, RynthNav's navmesh outdoors. // Reads the raycast geometry and hazards through the fields, so it follows their // (re)creation; dropped with the engine at teardown. _navPlanner = new NavRecoveryPlanner(Host, () => _raycast, () => _objectCache?.GetHazardCells()); _navigationEngine.SetRecoveryPlanner(_navPlanner); + _navigationEngine.EscapeRoom = _navPlanner.EscapeRoom; // in a dungeon, a burst turns to where the map has room if (_objectCache != null) _navigationEngine.SetWorldObjectCache(_objectCache); _navMarkerRenderer = new NavMarkerRenderer(Host, _dashboard.Settings) { @@ -801,6 +806,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase || (_dashboard?.Settings?.EnableBuffing == true && _buffManager.NeedsAnyBuff())); _combatManager.HoldNewTarget = LootHoldsNewTarget; // Boost Loot Priority: one kill, one loot (the death wait holds no target since 2026-11-15) _combatManager.HoldNewTargetWhy = LootHoldWhy; + _combatManager.HoldNewTargetThroughThreat = BoostLootHoldsThroughThreat; // corpses first (RynthAiPlugin.BoostLootFirst.cs) + _combatManager.SkipTarget = FenceSkipsTarget; // the hunt fence: monsters outside it are left alone _combatManager.ManaReserveHold = spellId => _buffManager?.OffensiveCastHold(spellId); // the mana reserve _combatManager.ManaCanEverAfford = spellId => _buffManager?.CanEverAfford(spellId) ?? true; // script hook: never-payable spells _combatManager.SetStaleBusyCallback(OnCombatBusyStale); @@ -1083,7 +1090,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase { case "macro": if (on && !dash.Settings.IsMacroRunning && RefuseMacroStartForVTank()) break; // one bot per client - if (dash.Settings.IsMacroRunning != on) dash.TogglePanelMacro(); + if (dash.Settings.IsMacroRunning != on) dash.TogglePanelMacro("a remote command (phone/web remote)"); break; case "combat": dash.SetSubsystemEnabled(0, on); break; case "buffing": dash.SetSubsystemEnabled(1, on); break; @@ -1101,7 +1108,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "cancelrebuff": dash.RequestCancelForceRebuff(); break; case "clearbusy": HandleClearBusyCommand(); break; case "hideui": _hideUi = on; dash.SetUiHidden(on); break; // applied each tick in OnTick - case "sendchat": if (!string.IsNullOrEmpty(value)) RunItemToolUntrusted(() => HandleRynthChatSubmit(value)); break; // a remote line is never the player at the keyboard + case "sendchat": if (!string.IsNullOrEmpty(value)) using (dash.Settings.MacroSource($"a remote chat line '{value}'")) RunItemToolUntrusted(() => HandleRynthChatSubmit(value)); break; // a remote line is never the player at the keyboard case "setsetting": ApplyRemoteSetting(value); break; // one advanced setting from the phone (clamped + persisted) case "hub": case "quests": @@ -1575,7 +1582,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase var pauseDash = _dashboard; if (pauseDash != null && !pauseDash.Settings.IsMacroRunning && !RefuseMacroStartForVTank()) { - pauseDash.TogglePanelMacro(); + pauseDash.TogglePanelMacro("the /ra pause timer running out"); ChatLine("[RynthAi] Pause elapsed — macro RESUMED."); } } @@ -1844,7 +1851,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase if (_buffManager != null) _buffManager.BusyCount = 0; Host.Log($"[RynthAi] Macro stopped: attack cancelled, " + (halt ? "movement stopped" : $"movement left alone (nothing of RynthAi's was moving, action {settings.BotAction})") + - $", busy {busyBefore} cleared."); + $", busy {busyBefore} cleared. {MacroStopWho(settings)}"); } catch (Exception ex) { Host.Log($"[RynthAi] Macro-stop cleanup failed: {ex.Message}"); } } @@ -1852,7 +1859,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // was heading to when stopped (after a recall that can be far away). // NavResumeNearest off keeps the last waypoint. if (!_macroWasRunning && settings.IsMacroRunning) + { + Host.Log($"[RynthAi] Macro started by {settings.MacroStartSource}."); _navigationEngine?.ResumeFromNearestWaypoint(); + } _macroWasRunning = settings.IsMacroRunning; _killClock.ObserveMacro(settings.IsMacroRunning); // a start counts even if nothing reads the clock meanwhile @@ -1894,7 +1904,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase && (_buffManager.PendingSpellId != 0 || _buffManager.WantsVitalRecharge || (settings.EnableBuffing && _buffManager.NeedsAnyBuff() - && !_buffManager.BuffsWaitForHealth())); // hurt in a fight: combat, not buffs + && !_buffManager.BuffsWaitForFight())); // in a fight: combat first, buffs after (2026-11-20) bool wantBuff = wantBuffRaw; // ── Buffing-coma watchdog (STEP 5: decides, no longer falls through) ── @@ -1967,6 +1977,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase bool wantLoot = HasLootWork(settings, nowMs); _lastWantLoot = wantLoot; + // Boost Loot Priority, corpses first (RynthAiPlugin.BoostLootFirst.cs): a close or fought + // monster doesn't take the tick from loot work while health is at or above Heal At. + if (engaged && wantLoot && BoostLootFirst(settings)) engaged = false; bool wantSalvage = _salvageManager != null && _salvageManager.IsBusy; bool followActive = IsFollowActive(settings); bool wantNav = NavWantsTick(settings); @@ -2012,6 +2025,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase } } + // ── Make kits when low: a run stops at once on danger ───────────── + // After the decision, ahead of every hold below (buffing above all), so a monster, a + // heal or a fight ends a kit run on this tick (RynthAiPlugin.Kits.cs). + Guard(TickStep.AutoKits, () => CheckAutoKitsDanger(settings)); + // ── Travel back to your corpse (TravelToOwnCorpse) ───────────────── // After the decision, ahead of every early return below: RynthNav walks only // while the arbiter says Idle, and is stopped the moment RynthAi wants the tick. @@ -2096,6 +2114,20 @@ public sealed partial class RynthAiPlugin : RynthPluginBase // hundreds of pending CreateObjects (RL hot-reload, fresh login), // the concurrent native walk has been causing intermittent crashes. bool inventorySettled = (RynthClock.Now - _loginCompletedAt).TotalMilliseconds > 3000; + + // Make kits when low (RynthAiPlugin.Kits.cs): while a kit run gets ready (peace mode, + // standing still) or goes, everything below waits, as it does for buffs: the item + // chores, crafting, combat, looting and navigation. A fault holds nothing. + if (inventorySettled && settings.IsMacroRunning + && GuardHold(TickStep.AutoKits, () => TickAutoKits(settings))) + { + StopNavFor(BotActivity.Idle); + KeepThreatScanFresh(settings); + FreezeCorpseTimeout(CorpseNowMs); // a claimed corpse must not time out while held + ThinkMeta(); + return; + } + if (inventorySettled) TickCramStack(settings); @@ -4176,6 +4208,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase case "find": HandleFindCommand(parts); break; // RynthAiPlugin.FeatureSearch.cs case "aetheria": HandleAetheriaCommand(parts); break; // RynthAiPlugin.Aetheria.cs case "autoconfirm": HandleAutoConfirmCommand(parts); break; // RynthAiPlugin.AutoConfirm.cs + case "kits": HandleKitsCommand(parts); break; // RynthAiPlugin.Kits.cs + case "petelement": HandlePetElementCommand(parts); break; // RynthAiPlugin.PetElement.cs case "why": HandleWhyCommand(); break; case "ghost": case "ghosts": HandleGhostsCommand(cmd, parts); break; diff --git a/Plugins/RynthCore.Plugin.RynthAi/ScriptInterface.cs b/Plugins/RynthCore.Plugin.RynthAi/ScriptInterface.cs index 59b3b4e..54ffc99 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ScriptInterface.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ScriptInterface.cs @@ -217,31 +217,127 @@ public sealed partial class RynthAiPlugin { if (_dashboard == null || _dashboard.Settings.IsMacroRunning == on) return; if (on && RefuseMacroStartForVTank()) return; // one bot per client (Decal bridge) - if (on) _dashboard.TogglePanelMacro(); - else HandleMacroRunCommand("stop", Array.Empty()); + if (on) _dashboard.TogglePanelMacro("a Lua script (ai.MacroRunning = true)"); + else HandleMacroRunCommand("stop", Array.Empty(), "a Lua script (ai.MacroRunning = false)"); } + /// + /// A script's ai.GoTo(ns, ew): a Once route to the point, the macro on. A script roaming a Thread in 80 m legs + /// and edges back 40 m with it, and a one-point straight route walked into every tree, rock and wall on the way + /// (2026-11-18). So the walk is planned as /ra navheading and /ra dunnav-to plan theirs: outdoors along RynthNav's + /// path with the Outdoor Hunt's flags, in a dungeon by the dungeon map; when neither answers, the straight route + /// as before. What the script sees is the same: true, a Once route ending on the point asked for (ranav[] name "" + /// and finished at its end), and the character walking there. + /// internal bool ScriptGoTo(double ns, double ew) { var dash = _dashboard; if (dash == null) return false; var st = dash.Settings; if (!st.IsMacroRunning && RefuseMacroStartForVTank()) return false; // one bot per client (Decal bridge) - float z = 0; - if (Host.HasGetPlayerPose) Host.TryGetPlayerPose(out _, out _, out _, out z, out _, out _, out _, out _); - var route = new NavRouteParser { RouteType = NavRouteType.Once }; - route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / 240.0 }); + uint cell = 0; + float lx = 0, ly = 0, z = 0; + bool pose = Host.HasGetPlayerPose && Host.TryGetPlayerPose(out cell, out lx, out ly, out z, out _, out _, out _, out _); + NavRouteParser? route = null; + string how = "straight (no position)"; + if (pose) + { + // Never worse than before: anything going wrong in planning leaves the straight route. + try { route = PlanGoTo(cell, lx, ly, z, ns, ew, out how); } + catch (Exception ex) { route = null; how = "straight (planning failed: " + ex.Message + ")"; } + } + if (route == null || route.Points.Count == 0) + { + route = new NavRouteParser { RouteType = NavRouteType.Once }; + route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / 240.0 }); + } + Host.Log(string.Create(CultureInfo.InvariantCulture, $"[RynthAi] GoTo: NS {ns:0.0000} EW {ew:0.0000}, {how}")); st.CurrentRoute = route; st.CurrentNavPath = string.Empty; st.ActiveNavIndex = 0; st.EnableNavigation = true; - if (!st.IsMacroRunning) dash.TogglePanelMacro(); + if (!st.IsMacroRunning) dash.TogglePanelMacro("a Lua script (GoTo)"); return true; } + /// The planned walk for , or null (with saying why) for the + /// straight route. The route always ends on (ns, ew). + private NavRouteParser? PlanGoTo(uint cell, float lx, float ly, float z, double ns, double ew, out string how) + { + if ((cell & 0xFFFF) >= 0x0100) + { + if (!InDungeon(cell)) { how = "straight (in a building's rooms: no map plans from here)"; return null; } + return PlanGoToDungeon(cell, lx, ly, z, ns, ew, out how); + } + + var at = new OutdoorHunt.Vec(((cell >> 24) & 0xFF) * 192.0 + lx, ((cell >> 16) & 0xFF) * 192.0 + ly, z); + var goal = new OutdoorHunt.Vec(DungeonGeometry.NavToWorld(ew), DungeonGeometry.NavToWorld(ns), z); + var path = HuntPath(at, goal); + if ((path.Status != OutdoorHunt.PathStatus.Ok && path.Status != OutdoorHunt.PathStatus.Partial) || path.Corners.Count == 0) + { + how = path.Status switch + { + OutdoorHunt.PathStatus.NoMesh => "straight (no RynthNav map here)", + OutdoorHunt.PathStatus.Unavailable => "straight (RynthNav isn't loaded)", + _ => "straight (RynthNav found no way)", + }; + return null; + } + var route = HeadingRoute(path.Corners); + route.NavmeshCorners = true; // RynthNav's corners: turned early only where its mesh shows the next one (the corner gate) + // The walk ends on the point asked for, as the straight route did: the last corner is moved onto it (RynthNav + // put it on the mesh, its height kept), or, a way that ends short (partial, the point off the mesh), the + // point follows it. + var last = route.Points[^1]; + double shortYd = Math.Sqrt(Sq(DungeonGeometry.NavToWorld(last.EW) - goal.X) + Sq(DungeonGeometry.NavToWorld(last.NS) - goal.Y)); + if (shortYd <= GoToEndSnapYd) { last.NS = ns; last.EW = ew; } + else route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = last.Z != 0 ? last.Z : z / 240.0 }); + var inv = CultureInfo.InvariantCulture; + how = path.Status == OutdoorHunt.PathStatus.Ok + ? string.Create(inv, $"round obstacles on RynthNav's map, {route.Points.Count} point(s), {path.Length:0} yd") + : string.Create(inv, $"round obstacles on RynthNav's map as far as it goes ({shortYd:0} yd short), then straight, {route.Points.Count} point(s)"); + return route; + } + + // RynthNav's last corner this close to the point asked for is the point (it snapped it onto the mesh). + private const double GoToEndSnapYd = 1.0; + // A dungeon point this far from every room's centre isn't in this dungeon (NavRecovery's DungeonCellReachYd). + private const double GoToDungeonReachYd = 30.0; + + private static double Sq(double v) => v * v; + + /// A GoTo in a dungeon: the dungeon map's walk from the character's cell to the point's, as /ra dunnav-to. + private NavRouteParser? PlanGoToDungeon(uint cell, float lx, float ly, float z, double ns, double ew, out string how) + { + uint lb = cell >> 16; + var map = DungeonMapOverride?.Invoke(lb); + var cellDat = _raycast?.GeometryLoader.CellDat; + if (map == null && (cellDat == null || !cellDat.IsLoaded)) { how = "straight (the dungeon map isn't loaded yet)"; return null; } + var graph = map?.Graph ?? DungeonPathfinder.GetGraph(lb, cellDat!); + if (graph.Count == 0) { how = "straight (no dungeon map here)"; return null; } + var geo = map != null ? map.Value.Geo : DungeonPathfinder.GetGeometry(lb, cellDat!, _raycast?.GeometryLoader?.DungeonLOS); + double lbX = ((cell >> 24) & 0xFF) * 192.0, lbY = ((cell >> 16) & 0xFF) * 192.0; + double pNs = DungeonGeometry.WorldToNav(lbY + ly), pEw = DungeonGeometry.WorldToNav(lbX + lx); + uint start = graph.ContainsKey(cell) ? cell : DungeonPathfinder.NearestCell(graph, pNs, pEw, z); + // The point's room: the cell whose floor holds it at the character's height (a script gives no z), else the nearest. + uint goal = DungeonPathfinder.CellAt(graph, geo, new NavPoint { Type = NavPointType.Point, NS = ns, EW = ew, Z = z / 240.0 }); + if (start == 0 || goal == 0 || !graph.TryGetValue(goal, out var goalNode)) { how = "straight (not on the dungeon map)"; return null; } + if (Math.Sqrt(Sq(goalNode.NS - ns) + Sq(goalNode.EW - ew)) * 240.0 > GoToDungeonReachYd) + { + how = "straight (the point isn't near any room of this dungeon)"; + return null; + } + var hazards = _objectCache?.GetHazardCells(); + var path = DungeonPathfinder.FindPath(start, goal, graph, hazards); + if (path.Count == 0) { how = $"straight (no walk from {start:X8} to {goal:X8} on the dungeon map)"; return null; } + var route = DungeonPathfinder.BuildNavRoute(path, graph, ns, ew, geo, hazards, pNs, pEw, z, z); + how = $"by the dungeon map, {path.Count} cell(s), {route.Points.Count} point(s)"; + return route; + } + internal void ScriptStop() { - if (_dashboard?.Settings.IsMacroRunning == true) HandleMacroRunCommand("stop", Array.Empty()); + if (_dashboard?.Settings.IsMacroRunning == true) HandleMacroRunCommand("stop", Array.Empty(), "a Lua script (Stop)"); else _navigationEngine?.Stop(); } @@ -275,5 +371,8 @@ public sealed partial class RynthAiPlugin /// (quiet when it works, errors in chat; CommandReply.cs), and the Item Tool refuses it (a script's /// line is never the player at the keyboard). internal void ScriptSubmitCommand(string text) - => Reply.AsScript(() => { RunItemToolUntrusted(() => HandleRynthChatSubmit(text)); return true; }); + { + using (_dashboard?.Settings.MacroSource($"a Lua script's command '{text}'")) + Reply.AsScript(() => { RunItemToolUntrusted(() => HandleRynthChatSubmit(text)); return true; }); + } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/VTankYield.cs b/Plugins/RynthCore.Plugin.RynthAi/VTankYield.cs index 438e235..b85f205 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/VTankYield.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/VTankYield.cs @@ -65,7 +65,7 @@ internal sealed class VTankYield Verdict v = Tick(settings.IsMacroRunning, macroWasRunning, settings.YieldToVTank); if (v == Verdict.None) return v; - settings.IsMacroRunning = false; + settings.SetMacroRunning(false, "VTank yield (VTank's macro runs: one bot per client)"); onStop?.Invoke(); if (v == Verdict.StopForVTankStart) chat(StoppedForStartLine); else if (v == Verdict.StopWhileVTankRuns) chat(StoppedWhileRunningLine); diff --git a/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs b/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs index 4521a58..e51d808 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/ChatBuffer.cs @@ -13,6 +13,9 @@ namespace RynthCore.Plugin.RynthChat; /// a fixed 500 before. Changing it keeps the newest lines and never touches the /// numbering: the engine (and its Discord relay) tell new lines from old by seq. /// +/// Player chat (0.4.0) is kept longer, in a second ring (see DefaultPlayerCapacity): a read +/// that starts before the main ring's oldest line gets those player lines first, in seq order. +/// /// JSON per line: {"seq":N,"ts":"HH:mm:ss","chan":"Chat","type":3,"sender":"Bob"|null,"text":"..."}. /// "type" (AC's ChatMessageType) was added in 0.2.0; engines before it ignore it. /// Every non-ASCII character is written as a \uXXXX escape, so the export is @@ -26,15 +29,62 @@ internal sealed class ChatBuffer internal const int MinCapacity = 100; internal const int MaxCapacity = 10000; + // Player chat (0.4.0, ChatClassifier.IsPlayerChat) is also kept in a ring of its own, so it + // outlasts the main ring: the engine's "Player chat history" (RynthChatSetPlayerCapacity). A + // busy hunt fills the main ring with combat lines in minutes; after an engine reload, or with + // the chat window closed for a while, the engine reads the scrollback from here, and the tells + // and fellowship lines are still in it. 0 turns the second ring off. + internal const int DefaultPlayerCapacity = 5000; + internal const int MaxPlayerCapacity = 20000; + private ChatLine?[] _ring; private readonly object _lock = new(); private int _head; // next write index (mod _ring.Length) private int _count; // lines stored (<= _ring.Length) private ulong _nextSeq = 1; + private ChatLine?[] _players; + private int _pHead, _pCount; - internal ChatBuffer(int capacity = DefaultCapacity) + internal ChatBuffer(int capacity = DefaultCapacity, int playerCapacity = DefaultPlayerCapacity) { _ring = new ChatLine?[Math.Clamp(capacity, MinCapacity, MaxCapacity)]; + _players = new ChatLine?[Math.Clamp(playerCapacity, 0, MaxPlayerCapacity)]; + } + + internal int PlayerCapacity + { + get { lock (_lock) return _players.Length; } + } + + /// + /// Keeps up to player lines (0..MaxPlayerCapacity) in their own + /// ring from now on; when it shrinks, the oldest go. Returns the capacity applied, or -1 for 0 + /// (off), so the engine can tell "applied" from "not up yet". Any thread. + /// + internal int SetPlayerCapacity(int capacity) + { + capacity = Math.Clamp(capacity, 0, MaxPlayerCapacity); + lock (_lock) + { + if (capacity != _players.Length) + { + (_players, _pHead, _pCount) = Resize(_players, _pHead, _pCount, capacity); + } + return capacity == 0 ? -1 : capacity; + } + } + + private static (ChatLine?[] Ring, int Head, int Count) Resize(ChatLine?[] old, int head, int count, int capacity) + { + int keep = Math.Min(count, capacity); + var ring = new ChatLine?[capacity]; + int oldCap = old.Length; + if (oldCap > 0) + { + int start = (head - keep + oldCap) % oldCap; // the oldest line kept + for (int i = 0; i < keep; i++) ring[i] = old[(start + i) % oldCap]; + } + return (ring, capacity == 0 ? 0 : keep % capacity, keep); } internal int Capacity @@ -58,14 +108,7 @@ internal sealed class ChatBuffer lock (_lock) { if (capacity == _ring.Length) return capacity; - int keep = Math.Min(_count, capacity); - var ring = new ChatLine?[capacity]; - int oldCap = _ring.Length; - int start = (_head - keep + oldCap) % oldCap; // the oldest line kept - for (int i = 0; i < keep; i++) ring[i] = _ring[(start + i) % oldCap]; - _ring = ring; - _count = keep; - _head = keep % capacity; + (_ring, _head, _count) = Resize(_ring, _head, _count, capacity); return capacity; } } @@ -78,12 +121,13 @@ internal sealed class ChatBuffer : ChatClassifier.ChannelFor(text, chatType); string? sender = ChatClassifier.SenderFor(text, chatType); string ts = DateTime.Now.ToString("HH:mm:ss"); + bool player = ChatClassifier.IsPlayerChat(channel, chatType, text); lock (_lock) { // Numbered under the lock, so the ring is always in seq order (the // engine skips anything at or below the last seq it has seen). - _ring[_head] = new ChatLine + var line = new ChatLine { Seq = _nextSeq++, Timestamp = ts, @@ -92,8 +136,15 @@ internal sealed class ChatBuffer Sender = sender, Text = text, }; + _ring[_head] = line; _head = (_head + 1) % _ring.Length; if (_count < _ring.Length) _count++; + if (player && _players.Length > 0) + { + _players[_pHead] = line; // the same object: no extra copy of the text + _pHead = (_pHead + 1) % _players.Length; + if (_pCount < _players.Length) _pCount++; + } } } @@ -111,10 +162,31 @@ internal sealed class ChatBuffer ulong newest = _nextSeq - 1; int n = sinceSeq >= newest ? 0 : (int)Math.Min((ulong)_count, newest - sinceSeq); if (n == 0) return "[]"; - lines = new ChatLine?[n]; + // Player lines older than the main ring (0.4.0), first: only when the reader is behind + // the main ring's oldest line (its first read after a bind or reload, or a long gap). + // An ordinary poll (a few new lines) skips this, so it still copies only those. + ulong oldestMain = newest - (ulong)_count + 1; + int older = 0; + int pCap = _players.Length; + int pStart = pCap == 0 ? 0 : (_pHead - _pCount + pCap) % pCap; + if (_pCount > 0 && sinceSeq + 1 < oldestMain) + for (int i = 0; i < _pCount; i++) + { + ChatLine? p = _players[(pStart + i) % pCap]; + if (p == null || p.Seq >= oldestMain) break; + if (p.Seq > sinceSeq) older++; + } + lines = new ChatLine?[older + n]; + int w = 0; + if (older > 0) + for (int i = 0; i < _pCount && w < older; i++) + { + ChatLine? p = _players[(pStart + i) % pCap]; + if (p != null && p.Seq > sinceSeq && p.Seq < oldestMain) lines[w++] = p; + } int cap = _ring.Length; int start = (_head - n + cap) % cap; - for (int i = 0; i < n; i++) lines[i] = _ring[(start + i) % cap]; + for (int i = 0; i < n; i++) lines[w + i] = _ring[(start + i) % cap]; } var sb = new StringBuilder(64 + lines.Length * 192); diff --git a/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs b/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs index b150bfc..26df5fb 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/ChatClassifier.cs @@ -74,6 +74,47 @@ internal static class ChatClassifier || text.StartsWith("[Admin]", StringComparison.OrdinalIgnoreCase); } + // ── Player chat (0.4.0) ──────────────────────────────────────────────── + // The engine's ChatPlayerText (RynthCore, UI/Data/ChatPlayerText.cs) has the same rule; keep + // the two the same. ChatBuffer keeps these lines in a ring of their own, so a reload or a + // closed chat window doesn't lose tells and fellowship lines to combat spam. + + /// + /// True for a line a player typed: say, tells both ways, emotes, allegiance, fellowship, every + /// channel line, an admin's tell, and a room line of any other type ("[Room] Name says, \""). + /// Never plugin output, item info, combat or spell words. + /// + internal static bool IsPlayerChat(string channel, int chatType, string? text) + { + if (channel is Rynth or Items) return false; + if (channel is Chat or Channels) return true; + if (chatType == 0x1F) return true; // AdminTell + if (channel == Combat) return false; + return LooksLikeSpeech(text); + } + + /// "[Tag] Name says, \"" / "[Tag] Name tells you, \"" (AC's name links allowed), or "You say ..., \"". + internal static bool LooksLikeSpeech(string? text) + { + if (string.IsNullOrEmpty(text) || text.Length < 8) return false; + int start = 0; + bool tagged = false; + if (text[0] == '[') + { + int close = text.IndexOf(']', 1); + if (close < 2 || close > 41 || close + 1 >= text.Length || text[close + 1] != ' ') return false; + if (text.IndexOf('[', 1, close - 1) >= 0) return false; + start = close + 2; + tagged = true; + } + int quote = text.IndexOf(", \"", start, StringComparison.Ordinal); + if (quote < 0 || quote - start > 220) return false; + string who = text.Substring(start, quote - start); + if (who.IndexOf('"') >= 0) return false; + if (who.StartsWith("You say", StringComparison.Ordinal) || who.StartsWith("You tell ", StringComparison.Ordinal)) return true; + return tagged && (who.Contains(" says", StringComparison.Ordinal) || who.Contains(" tells you", StringComparison.Ordinal)); + } + internal static uint ColorFor(string channel) => channel switch { Chat => 0xFFE0E0E0, diff --git a/Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs b/Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs index 61e049a..3619e2d 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/PluginExports.cs @@ -88,6 +88,19 @@ public static unsafe class PluginExports catch { return 0; } } + /// + /// How many player lines (tells, say, fellowship, allegiance, channels) the scrollback keeps in + /// a ring of their own, past the main one (the engine's "Player chat history"; 0.4.0). Returns + /// the number applied (clamped to 0..20000; -1 for 0, off), or 0 before the plugin is up. + /// Engines before it never call this, and the plugin keeps ChatBuffer.DefaultPlayerCapacity. + /// + [UnmanagedCallersOnly(EntryPoint = "RynthChatSetPlayerCapacity", CallConvs = new[] { typeof(CallConvCdecl) })] + public static int SetPlayerCapacity(int lines) + { + try { return Runtime.Plugin?.SetPlayerScrollbackCapacity(lines) ?? 0; } + catch { return 0; } + } + [UnmanagedCallersOnly(EntryPoint = "RynthChatSendLine", CallConvs = new[] { typeof(CallConvCdecl) })] public static void SendLine(IntPtr ansiText) { diff --git a/Plugins/RynthCore.Plugin.RynthChat/RynthChatPlugin.cs b/Plugins/RynthCore.Plugin.RynthChat/RynthChatPlugin.cs index 78cccc3..99206a7 100644 --- a/Plugins/RynthCore.Plugin.RynthChat/RynthChatPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthChat/RynthChatPlugin.cs @@ -7,7 +7,7 @@ namespace RynthCore.Plugin.RynthChat; public sealed class RynthChatPlugin : RynthPluginBase { internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthChat"); - internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.3.0"); + internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.4.0"); private readonly ChatBuffer _buffer = new(); @@ -44,6 +44,8 @@ public sealed class RynthChatPlugin : RynthPluginBase internal int SetScrollbackCapacity(int lines) => _buffer.SetCapacity(lines); + internal int SetPlayerScrollbackCapacity(int lines) => _buffer.SetPlayerCapacity(lines); + // Called on the game thread from the engine's deferred chat dispatch // (Win32Backend posts WM_RYNTHCORE_CHAT so this runs on a fresh, non-reentrant // message dispatch rather than inline inside the Enter keystroke handler). diff --git a/Plugins/RynthCore.Plugin.RynthNav/AutoRunGate.cs b/Plugins/RynthCore.Plugin.RynthNav/AutoRunGate.cs index 2160244..6dcc23e 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/AutoRunGate.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/AutoRunGate.cs @@ -27,6 +27,9 @@ internal sealed class AutoRunGate private bool _halted; // a StopCompletely went through and nothing has started since private long _retryAtMs; // a call was refused: nothing but Stop() before this + /// Autorun is on, as far as what went through says (the trip clock's run speed samples). + public bool Running => _run == 1; + public AutoRunGate(Func setAutoRun, Func stopCompletely, Func now) { _setAutoRun = setAutoRun; diff --git a/Plugins/RynthCore.Plugin.RynthNav/Entrance.cs b/Plugins/RynthCore.Plugin.RynthNav/Entrance.cs index c2efe4e..d3c8882 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/Entrance.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/Entrance.cs @@ -72,13 +72,17 @@ internal static class Entrance public static List EndingInPortal(List? route, double ns, double ew, string label) { var steps = route == null ? new List() : new List(route); + double estAfter = 0; // the walk's cost, kept for the trip's time left (RouteStep.EstAfter) if (steps.Count > 0) { RouteStep last = steps[^1]; if (!last.UsePortal && !last.UseRecall && !last.IsHub && NavCoords.Distance(last.Ns, last.Ew, ns, ew) < 1.0) + { + estAfter = last.EstAfter; steps.RemoveAt(steps.Count - 1); + } } - steps.Add(new RouteStep(ns, ew, usePortal: true, useRecall: false, label)); + steps.Add(new RouteStep(ns, ew, usePortal: true, useRecall: false, label) { EstAfter = estAfter }); return steps; } diff --git a/Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs b/Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs index 1a55b9d..617b28a 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/NavCoarse.cs @@ -276,9 +276,11 @@ internal sealed class NavCoarse /// /// ; with a /// (not -1) it picks ground a walk from there can end on - /// (). + /// (). : the height isn't known, so the + /// ground nearest the tile's lowest point (the land, not a roof above it); unused. /// - public static Probe? ProbeFile(NavGraph g, string navDataDir, double ew, double up, double ns, float reach, int startRegion, out bool moved) + public static Probe? ProbeFile(NavGraph g, string navDataDir, double ew, double up, double ns, float reach, int startRegion, out bool moved, + bool fromBottom = false) { moved = false; int x = (int)Math.Floor(ew / 192.0), y = (int)Math.Floor(ns / 192.0); @@ -295,7 +297,7 @@ internal sealed class NavCoarse var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 2, maxPolys = 1 << 16 }; nav.Init(ref prm, 6); nav.AddTile(md, 0, 0, out _); - double u = float.IsFinite((float)up) ? up : 0; + double u = fromBottom ? md.header.bmin.Y : float.IsFinite((float)up) ? up : 0; return startRegion < 0 ? ProbeNear(g, nav, new DtNavMeshQuery(nav), ew, u, ns, reach, regions) : ProbeReachable(g, nav, new DtNavMeshQuery(nav), ew, u, ns, reach, regions, startRegion, out moved); diff --git a/Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs b/Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs index b9059c5..fe40b54 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs @@ -66,6 +66,31 @@ internal static class NavPathQuery private static int Lb(double world) => (int)Math.Clamp(Math.Floor(world / 192.0), 0, 255); + /// A portal's own floor: within 2.5 u across, and 3 u up or down, of where it stands. + public static readonly RcVec3f PortalFloorExtents = new(2.5f, 3f, 2.5f); + + /// + /// The polygon a portal stands on, at its own height (Detour: east, height, north), 0 when the navmesh + /// has none there. A portal in a cellar or a tunnel under a town (11-18: Zaikhal's Olthoi Tunnel, 7.7 u + /// under the street) is found by its height, not by the walker's: looked for from the street, the + /// nearest polygon is the street right above it. + /// + public static long PortalFloor(DtNavMeshQuery q, IDtQueryFilter filter, double east, double height, double north, out RcVec3f pt) + { + q.FindNearestPoly(new RcVec3f((float)east, (float)height, (float)north), PortalFloorExtents, filter, out long r, out pt, out _); + return r; + } + + /// Whether a walk from reaches : a whole corridor that ends on it. + public static bool Reaches(DtNavMeshQuery q, long sRef, RcVec3f sPt, long gRef, RcVec3f gPt, IDtQueryFilter filter) + { + if (sRef == 0 || gRef == 0) return false; + if (sRef == gRef) return true; + Span polys = new long[MaxPolys]; + DtStatus st = q.FindPath(sRef, gRef, sPt, gPt, filter, polys, out int pc, polys.Length); + return !st.Failed() && pc > 0 && polys[pc - 1] == gRef; + } + /// The polygon under (Detour axes): close up first, then the wide search. public static long SnapStart(DtNavMeshQuery q, RcVec3f p, IDtQueryFilter filter, out RcVec3f pt) { @@ -74,27 +99,85 @@ internal static class NavPathQuery return r; } + /// + /// How far past a circle's edge the plain corridor's straight path must stay, everywhere, for it to be + /// taken over the corridor round the circles (): the corners pushed off the walls + /// afterwards move up to the wall clearance (1 m by default). + /// + public const double PlainClearMargin = 2.0; + /// /// The polygon corridor from sRef to gRef through ; when that doesn't reach /// the goal and is set (the first filter keeps out of portals), planned /// again through (). is - /// the last FindPath's (its partial flag included). + /// the last FindPath's (its partial flag included). When the way round the circles does reach the goal, + /// the plain corridor is taken instead if its straight path is shorter and keeps clear of every circle + /// (). /// public static int Corridor(DtNavMeshQuery q, long sRef, long gRef, RcVec3f sPt, RcVec3f gPt, IDtQueryFilter first, IDtQueryFilter plain, bool fallback, Span polys, - out bool fellBack, out DtStatus status) + out bool fellBack, out DtStatus status, out bool plainTaken) { - fellBack = false; + fellBack = false; plainTaken = false; status = q.FindPath(sRef, gRef, sPt, gPt, first, polys, out int pc, polys.Length); if ((pc == 0 || polys[pc - 1] != gRef) && fallback) { // No way round the portals to there: plan as before (the caller's steering keeps out of them). status = q.FindPath(sRef, gRef, sPt, gPt, plain, polys, out pc, polys.Length); fellBack = true; + return pc; + } + // The way round the circles can go far round for nothing: every polygon a circle touches is left out, + // and on open ground one polygon can be a whole town square. 2026-11-18, a DreamWeave Thread in Yaraq: + // the Thread Exit's 4 m circle touched the edge of the 73 x 161 m polygon that is the town's middle + // (7D64), so every hunt walk west went round the north edge of town, 262-380 m for 72-119 m, the hunt + // called them all "too far round" and stood waiting. The plain corridor goes 40-97 m clear of the Exit. + if (fallback && pc > 0 && first is AvoidFilter round && round.Portals.Count > 0) + { + Span alt = new long[polys.Length]; + DtStatus st = q.FindPath(sRef, gRef, sPt, gPt, plain, alt, out int apc, alt.Length); + if (!st.Failed() && apc > 0 && alt[apc - 1] == gRef + && StraightLength(q, sPt, gPt, alt[..apc], round.Portals, out double plainLen, out bool clear) && clear + && StraightLength(q, sPt, gPt, polys[..pc], null, out double roundLen, out _) && plainLen < roundLen - 0.5) + { + alt[..apc].CopyTo(polys); + pc = apc; status = st; plainTaken = true; + } } return pc; } + /// + /// The flat length of the straight path along ; with , + /// whether every leg keeps past every circle's edge (never, then, when a + /// circle holds the start or the end). False when Detour gives no straight path (or more corners than it holds). + /// + internal static bool StraightLength(DtNavMeshQuery q, RcVec3f sPt, RcVec3f gPt, Span corridor, + PortalAvoid? circles, out double length, out bool clear) + { + length = 0; clear = false; + Span sp = new DtStraightPath[MaxStraightCorners]; + DtStatus st = q.FindStraightPath(sPt, gPt, corridor, corridor.Length, sp, out int n, MaxStraightCorners, 0); + if (st.Failed() || n < 1 || st.Has(DtStatus.DT_BUFFER_TOO_SMALL)) return false; + for (int i = 1; i < n; i++) + { + double dx = sp[i].pos.X - sp[i - 1].pos.X, dy = sp[i].pos.Z - sp[i - 1].pos.Z; + length += Math.Sqrt(dx * dx + dy * dy); + } + if (circles == null) return true; + clear = true; + foreach (PortalAvoid.Spot s in circles.Spots) + { + double need = s.R + PlainClearMargin; + double a0x = sp[0].pos.X, a0y = sp[0].pos.Z; + if (n == 1 && PortalAvoid.SegmentDistance(s.X, s.Y, a0x, a0y, a0x, a0y) < need) { clear = false; break; } + for (int i = 1; i < n; i++) + if (PortalAvoid.SegmentDistance(s.X, s.Y, sp[i - 1].pos.X, sp[i - 1].pos.Z, sp[i].pos.X, sp[i].pos.Z) < need) { clear = false; break; } + if (!clear) break; + } + return true; + } + /// On the mesh = inside a polygon (the nearest point on the mesh is the point itself), not merely near one. public static bool OnMesh(DtNavMeshQuery q, IDtQueryFilter filter, double x, double y, float z) { @@ -172,8 +255,8 @@ internal static class NavPathQuery Span polys = new long[MaxPolys]; IDtQueryFilter first = avoid ? portals! : plain; - int pc = Corridor(q, sRef, gRef, sPt, gPt, first, plain, avoid, polys, out bool fellBack, out DtStatus st); - r.Polys = pc; r.FellBack = fellBack; + int pc = Corridor(q, sRef, gRef, sPt, gPt, first, plain, avoid, polys, out bool fellBack, out DtStatus st, out bool plainTaken); + r.Polys = pc; r.FellBack = fellBack; r.PlainClear = plainTaken; if (st.Failed() || pc == 0) return r.Fail(RynthNavPathApiV1.ResultNoPath, "no way on the navmesh"); // Detour's partial result: the corridor ends at the polygon nearest the goal it could reach. bool partial = st.IsPartial() || polys[pc - 1] != gRef; @@ -287,6 +370,8 @@ internal sealed class PathExResult /// From the last corner to the requested goal (3D), world units. public double EndDistance; public bool Partial, Truncated, FellBack; + /// The plain corridor was taken: shorter than the way round the circles, and clear of them all (NavPathQuery.Corridor). + public bool PlainClear; public int Polys, Portals, Bent, Pushed; public string Note = ""; @@ -295,7 +380,7 @@ internal sealed class PathExResult Code = RynthNavPathApiV1.ResultNoPath; Corners.Clear(); Length = EndDistance = 0; - Partial = Truncated = FellBack = false; + Partial = Truncated = FellBack = PlainClear = false; Polys = Portals = Bent = Pushed = 0; Note = ""; } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RealWalk.cs b/Plugins/RynthCore.Plugin.RynthNav/RealWalk.cs new file mode 100644 index 0000000..f90e273 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RealWalk.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using RynthCore.Plugin.RynthNav; + +namespace RynthNav.Routing; + +/// +/// Walking distances for the trip planner (PortalRoute's walkCost, 11-19): between two map points, +/// along the route graph (NavGraph.FindRoute), the way the walker will go round a ridge or a bay. +/// Each point's ground and region come from its tile file (NavCoarse.ProbeFile), cached for the plan; +/// the start's at the player's height, the rest the land under the point. NaN (the planner keeps the +/// straight line) when a point has no tile or ground, both ends are in one region (straight is near +/// enough there), the graph finds no route, or the plan has spent its time on it: the best way's walks +/// may take , the other ways' (after ) a further +/// . 11-20 live, one 60 ms budget for the lot: the first walk after a load (cold +/// tile files) or the 39,000 u walk-all-the-way spent it, and the best way kept its straight lines. +/// One per plan, on the thread that plans (the tick). Host-free: the probes use it too. +/// +internal sealed class RealWalk +{ + /// Time one plan may spend costing the best way's walks; after it, the rest keep the straight line. + public const double BestBudgetMs = 150; + /// Time on top for the other ways' walks (PlanOptions, after the best way). + public const double OthersBudgetMs = 60; + /// A route graph search gives up after this many expansions (the walker's own allows 2,000,000). + public const int MaxExpand = 400_000; + /// How far from a point its ground may be (a portal on a ledge, a place in a building). + public const float GroundReach = 24f; + + private readonly NavGraph _g; + private readonly string _dir; + private readonly double _startNs, _startEw, _startUp, _othersMs; + private double _limitMs; + private bool _bestDone; + private readonly Dictionary<(int X, int Y, int From), NavCoarse.Probe?> _probes = new(); + private readonly Stopwatch _clock = new(); + + /// Walks asked about, and how many of those the route graph costed. + public int Asked, Costed; + public double Ms => _clock.Elapsed.TotalMilliseconds; + /// Time spent on the best way's walks (all of it until ). + public double BestMs { get; private set; } = double.NaN; + + /// The player's height at the start (NaN: the land there, like any other point). + /// Time for the best way's walks (tools: +infinity). + /// Time on top for the other ways' walks. + public RealWalk(NavGraph g, string navDataDir, double startNs, double startEw, double startUp, + double budgetMs = BestBudgetMs, double othersMs = OthersBudgetMs) + { + _g = g; _dir = navDataDir; _startNs = startNs; _startEw = startEw; _startUp = startUp; _limitMs = budgetMs; _othersMs = othersMs; + } + + /// The best way is planned: the other ways' walks get more (PortalRoute's bestPlanned). + public void BestPlanned() + { + if (_bestDone) return; + _bestDone = true; + BestMs = Ms; + if (!double.IsPositiveInfinity(_limitMs)) _limitMs = BestMs + _othersMs; + } + + public double Cost(double fromNs, double fromEw, double toNs, double toEw) + { + Asked++; + if (_clock.Elapsed.TotalMilliseconds > _limitMs) return double.NaN; + _clock.Start(); + try + { + NavCoarse.Probe? a = Ground(fromNs, fromEw, -1); + if (a == null) return double.NaN; + NavCoarse.Probe? b = Ground(toNs, toEw, a.Region); + if (b == null || b.Region == a.Region) return double.NaN; + List? route = _g.FindRoute(a.Region, a.Pt.X, a.Pt.Z, b.Region, b.Pt.X, b.Pt.Z, out float cost, out _, MaxExpand); + if (route == null || !float.IsFinite(cost)) return double.NaN; + Costed++; + return cost; + } + catch (Exception) { return double.NaN; } // a tile that won't read: the straight line + finally { _clock.Stop(); } + } + + /// The ground at a map point (a walk from 's region can end on, when given). + private NavCoarse.Probe? Ground(double ns, double ew, int from) + { + double x = NavCoords.WorldX(ew), y = NavCoords.WorldY(ns); + var key = ((int)Math.Round(x), (int)Math.Round(y), from); + if (_probes.TryGetValue(key, out NavCoarse.Probe? p)) return p; + bool isStart = Math.Abs(ns - _startNs) < 0.005 && Math.Abs(ew - _startEw) < 0.005; // within about a unit + p = isStart && double.IsFinite(_startUp) + ? NavCoarse.ProbeFile(_g, _dir, x, _startUp, y, GroundReach, from, out _) + : NavCoarse.ProbeFile(_g, _dir, x, 0, y, GroundReach, from, out _, fromBottom: true); + _probes[key] = p; + return p; + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs b/Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs index 66fdd97..61e4d6b 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RecallPlanner.cs @@ -17,7 +17,9 @@ internal sealed class RecallOption /// Learned in game (RecallMemory), not fixed by the world data. public bool Learned; - public RecallLink ToLink() => new(Ns, Ew, Name, PortalRoute.RecallCostUnits(CastSeconds)); + /// The planner's recall: its cost the flat way, or (TripTimes) the cast and portal space it takes. + public RecallLink ToLink(TripTimes? times = null) + => new(Ns, Ew, Name, times == null ? PortalRoute.RecallCostUnits(CastSeconds) : times.RecallUnits(SpellId != 0)); } /// @@ -232,10 +234,10 @@ internal static class RecallPlanner _ => "Allegiance hometown recall", }; - public static List Links(List options) + public static List Links(List options, TripTimes? times = null) { var links = new List(options.Count); - foreach (var o in options) links.Add(o.ToLink()); + foreach (var o in options) links.Add(o.ToLink(times)); return links; } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs index a202367..4b17c33 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Avoid.cs @@ -24,6 +24,7 @@ public sealed partial class RynthNavPlugin private AvoidFilter? _avoidFilter; private long _nextAvoidMs; private bool _avoidFallbackSaid; + private bool _avoidPlainSaid; // once: the plain corridor taken over a far way round (NavPathQuery.Corridor) private Atlas? _avoidAtlas; private List _atlasPortals = new(); private int _avoidLogged = -1; @@ -134,7 +135,8 @@ public sealed partial class RynthNavPlugin } if (parts.Count == 0) parts.Add($"walk {NavCoords.Distance(startNs, startEw, goalNs, goalEw):F0} yd"); double straight = NavCoords.Distance(startNs, startEw, goalNs, goalEw); - return string.Join(" → ", parts) + $"; cost ~{(double.IsInfinity(est) ? "none" : est.ToString("F0"))}u; walking straight {straight:F0} yd" + string eta = AboutTime(_planTimes, est); + return string.Join(" → ", parts) + $"; cost ~{(double.IsInfinity(est) ? "none" : est.ToString("F0"))}u{(eta.Length > 0 ? ", " + eta : "")}; walking straight {straight:F0} yd" + (land == false ? " (not possible: another landmass)" : ""); } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs index 42668f6..a226d76 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Blocked.cs @@ -38,11 +38,12 @@ public sealed partial class RynthNavPlugin private readonly List _blockedSpots = new(); /// DriveTo for the walk's own steering: remembers that it ran and which way. - private void WalkDrive(double deg) + private void WalkDrive(double deg, bool tight = false) { - DriveTo(deg, _steerOpen); + WalkSteer servo = tight ? _steerTight : _steerOpen; + DriveTo(deg, servo); _lastDriveDeg = deg; - _ranLastTick = !_steerOpen.TurnInPlace; + _ranLastTick = !servo.TurnInPlace; } /// diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs index 817792f..10b5e0b 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Panel.cs @@ -26,6 +26,7 @@ public sealed partial class RynthNavPlugin // Read under _gate. private string _goLine = "", _goPhase = ""; private double _goLeft = -1; + private double _goEta = -1; // the trip's time left, seconds (RynthNavPlugin.TripTime.cs) // Rebuild only when these change (tick thread). private string _glPhase = "", _glNote = ""; private int _glIdx = -2; @@ -68,14 +69,20 @@ public sealed partial class RynthNavPlugin } } } + RefreshClockLine(); + double eta = TripSecondsLeft(phase, left); + lock (_gate) _goEta = eta < 0 ? -1 : Math.Round(eta); // Whole yards under 1000, tens of yards above (FmtDistance shows 0.1k there). long leftKey = left < 0 ? -1 : left < 1000 ? (long)left : 100000 + (long)(left / 100); int sub = phase == "town" ? (_hubLanded ? 1 : 0) + (HubIsWaiting ? 2 : 0) : 0; // the hub step's line changes with these + bool paused = active && _paused; // RynthNavPlugin.Pause.cs + if (paused) sub |= 4; if (active == _glActive && phase == _glPhase && idx == _glIdx && leftKey == _glLeftKey && sub == _glSub && ReferenceEquals(_goNote, _glNote)) return; _glActive = active; _glPhase = phase; _glIdx = idx; _glLeftKey = leftKey; _glSub = sub; _glNote = _goNote; string line = active ? GoLine(phase, left) : _goNote; + if (paused) { line = "paused: " + line + " (Resume carries on)"; phase = "paused"; } lock (_gate) { _goLine = line; _goPhase = phase; _goLeft = left; } } @@ -142,17 +149,19 @@ public sealed partial class RynthNavPlugin { Interlocked.Exchange(ref _lastStatusPollMs, NowMs); var ci = CultureInfo.InvariantCulture; - string line, phase; double left; - lock (_gate) { line = _goLine; phase = _goPhase; left = _goLeft; } + string line, phase; double left, eta; + lock (_gate) { line = _goLine; phase = _goPhase; left = _goLeft; eta = _goEta; } sb.Append(",\"v\":\"").Append(PluginVersion).Append('"'); sb.Append(",\"go\":{\"line\":\"").Append(Esc(line)).Append("\",\"phase\":\"").Append(phase) - .Append("\",\"left\":").Append(left < 0 ? "-1" : left.ToString("F0", ci)).Append('}'); + .Append("\",\"left\":").Append(left < 0 ? "-1" : left.ToString("F0", ci)) + .Append(",\"eta\":").Append(eta < 0 ? "-1" : eta.ToString("F0", ci)).Append('}'); uint cell = _cellId; sb.Append(",\"info\":{\"dir\":\"").Append(Esc(NavDataDir)).Append("\",\"source\":\"").Append(Esc(NavConfig.Source)) .Append("\",\"graph\":").Append(_graph != null ? 1 : 0).Append(",\"graphStatus\":\"").Append(Esc(_graphStatus)) .Append("\",\"tileHere\":").Append(_tileHere).Append(",\"indoors\":").Append(_hasPose && (cell & 0xFFFF) >= 0x100 ? 1 : 0) .Append(",\"onDisk\":").Append(_tilesOnDisk) - .Append(",\"townNet\":").Append(_townNet != null ? 1 : 0).Append(",\"townNetStatus\":\"").Append(Esc(_townNetStatus)).Append("\"}"); + .Append(",\"townNet\":").Append(_townNet != null ? 1 : 0).Append(",\"townNetStatus\":\"").Append(Esc(_townNetStatus)) + .Append("\",\"times\":\"").Append(Esc(_clockLine)).Append("\"}"); // how long trips take (RynthNavPlugin.TripTime.cs) // Path markers (RynthNavPlugin.Markers.cs) and "save as nav route" (RynthNavPlugin.SaveRoute.cs), 0.6.6+. The mesh view (RynthNavPlugin.MeshView.cs), 0.6.7+. sb.Append(",\"mesh\":{\"on\":").Append(_meshOn ? 1 : 0).Append(",\"floor\":").Append(_meshFloor ? 1 : 0) .Append(",\"walls\":").Append(_meshWalls ? 1 : 0).Append(",\"radius\":").Append(_meshRadius.ToString("F0", ci)) diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs index d9d0a15..181379e 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs @@ -118,7 +118,7 @@ public sealed partial class RynthNavPlugin _ => $"no path: {r.Note}", }; string extras = ""; - if (r.Portals > 0) extras += $"; {r.Portals} portal(s) avoided{(r.FellBack ? " (no way round them: plain path)" : "")}{(r.Bent > 0 ? $", bent round {r.Bent}" : "")}"; + if (r.Portals > 0) extras += $"; {r.Portals} portal(s) avoided{(r.FellBack ? " (no way round them: plain path)" : r.PlainClear ? " (the plain path, shorter and clear of them)" : "")}{(r.Bent > 0 ? $", bent round {r.Bent}" : "")}"; if (r.Pushed > 0) extras += $"; {r.Pushed} corner(s) {_wallClearance:0.#} m off the walls"; Host.Log($"[RynthNav] path request ex (flags 0x{flags:X}): {what}{extras}; ({sx:F0},{sy:F0}) -> ({gx:F0},{gy:F0}), {_tileCount} tiles, {ms:F1} ms"); } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Pause.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Pause.cs new file mode 100644 index 0000000..faad3bc --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Pause.cs @@ -0,0 +1,79 @@ +using System; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +// Pause and Resume (11-19, a player: "Can auto nav have a pause button? So that if it messes up I can +// still see the current planned route"). Stop ends the trip and the route goes from the World Map; +// Pause stops walking and keeps all of it: the route, the leg, the path, the markers and the arrow. +// While paused you drive (the keys, or the panel's d-pad, which no longer ends the trip), and Resume +// carries on: the same leg from where you stand, or, when you've gone elsewhere meanwhile (through a +// portal by hand, a recall) or it was paused in the middle of a teleport, the trip planned again +// from here, keeping the way chosen (route next) and not counted as one of the trip's replans. +// +// Tick thread: the commands run there (RunCommand), as StepGoto does. +public sealed partial class RynthNavPlugin +{ + /// Resume farther than this from where Pause was pressed: plan the trip again from here. + private const double ResumeReplanUnits = 60.0; + + private volatile bool _paused; + private double _pauseWx, _pauseWy; + private uint _pauseCell; + private bool _pausedMidTeleport; + + private void CmdPause() + { + if (!_gotoActive) { Say("pause: not walking anywhere (/rnav go starts a trip)"); return; } + if (_paused) { Say("pause: already paused. /rnav resume carries on, /rnav stop ends the trip"); return; } + _paused = true; + _pauseWx = _wx; _pauseWy = _wy; _pauseCell = _cellId; + _pausedMidTeleport = _portalWait || _recallWait || _settling || CurrentStepIsHub; + AutoRun.Stop(); // ApplyMovement stops the rest (its "goto ended" branch) on the next tick + string line; lock (_gate) line = _goLine; + lock (_gate) _status = "paused"; + Host.Log($"[RynthNav] paused ({(line.Length > 0 ? line : "walking")}) at {NavCoords.Fmt(NavCoords.NsFromWorld(_wy), NavCoords.EwFromWorld(_wx))}"); + Note("paused: the route stays on the map. /rnav resume carries on, /rnav stop ends the trip"); + } + + private void CmdResume() + { + if (!_paused || !_gotoActive) + { + _paused = false; + Say(_gotoActive ? "resume: not paused, still walking" : "resume: no trip to carry on (/rnav go )"); + return; + } + _paused = false; + // Whatever the d-pad was doing while paused stops: the walk drives again. + lock (_moveGate) { _desiredRun = 0; _turnState = 0; } + if (_appliedTurn == -1) Host.SetMotion(MotionTurnLeft, false); + else if (_appliedTurn == 1) Host.SetMotion(MotionTurnRight, false); + if (_appliedRun == 2) Host.StopMovement(MotionWalkBackward, HoldKeyRun); + else if (_appliedRun == 1) Host.SetAutoRun(false); + _appliedRun = 0; _appliedTurn = 0; + AutoRun.Forget(); + + double moved = Math.Sqrt((_wx - _pauseWx) * (_wx - _pauseWx) + (_wy - _pauseWy) * (_wy - _pauseWy)); + bool elsewhere = moved > ResumeReplanUnits || InDungeon(_cellId) != InDungeon(_pauseCell); + if (_pausedMidTeleport || elsewhere) + { + string why = _pausedMidTeleport ? "paused mid-teleport" : $"{NavCoords.FmtDistance(moved)} from where it paused"; + Host.Log($"[RynthNav] resume: {why}: the trip planned again from here"); + Say($"resumed: {why}, so planning the rest of the trip from here"); + string goal = _gotoName, type = _gotoType, enter = _enterName, enterType = _enterType; + double gns = NavCoords.NsFromWorld(_finalTns), gew = NavCoords.EwFromWorld(_finalTew); + if (_recallWait) EndRecall(); + // landReplan: keeps this trip's replan count and refusals; the way chosen sticks (PlanRoute). + StartWalk(goal.Length > 0 ? goal : NavCoords.Fmt(gns, gew), type, gns, gew, enter, enterType, landReplan: true); + return; + } + // The same leg from here: a fresh path and a fresh progress watchdog. + SetSubGoalToCurrentLeg(); + lock (_gotoGate) { _gotoPath = null; _gotoIdx = 0; } + _replanTick = 0; + lock (_gate) _status = "walking"; + Host.Log($"[RynthNav] resumed (leg {_routeIdx + 1} of {_route?.Count ?? 1})"); + Note("resumed: walking on"); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs index adc9e70..06ab56c 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PortalAim.cs @@ -25,6 +25,7 @@ public sealed partial class RynthNavPlugin { _portalTryStartMs = NowMs; _portalBackoffUntilMs = 0; _nextPortalSnapMs = 0; _portalTries = 1; _portalSnapped = false; _portalLiveId = 0; _portalLastUseMs = 0; + _portalWaitBeganMs = NowMs; _portalLiveZ = double.NaN; } /// The name the step's portal goes by (route step label, or the dungeon's entrance). @@ -42,11 +43,11 @@ public sealed partial class RynthNavPlugin _nextPortalSnapMs = now + 500; string want = PortalStepName(); double bestNamed = double.MaxValue, bestAny = double.MaxValue; - double nx = 0, ny = 0, ax = 0, ay = 0; string nName = "", aName = ""; uint nId = 0, aId = 0; + double nx = 0, ny = 0, ax = 0, ay = 0, nz = double.NaN, az = double.NaN; string nName = "", aName = ""; uint nId = 0, aId = 0; foreach (uint id in Host.GetLiveObjectIds()) { if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue; - if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out _) || cell == 0) continue; + if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out float z) || cell == 0) continue; double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y; double d = Math.Sqrt((wx - _gotoTew) * (wx - _gotoTew) + (wy - _gotoTns) * (wy - _gotoTns)); if (d > PortalSnapUnits) continue; @@ -54,8 +55,8 @@ public sealed partial class RynthNavPlugin name ??= ""; bool named = want.Length > 0 && name.Length > 0 && (name.IndexOf(want, StringComparison.OrdinalIgnoreCase) >= 0 || want.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0); - if (named && d < bestNamed) { bestNamed = d; nx = wx; ny = wy; nName = name; nId = id; } - if (d < bestAny) { bestAny = d; ax = wx; ay = wy; aName = name; aId = id; } + if (named && d < bestNamed) { bestNamed = d; nx = wx; ny = wy; nz = z; nName = name; nId = id; } + if (d < bestAny) { bestAny = d; ax = wx; ay = wy; az = z; aName = name; aId = id; } } bool haveNamed = bestNamed < double.MaxValue; if (!haveNamed && !(bestAny < 12.0)) return; // an unnamed match only when it's clearly the one @@ -63,6 +64,7 @@ public sealed partial class RynthNavPlugin double shift = Math.Sqrt((tx - _gotoTew) * (tx - _gotoTew) + (ty - _gotoTns) * (ty - _gotoTns)); _gotoTew = tx; _gotoTns = ty; _portalLiveId = haveNamed ? nId : aId; + _portalLiveZ = haveNamed ? nz : az; // its height: on another level, StepPortalWait doesn't circle it for ever if (!_portalSnapped) { _portalSnapped = true; @@ -90,8 +92,17 @@ public sealed partial class RynthNavPlugin { if (_portalTries >= PortalMaxTries) { - Host.Log($"[RynthNav] portal did not fire after {_portalTries} tries — stopping"); bool entrance = _enterName.Length > 0 && _route != null && _routeIdx >= _route.Count - 1; + string? via = _route != null && _routeIdx < _route.Count ? _route[_routeIdx].Via : null; + if (!entrance && via != null) + { + // A portal on the way that won't take you: another way there (RynthNavPlugin.Ways.cs). + Host.Log($"[RynthNav] portal did not fire after {_portalTries} tries — leaving it out and planning again"); + _refused[via] = (PortalStepName(), $"didn't take you after {_portalTries} tries", NowMs); + ReplanTrip($"the portal '{PortalStepName()}' didn't take you after {_portalTries} tries"); + return true; + } + Host.Log($"[RynthNav] portal did not fire after {_portalTries} tries — stopping"); FinishGoto(entrance ? Entrance.NoTeleportText(_enterName) : $"stopped: the portal '{PortalStepName()}' didn't take you after {_portalTries} tries"); return true; } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs index 6d41b49..04beeca 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Settle.cs @@ -43,9 +43,18 @@ public sealed partial class RynthNavPlugin if (!_settleSawPortal && now - _settleJumpMs < SettleNoPortalMs) return; _settling = false; + if (_settleSawPortal) ClockSpace(_settleJumpMs); // portal space, for the trip clock (RynthNavPlugin.TripTime.cs) _lastLandMs = now; // the portal cooldown counts from the real landing RefreshTiles(CurrentLandblock); Host.Log($"[RynthNav] arrived after the teleport ({(now - _settleJumpMs) / 1000.0:F1} s{(_settleSawPortal ? ", portal space over" : "")}) — next step"); + // Landed somewhere else (another portal's destination, a recall tied elsewhere, a dungeon): the + // next legs start from the wrong place, so plan the rest from here (RynthNavPlugin.Ways.cs). + if (!LandedWherePlanned(out string where)) + { + string what = _route != null && _routeIdx < _route.Count && _route[_routeIdx].UseRecall ? "recall" : "portal"; + ReplanTrip($"the {what} '{(_route != null && _routeIdx < _route.Count ? Trunc(_route[_routeIdx].Label) : "")}' took you to {where}"); + return; + } AdvanceRoute(); } } diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs index 3d7d5f3..5987586 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TownNet.cs @@ -25,7 +25,7 @@ public sealed partial class RynthNavPlugin private volatile TownNet? _townNet; private volatile string _townNetStatus = "loading…"; private HubLinks? _hubLinks; - private (TownNet? Net, int Level, bool Olthoi) _hubLinksKey; + private (TownNet? Net, int Level, bool Olthoi, uint Pk, bool? Vitae) _hubLinksKey; // The hub step being walked (tick thread). private bool _hubActive, _hubLanded, _hubWaitSaid; @@ -72,16 +72,19 @@ public sealed partial class RynthNavPlugin } /// The Town Network as this character's route planner sees it; null without townnet.json. - private HubLinks? CurrentHubLinks(List? notes) + private HubLinks? CurrentHubLinks(List? notes) => CurrentHubLinks(notes, ReadTraveller()); + + private HubLinks? CurrentHubLinks(List? notes, in Traveller who) { TownNet? t = _townNet; if (t == null) return null; - ReadCharacterRules(out int level, out bool olthoi); - if (notes == null && _hubLinks != null && ReferenceEquals(_hubLinksKey.Net, t) && _hubLinksKey.Level == level && _hubLinksKey.Olthoi == olthoi) + var key = (t, who.Level, who.Olthoi, who.PkStatus, who.Vitae); + if (notes == null && _hubLinks != null && ReferenceEquals(_hubLinksKey.Net, t) && _hubLinksKey.Level == key.Level + && _hubLinksKey.Olthoi == key.Olthoi && _hubLinksKey.Pk == key.PkStatus && _hubLinksKey.Vitae == key.Vitae) return _hubLinks; - HubLinks links = t.Links(level, olthoi, notes); + HubLinks links = t.Links(who, notes); _hubLinks = links; - _hubLinksKey = (t, level, olthoi); + _hubLinksKey = key; return links; } @@ -255,24 +258,29 @@ public sealed partial class RynthNavPlugin private List? PlanFromInsideHub(double goalNs, double goalEw, out double est, out int teleports) { est = 0; teleports = 0; + TripTimes times = PlanTimes(); // a portal costs its time (RynthNavPlugin.TripTime.cs) TownNet? t = _townNet; - HubLinks? links = CurrentHubLinks(null); + Traveller who = ReadTraveller(); + HubLinks? links = CurrentHubLinks(null, who); if (t == null || links == null) return null; double px = LocalX, py = LocalY; List? best = null; double bestCost = double.MaxValue; int bestUsed = 0; if (_portalsEnabled) EnsurePortalsLoaded(); + // Portals and exits that would refuse you, or did (RynthNavPlugin.Ways.cs). + HashSet bans = PlanBans(who, null); foreach (HubExit hx in links.Exits) { + if (bans.Contains(PortalRoute.HubExitKey(hx.Id))) continue; List? way = t.WayTo(hx.Id, px, py, HubOffRouteUnits, out _); if (way == null) continue; - double inside = TownNet.PathLength(way, 0) + PortalRoute.PortalPenaltyUnits; + double inside = TownNet.PathLength(way, 0) + times.PortalUnits; List rest; double restCost; int used = 0; if (_portalsEnabled && _portals is { Count: > 0 }) - rest = PortalRoute.Plan(_portals, null, hx.DstNs, hx.DstEw, goalNs, goalEw, out restCost, out used); + rest = PortalRoute.Plan(_portals, null, null, hx.DstNs, hx.DstEw, goalNs, goalEw, out restCost, out used, null, true, bans, null, times); else { restCost = NavCoords.Distance(hx.DstNs, hx.DstEw, goalNs, goalEw); @@ -280,8 +288,8 @@ public sealed partial class RynthNavPlugin } if (inside + restCost >= bestCost) continue; bestCost = inside + restCost; - best = new List { RouteStep.Hub(hx.DstNs, hx.DstEw, hx.Name, hx.Id) }; - best.AddRange(rest); + best = new List { RouteStep.Hub(hx.DstNs, hx.DstEw, hx.Name, hx.Id) with { Via = PortalRoute.HubExitKey(hx.Id), EstAfter = inside } }; + foreach (RouteStep r in rest) best.Add(r with { EstAfter = r.EstAfter > 0 ? r.EstAfter + inside : inside + restCost }); bestUsed = used + 1; } est = bestCost; diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs index 80663a4..8f4004a 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Travel.cs @@ -164,6 +164,7 @@ public sealed partial class RynthNavPlugin private void OnLogoutTravel() { _recallWait = false; + _refused.Clear(); // another character may be let through _trkHaveLast = false; _trkPortaling = false; _known = null; _charKey = ""; SaveStores(force: true); @@ -461,6 +462,7 @@ public sealed partial class RynthNavPlugin if (!Host.HasGetLastWeenieError || !Host.TryGetLastWeenieError(out int seq, out uint error, out _, out _)) return; if (_weenieSeq < 0 || seq == _weenieSeq) { _weenieSeq = seq; return; } // the first look only notes where the count stands _weenieSeq = seq; + if (OnPortalRefused(error)) return; // a portal on the route won't take you (RynthNavPlugin.Ways.cs) int cast = _castRecallSpell != 0 && NowMs - _castRecallMs < RecallCastWindowMs ? _castRecallSpell : 0; if (RecallPlanner.SlotUnlinked(error, cast) is not RecallSlot slot || _charKey.Length == 0) return; bool had = _memory.Get(_charKey, slot) != null; @@ -733,6 +735,7 @@ public sealed partial class RynthNavPlugin _recallLastCastMs = 0; _recallLastStanceMs = 0; _recallWandTried = false; _recallChangedStance = false; _recallSent = false; _recallWasPortaling = false; _recallPreLb = CurrentLandblock; _recallPreWx = _wx; _recallPreWy = _wy; + ResetTeleportJump(); BeginWand(); AutoRun.Stop(); RecallOption? o = CurrentRecallOption(); @@ -761,9 +764,11 @@ public sealed partial class RynthNavPlugin bool portaling = Host.HasIsPortaling && Host.IsPortaling(); if (portaling) _recallWasPortaling = true; double moved = Math.Sqrt((_wx - _recallPreWx) * (_wx - _recallPreWx) + (_wy - _recallPreWy) * (_wy - _recallPreWy)); - if ((_recallWasPortaling && !portaling) || CurrentLandblock != _recallPreLb || moved > PortalJumpUnits) + bool jumped = TeleportJump(out _); + if ((_recallWasPortaling && !portaling) || CurrentLandblock != _recallPreLb || moved > PortalJumpUnits || jumped) { Host.Log($"[RynthNav] recall {o.Name}: teleported (moved {moved:F0}u)"); + ClockRecall(o); _lastLandMs = NowMs; EndRecall(); AutoRun.Stop(); @@ -953,7 +958,12 @@ public sealed partial class RynthNavPlugin { sb.Append("{\"for\":\"").Append(Esc(_shownRouteFor)).Append("\",\"est\":").Append(_shownRouteEst.ToString("F0", ci)) .Append(",\"active\":").Append(_gotoActive && _shownRouteLive ? 1 : 0) - .Append(",\"idx\":").Append(_gotoActive && _shownRouteLive ? (_route != null ? routeIdx : 0) : -1).Append(",\"steps\":["); + .Append(",\"idx\":").Append(_gotoActive && _shownRouteLive ? (_route != null ? routeIdx : 0) : -1); + // How long the trip takes, in seconds (RynthNavPlugin.TripTime.cs; -1 = not known). + double secs = double.IsFinite(_shownRouteEst) ? _planTimes.Seconds(_shownRouteEst) : -1; + sb.Append(",\"secs\":").Append(secs.ToString("F0", ci)); + AppendWayJson(sb); // which of the ways there (RynthNavPlugin.Ways.cs) + sb.Append(",\"steps\":["); for (int i = 0; i < _shownRoute.Count; i++) { RouteStep s = _shownRoute[i]; @@ -1016,8 +1026,11 @@ public sealed partial class RynthNavPlugin "/rnav arrow | arrow off | arrow route — the arrow\n" + "/rnav go — walk there (route with portals/recalls when /rnav portals on)\n" + "/rnav route — plan a route (portals and recalls), no walking\n" + + "/rnav route next — another way to the same place (switches a running goto) | route go — walk the way shown\n" + "/rnav atlas — find places | fav [place] — favorite | recalls [on|off] | tie 1|2|lifestone\n" + "/rnav goto | preview | portals on|off | stop | here | load | test | navdata\n" + + "/rnav pause — stop walking, keep the trip on the map (drive by hand meanwhile) | resume — carry on\n" + + "/rnav times — how long this character's trips take (run speed, portals, recalls, portal space)\n" + "/rnav avoid — show; avoid portals on|off| | walls on|off| | corners \n" + "/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" + "/rnav mesh on|off | floor on|off | walls on|off | radius | triangles — draw the navmesh: green floor, red walls\n" + @@ -1060,6 +1073,9 @@ public sealed partial class RynthNavPlugin Say($"portal and recall routing {(_portalsEnabled ? "ON" : "OFF")} for walking (go/goto)"); break; case "stop": DoMove(5); Say("stopped"); break; + case "pause": CmdPause(); break; // RynthNavPlugin.Pause.cs + case "times": CmdTimes(); break; // RynthNavPlugin.TripTime.cs + case "resume": CmdResume(); break; case "goto": case "go": CmdGo(rest); @@ -1180,27 +1196,12 @@ public sealed partial class RynthNavPlugin private void CmdRoute(string rest) { - if (!ResolveTarget(rest, out string name, out _, out double ns, out double ew, out string error)) { Note(error); return; } + // "route next": another way to the last place planned for; "route go": walk the way shown. + if (rest.Equals("next", StringComparison.OrdinalIgnoreCase) || rest.Equals("another", StringComparison.OrdinalIgnoreCase)) { CmdRouteNext(); return; } + if (rest.Equals("go", StringComparison.OrdinalIgnoreCase)) { CmdRouteGo(); return; } + if (!ResolveTarget(rest, out string name, out string type, out double ns, out double ew, out string error)) { Note(error); return; } if (!_hasPose) { Note("no player pose yet"); return; } - List? steps = PlanAndShow(name, ns, ew, out int used, out double est, out string refusal); - if (refusal.Length > 0) { Note($"route to {name}: {refusal}"); return; } - if (steps == null || used == 0) - { - Note(_portalsEnabled - ? $"route to {name}: walk ({NavCoords.FmtDistance(est)}; no portal or recall helps)" - : $"route to {name}: walk ({NavCoords.FmtDistance(est)}; portals and recalls are off)"); - return; - } - _goNote = $"route to {name}: {used} teleport(s), {steps.Count} step(s)"; - Say($"route to {name} {NavCoords.Fmt(ns, ew)}: ~{est:F0} yd-equivalent, {used} teleport(s):"); - for (int i = 0; i < steps.Count; i++) - { - RouteStep s = steps[i]; - string act = s.UseRecall ? $"recall: {s.Label}" - : s.IsHub ? $"in the Town Network, walk to the {s.Label} and take it to {NavCoords.Fmt(s.LandNs, s.LandEw)}" - : s.UsePortal ? $"walk to {NavCoords.Fmt(s.Ns, s.Ew)}, take '{Trunc(s.Label)}'" : $"walk to {NavCoords.Fmt(s.Ns, s.Ew)}"; - Say($" {i + 1}. {act}"); - } + ShowRoute(name, type, ns, ew); } private void CmdAtlas(string rest) diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TripTime.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TripTime.cs new file mode 100644 index 0000000..4c7caf9 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.TripTime.cs @@ -0,0 +1,104 @@ +using System; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +// How long a trip takes (11-19, wave 2). The planner costs teleports by the time they take (TripTimes), +// with this character's own times as they're measured (TripClock): its run speed while a goto runs +// straight on, each portal step from its entrance to the jump, each recall step from its start to the +// jump, and portal space from the jump to standing. The trip's time shows when it's planned ("walking to +// X via 3 teleports, about 4 min"), in the route view ("secs") and, while walking, as the time left +// ("eta", RynthNavFace). /rnav times says what has been measured. Tick thread. +public sealed partial class RynthNavPlugin +{ + private readonly TripClock _clock = new(); + private string _clockChar = ""; + /// The times the last plan was made with. + private TripTimes _planTimes = new(); + /// The goto's plan: its cost (units) and its times (NaN = no trip). + private double _tripEst = double.NaN; + private TripTimes _tripTimes = new(); + /// When the current portal step reached its entrance (0 = not at one). + private long _portalStepMs; + /// The panel's Info line (status JSON "info.times"): built on the tick, read on any thread. + private volatile string _clockLine = ""; + private long _clockLineMs; + + /// The Info line, every few seconds. Tick thread. + private void RefreshClockLine() + { + long now = NowMs; + if (now - _clockLineMs < 5000 && _clockLine.Length > 0) return; + _clockLineMs = now; + _clockLine = _clock.Describe(); + } + + /// The times to plan with: this character's (a new character starts from the defaults). + private TripTimes PlanTimes() + { + if (_charKey.Length > 0 && !_charKey.Equals(_clockChar, StringComparison.Ordinal)) + { + _clockChar = _charKey; + _clock.Reset(); + } + _planTimes = _clock.Times; + return _planTimes; + } + + /// "about 4 min" for a plan's cost (units) with the times it was made with. + private static string AboutTime(TripTimes t, double est) => double.IsFinite(est) ? TripTimes.About(t.Seconds(est)) : ""; + + private void ClockPortal() + { + if (_portalStepMs == 0) return; + _clock.Portal((NowMs - _portalStepMs) / 1000.0, PortalArriveUnits); + _portalStepMs = 0; + Host.Log($"[RynthNav] trip times: {_clock.Describe()}"); + } + + private void ClockRecall(RecallOption o) + { + _clock.Recall((NowMs - _recallStartMs) / 1000.0, o.SpellId != 0); + } + + private void ClockSpace(long fromJumpMs) + { + _clock.Space((NowMs - fromJumpMs) / 1000.0); + } + + /// + /// The trip's time left, in seconds (-1: not known): what is left of the current step, from where + /// you stand and how long its teleport has been going, plus the plan's cost of the steps after it. + /// + private double TripSecondsLeft(string phase, double left) + { + if (!_gotoActive || !double.IsFinite(_tripEst)) return -1; + TripTimes t = _tripTimes; + double walk = left >= 0 ? t.Seconds(left) : 0; + if (_route == null || _route.Count == 0) return left >= 0 ? walk : -1; + int i = Math.Clamp(_routeIdx, 0, _route.Count - 1); + RouteStep step = _route[i]; + double rest = step.EstAfter > 0 ? t.Seconds(Math.Max(0, _tripEst - step.EstAfter)) : 0; + double portal = t.PortalSeconds + t.SpaceSeconds; + double here; + if (_settling) here = Math.Max(0.5, t.SpaceSeconds - (NowMs - _settleJumpMs) / 1000.0); + else if (phase == "recall") + { + RecallOption? o = CurrentRecallOption(); + double total = (o == null || o.SpellId != 0 ? t.SpellCastSeconds : t.CommandCastSeconds) + t.SpaceSeconds; + here = Math.Max(1, total - (NowMs - _recallStartMs) / 1000.0); + } + else if (phase == "portal") here = Math.Max(1, portal - (_portalStepMs > 0 ? (NowMs - _portalStepMs) / 1000.0 : 0)); + else if (phase == "town") here = walk + portal; + else if (step.UseRecall) here = t.SpellCastSeconds + t.SpaceSeconds; + else here = walk + (step.UsePortal ? portal : 0); + return here + rest; + } + + /// /rnav times: what this character's trips have been measured to take. + private void CmdTimes() + { + Say($"trip times ({(_clockChar.Length > 0 ? "this character" : "not logged in")}): {_clock.Describe()}. " + + "A portal costs its time at the portal and in portal space, a recall its cast and portal space, at your run speed."); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Ways.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Ways.cs new file mode 100644 index 0000000..4ada62a --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Ways.cs @@ -0,0 +1,411 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using DotRecast.Core.Numerics; +using DotRecast.Detour; +using RynthNav.Routing; + +namespace RynthCore.Plugin.RynthNav; + +// Who may use which portal, what to do when the server says no, and the other ways there. +// - The planner leaves out a portal the server would refuse this character (PortalRules: its level, +// player killer status, Olthoi, vitae; NavData's portals.tsv carries each portal's rules). 11-18 a +// goto routed a non-player killer through the PK-only Olthoi Tunnel and asked it ~40 times. +// - A portal the server refuses all the same (WeenieError, e.g. "Non-player killers may not interact +// with that portal!") is left out for a while and the whole trip is planned again from where you +// stand. So is a teleport that lands somewhere the route didn't expect. +// - Other ways: each plan keeps up to MaxWays different ways there (PortalRoute.PlanOptions). +// "/rnav route next" (the panel's Another way) shows the next, and switches a running goto to +// it; later plans to the same place keep to it (the teleports it avoids stay left out). +// Tick thread. +public sealed partial class RynthNavPlugin +{ + private const uint StypePlayerKillerStatus = 134; + private const int MaxWays = 4; + private const int MaxTripReplans = 4; // a goto plans again at most this often, then stops + private const long RefusedForgetMs = 30 * 60 * 1000; // a refused portal is left out this long + private const double LandingSlackUnits = 120.0; // a teleport landing this close to the planned spot is it + private const long WayChoiceKeepMs = 20 * 60 * 1000; // a way chosen for a place is kept this long (and until you arrive) + + private const double PortalLevelUnits = 3.0; // a portal this far above or below you is on another level + private const long PortalOtherLevelGiveUpMs = 8000; // at a portal on another level with no way to its floor: give up after this + + private readonly Dictionary _refused = new(StringComparer.Ordinal); + + // The current leg's portal, exactly (portals.tsv's cell and x, y, z): its height, whether it stands + // indoors, and whether the navmesh reaches its floor from here (null = not looked yet). + private double _legSpotZ = double.NaN; + private bool _legSpotIndoor; + private bool? _legFloorReach; + private double _portalLiveZ = double.NaN; // the live portal object's height (SnapToLivePortal) + private long _portalWaitBeganMs; + private int _tripReplans; + + // The other ways (the last plan's), and the one chosen. + private List _ways = new(); + private string _waysFor = "", _waysType = ""; + private double _waysNs = double.NaN, _waysEw = double.NaN; + private int _wayIdx, _wayCount; + private HashSet _wayBans = new(StringComparer.Ordinal); // the chosen way's own (beyond the rules) + private bool _wayWalk; // the chosen way is walking all the way + private long _wayChosenMs; // when it was chosen (0 = forget it) + private bool _lbCrossSaid; // "crossed a landblock line at the portal" logged + private List _wayAvoids = new(); + + // ── Who is travelling ──────────────────────────────────────────────────── + + /// The character as the server's portal checks see them. Tick thread. + private Traveller ReadTraveller() + { + ReadCharacterRules(out int level, out bool olthoi); + uint pk = 0; + bool? vitae = null; + uint me = Host.HasGetPlayerId ? Host.GetPlayerId() : 0; + if (me != 0) + { + if (Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(me, StypePlayerKillerStatus, out int s) && s > 0) pk = (uint)s; + // No PropertyInt 134 (11-20, DreamWeave and Aelrynth): the PK flags every object is sent with. + if (pk == 0 && Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(me, out uint bf)) pk = PortalRules.StatusFromBitfield(bf); + if (Host.HasGetVitae) vitae = Host.GetVitae(me) < 0.995f; + } + return new Traveller(level, pk, olthoi, vitae); + } + + /// + /// The teleports a plan for may not take: portals whose rules refuse them, and + /// portals the server refused them lately. Says why in . + /// + private HashSet PlanBans(in Traveller t, List? notes) + { + var bans = new HashSet(StringComparer.Ordinal); + List? portals = _portals; + if (portals != null) + { + var why = new Dictionary(StringComparer.Ordinal); + for (int i = 0; i < portals.Count; i++) + { + string w = PortalRules.Refusal(portals[i], t); + if (w.Length == 0) continue; + bans.Add(PortalRoute.PortalKey(i)); + why[w] = why.TryGetValue(w, out int c) ? c + 1 : 1; + } + if (why.Count > 0) + notes?.Add($"{bans.Count} portal(s) left out for you ({t}): " + string.Join(", ", why.Select(kv => $"{kv.Key} x{kv.Value}"))); + } + long now = NowMs; + List? stale = null; + foreach (var kv in _refused) + { + if (now - kv.Value.Ms >= RefusedForgetMs) { (stale ??= new()).Add(kv.Key); continue; } + bans.Add(kv.Key); + notes?.Add($"left out: '{kv.Value.Name}' refused you {(now - kv.Value.Ms) / 60000} min ago ({kv.Value.Why})"); + } + if (stale != null) foreach (string k in stale) _refused.Remove(k); + return bans; + } + + // ── The server says no ─────────────────────────────────────────────────── + + /// + /// A WeenieError while a goto takes a portal: a refusal that won't change (PortalRules.RefusalFromServer) + /// leaves that portal out and plans the trip again from here. True when it was ours to handle. + /// + private bool OnPortalRefused(uint error) + { + string? why = PortalRules.RefusalFromServer(error); + if (why == null || !_gotoActive || _route == null || _routeIdx >= _route.Count) return false; + RouteStep step = _route[_routeIdx]; + bool taking = _portalWait || step.IsHub; + if (!taking) return false; + string name = PortalStepName(); + Host.Log($"[RynthNav] portal refused: '{name}' (0x{error:X4}: {why}){(step.Via != null ? $", key {step.Via}" : "")}"); + bool entrance = _enterName.Length > 0 && _routeIdx >= _route.Count - 1; + if (entrance || step.Via == null) + { + FinishGoto($"stopped: the server won't let you through '{name}' ({why})"); + return true; + } + _refused[step.Via] = (name, why, NowMs); + ReplanTrip($"the server won't let you through '{name}' ({why})"); + return true; + } + + /// + /// Plans the running goto again from where you stand (portals refused meanwhile are left out, the + /// chosen way kept), at most MaxTripReplans times; then stops and says why. + /// + private void ReplanTrip(string why) + { + string goal = _gotoName, type = _gotoType, enter = _enterName, enterType = _enterType; + double gns = NavCoords.NsFromWorld(_finalTns), gew = NavCoords.EwFromWorld(_finalTew); + if (_tripReplans >= MaxTripReplans) + { + FinishGoto($"stopped: {why}, and I've planned the trip again {MaxTripReplans} times already"); + return; + } + _tripReplans++; + Host.Log($"[RynthNav] replan {_tripReplans}/{MaxTripReplans}: {why}"); + Say($"goto: {why}; planning another way from here"); + if (_recallWait) EndRecall(); + StartWalk(goal.Length > 0 ? goal : NavCoords.Fmt(gns, gew), type, gns, gew, enter, enterType, landReplan: true); + } + + // ── Teleports: did one happen, and did it land where planned ───────────── + + private bool _tjHave; + private double _tjWx, _tjWy; + private long _tjMs; + + /// Forget the last position: the next TeleportJump measures from there. + private void ResetTeleportJump() => _tjHave = false; + + /// + /// A jump since the last tick too far and too fast to be running: a teleport. A landblock line + /// crossed while backing off a portal is not one (11-18: 25 u across 7F8F -> 7F8E was taken for + /// the teleport, and the next leg planned from the wrong side of the world). + /// + private bool TeleportJump(out double jump) + { + long now = NowMs; + jump = 0; + bool teleport = false; + if (_tjHave) + { + jump = Math.Sqrt((_wx - _tjWx) * (_wx - _tjWx) + (_wy - _tjWy) * (_wy - _tjWy)); + teleport = PortalRules.IsTeleportJump(jump, (now - _tjMs) / 1000.0); + } + _tjHave = true; _tjWx = _wx; _tjWy = _wy; _tjMs = now; + return teleport; + } + + /// + /// After a portal or recall step's teleport: true when it landed where the plan said (or the plan + /// doesn't say: the Town Network's entry lands inside). Else where it did land. + /// + private bool LandedWherePlanned(out string where) + { + where = ""; + if (_route == null || _routeIdx >= _route.Count) return true; + RouteStep s = _route[_routeIdx]; + if (!(s.UsePortal || s.UseRecall) || double.IsNaN(s.LandNs) || double.IsNaN(s.LandEw)) return true; + if (!IsOnMap(_cellId)) { where = $"a dungeon (landblock 0x{CurrentLandblock:X4})"; return false; } + double ns = NavCoords.NsFromWorld(_wy), ew = NavCoords.EwFromWorld(_wx); + double off = NavCoords.Distance(ns, ew, s.LandNs, s.LandEw); + if (off <= LandingSlackUnits) return true; + where = $"{NavCoords.Fmt(ns, ew)}, {off:F0} yd from {NavCoords.Fmt(s.LandNs, s.LandEw)}"; + return false; + } + + // ── A portal on another level (a cellar, a tunnel under a town) ────────── + + /// The portal a leg walks to, exactly, when portals.tsv says where it stands. + private bool LegPortal(RouteStep s, out PortalLink portal) + { + portal = default; + if (!s.UsePortal || s.Via == null || !s.Via.StartsWith("p", StringComparison.Ordinal) || _portals == null) return false; + if (!int.TryParse(s.Via.AsSpan(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int i) || i < 0 || i >= _portals.Count) return false; + portal = _portals[i]; + return portal.HasSpot; + } + + /// A new leg: aim at its portal's exact spot (the map coordinates are 0.1 out, up to 24 u), and its height. + private void SetLegSpot(RouteStep s) + { + _legSpotZ = double.NaN; _legSpotIndoor = false; _legFloorReach = null; _portalLiveZ = double.NaN; + if (!LegPortal(s, out PortalLink p)) return; + _gotoTew = p.WorldEast; _gotoTns = p.WorldNorth; + _legSpotZ = p.Z; _legSpotIndoor = p.Indoor; + } + + /// + /// The goal polygon for a leg to a portal in a building or below the street: its own floor, when a + /// walk from here reaches it (down the cellar stairs). Else false: the goal is looked up as before (the + /// ground nearest, from your height), and taking it is left to using it from there (StepPortalWait + /// gives up on it after PortalOtherLevelGiveUpMs). Tick thread. + /// + private bool PortalFloorGoal(long sRef, RcVec3f sPt, IDtQueryFilter filter, out long gRef, out RcVec3f gPt) + { + gRef = 0; gPt = default; + if (double.IsNaN(_legSpotZ) || _query == null) return false; + if (!_legSpotIndoor && Math.Abs(_legSpotZ - _wz) <= PortalLevelUnits) return false; // out on the ground: as before + long f = NavPathQuery.PortalFloor(_query, filter, _gotoTew, _legSpotZ, _gotoTns, out RcVec3f fPt); + bool reach = f != 0 && NavPathQuery.Reaches(_query, sRef, sPt, f, fPt, filter); + if (_legFloorReach != reach) + { + double dz = _legSpotZ - _wz; + Host.Log(reach + ? $"[RynthNav] portal '{PortalStepName()}' stands {Math.Abs(dz):F1}u {(dz < 0 ? "below" : "above")} you: walking to its own floor" + : $"[RynthNav] portal '{PortalStepName()}' stands {Math.Abs(dz):F1}u {(dz < 0 ? "below" : "above")} you{(f == 0 ? " (no navmesh at its floor)" : ", and the navmesh doesn't reach its floor from here")}: going as near as it lets me and using it"); + } + _legFloorReach = reach; + if (!reach) return false; + gRef = f; gPt = fPt; + return true; + } + + /// A portal leg whose portal is on another level, its floor reached by the walk: not there until on that floor. + private bool PortalOnOtherLevel => _legFloorReach == true && !double.IsNaN(_legSpotZ) && Math.Abs(_wz - _legSpotZ) > PortalLevelUnits; + + /// + /// At the portal, waiting: it stands on another level right under (or over) you, with no way to its + /// floor, and using it hasn't taken you for PortalOtherLevelGiveUpMs. 11-18 the walker stood 1 u from + /// Zaikhal's Olthoi Tunnel, 7.7 u above it on the street, and circled it until it was taken over by hand. + /// Leave the portal out and plan another way (a dungeon's own entrance: stop and say so). True when it gave up. + /// + private bool GiveUpOnOtherLevel(double horizontal) + { + double pz = !double.IsNaN(_portalLiveZ) ? _portalLiveZ : _legSpotZ; + if (double.IsNaN(pz) || horizontal > PortalContactUnits || Math.Abs(pz - _wz) <= PortalLevelUnits) return false; + if (NowMs - _portalWaitBeganMs < PortalOtherLevelGiveUpMs) return false; + double dz = pz - _wz; + string name = PortalStepName(); + string why = $"'{name}' is {Math.Abs(dz):F0} yd {(dz < 0 ? "below" : "above")} you and I can't find the way {(dz < 0 ? "down" : "up")} to it"; + Host.Log($"[RynthNav] portal on another level: {why} ({(NowMs - _portalWaitBeganMs) / 1000.0:F0} s without a teleport)"); + bool entrance = _enterName.Length > 0 && _route != null && _routeIdx >= _route.Count - 1; + RouteStep? step = _route != null && _routeIdx < _route.Count ? _route[_routeIdx] : null; + if (entrance || step?.Via == null) { FinishGoto($"stopped: {why}; take it by hand"); return true; } + _refused[step.Value.Via!] = (name, $"{Math.Abs(dz):F0} yd {(dz < 0 ? "below" : "above")} the ground I can walk", NowMs); + ReplanTrip(why); + return true; + } + + // ── Other ways ─────────────────────────────────────────────────────────── + + private bool SameWayTarget(double ns, double ew) => + !double.IsNaN(_waysNs) && Math.Abs(ns - _waysNs) < 0.02 && Math.Abs(ew - _waysEw) < 0.02; + + /// The teleports a route takes from step on, as PlanOptions' signature. + private static string WaySignature(List? steps, int from = 0) + { + if (steps == null) return ""; + var sb = new StringBuilder(); + for (int i = Math.Max(0, from); i < steps.Count; i++) + if (steps[i].Via != null) { if (sb.Length > 0) sb.Append('|'); sb.Append(steps[i].Via); } + return sb.ToString(); + } + + /// A plan to a new place forgets the way chosen for the last one. + private void ForgetWayChoice(double goalNs, double goalEw) + { + if (SameWayTarget(goalNs, goalEw) && _wayChosenMs > 0 && NowMs - _wayChosenMs < WayChoiceKeepMs) return; + if (SameWayTarget(goalNs, goalEw) && _wayIdx == 0 && _wayBans.Count == 0 && !_wayWalk) return; // nothing chosen + _wayBans = new HashSet(StringComparer.Ordinal); + _wayAvoids = new List(); + _wayWalk = false; + _wayIdx = 0; _wayCount = 0; + } + + /// Keeps the ways a plan found (PlanRoute), for "another way". + private void KeepWays(TravelPlan.Result r, string name, double goalNs, double goalEw, bool chosen) + { + _ways = r.Options; + _waysFor = name; _waysNs = goalNs; _waysEw = goalEw; + if (!chosen) { _wayIdx = 0; _wayCount = r.Options.Count; } + _routeVersion++; // the panel's "way n of m" + } + + /// "way 2 of 4 (avoids Olthoi Tunnel)", or "" with one way. + private string WayText() + { + if (_wayCount <= 1) return ""; + string avoids = _wayIdx > 0 && _wayAvoids.Count > 0 ? $" (avoids {string.Join(", ", _wayAvoids)})" : ""; + return $"way {_wayIdx + 1} of {_wayCount}{avoids}"; + } + + /// + /// /rnav route next: the next of the ways to the last place planned for, planned again from here. + /// A running goto to it switches to that way; otherwise it is shown (the panel, the arrow, chat). + /// + private void CmdRouteNext() + { + if (!_hasPose) { Note("no player pose yet"); return; } + if (double.IsNaN(_waysNs) || _waysFor.Length == 0) { Note("another way to where? Plan a route first (/rnav route , or Route here on the map)"); return; } + if (_townNet?.Contains(CurrentLandblock) == true) { Note("you're in the Town Network: pick another way once you're out of it"); return; } + bool walking = _gotoActive && SameWayTarget(NavCoords.NsFromWorld(_finalTns), NavCoords.EwFromWorld(_finalTew)); + string current = walking ? WaySignature(_route, _routeIdx) : WaySignature(_shownRoute); + string name = _waysFor, type = _waysType; + double ns = _waysNs, ew = _waysEw; + + // Every way from here, the choice left out. + TravelPlan.Result all = PlanRoute(name, ns, ew, out _, ignoreChoice: true); + if (all.Refusal.Length > 0 || all.Options.Count == 0) { Note($"route to {name}: {(all.Refusal.Length > 0 ? all.Refusal : "no way there")}"); return; } + if (all.Options.Count == 1) + { + Note($"route to {name}: there's only the one way from here"); + _wayBans = new HashSet(StringComparer.Ordinal); _wayAvoids = new List(); _wayWalk = false; + KeepWays(all, name, ns, ew, chosen: false); + return; + } + int at = all.Options.FindIndex(o => o.Signature == current); + int next = at < 0 ? (current == all.Options[0].Signature ? 1 : 0) : (at + 1) % all.Options.Count; + TravelPlan.Option pick = all.Options[next]; + _ways = all.Options; + _wayIdx = next; _wayCount = all.Options.Count; + _wayBans = new HashSet(pick.Bans, StringComparer.Ordinal); + _wayAvoids = new List(pick.Avoids); + _wayWalk = next > 0 && pick.Teleports == 0; + _wayChosenMs = NowMs; + string text = WayText(); + Host.Log($"[RynthNav] another way to {name}: {(text.Length > 0 ? text : "way 1")}, ~{pick.Est:F0}u, {pick.Teleports} teleport(s)"); + + if (walking) + { + Say($"goto: switching to {(text.Length > 0 ? text : "the first way")}"); + _nextEnterPortal = _enterPortal; // the same entrance portal (a saved nav route names it) + StartWalk(name, _gotoType, ns, ew, _enterName, _enterType); + return; + } + ShowRoute(name, type, ns, ew); + } + + /// /rnav route go: walk the way shown (the last place planned for, the way chosen). + private void CmdRouteGo() + { + if (double.IsNaN(_waysNs) || _waysFor.Length == 0) { Note("go which way? Plan a route first (/rnav route )"); return; } + StartGoto(_waysFor, _waysType, _waysNs, _waysEw); + } + + /// The route's lines in chat, and the way it is, after a plan or "another way". + private void SayRoute(string name, double ns, double ew, List? steps, int used, double est) + { + string way = WayText(); + if (steps == null || used == 0) + { + Note(_portalsEnabled + ? $"route to {name}: walk ({NavCoords.FmtDistance(est)}, {AboutTime(_planTimes, est)}{(way.Length > 0 ? "; " + way : "; no portal or recall helps")})" + : $"route to {name}: walk ({NavCoords.FmtDistance(est)}; portals and recalls are off)"); + if (_wayCount > 1) Say($" {_wayCount} ways in all: /rnav route next for another"); + return; + } + _goNote = $"route to {name}: {used} teleport(s), {steps.Count} step(s)"; + string eta = AboutTime(_planTimes, est); + Say($"route to {name} {NavCoords.Fmt(ns, ew)}: {(eta.Length > 0 ? eta + ", " : "")}{used} teleport(s) (~{est:F0} yd-equivalent){(way.Length > 0 ? ", " + way : "")}:"); + for (int i = 0; i < steps.Count; i++) + { + RouteStep s = steps[i]; + string act = s.UseRecall ? $"recall: {s.Label}" + : s.IsHub ? $"in the Town Network, walk to the {s.Label} and take it to {NavCoords.Fmt(s.LandNs, s.LandEw)}" + : s.UsePortal ? $"walk to {NavCoords.Fmt(s.Ns, s.Ew)}, take '{Trunc(s.Label)}'" : $"walk to {NavCoords.Fmt(s.Ns, s.Ew)}"; + Say($" {i + 1}. {act}"); + } + if (_wayCount > 1) Say($" {_wayCount} ways in all: /rnav route next for another, /rnav route go to walk this one"); + } + + /// Plans (with the way chosen) and shows the route to a place: the panel, the arrow, chat. + private void ShowRoute(string name, string type, double ns, double ew) + { + List? steps = PlanAndShow(name, ns, ew, out int used, out double est, out string refusal); + _waysType = type; + if (refusal.Length > 0) { Note($"route to {name}: {refusal}"); return; } + SayRoute(name, ns, ew, steps, used, est); + } + + /// The route JSON's way fields: which of how many, and what it avoids. + private void AppendWayJson(StringBuilder sb) + { + sb.Append(",\"way\":").Append(_wayIdx + 1).Append(",\"ways\":").Append(_wayCount) + .Append(",\"avoids\":\"").Append(Esc(_wayIdx > 0 ? string.Join(", ", _wayAvoids) : "")).Append('"'); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs index 36cb320..c850e75 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Linq; using System.Runtime.InteropServices; using System.Text; using DotRecast.Core.Numerics; @@ -42,6 +43,13 @@ public sealed partial class RynthNavPlugin : RynthPluginBase private const int MaxTiles = 256; private const int MaxCorridorTiles = 220; private const double ArrivalUnits = 7.0; + // The goto's own goal (the coords given, not a portal or a route leg's end) is stood on: within + // FinalArrivalUnits, run at with the tight servo from FinalApproachUnits out. A spot it can't get + // that close to (something standing on it) counts once within ArrivalUnits and no closer for + // CloseEnoughMs. Before 11-19 every leg ended 7 u out (a player: "it stops 1 yard or so before"). + private const double FinalArrivalUnits = 2.5; + private const double FinalApproachUnits = 20.0; + private const long CloseEnoughMs = 2000; private const double CornerLookaheadUnits = 6.0; // a path corner is cut from this far out when the next is in plain view private const int PreviewMaxLandblocks = 3; // preview only targets this many landblocks away (a <= 6x6 tile box) private const int BlindPushTicks = 45; // ~1.5 s straight at the goal when the plan runs out short of it (crosses a seam) @@ -105,14 +113,16 @@ public sealed partial class RynthNavPlugin : RynthPluginBase private int _blindTicks; // ticks since the plan ran out (see BlindPushTicks) private int _legTicks, _bestTick; // progress watchdog for the current leg private double _bestDist = double.MaxValue; + private double _nearBest = double.MaxValue; // the closest yet within ArrivalUnits of the final goal... + private long _nearBestMs; // ...and when (CloseEnoughMs) private string _gotoName = ""; // what the goto is walking to (for its chat lines) private volatile bool _echoChat; // the pending load/test/preview came from chat: answer there // Portal route execution (tick thread only). private List? _portals; // loaded lazily from NavData\portals.tsv - // OFF by default: goto walks straight to the coord (the original, working behavior). - // Portal routing is opt-in via "/rnav portals on" while we get it reliable. - private volatile bool _portalsEnabled = false; + // ON by default since 2026-11-19: Go and Route take portals, the Town Network and recalls when + // that is quicker. "/rnav portals off" (or the panel's switch) walks only; the choice is saved. + private volatile bool _portalsEnabled = true; private List? _route; // current planned legs (null = pure navmesh goto) private int _routeIdx; private bool _portalWait; // standing at a portal entrance, waiting for the teleport @@ -142,7 +152,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // Every use logged (Plugins/Shared/UseAudit.cs). No macro here: no door/corpse guard. RynthCore.Plugin.Shared.UseAudit.Reset("RynthNav", null); // The panel's switches survive reloads and relogs (rynthnav.json, next to navDataDir). - _portalsEnabled = NavDataConfig.ReadSwitch("portals", false); + _portalsEnabled = NavDataConfig.ReadSwitch("portals", true); _recallsEnabled = NavDataConfig.ReadSwitch("recalls", true); LoadAvoidSettings(); LoadMarkerSettings(); @@ -179,7 +189,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase _hasPose = false; _lastSeenLb = 0; lock (_gate) { _status = "logged out"; _lastPath = ""; } lock (_moveGate) { _desiredRun = 0; _turnState = 0; _haltPending = true; } - _gotoActive = false; + _gotoActive = false; _paused = false; _route = null; _portalWait = false; _portalWaitTicks = 0; _wasPortaling = false; _settling = false; ResetHub(); lock (_gotoGate) { _gotoPath = null; _gotoIdx = 0; } @@ -381,7 +391,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase if (cancel) { if (_gotoActive) _goNote = "stopped"; // the panel's status line (the d-pad and Stop say nothing in chat) - _gotoActive = false; _route = null; _portalWait = false; if (_recallWait) EndRecall(); + _gotoActive = false; _paused = false; _route = null; _portalWait = false; if (_recallWait) EndRecall(); ResetHub(); HideMarkers("cancelled"); } @@ -470,7 +480,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase { if (!_hasPose) { lock (_gate) _status = "no pose"; Note("goto: no player position yet"); return; } // A new goto (not the re-plan after "no route over land") may re-plan once again. - if (!landReplan) { _landReplanned = false; _enterPortal = enter.Length > 0 ? _nextEnterPortal : ""; _nextEnterPortal = ""; } + if (!landReplan) { _landReplanned = false; _tripReplans = 0; _enterPortal = enter.Length > 0 ? _nextEnterPortal : ""; _nextEnterPortal = ""; } // Whatever was running stops first: a refused goto must not leave the old one half-changed. if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); AutoRun.Stop(); HideMarkers("a new goto"); } double twx = NavCoords.WorldX(tew), twy = NavCoords.WorldY(tns); @@ -481,6 +491,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase return; } if (_recallWait) EndRecall(); + _paused = false; _finalTew = twx; _finalTns = twy; _replanTick = 0; _portalWait = false; _portalWaitTicks = 0; _wasPortaling = false; _settling = false; @@ -516,6 +527,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase _route = plan.Steps; portalsUsed = plan.Teleports; est = plan.Est; } _routeRecalls = recalls; + _tripEst = est; _tripTimes = inHub ? PlanTimes() : _planTimes; // the time left (RynthNavPlugin.TripTime.cs) _routeIdx = 0; // Into a dungeon (or through a portal): the last leg walks into its portal and waits for @@ -560,7 +572,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase _gotoActive = true; _gotoName = name; _gotoType = type; _walkHaveLast = false; - string via = (_route != null && portalsUsed > 0) ? $" via {portalsUsed} teleport(s), ~{est:F0}u" : ""; + string eta = AboutTime(_tripTimes, est); + string via = (_route != null && portalsUsed > 0) ? $" via {portalsUsed} teleport(s), {(eta.Length > 0 ? eta + " " : "")}(~{est:F0}u)" + : eta.Length > 0 ? ", " + eta : ""; lock (_gate) { _status = $"walking -> {NavCoords.Fmt(tns, tew)}{via}"; _lastPath = "planning…"; } Host.Log($"[RynthNav] goto {name} ({tns:F2},{tew:F2}){via}"); string at = name == NavCoords.Fmt(tns, tew) ? name : $"{name} at {NavCoords.Fmt(tns, tew)}"; @@ -577,7 +591,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // #17) instead of mutating _gotoActive/_route/_portalWait directly — // those are tick-thread-owned state read non-atomically by // StepGoto/OnSubGoalReached. - lock (_reqGate) _reqCancel = true; + // While paused the d-pad moves you and the trip stays on the map; its Stop still ends the trip. + if (!_paused || cmd == 5) lock (_reqGate) _reqCancel = true; lock (_moveGate) { switch (cmd) @@ -593,7 +608,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase private void ApplyMovement() { - if (_gotoActive) { _wasGoto = true; StepGoto(); return; } + // Paused (RynthNavPlugin.Pause.cs): the trip stays, the walking stops, the d-pad works. + if (_gotoActive && !_paused) { _wasGoto = true; StepGoto(); return; } if (_wasGoto) { _wasGoto = false; @@ -675,17 +691,35 @@ public sealed partial class RynthNavPlugin : RynthPluginBase return; } _walkHaveLast = true; _walkLastWx = _wx; _walkLastWy = _wy; + _clock.RunTick(NowMs, _wx, _wy, AutoRun.Running); // run speed (RynthNavPlugin.TripTime.cs) RefreshAvoid(force: false); bool isPortalLeg = _route != null && _routeIdx < _route.Count && _route[_routeIdx].UsePortal; - double arrive = isPortalLeg ? PortalArriveUnits : ArrivalUnits; + // The goto's own goal: stood on, not stopped 7 u short of (FinalArrivalUnits). + bool finalLeg = !isPortalLeg && (_route == null || _routeIdx >= _route.Count - 1); + double endReach = finalLeg ? FinalArrivalUnits : ArrivalUnits; + double arrive = isPortalLeg ? PortalArriveUnits : endReach; double fdew = _gotoTew - _wx, fdns = _gotoTns - _wy; double toGoal = Math.Sqrt(fdew * fdew + fdns * fdns); // A /loc inside a building, a tree or on a steep slope has no walkable ground: // the path ends at the nearest walkable spot, which can be more than // ArrivalUnits from the typed point. Standing on that spot is arriving. - bool atMeshGoal = !isPortalLeg && _goalOnMesh && - Math.Sqrt((_goalMeshEw - _wx) * (_goalMeshEw - _wx) + (_goalMeshNs - _wy) * (_goalMeshNs - _wy)) < ArrivalUnits; + double toMeshGoal = Math.Sqrt((_goalMeshEw - _wx) * (_goalMeshEw - _wx) + (_goalMeshNs - _wy) * (_goalMeshNs - _wy)); + bool atMeshGoal = !isPortalLeg && _goalOnMesh && toMeshGoal < endReach; + // Close to the goal but no closer for CloseEnoughMs (an NPC, a chest or a tree on the spot): there. + if (finalLeg && !atMeshGoal) + { + double near = _goalOnMesh ? Math.Min(toGoal, toMeshGoal) : toGoal; + if (near < ArrivalUnits) + { + if (near < _nearBest - 0.3) { _nearBest = near; _nearBestMs = NowMs; } + else if (NowMs - _nearBestMs > CloseEnoughMs) + { + Host.Log($"[RynthNav] goto: {near:F1}u from the goal and no closer for {CloseEnoughMs / 1000} s: arrived"); + atMeshGoal = true; + } + } + } // A portal is run into straight from PortalArriveUnits: only with nothing between, as far as // the navmesh shows. A portal round a corner (a wall within 14 u of it) is reached along // the path first; it used to be run at through the wall, 12 s a try, five tries. @@ -695,7 +729,12 @@ public sealed partial class RynthNavPlugin : RynthPluginBase lock (_gotoGate) pathLeft = _gotoPath != null && _gotoIdx < _gotoPath.Count; if (pathLeft && !StraightOnMesh(_gotoTew, _gotoTns)) arrive = PortalContactUnits; } - if (toGoal < arrive || atMeshGoal) + // A portal down the cellar stairs is right under you from the street: arrived only on its floor. + // Close to one whose floor hasn't been looked for yet: plan once now, which looks (PortalFloorGoal). + if (isPortalLeg && toGoal < arrive && _legFloorReach == null && !double.IsNaN(_legSpotZ) + && (_legSpotIndoor || Math.Abs(_legSpotZ - _wz) > PortalLevelUnits)) + Replan(); + if ((toGoal < arrive || atMeshGoal) && !(isPortalLeg && PortalOnOtherLevel)) { OnSubGoalReached(); return; @@ -750,7 +789,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // straight (the navmesh's raycast: the agent radius from every wall it knows, and out // of the portal circles): the walk turns smoothly instead of overshooting each corner // at run speed and turning back to it (11-01). - idx = PathFollow.Advance(path, idx, _wx, _wy, _cornerReach, ArrivalUnits, CornerLookaheadUnits, WalkableStraight); + idx = PathFollow.Advance(path, idx, _wx, _wy, _cornerReach, endReach, CornerLookaheadUnits, WalkableStraight); lock (_gotoGate) _gotoIdx = idx; } if (path == null || idx >= path.Count) @@ -785,7 +824,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // hub portals' circles, a wall beside), it held 234 deg into the wall while the path wanted // 301 and re-planned every 0.6 s (10-01 20:07, "just spazzing"). Steering is for the // blind push and the last steps onto a portal, where there is no path. - WalkDrive(desired); + // The last FinalApproachUnits to the goal: the tight servo (4 deg dead zone, stops to turn past + // 20), so the run lines up on a 2.5 u spot instead of passing beside it. + WalkDrive(desired, tight: finalLeg && toGoal < FinalApproachUnits); } // ── Portal routing ─────────────────────────────────────────────────────────── @@ -803,7 +844,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase if (step.UsePortal) { _portalWait = true; _portalWaitTicks = 0; _wasPortaling = false; + _portalStepMs = NowMs; // the trip clock: from here to the jump (RynthNavPlugin.TripTime.cs) _prePortalWx = _wx; _prePortalWy = _wy; _prePortalLb = CurrentLandblock; + ResetTeleportJump(); BeginPortalAim(); lock (_gate) _status = $"taking portal '{Trunc(step.Label)}'"; Host.Log($"[RynthNav] at portal entrance '{step.Label}' lb=0x{_prePortalLb:X4} — approaching"); @@ -829,8 +872,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase var s = _route[_routeIdx]; _gotoTew = (s.Ew * 10.0 + 1019.5) * 24.0; _gotoTns = (s.Ns * 10.0 + 1019.5) * 24.0; + SetLegSpot(s); // a portal: exactly where it stands, and its height (RynthNavPlugin.Ways.cs) } - else { _gotoTew = _finalTew; _gotoTns = _finalTns; } + else { _gotoTew = _finalTew; _gotoTns = _finalTns; SetLegSpot(default); } // New leg: fresh progress watchdog, and the old leg's walkable end no longer counts. ResetHub(); ResetBlocked(); @@ -840,13 +884,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase _walkHaveLast = false; // a new leg starts where the last step's teleport put us _goalOnMesh = false; _blindTicks = 0; _legTicks = 0; _bestTick = 0; _bestDist = double.MaxValue; + _nearBest = double.MaxValue; _nearBestMs = NowMs; ResetCoarse(); } private void FinishGoto(string status) { if (_recallWait) EndRecall(); - _gotoActive = false; _route = null; _portalWait = false; + _gotoActive = false; _paused = false; _route = null; _portalWait = false; + _tripEst = double.NaN; _portalStepMs = 0; ResetHub(); _avoid.Clear(); _coarseHoldTicks = 0; ResetBlocked(); @@ -856,28 +902,39 @@ public sealed partial class RynthNavPlugin : RynthPluginBase Host.Log($"[RynthNav] goto: {status}"); Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}"); _goNote = status == "arrived" && _gotoName.Length > 0 ? $"arrived at {_gotoName}" : status; + if (status == "arrived") _wayChosenMs = 0; // there: the next trip there is planned afresh (RynthNavPlugin.Ways.cs) _enterName = ""; _enterType = ""; HideMarkers(status == "arrived" ? "arrived" : "the goto ended"); } - // At a portal entrance, waiting for the teleport. A portal ALWAYS changes the - // landblock, so a landblock change is the reliable trigger signal (the old - // distance check missed teleports). To avoid orbiting the entrance at run speed - // we approach to a small radius then settle and let the collision fire. + // At a portal entrance, waiting for the teleport: portal space ending, or a jump (TeleportJump: too far + // and too fast between two ticks to be running). A landblock change alone is not one: 15% of the + // portals stand within 14 u of a landblock line, and backing off to try again crossed it (11-18). + // To avoid orbiting the entrance at run speed we approach to a small radius then settle and let + // the collision fire. private void StepPortalWait() { bool portaling = Host.HasIsPortaling && Host.IsPortaling(); if (portaling) _wasPortaling = true; bool lbChanged = CurrentLandblock != _prePortalLb; double moved = Math.Sqrt((_wx - _prePortalWx) * (_wx - _prePortalWx) + (_wy - _prePortalWy) * (_wy - _prePortalWy)); - bool teleported = lbChanged || (_wasPortaling && !portaling) || moved > PortalJumpUnits; + bool jumped = TeleportJump(out double jump); + bool teleported = (_wasPortaling && !portaling) || moved > PortalJumpUnits || jumped; + if (!teleported && lbChanged && !_lbCrossSaid) + { + _lbCrossSaid = true; + Host.Log($"[RynthNav] at the portal: crossed into landblock 0x{CurrentLandblock:X4} ({moved:F0}u from where the try began): not a teleport"); + } if (teleported) { AutoRun.Stop(); _portalWait = false; _lastLandMs = NowMs; - Host.Log($"[RynthNav] teleport detected (lb 0x{_prePortalLb:X4}->0x{CurrentLandblock:X4}, moved {moved:F0}u) — next leg"); + _lbCrossSaid = false; + ClockPortal(); + Host.Log($"[RynthNav] teleport detected (lb 0x{_prePortalLb:X4}->0x{CurrentLandblock:X4}, moved {moved:F0}u{(jumped ? $", a {jump:F0}u jump" : "")}" + + $"{(_wasPortaling ? ", portal space" : "")}) — next leg"); RefreshTiles(CurrentLandblock); // stream the area we landed in if (_enterName.Length > 0 && _route != null && _routeIdx >= _route.Count - 1) { @@ -913,6 +970,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase } _cooldownSaid = false; + // Right over (or under) a portal on another level with no way to its floor: not for ever. + if (GiveUpOnOtherLevel(d)) return; + _portalWaitTicks++; DriveIntoPortal(dew, dns, d); } @@ -921,6 +981,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase { if (_portals != null) return; var list = new List(); + int withRules = 0; try { string path = Path.Combine(NavDataDir, "portals.tsv"); @@ -928,18 +989,16 @@ public sealed partial class RynthNavPlugin : RynthPluginBase { foreach (var line in File.ReadAllLines(path)) { - if (string.IsNullOrWhiteSpace(line)) continue; - var f = line.Split('\t'); - if (f.Length < 4) continue; - if (!double.TryParse(f[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double sns)) continue; - if (!double.TryParse(f[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double sew)) continue; - if (!double.TryParse(f[2], NumberStyles.Float, CultureInfo.InvariantCulture, out double dns)) continue; - if (!double.TryParse(f[3], NumberStyles.Float, CultureInfo.InvariantCulture, out double dew)) continue; - string pname = f.Length > 4 ? f[4] : ""; - if (Entrance.IsDestroyed(pname)) continue; // wrecks take you nowhere - list.Add(new PortalLink(sns, sew, dns, dew, pname)); + // Who may use it (NavData from 11-19 on): minLevel, maxLevel, PortalBitmask. An older + // portals.tsv has none: every portal is then planned as open to anyone, as before. + if (!PortalLink.TryParseTsv(line, out PortalLink link, out bool rules)) continue; + if (Entrance.IsDestroyed(link.Name)) continue; // wrecks take you nowhere + if (rules) withRules++; + list.Add(link); } - Host.Log($"[RynthNav] loaded {list.Count} portals from portals.tsv"); + Host.Log($"[RynthNav] loaded {list.Count} portals from portals.tsv " + + (withRules > 0 ? $"({list.Count(p => p.HasRules)} with use rules)" + : "(no use rules in it: an older NavData; a refusal is learned instead)")); } else Host.Log("[RynthNav] portals.tsv not found — portal routing off"); } @@ -955,18 +1014,27 @@ public sealed partial class RynthNavPlugin : RynthPluginBase /// : use portals and recalls or not this once (null: the switch; the /// route maker's plan op). Tick thread. /// - private TravelPlan.Result PlanRoute(string name, double goalNs, double goalEw, out List recalls, bool? portals = null) + private TravelPlan.Result PlanRoute(string name, double goalNs, double goalEw, out List recalls, bool? portals = null, + bool ignoreChoice = false) { - bool portalsOn = portals ?? _portalsEnabled; + // The way chosen for this place (RynthNavPlugin.Ways.cs), unless asked for every way. + if (!ignoreChoice) ForgetWayChoice(goalNs, goalEw); + bool chosen = !ignoreChoice && SameWayTarget(goalNs, goalEw) && (_wayBans.Count > 0 || _wayWalk); + bool portalsOn = (portals ?? _portalsEnabled) && !(chosen && _wayWalk); double startNs = NavCoords.NsFromWorld(_wy), startEw = NavCoords.EwFromWorld(_wx); bool startOnMap = IsOnMap(_cellId); var recallNotes = new List(); + TripTimes times = PlanTimes(); // teleports costed by how long they take (RynthNavPlugin.TripTime.cs) recalls = _charKey.Length == 0 ? new List() : RecallPlanner.Build(_atlas, _known, _memory, _charKey, recallNotes); if (_charKey.Length == 0) recallNotes.Add("not logged in yet"); var hubNotes = new List(); - HubLinks? hub = portalsOn ? CurrentHubLinks(hubNotes) : null; + Traveller who = ReadTraveller(); + HubLinks? hub = portalsOn ? CurrentHubLinks(hubNotes, who) : null; if (hub != null && _preferAphus && _recallsEnabled) hub = ViaAphus(hub, recalls, hubNotes); if (portalsOn) EnsurePortalsLoaded(); + var banNotes = new List(); + HashSet bans = portalsOn ? PlanBans(who, banNotes) : new HashSet(StringComparer.Ordinal); + if (chosen) bans.UnionWith(_wayBans); // Walks that can't be done over land (another landmass) are left out, so an island or the // far side of water is only reached by a portal, a recall or the Town Network. NavGraph? g = UsableGraph(); @@ -974,17 +1042,36 @@ public sealed partial class RynthNavPlugin : RynthPluginBase : (ans, aew, bns, bew) => g.SameLand(NavGraph.LandblockAt(NavCoords.WorldX(aew), NavCoords.WorldY(ans)), NavGraph.LandblockAt(NavCoords.WorldX(bew), NavCoords.WorldY(bns))) != false; bool? land = startOnMap && g != null ? g.SameLand(CurrentLandblock, NavGraph.LandblockAt(NavCoords.WorldX(goalEw), NavCoords.WorldY(goalNs))) : null; + // Walks costed on the route graph, not as straight lines (RealWalk.cs): a portal landing on the far + // side of a ridge isn't a short walk from the goal (11-19, Mountain Shortcut and the Olthoi tents). + RealWalk? real = g != null && portalsOn ? new RealWalk(g, NavDataDir, startNs, startEw, _wz) : null; - TravelPlan.Result r = TravelPlan.Plan(portalsOn ? _portals : null, RecallPlanner.Links(recalls), hub, - portalsOn, _recallsEnabled, startOnMap, startNs, startEw, goalNs, goalEw, canWalk, land, name); + TravelPlan.Result r = TravelPlan.Plan(portalsOn ? _portals : null, RecallPlanner.Links(recalls, times), hub, + portalsOn, _recallsEnabled, startOnMap, startNs, startEw, goalNs, goalEw, canWalk, land, name, bans, MaxWays, + real == null ? null : real.Cost, times, real == null ? null : real.BestPlanned); + if (chosen && (r.Refusal.Length > 0 || r.Options.Count == 0)) + { + // The way chosen goes nowhere from here: the best way, and the choice forgotten. + Host.Log($"[RynthNav] plan {name}: {WayText()} has no way from here; planning the best way"); + _wayBans = new HashSet(StringComparer.Ordinal); _wayAvoids = new List(); _wayWalk = false; _wayIdx = 0; + return PlanRoute(name, goalNs, goalEw, out recalls, portals); + } + if (!ignoreChoice) KeepWays(r, name, goalNs, goalEw, chosen); Host.Log($"[RynthNav] plan {name}: {r.Basis}; {(portalsOn ? $"{_portals?.Count ?? 0} portals" : "no portals")}, " + $"{recalls.Count} recall(s) ready" + (recalls.Count > 0 ? " (" + string.Join(", ", recalls.ConvertAll(o => o.Name)) + ")" : "") + $", Town Network {(hub == null ? (portalsOn ? "not loaded" : "unused") : $"{hub.Entries.Count} entries / {hub.Exits.Count} exits")}" + $", land check {(canWalk == null ? "off (no route graph)" : "on")}" + + (real == null ? "" : $", walks costed on the route graph {real.Costed} of {real.Asked} ({real.Ms:F0} ms{(double.IsNaN(real.BestMs) ? "" : $", {real.BestMs:F0} for the best way")})") + + $", a portal {times.PortalSeconds + times.SpaceSeconds:F1} s, running {times.RunSpeed:F1} u/s" + (startOnMap ? "" : $" (in landblock 0x{CurrentLandblock:X4})")); foreach (string n in recallNotes) Host.Log($"[RynthNav] plan: recall left out: {n}"); foreach (string n in hubNotes) Host.Log($"[RynthNav] plan: {n}"); + foreach (string n in banNotes) Host.Log($"[RynthNav] plan: {n}"); + if (chosen) Host.Log($"[RynthNav] plan: the way chosen: {WayText()}"); + if (r.Options.Count > 1) + Host.Log($"[RynthNav] plan: {r.Options.Count} ways: " + string.Join("; ", r.Options.Select((o, i) => + $"{i + 1}. ~{o.Est:F0}u, {o.Teleports} teleport(s){(o.Avoids.Count > 0 ? " avoiding " + string.Join(", ", o.Avoids) : "")}"))); Host.Log(r.Refusal.Length > 0 ? $"[RynthNav] route to {name}: none: {r.Refusal}" : $"[RynthNav] route to {name}: {RouteLine(r.Steps, startNs, startEw, goalNs, goalEw, r.Est, land)}"); @@ -1034,7 +1121,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase // (AllowB below). Through the avoid filter, a big open-ground polygon that also reaches // another portal's circle hid the goal: 10-02 16:05, Lucy at the Lady Maila Estates Portal // in a cluster of housing portals: "no tile ahead", 74u short, on the collision-built tiles. - _query.FindNearestPoly(targetP, steer != null ? new RcVec3f(8, 32, 8) : new RcVec3f(12, 256, 12), filter, out long gRef, out RcVec3f gPt, out _); + long gRef; RcVec3f gPt; + // A portal in a cellar or a tunnel below the street: its own floor, when the walk reaches it (RynthNavPlugin.Ways.cs). + if (steer != null || !PortalFloorGoal(sRef, sPt, filter, out gRef, out gPt)) + _query.FindNearestPoly(targetP, steer != null ? new RcVec3f(8, 32, 8) : new RcVec3f(12, 256, 12), filter, out gRef, out gPt, out _); bool direct = gRef != 0 && steer == null; if (gRef == 0) gRef = FindGoalToward(aimEw, aimNs, out gPt); if (gRef == 0) { lock (_gate) _status = "no tile ahead — bake the route"; lock (_gotoGate) _gotoPath = null; return; } @@ -1042,8 +1132,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase Span p = new long[NavPathQuery.MaxPolys]; avoid.AllowB = gRef; // No way round the portals to there: planned as before; steering still keeps out of them. - int pc = NavPathQuery.Corridor(_query, sRef, gRef, sPt, gPt, avoid, filter, _avoid.Count > 0, p, out bool fellBack, out _); + int pc = NavPathQuery.Corridor(_query, sRef, gRef, sPt, gPt, avoid, filter, _avoid.Count > 0, p, out bool fellBack, out _, out bool plainTaken); if (fellBack && !_avoidFallbackSaid) { _avoidFallbackSaid = true; Host.Log("[RynthNav] avoid: no path round the portals here; steering round them instead"); } + if (plainTaken && !_avoidPlainSaid) { _avoidPlainSaid = true; Host.Log("[RynthNav] avoid: the way round the portals went far round; the plain path, clear of them all, is taken"); } Span sp = new DtStraightPath[512]; _query.FindStraightPath(sPt, gPt, p[..pc], pc, sp, out int spc, 512, 0); if (spc < 2) { lock (_gate) _status = "no path"; lock (_gotoGate) _gotoPath = null; return; } @@ -1224,6 +1315,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase sb.Append("\"runState\":").Append(_appliedRun).Append(','); sb.Append("\"turnState\":").Append(_appliedTurn).Append(','); sb.Append("\"goto\":").Append(_gotoActive ? 1 : 0).Append(','); + sb.Append("\"paused\":").Append(_gotoActive && _paused ? 1 : 0).Append(','); sb.Append("\"status\":\"").Append(Esc(status)).Append("\","); sb.Append("\"lastPath\":\"").Append(Esc(lastPath)).Append('"'); string travel; diff --git a/Plugins/RynthCore.Plugin.RynthNav/TownNet.cs b/Plugins/RynthCore.Plugin.RynthNav/TownNet.cs index 86914fb..90d8ac8 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/TownNet.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/TownNet.cs @@ -38,26 +38,26 @@ internal sealed class TownNetRules /// /// Why this character can't use the portal ("" = it can). Level 0 = not known yet: a portal with a /// level rule is then left out, since it can't be shown to be open. Rules the plugin can't check - /// (quests, player killer status, vitae) leave the portal out too. + /// (quests, player killer status or vitae not known yet) leave the portal out too. /// - public string Blocks(int level, bool olthoi) + public string Blocks(int level, bool olthoi) => Blocks(new Traveller(level, 0, olthoi, null)); + + /// As above, for a character whose PK status and vitae may be known (PortalRules). + public string Blocks(in Traveller t) { if (Closed) return "closed"; if (AdvocateOnly) return "advocates only"; if (Quest.Length > 0) return "needs a quest flag"; - if (olthoi && NoOlthoi) return "no Olthoi"; - if (!olthoi && OnlyOlthoi) return "Olthoi only"; - if (MinLevel > 0 || MaxLevel > 0) - { - if (level <= 0) return MinLevel > 0 ? $"needs level {MinLevel} (your level isn't known yet)" : $"level {MaxLevel} or lower (your level isn't known yet)"; - if (MinLevel > 0 && level < MinLevel) return $"needs level {MinLevel}"; - if (MaxLevel > 0 && level > MaxLevel) return $"level {MaxLevel} or lower"; - } - if (NoPk || NoPkLite || NoNpk) return "player killer rules"; - if (NoVitae) return "no vitae"; - if (NoNewAccounts || AccountRequirements > 1) return "account rules"; - return ""; + if (AccountRequirements > 1) return "account rules"; + string why = PortalRules.Refusal(MinLevel, MaxLevel, Bitmask, t); + return why; } + + /// These rules as a PortalBitmask (PortalRules), for the shared check. + private int Bitmask => + PortalRules.Unrestricted | (NoPk ? PortalRules.NoPk : 0) | (NoPkLite ? PortalRules.NoPkLite : 0) | (NoNpk ? PortalRules.NoNpk : 0) + | (OnlyOlthoi ? PortalRules.OnlyOlthoi : 0) | (NoOlthoi ? PortalRules.NoOlthoi : 0) | (NoVitae ? PortalRules.NoVitae : 0) + | (NoNewAccounts ? PortalRules.NoNewAccounts : 0); } internal sealed class TownNetEntry @@ -241,7 +241,10 @@ internal sealed class TownNet /// and exits in dungeons have no map position and are left out too (silently: they never could /// be on a map route). is the index into . /// - public HubLinks Links(int level, bool olthoi, List? notes) + public HubLinks Links(int level, bool olthoi, List? notes) => Links(new Traveller(level, 0, olthoi, null), notes); + + /// As above, for a character whose PK status and vitae may be known. + public HubLinks Links(in Traveller t, List? notes) { var hub = new HubLinks { Name = "Town Network", Arrivals = Arrivals.Count }; int entriesBlocked = 0; @@ -249,7 +252,7 @@ internal sealed class TownNet foreach (TownNetEntry e in Entries) { if (!e.OnMap || e.Arrival < 0) continue; - string why = e.Rules.Blocks(level, olthoi); + string why = e.Rules.Blocks(t); if (why.Length > 0) { entriesBlocked++; entryWhy = why; continue; } hub.Entries.Add(new HubEntry(e.Ns, e.Ew, e.Arrival, e.Name)); } @@ -259,7 +262,7 @@ internal sealed class TownNet { TownNetExit ex = Exits[x]; if (!ex.DestOnMap) continue; - string why = ex.Rules.Blocks(level, olthoi); + string why = ex.Rules.Blocks(t); if (why.Length > 0) { notes?.Add($"Town Network: {ex.Name} left out ({why})."); continue; } var walk = new double[Arrivals.Count]; bool any = false; diff --git a/Plugins/RynthCore.Plugin.RynthNav/TravelPlan.cs b/Plugins/RynthCore.Plugin.RynthNav/TravelPlan.cs index bca62d1..14a6a4a 100644 --- a/Plugins/RynthCore.Plugin.RynthNav/TravelPlan.cs +++ b/Plugins/RynthCore.Plugin.RynthNav/TravelPlan.cs @@ -15,6 +15,12 @@ namespace RynthCore.Plugin.RynthNav; /// portal at 86S). With no recall to cast, it refuses and says why. /// - Walks between landmasses are left out (canWalk); a target only reachable over water needs a /// portal, a recall or the Town Network. +/// - Bans: teleports this plan may not take (PortalRoute's keys): portals the server would refuse +/// this character (PortalRules), and ones it has refused already. +/// - Options: up to that many different ways (PortalRoute.PlanOptions), cheapest first; the first is +/// the plan itself. "Another way" in the panel and /rnav route next walk through them. +/// - walkCost: walks costed on the route graph (PortalRoute's real walk costs); null = straight lines. +/// - times: teleports costed by how long they take (TripTimes); null = the flat costs. /// internal static class TravelPlan { @@ -28,12 +34,33 @@ internal static class TravelPlan public string Refusal = ""; /// One line on what was allowed, for the log. public string Basis = ""; + /// The ways there, cheapest first (Options[0] is this plan); empty when there is none. + public readonly List