Snapshot for release 2026.11.2.1 (internal 03dbb32)
This commit is contained in:
parent
ce1cc11ebe
commit
79cbb84d61
77 changed files with 8622 additions and 224 deletions
|
|
@ -20,6 +20,9 @@ internal sealed class AvoidFilter : IDtQueryFilter
|
|||
|
||||
public AvoidFilter(PortalAvoid avoid) { _avoid = avoid; }
|
||||
|
||||
/// <summary>The circles this filter keeps out of.</summary>
|
||||
public PortalAvoid Portals => _avoid;
|
||||
|
||||
public bool PassFilter(long refs, DtMeshTile tile, DtPoly poly)
|
||||
{
|
||||
if (!_inner.PassFilter(refs, tile, poly)) return false;
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ internal sealed class NavCoarse
|
|||
private int _idx; // portals crossed so far
|
||||
public double GoalEw { get; }
|
||||
public double GoalNs { get; }
|
||||
/// <summary>The goal's height on the navmesh (NaN: not known, a route planned without a navmesh).</summary>
|
||||
public double GoalUp { get; private set; } = double.NaN;
|
||||
public float Cost { get; }
|
||||
public int Count => _portals.Count;
|
||||
public int Crossed => _idx;
|
||||
|
|
@ -57,12 +59,12 @@ internal sealed class NavCoarse
|
|||
internal sealed class Request
|
||||
{
|
||||
public int StartRegion, GoalRegion;
|
||||
public float Sx, Sz, Gx, Gz;
|
||||
public float Sx, Sz, Gx, Gz, Gy = float.NaN;
|
||||
public Dictionary<int, float> StartLegs = new(), GoalLegs = new();
|
||||
|
||||
public static Request Measure(NavGraph g, Probe start, Probe goal)
|
||||
{
|
||||
var r = new Request { StartRegion = start.Region, GoalRegion = goal.Region, Sx = start.Pt.X, Sz = start.Pt.Z, Gx = goal.Pt.X, Gz = goal.Pt.Z };
|
||||
var r = new Request { StartRegion = start.Region, GoalRegion = goal.Region, Sx = start.Pt.X, Sz = start.Pt.Z, Gx = goal.Pt.X, Gz = goal.Pt.Z, Gy = goal.Pt.Y };
|
||||
foreach (int p in g.RegionPortals(start.Region)) r.StartLegs[p] = start.WalkTo(g.Portal(p));
|
||||
if (start.Region != goal.Region)
|
||||
foreach (int p in g.RegionPortals(goal.Region)) r.GoalLegs[p] = goal.WalkTo(g.Portal(p));
|
||||
|
|
@ -76,7 +78,7 @@ internal sealed class NavCoarse
|
|||
List<int>? route = g.FindRoute(q.StartRegion, q.Sx, q.Sz, q.GoalRegion, q.Gx, q.Gz, out float cost, out expanded,
|
||||
startLeg: p => q.StartLegs.TryGetValue(p, out float c) ? c : float.NaN,
|
||||
goalLeg: p => q.GoalLegs.TryGetValue(p, out float c) ? c : float.NaN);
|
||||
return route == null ? null : new NavCoarse(g, route, q.StartRegion, q.Gx, q.Gz, cost);
|
||||
return route == null ? null : new NavCoarse(g, route, q.StartRegion, q.Gx, q.Gz, cost) { GoalUp = q.Gy };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -195,6 +197,64 @@ internal sealed class NavCoarse
|
|||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Can a walk from <paramref name="startRegion"/> end in <paramref name="region"/>, as far as the
|
||||
/// graph tells? The start's own region, or one with border links (portals) on the start's
|
||||
/// landmass. A region with no portal is a pocket nothing links into (ground fenced in by a
|
||||
/// building's walls, a roof, the top of a rock): the route search can never reach it.
|
||||
/// </summary>
|
||||
public static bool Reachable(NavGraph g, int startRegion, int region)
|
||||
{
|
||||
if (region < 0) return false;
|
||||
if (region == startRegion) return true;
|
||||
if (g.RegionPortals(region).Length == 0) return false;
|
||||
int cs = g.Component(startRegion), cr = g.Component(region);
|
||||
// Components not built, or the start on a roof or a ledge of its own: any linked region.
|
||||
if (cs < 0 || cr < 0 || g.ComponentSize(cs) < 8) return true;
|
||||
return cs == cr;
|
||||
}
|
||||
|
||||
private const int ProbeMaxPolys = 16384;
|
||||
|
||||
/// <summary>
|
||||
/// The goal end of a route: the polygon nearest (<paramref name="ew"/>, <paramref name="ns"/>), as
|
||||
/// <see cref="ProbeNear"/>, when a walk from <paramref name="startRegion"/> can end there; else
|
||||
/// the nearest polygon within <paramref name="reach"/> (then 96 units) that one can
|
||||
/// (<see cref="Reachable"/>), with <paramref name="moved"/> set; else the nearest polygon as
|
||||
/// before (the search then finds no route).
|
||||
///
|
||||
/// 11-01: a /loc on a spot fenced in by a building's walls (a pocket region of one polygon, no
|
||||
/// portals, the open ground 0.2 m lower and under 6 m away) was the goal of every search: "route:
|
||||
/// none ... (0 expanded)" from everywhere, and the walk fell back to heading straight for it,
|
||||
/// into a bridge, round in circles.
|
||||
/// </summary>
|
||||
public static Probe? ProbeReachable(NavGraph g, DtNavMesh nav, DtNavMeshQuery q, double ew, double up, double ns, float reach,
|
||||
IReadOnlyDictionary<uint, int[]> tileRegions, int startRegion, out bool moved)
|
||||
{
|
||||
moved = false;
|
||||
Probe? first = ProbeNear(g, nav, q, ew, up, ns, reach, tileRegions);
|
||||
if (first != null && Reachable(g, startRegion, first.Region)) return first;
|
||||
var filter = new DtQueryDefaultFilter();
|
||||
var centre = new RcVec3f((float)ew, (float)up, (float)ns);
|
||||
var polys = new long[ProbeMaxPolys];
|
||||
foreach (float r in new[] { reach, Math.Max(reach, 96f) })
|
||||
{
|
||||
q.QueryPolygons(centre, new RcVec3f(r, 512, r), filter, polys, out int pc, polys.Length);
|
||||
long bestRef = 0; RcVec3f bestPt = default; int bestRegion = -1; double best = double.MaxValue;
|
||||
for (int i = 0; i < pc; i++)
|
||||
{
|
||||
int region = RegionOf(g, nav, polys[i], tileRegions);
|
||||
if (!Reachable(g, startRegion, region)) continue;
|
||||
if (q.ClosestPointOnPoly(polys[i], centre, out RcVec3f cp, out _).Failed()) continue;
|
||||
// Flat distance first; height only breaks near-ties (a bridge deck over a road).
|
||||
double d = Math.Sqrt((cp.X - ew) * (cp.X - ew) + (cp.Z - ns) * (cp.Z - ns)) + 0.05 * Math.Abs(cp.Y - up);
|
||||
if (d < best) { best = d; bestRef = polys[i]; bestPt = cp; bestRegion = region; }
|
||||
}
|
||||
if (bestRef != 0) { moved = true; return new Probe(q, bestRef, bestPt, bestRegion); }
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
/// <summary>The graph region of a polygon of a loaded tile, or -1.</summary>
|
||||
public static int RegionOf(NavGraph g, DtNavMesh nav, long polyRef, IReadOnlyDictionary<uint, int[]> tileRegions)
|
||||
{
|
||||
|
|
@ -211,7 +271,16 @@ internal sealed class NavCoarse
|
|||
/// ground is within <paramref name="reach"/> units.
|
||||
/// </summary>
|
||||
public static Probe? ProbeFile(NavGraph g, string navDataDir, double ew, double up, double ns, float reach)
|
||||
=> ProbeFile(g, navDataDir, ew, up, ns, reach, -1, out _);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ProbeFile(NavGraph, string, double, double, double, float)"/>; with a
|
||||
/// <paramref name="startRegion"/> (not -1) it picks ground a walk from there can end on
|
||||
/// (<see cref="ProbeReachable"/>).
|
||||
/// </summary>
|
||||
public static Probe? ProbeFile(NavGraph g, string navDataDir, double ew, double up, double ns, float reach, int startRegion, out bool moved)
|
||||
{
|
||||
moved = false;
|
||||
int x = (int)Math.Floor(ew / 192.0), y = (int)Math.Floor(ns / 192.0);
|
||||
if (x < 0 || x > 255 || y < 0 || y > 255) return null;
|
||||
uint lb = (uint)((x << 8) | y);
|
||||
|
|
@ -226,6 +295,9 @@ internal sealed class NavCoarse
|
|||
var prm = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = 2, maxPolys = 1 << 16 };
|
||||
nav.Init(ref prm, 6);
|
||||
nav.AddTile(md, 0, 0, out _);
|
||||
return ProbeNear(g, nav, new DtNavMeshQuery(nav), ew, float.IsFinite((float)up) ? up : 0, ns, reach, regions);
|
||||
double u = float.IsFinite((float)up) ? up : 0;
|
||||
return startRegion < 0
|
||||
? ProbeNear(g, nav, new DtNavMeshQuery(nav), ew, u, ns, reach, regions)
|
||||
: ProbeReachable(g, nav, new DtNavMeshQuery(nav), ew, u, ns, reach, regions, startRegion, out moved);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
311
Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs
Normal file
311
Plugins/RynthCore.Plugin.RynthNav/NavPathQuery.cs
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// The navmesh steps a walk is planned with, shared by RynthNav's own walker (Replan) and the
|
||||
/// "RynthNav.Path" interface (Shared/RynthNavPathApi.cs) v2: the start snapped close up first and
|
||||
/// only then wide, the corridor kept off portals with the plain filter as the fallback, the corners
|
||||
/// bent round portals and pushed out from walls, and (FindPathEx, Raycast) the finished path's
|
||||
/// length and end. Host-free (Detour only): the graph tests drive it on baked floors. Tick thread
|
||||
/// in the plugin. World units in and out: x east, y north, z height (Detour's x, z, y).
|
||||
/// </summary>
|
||||
internal static class NavPathQuery
|
||||
{
|
||||
public const int MaxPolys = 512;
|
||||
/// <summary>FindPathEx's straight path before bends (FindPath v1's cap too).</summary>
|
||||
public const int MaxStraightCorners = 256;
|
||||
/// <summary>A path ending farther than this from the snapped goal didn't get there (partial).</summary>
|
||||
public const double GoalSlackUnits = 6.0;
|
||||
/// <summary>The tile box FindPath loads, and FindPathEx with maxTiles 0: at most a 5x5 block.</summary>
|
||||
public const int DefaultMaxTiles = 25;
|
||||
/// <summary>FindPathEx's maxTiles is held to this (a 7x7 block, ~14 MB of tile files the first time).</summary>
|
||||
public const int MaxTilesCap = 49;
|
||||
|
||||
/// <summary>The ground we stand on: the mesh keeps the agent radius (2 m) from walls, so close up it's within that, at our height.</summary>
|
||||
public static readonly RcVec3f TightStartExtents = new(2.5f, 4, 2.5f);
|
||||
/// <summary>Then the wide search, which can pick ground on the far side of a thin wall or a roof overhead.</summary>
|
||||
public static readonly RcVec3f WideExtents = new(8, 64, 8);
|
||||
private static readonly RcVec3f OnMeshExtents = new(0.5f, 24, 0.5f);
|
||||
private static readonly RcVec3f PushExtents = new(0.3f, 24, 0.3f);
|
||||
|
||||
/// <summary>
|
||||
/// Whether RynthPluginQueryInterface hands out the "RynthNav.Path" table for a request: any version
|
||||
/// from 1 up to the one built. The table is append-only, so a v1 caller gets the v2 table and uses
|
||||
/// only the fields it knows (callers check Version and StructSize before a later field).
|
||||
/// </summary>
|
||||
public static bool ServesInterface(string? iface, uint version) =>
|
||||
iface == RynthNavPathApiV1.InterfaceName && version >= 1 && version <= RynthNavPathApiV1.InterfaceVersion;
|
||||
|
||||
/// <summary>FindPathEx's maxTiles: 0 (or less) = the default 25, else at most <see cref="MaxTilesCap"/>.</summary>
|
||||
public static int ClampMaxTiles(int maxTiles) => maxTiles <= 0 ? DefaultMaxTiles : Math.Min(maxTiles, MaxTilesCap);
|
||||
|
||||
/// <summary>
|
||||
/// The landblock box to load for a query from (sx, sy) to (gx, gy): both ends' landblocks and every one
|
||||
/// between, plus a one-tile margin (room for a path that goes round). False when that is more than
|
||||
/// <paramref name="maxTiles"/>; with <paramref name="shrinkMargin"/> the box without the margin is
|
||||
/// tried first (FindPathEx, Raycast), without it the answer is no (FindPath v1).
|
||||
/// </summary>
|
||||
public static bool TileBox(double sx, double sy, double gx, double gy, int maxTiles, bool shrinkMargin,
|
||||
out int minX, out int minY, out int maxX, out int maxY)
|
||||
{
|
||||
int sLbX = Lb(sx), sLbY = Lb(sy), gLbX = Lb(gx), gLbY = Lb(gy);
|
||||
for (int margin = 1; margin >= (shrinkMargin ? 0 : 1); margin--)
|
||||
{
|
||||
minX = Math.Max(0, Math.Min(sLbX, gLbX) - margin); maxX = Math.Min(255, Math.Max(sLbX, gLbX) + margin);
|
||||
minY = Math.Max(0, Math.Min(sLbY, gLbY) - margin); maxY = Math.Min(255, Math.Max(sLbY, gLbY) + margin);
|
||||
if ((maxX - minX + 1) * (maxY - minY + 1) <= maxTiles) return true;
|
||||
}
|
||||
minX = minY = maxX = maxY = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int Lb(double world) => (int)Math.Clamp(Math.Floor(world / 192.0), 0, 255);
|
||||
|
||||
/// <summary>The polygon under <paramref name="p"/> (Detour axes): close up first, then the wide search.</summary>
|
||||
public static long SnapStart(DtNavMeshQuery q, RcVec3f p, IDtQueryFilter filter, out RcVec3f pt)
|
||||
{
|
||||
q.FindNearestPoly(p, TightStartExtents, filter, out long r, out pt, out _);
|
||||
if (r == 0) q.FindNearestPoly(p, WideExtents, filter, out r, out pt, out _);
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The polygon corridor from sRef to gRef through <paramref name="first"/>; when that doesn't reach
|
||||
/// the goal and <paramref name="fallback"/> is set (the first filter keeps out of portals), planned
|
||||
/// again through <paramref name="plain"/> (<paramref name="fellBack"/>). <paramref name="status"/> is
|
||||
/// the last FindPath's (its partial flag included).
|
||||
/// </summary>
|
||||
public static int Corridor(DtNavMeshQuery q, long sRef, long gRef, RcVec3f sPt, RcVec3f gPt,
|
||||
IDtQueryFilter first, IDtQueryFilter plain, bool fallback, Span<long> polys,
|
||||
out bool fellBack, out DtStatus status)
|
||||
{
|
||||
fellBack = false;
|
||||
status = q.FindPath(sRef, gRef, sPt, gPt, first, polys, out int pc, polys.Length);
|
||||
if ((pc == 0 || polys[pc - 1] != gRef) && fallback)
|
||||
{
|
||||
// No way round the portals to there: plan as before (the caller's steering keeps out of them).
|
||||
status = q.FindPath(sRef, gRef, sPt, gPt, plain, polys, out pc, polys.Length);
|
||||
fellBack = true;
|
||||
}
|
||||
return pc;
|
||||
}
|
||||
|
||||
/// <summary>On the mesh = inside a polygon (the nearest point on the mesh is the point itself), not merely near one.</summary>
|
||||
public static bool OnMesh(DtNavMeshQuery q, IDtQueryFilter filter, double x, double y, float z)
|
||||
{
|
||||
q.FindNearestPoly(new RcVec3f((float)x, z, (float)y), OnMeshExtents, filter, out long r, out RcVec3f np, out _);
|
||||
return r != 0 && Math.Abs(np.X - x) < 0.05 && Math.Abs(np.Z - y) < 0.05;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path (east, north corners) bent round any portal it still crosses (big open-ground polygons
|
||||
/// let it cut straight over one): <see cref="PortalAvoid.Bend"/> with corners and legs only on the mesh
|
||||
/// (a leg is on the mesh when every metre of it is). <paramref name="zAt"/>: the height to look at.
|
||||
/// </summary>
|
||||
public static List<(double X, double Y)> BendRoundPortals(DtNavMeshQuery q, PortalAvoid portals, List<(double X, double Y)> wps,
|
||||
IDtQueryFilter filter, Func<double, double, float> zAt)
|
||||
{
|
||||
bool OnMeshAt(double x, double y) => OnMesh(q, filter, x, y, zAt(x, y));
|
||||
bool LegOnMesh(double ax, double ay, double bx, double by)
|
||||
{
|
||||
double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
|
||||
int n = Math.Max(1, (int)Math.Ceiling(len));
|
||||
for (int k = 1; k < n; k++)
|
||||
if (!OnMeshAt(ax + (bx - ax) * k / n, ay + (by - ay) * k / n)) return false;
|
||||
return true;
|
||||
}
|
||||
return portals.Bend(wps, OnMeshAt, 12, LegOnMesh);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Walls: each corner the path turns round sits on the mesh's edge (the agent radius from a building);
|
||||
/// push it <paramref name="clearance"/> out along the turn's outside bisector where the ground is
|
||||
/// walkable (inside a polygon, not merely near it: near it, the moved corner could sit closer to the
|
||||
/// wall than the body is wide). In place, first corner to last; the ends never move. Returns how many moved.
|
||||
/// </summary>
|
||||
public static int PushFromWalls(DtNavMeshQuery q, List<(double X, double Y)> wps, double clearance,
|
||||
IDtQueryFilter filter, Func<double, double, float> zAt)
|
||||
{
|
||||
if (clearance <= 0 || wps.Count <= 2) return 0;
|
||||
int moved = 0;
|
||||
for (int i = 1; i < wps.Count - 1; i++)
|
||||
{
|
||||
var (px, py) = wps[i]; var (ax, ay) = wps[i - 1]; var (bx, by) = wps[i + 1];
|
||||
double ux = ax - px, uy = ay - py, ul = Math.Sqrt(ux * ux + uy * uy);
|
||||
double vx = bx - px, vy = by - py, vl = Math.Sqrt(vx * vx + vy * vy);
|
||||
if (ul < 0.5 || vl < 0.5) continue;
|
||||
double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy);
|
||||
if (ol < 0.05) continue; // straight on: no corner to clear
|
||||
double nx = px + ox / ol * clearance, ny = py + oy / ol * clearance;
|
||||
q.FindNearestPoly(new RcVec3f((float)nx, zAt(nx, ny), (float)ny), PushExtents, filter, out long rr, out RcVec3f rp, out _);
|
||||
if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) { wps[i] = (nx, ny); moved++; }
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "RynthNav.Path" FindPathEx on the tiles already loaded: from (sx, sy, sz) to (gx, gy, gz) with the
|
||||
/// Path* <paramref name="flags"/>; <paramref name="portals"/> (its circles already set) for
|
||||
/// PathAvoidPortals, <paramref name="wallClearance"/> for PathWallClearance. At most
|
||||
/// <paramref name="maxCorners"/> corners. Fills <paramref name="r"/> and returns its code: ResultOk,
|
||||
/// ResultPartial (PathAllowPartial only), ResultNoPath, or ResultNoMesh (no mesh at either end).
|
||||
/// </summary>
|
||||
public static int FindPathEx(DtNavMeshQuery q, double sx, double sy, double sz, double gx, double gy, double gz,
|
||||
int flags, int maxCorners, AvoidFilter? portals, double wallClearance, PathExResult r)
|
||||
{
|
||||
r.Reset();
|
||||
var plain = new DtQueryDefaultFilter();
|
||||
long sRef = SnapStart(q, new RcVec3f((float)sx, (float)sz, (float)sy), plain, out RcVec3f sPt);
|
||||
if (sRef == 0) return r.Fail(RynthNavPathApiV1.ResultNoMesh, "no navmesh at the start");
|
||||
// The goal is looked up WITHOUT the portal circles; its polygon is always allowed (AllowB), as Replan.
|
||||
q.FindNearestPoly(new RcVec3f((float)gx, (float)gz, (float)gy), WideExtents, plain, out long gRef, out RcVec3f gPt, out _);
|
||||
if (gRef == 0) return r.Fail(RynthNavPathApiV1.ResultNoMesh, "no navmesh at the goal");
|
||||
|
||||
bool avoid = (flags & RynthNavPathApiV1.PathAvoidPortals) != 0 && portals != null && portals.Portals.Count > 0;
|
||||
if (avoid) { portals!.AllowA = sRef; portals.AllowB = gRef; }
|
||||
r.Portals = avoid ? portals!.Portals.Count : 0;
|
||||
|
||||
Span<long> polys = new long[MaxPolys];
|
||||
IDtQueryFilter first = avoid ? portals! : plain;
|
||||
int pc = Corridor(q, sRef, gRef, sPt, gPt, first, plain, avoid, polys, out bool fellBack, out DtStatus st);
|
||||
r.Polys = pc; r.FellBack = fellBack;
|
||||
if (st.Failed() || pc == 0) return r.Fail(RynthNavPathApiV1.ResultNoPath, "no way on the navmesh");
|
||||
// Detour's partial result: the corridor ends at the polygon nearest the goal it could reach.
|
||||
bool partial = st.IsPartial() || polys[pc - 1] != gRef;
|
||||
|
||||
Span<DtStraightPath> sp = new DtStraightPath[MaxStraightCorners];
|
||||
DtStatus sst = q.FindStraightPath(sPt, gPt, polys[..pc], pc, sp, out int spc, MaxStraightCorners, 0);
|
||||
if (sst.Failed() || spc < 1) return r.Fail(RynthNavPathApiV1.ResultNoPath, "no straight path");
|
||||
r.Truncated = sst.Has(DtStatus.DT_BUFFER_TOO_SMALL);
|
||||
RcVec3f end = sp[spc - 1].pos;
|
||||
double slackE = end.X - gPt.X, slackN = end.Z - gPt.Z;
|
||||
if (Math.Sqrt(slackE * slackE + slackN * slackN) > GoalSlackUnits) partial = true;
|
||||
if (partial && (flags & RynthNavPathApiV1.PathAllowPartial) == 0)
|
||||
return r.Fail(RynthNavPathApiV1.ResultNoPath, r.Truncated ? "more corners than it plans" : "the goal can't be reached");
|
||||
|
||||
var wps = new List<(double X, double Y)>(spc + 4);
|
||||
var ox = new double[Math.Max(spc, 2)]; var oy = new double[ox.Length]; var oz = new double[ox.Length];
|
||||
for (int i = 0; i < spc; i++)
|
||||
{
|
||||
wps.Add((sp[i].pos.X, sp[i].pos.Z));
|
||||
ox[i] = sp[i].pos.X; oy[i] = sp[i].pos.Z; oz[i] = sp[i].pos.Y;
|
||||
}
|
||||
if (spc == 1) { wps.Add(wps[0]); ox[1] = ox[0]; oy[1] = oy[0]; oz[1] = oz[0]; } // start and goal in one spot
|
||||
// Heights for the mesh tests at a bend or a pushed corner: the nearest straight-path corner's.
|
||||
float ZAt(double x, double y)
|
||||
{
|
||||
int best = 0; double bd = double.MaxValue;
|
||||
for (int i = 0; i < ox.Length; i++)
|
||||
{
|
||||
double d = (ox[i] - x) * (ox[i] - x) + (oy[i] - y) * (oy[i] - y);
|
||||
if (d < bd) { bd = d; best = i; }
|
||||
}
|
||||
return (float)oz[best];
|
||||
}
|
||||
|
||||
if (avoid)
|
||||
{
|
||||
int before = wps.Count;
|
||||
wps = BendRoundPortals(q, portals!.Portals, wps, plain, ZAt);
|
||||
r.Bent = wps.Count - before;
|
||||
}
|
||||
if ((flags & RynthNavPathApiV1.PathWallClearance) != 0) r.Pushed = PushFromWalls(q, wps, wallClearance, plain, ZAt);
|
||||
|
||||
int limit = Math.Max(2, maxCorners);
|
||||
if (wps.Count > limit)
|
||||
{
|
||||
if ((flags & RynthNavPathApiV1.PathAllowPartial) == 0)
|
||||
return r.Fail(RynthNavPathApiV1.ResultNoPath, $"{wps.Count} corners, room for {limit}");
|
||||
wps.RemoveRange(limit, wps.Count - limit); // the first stretch of the way; plan again from its end
|
||||
partial = true; r.Truncated = true;
|
||||
}
|
||||
|
||||
for (int i = 0; i < wps.Count; i++)
|
||||
{
|
||||
var (x, y) = wps[i];
|
||||
double z = double.NaN;
|
||||
for (int k = 0; k < ox.Length && double.IsNaN(z); k++)
|
||||
if (ox[k] == x && oy[k] == y) z = oz[k]; // a corner Detour gave: its own height
|
||||
if (double.IsNaN(z)) z = HeightAt(q, plain, x, y, ZAt(x, y));
|
||||
r.Corners.Add((x, y, z));
|
||||
if (i > 0)
|
||||
{
|
||||
var a = r.Corners[i - 1];
|
||||
r.Length += Math.Sqrt((x - a.X) * (x - a.X) + (y - a.Y) * (y - a.Y) + (z - a.Z) * (z - a.Z));
|
||||
}
|
||||
}
|
||||
var last = r.Corners[^1];
|
||||
r.EndDistance = Math.Sqrt((gx - last.X) * (gx - last.X) + (gy - last.Y) * (gy - last.Y) + (gz - last.Z) * (gz - last.Z));
|
||||
r.Partial = partial;
|
||||
r.Code = partial ? RynthNavPathApiV1.ResultPartial : RynthNavPathApiV1.ResultOk;
|
||||
return r.Code;
|
||||
}
|
||||
|
||||
/// <summary>The mesh's height under (x, y) near <paramref name="zGuess"/>; the guess when there's no polygon there.</summary>
|
||||
private static double HeightAt(DtNavMeshQuery q, IDtQueryFilter filter, double x, double y, float zGuess)
|
||||
{
|
||||
q.FindNearestPoly(new RcVec3f((float)x, zGuess, (float)y), OnMeshExtents, filter, out long r, out RcVec3f np, out _);
|
||||
return r != 0 ? np.Y : zGuess;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "RynthNav.Path" Raycast on the tiles already loaded: a Detour raycast along the mesh surface from
|
||||
/// the start's polygon (snapped as FindPathEx's start) toward the goal. RayClear when it reaches the
|
||||
/// goal's spot (Detour's hit parameter 1 or more: no wall in the way), RayBlocked when it hits the
|
||||
/// mesh's edge first (a wall, a building, a drop), ResultNoMesh when either end has no mesh.
|
||||
/// <paramref name="t"/>: how far along it got (0..1; float.MaxValue = all the way).
|
||||
/// </summary>
|
||||
public static int Raycast(DtNavMeshQuery q, double sx, double sy, double sz, double gx, double gy, double gz, out float t)
|
||||
{
|
||||
t = 0;
|
||||
var plain = new DtQueryDefaultFilter();
|
||||
long sRef = SnapStart(q, new RcVec3f((float)sx, (float)sz, (float)sy), plain, out RcVec3f sPt);
|
||||
if (sRef == 0) return RynthNavPathApiV1.ResultNoMesh;
|
||||
var goal = new RcVec3f((float)gx, (float)gz, (float)gy);
|
||||
q.FindNearestPoly(goal, WideExtents, plain, out long gRef, out _, out _);
|
||||
if (gRef == 0) return RynthNavPathApiV1.ResultNoMesh;
|
||||
// The visited polygons aren't needed; a full buffer only sets a flag, the ray goes on.
|
||||
Span<long> visited = stackalloc long[64];
|
||||
DtStatus st = q.Raycast(sRef, sPt, goal, plain, out t, out _, visited, out _, visited.Length);
|
||||
if (st.Failed()) return RynthNavPathApiV1.RayBlocked;
|
||||
return t >= 1f ? RynthNavPathApiV1.RayClear : RynthNavPathApiV1.RayBlocked;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>FindPathEx's answer: the corners (east, north, height) and what the info array and the log line say.</summary>
|
||||
internal sealed class PathExResult
|
||||
{
|
||||
public int Code;
|
||||
public readonly List<(double X, double Y, double Z)> Corners = new();
|
||||
/// <summary>The sum of the legs (3D), world units.</summary>
|
||||
public double Length;
|
||||
/// <summary>From the last corner to the requested goal (3D), world units.</summary>
|
||||
public double EndDistance;
|
||||
public bool Partial, Truncated, FellBack;
|
||||
public int Polys, Portals, Bent, Pushed;
|
||||
public string Note = "";
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Code = RynthNavPathApiV1.ResultNoPath;
|
||||
Corners.Clear();
|
||||
Length = EndDistance = 0;
|
||||
Partial = Truncated = FellBack = false;
|
||||
Polys = Portals = Bent = Pushed = 0;
|
||||
Note = "";
|
||||
}
|
||||
|
||||
public int Fail(int code, string note)
|
||||
{
|
||||
Corners.Clear();
|
||||
Length = EndDistance = 0;
|
||||
Partial = false;
|
||||
Code = code; Note = note;
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ using System;
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
|
|
@ -10,20 +11,25 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
/// table RynthPluginQueryInterface hands out. The functions run on the plugin pump
|
||||
/// thread (the caller's OnTick) and act on the current plugin instance, so the table
|
||||
/// survives a re-Init. <see cref="Release"/> frees it at RynthPluginShutdown.
|
||||
/// Version 2 (2026-10-23) appends FindPathEx and Raycast; a caller asking for version 1
|
||||
/// gets the same table (it checks Version/StructSize before a field past the ones it knows).
|
||||
/// </summary>
|
||||
internal static unsafe class PathInterface
|
||||
{
|
||||
private static RynthNavPathApiV1* _table;
|
||||
private static long _lastErrorLogMs;
|
||||
|
||||
public static IntPtr Query(string iface, uint version)
|
||||
{
|
||||
if (iface != RynthNavPathApiV1.InterfaceName || version != RynthNavPathApiV1.InterfaceVersion) return IntPtr.Zero;
|
||||
if (!NavPathQuery.ServesInterface(iface, version)) return IntPtr.Zero;
|
||||
if (_table == null)
|
||||
{
|
||||
var t = (RynthNavPathApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthNavPathApiV1));
|
||||
t->Version = RynthNavPathApiV1.InterfaceVersion;
|
||||
t->StructSize = (uint)sizeof(RynthNavPathApiV1);
|
||||
t->FindPath = &FindPath;
|
||||
t->FindPathEx = &FindPathEx;
|
||||
t->Raycast = &Raycast;
|
||||
_table = t;
|
||||
}
|
||||
return (IntPtr)_table;
|
||||
|
|
@ -53,4 +59,59 @@ internal static unsafe class PathInterface
|
|||
return RynthNavPathApiV1.ResultNoMesh;
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int FindPathEx(double sx, double sy, double sz, double gx, double gy, double gz, int flags, int maxTiles,
|
||||
double* points, int maxPoints, int* count, double* info)
|
||||
{
|
||||
try
|
||||
{
|
||||
Clear(count, info);
|
||||
var p = PluginExports.Runtime.Plugin;
|
||||
if (p == null) return RynthNavPathApiV1.ResultNoMesh;
|
||||
return p.InterfaceFindPathEx(sx, sy, sz, gx, gy, gz, flags, maxTiles, points, maxPoints, count, info);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Clear(count, info); // no half-written path counts
|
||||
LogError("FindPathEx", ex);
|
||||
return RynthNavPathApiV1.ResultNoMesh;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>FindPathEx's outputs before an answer: no corners, info all 0.</summary>
|
||||
private static void Clear(int* count, double* info)
|
||||
{
|
||||
if (count != null) *count = 0;
|
||||
if (info != null) for (int i = 0; i < RynthNavPathApiV1.InfoLength; i++) info[i] = 0;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int Raycast(double sx, double sy, double sz, double gx, double gy, double gz)
|
||||
{
|
||||
try
|
||||
{
|
||||
var p = PluginExports.Runtime.Plugin;
|
||||
if (p == null) return RynthNavPathApiV1.ResultNoMesh;
|
||||
return p.InterfaceRaycast(sx, sy, sz, gx, gy, gz);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogError("Raycast", ex);
|
||||
return RynthNavPathApiV1.ResultNoMesh;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A failure inside an interface call, logged at most every 10 s (a caller may ask many times a second).</summary>
|
||||
private static void LogError(string what, Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (now - _lastErrorLogMs < 10_000) return;
|
||||
_lastErrorLogMs = now;
|
||||
PluginExports.Runtime.Plugin?.LogFromExport($"[RynthNav] path interface: {what} failed: {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
catch { /* never throw out of a native export */ }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,8 +14,9 @@ public static unsafe class PluginExports
|
|||
{
|
||||
internal static readonly RynthPluginRuntime<RynthNavPlugin> Runtime = new();
|
||||
|
||||
// Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthNav.Path" v1
|
||||
// (RynthAi plans stuck-recovery detours with it). Fixed signature: void* (const char* iface, uint version).
|
||||
// Typed interfaces for other plugins (host GetPluginInterface, API v68): "RynthNav.Path" v2, also
|
||||
// handed to v1 callers (RynthAi plans stuck-recovery detours with FindPath, and its outdoor hunting
|
||||
// walks with FindPathEx and Raycast). Fixed signature: void* (const char* iface, uint version).
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -46,7 +46,9 @@ public sealed partial class RynthNavPlugin
|
|||
long now = NowMs;
|
||||
if (!force && now < _nextAvoidMs) return;
|
||||
_nextAvoidMs = now + AvoidRefreshMs;
|
||||
if (!_avoidPortals) { _avoid.Clear(); return; }
|
||||
// What the walk ran into on this leg (RynthNavPlugin.Blocked.cs) is kept out of like a
|
||||
// portal, whatever the portals setting.
|
||||
if (!_avoidPortals) { _avoid.Set(_blockedSpots, Array.Empty<PortalAvoid.Spot>()); return; }
|
||||
|
||||
IReadOnlyList<PortalAvoid.Spot> atlasPortals = AtlasPortalSpots();
|
||||
var map = new List<PortalAvoid.Spot>();
|
||||
|
|
@ -54,27 +56,38 @@ public sealed partial class RynthNavPlugin
|
|||
if (Math.Abs(sp.X - _wx) < AvoidNearUnits && Math.Abs(sp.Y - _wy) < AvoidNearUnits) map.Add(sp);
|
||||
|
||||
var live = new List<PortalAvoid.Spot>();
|
||||
if (Host.HasGetLiveObjectIds)
|
||||
{
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue;
|
||||
if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out _) || cell == 0) continue;
|
||||
double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y;
|
||||
if (Math.Abs(wx - _wx) > AvoidNearUnits || Math.Abs(wy - _wy) > AvoidNearUnits) continue;
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
live.Add(new PortalAvoid.Spot(wx, wy, PortalAvoid.LiveRadius, name ?? ""));
|
||||
}
|
||||
}
|
||||
LivePortalSpots(live, _wx - AvoidNearUnits, _wy - AvoidNearUnits, _wx + AvoidNearUnits, _wy + AvoidNearUnits);
|
||||
|
||||
// The step's own target: walking into a portal (a route's portal step, a dungeon's entrance).
|
||||
bool portalLeg = _route != null && _routeIdx < _route.Count && _route[_routeIdx].UsePortal;
|
||||
int portals = live.Count, mapPortals = map.Count;
|
||||
map.AddRange(_blockedSpots); // after the live portals: one inside a live portal's circle adds nothing
|
||||
if (portalLeg) _avoid.Set(live, map, _gotoTew, _gotoTns, AvoidTargetUnits);
|
||||
else _avoid.Set(live, map);
|
||||
if (_avoid.Count != _avoidLogged)
|
||||
{
|
||||
_avoidLogged = _avoid.Count;
|
||||
Host.Log($"[RynthNav] avoid: {_avoid.Count} portal(s) near you to keep out of ({live.Count} seen, {map.Count} from the Atlas){(portalLeg ? "; the step's own portal excepted" : "")}");
|
||||
string blocked = _blockedSpots.Count > 0 ? $", {_blockedSpots.Count} spot(s) it ran into" : "";
|
||||
Host.Log($"[RynthNav] avoid: {_avoid.Count} spot(s) near you to keep out of ({portals} portal(s) seen, {mapPortals} from the Atlas{blocked}){(portalLeg ? "; the step's own portal excepted" : "")}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every portal object the client knows standing in the box (world units, edges included), as
|
||||
/// circles of <see cref="PortalAvoid.LiveRadius"/>: exact positions. The walker's set and
|
||||
/// FindPathEx's (RynthNavPlugin.PathApi.cs) both start from these.
|
||||
/// </summary>
|
||||
private void LivePortalSpots(List<PortalAvoid.Spot> into, double minX, double minY, double maxX, double maxY)
|
||||
{
|
||||
if (!Host.HasGetLiveObjectIds) return;
|
||||
foreach (uint id in Host.GetLiveObjectIds())
|
||||
{
|
||||
if (!Host.TryGetItemType(id, out uint type) || (type & ItemTypePortal) == 0) continue;
|
||||
if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out _) || cell == 0) continue;
|
||||
double wx = ((cell >> 24) & 0xFF) * 192.0 + x, wy = ((cell >> 16) & 0xFF) * 192.0 + y;
|
||||
if (wx < minX || wx > maxX || wy < minY || wy > maxY) continue;
|
||||
Host.TryGetObjectName(id, out string name);
|
||||
into.Add(new PortalAvoid.Spot(wx, wy, PortalAvoid.LiveRadius, name ?? ""));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
|
|
@ -9,28 +11,38 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
// little islands (Shoushi's plaza, where the Town Network drops you, 10-08); where the plan runs
|
||||
// out the walk heads straight for its goal for a moment (BlindPushTicks), and that, or a wall the
|
||||
// mesh doesn't show, used to mean running into it until the 30 s progress watchdog. Now: blocked
|
||||
// for StuckWindowMs = turn away at an angle (alternating sides), plan again, and after
|
||||
// StuckMaxTries on one leg without progress stop and say where.
|
||||
// for StuckWindowMs = turn away toward open ground (WalkSteer.UnstickHeading), remember the spot as
|
||||
// something to keep out of (the next plan bends round it, like round a portal), plan again, and
|
||||
// after StuckMaxTries on one leg without progress stop and say where.
|
||||
//
|
||||
// 11-01, at a bridge the navmesh doesn't show (flat open ground in the tile, nothing in the way):
|
||||
// it turned 120 degrees off, alternating sides, ran 1.6 s, planned the same path again and ran back
|
||||
// into the same spot, four times in 20 s, then stopped. The remembered spots now make each new
|
||||
// plan go round what it ran into.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const long StuckWindowMs = 1200; // running this long...
|
||||
private const double StuckMoveUnits = 0.6; // ...and moved less than this = blocked (a run covers 4+ u/s)
|
||||
private const long UnstickMs = 1600; // then turn away from it and run this long (~0.5 s of it turning)
|
||||
private const double UnstickAngleDeg = 120.0; // away from where it was heading, off to one side
|
||||
private const int StuckMaxTries = 4; // blocked this often on a leg without progress = stop
|
||||
private const double BlockedAheadUnits = 3.5; // the remembered spot: this far ahead of where it stuck...
|
||||
private const double BlockedRadiusUnits = 2.5; // ...this big (the character stays outside it)
|
||||
private const int BlockedMaxSpots = 12;
|
||||
private const double UnstickOpenUnits = 6.0; // a way out is open ground this far along it
|
||||
|
||||
private bool _ranLastTick; // the walk asked to run last tick (not standing, not turning in place)
|
||||
private double _lastDriveDeg;
|
||||
private long _stuckWinMs, _unstickUntilMs;
|
||||
private double _stuckWx, _stuckWy, _unstickDeg;
|
||||
private int _stuckTries, _stuckSide = 1;
|
||||
private readonly List<PortalAvoid.Spot> _blockedSpots = new();
|
||||
|
||||
/// <summary>DriveTo for the walk's own steering: remembers that it ran and which way.</summary>
|
||||
private void WalkDrive(double deg)
|
||||
{
|
||||
DriveTo(deg);
|
||||
DriveTo(deg, _steerOpen);
|
||||
_lastDriveDeg = deg;
|
||||
_ranLastTick = !_turnInPlace;
|
||||
_ranLastTick = !_steerOpen.TurnInPlace;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -53,11 +65,36 @@ public sealed partial class RynthNavPlugin
|
|||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A straight walk from (ax, ay) to (bx, by) stays on the navmesh (Detour's raycast along the
|
||||
/// polygons from the one underfoot: no mesh edge, so at least the 2 m agent radius from every
|
||||
/// wall it knows) and out of every circle being kept out of. False without a query or ground underfoot.
|
||||
/// </summary>
|
||||
private bool WalkableStraight(double ax, double ay, double bx, double by)
|
||||
{
|
||||
if (_query == null) return false;
|
||||
for (int i = 0; i < _avoid.Count; i++)
|
||||
{
|
||||
PortalAvoid.Spot s = _avoid.Spots[i];
|
||||
if (PortalAvoid.SegmentDistance(s.X, s.Y, ax, ay, bx, by) < s.R + PortalAvoid.SteerMargin) return false;
|
||||
}
|
||||
// The default filter: the circles were checked above (the avoid filter drops every big
|
||||
// polygon that merely reaches into one, which would read as a wall far from the line).
|
||||
var filter = new DtQueryDefaultFilter();
|
||||
var start = new RcVec3f((float)ax, (float)_wz, (float)ay);
|
||||
_query.FindNearestPoly(start, new RcVec3f(2.5f, 4, 2.5f), filter, out long sRef, out RcVec3f sPt, out _);
|
||||
if (sRef == 0) return false;
|
||||
Span<long> path = stackalloc long[64];
|
||||
var st = _query.Raycast(sRef, sPt, new RcVec3f((float)bx, sPt.Y, (float)by), filter, out float t, out _, path, out _, 64);
|
||||
return st.Succeeded() && t >= 1.0f;
|
||||
}
|
||||
|
||||
/// <summary>A new leg (or goto): nothing blocked yet.</summary>
|
||||
private void ResetBlocked()
|
||||
{
|
||||
_ranLastTick = false;
|
||||
_stuckWinMs = 0; _unstickUntilMs = 0; _stuckTries = 0;
|
||||
_blockedSpots.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -71,7 +108,7 @@ public sealed partial class RynthNavPlugin
|
|||
_ranLastTick = false;
|
||||
if (_unstickUntilMs > now)
|
||||
{
|
||||
DriveTo(_unstickDeg);
|
||||
DriveTo(_unstickDeg, _steerOpen);
|
||||
lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})";
|
||||
return true;
|
||||
}
|
||||
|
|
@ -97,12 +134,23 @@ public sealed partial class RynthNavPlugin
|
|||
FinishGoto($"stopped: blocked at {at} ({StuckMaxTries} tries to get round it; something in the way the map doesn't show) ({why})");
|
||||
return true;
|
||||
}
|
||||
// Remember what it ran into, so the next plans go round it (RefreshAvoid adds these).
|
||||
double rad = _lastDriveDeg * Math.PI / 180.0;
|
||||
if (_blockedSpots.Count >= BlockedMaxSpots) _blockedSpots.RemoveAt(0);
|
||||
_blockedSpots.Add(new PortalAvoid.Spot(_wx + Math.Sin(rad) * BlockedAheadUnits, _wy + Math.Cos(rad) * BlockedAheadUnits,
|
||||
BlockedRadiusUnits, "something in the way"));
|
||||
RefreshAvoid(force: true);
|
||||
|
||||
_stuckSide = -_stuckSide;
|
||||
_unstickDeg = ((_lastDriveDeg + 180.0 - _stuckSide * (180.0 - UnstickAngleDeg)) % 360.0 + 360.0) % 360.0;
|
||||
_unstickDeg = WalkSteer.UnstickHeading(_lastDriveDeg, _stuckSide, h =>
|
||||
{
|
||||
double r = h * Math.PI / 180.0;
|
||||
return WalkableStraight(_wx, _wy, _wx + Math.Sin(r) * UnstickOpenUnits, _wy + Math.Cos(r) * UnstickOpenUnits);
|
||||
});
|
||||
_unstickUntilMs = now + UnstickMs;
|
||||
Host.Log($"[RynthNav] walk: blocked at {at} heading {_lastDriveDeg:F0} (moved {moved:F1}u in {StuckWindowMs / 1000.0:F1} s); "
|
||||
+ $"turning to {_unstickDeg:F0} and planning again ({_stuckTries}/{StuckMaxTries})");
|
||||
DriveTo(_unstickDeg);
|
||||
+ $"turning to {_unstickDeg:F0}, keeping out of that spot ({_blockedSpots.Count} so far) and planning again ({_stuckTries}/{StuckMaxTries})");
|
||||
DriveTo(_unstickDeg, _steerOpen);
|
||||
lock (_gate) _status = $"blocked: stepping round it ({_stuckTries}/{StuckMaxTries})";
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ public sealed partial class RynthNavPlugin
|
|||
private NavCoarse? _coarse; // the current leg's route (null = none, or none yet)
|
||||
private int _coarseRetry; // re-plans left before planning a route again
|
||||
private int _coarseOff; // re-plans in a row off the route
|
||||
private bool _coarseAnnounced, _coarseNoRouteSaid;
|
||||
private bool _coarseAnnounced, _coarseNoRouteSaid, _coarseGoalMovedSaid;
|
||||
private double _aimEw, _aimNs; // where the last re-plan aimed (the blind push follows it)
|
||||
|
||||
private void LoadGraph()
|
||||
|
|
@ -107,7 +107,7 @@ public sealed partial class RynthNavPlugin
|
|||
|
||||
private void ResetCoarse()
|
||||
{
|
||||
_coarse = null; _coarseRetry = 0; _coarseOff = 0; _coarseAnnounced = false; _coarseNoRouteSaid = false;
|
||||
_coarse = null; _coarseRetry = 0; _coarseOff = 0; _coarseAnnounced = false; _coarseNoRouteSaid = false; _coarseGoalMovedSaid = false;
|
||||
_coarseTask = null; _coarseVersion++;
|
||||
}
|
||||
|
||||
|
|
@ -167,14 +167,24 @@ public sealed partial class RynthNavPlugin
|
|||
NavCoarse.Probe? target = null;
|
||||
int gx = (int)Math.Floor(_gotoTew / 192.0), gy = (int)Math.Floor(_gotoTns / 192.0);
|
||||
uint goalLb = gx is >= 0 and <= 255 && gy is >= 0 and <= 255 ? (uint)((gx << 8) | gy) : 0;
|
||||
bool moved = false;
|
||||
try
|
||||
{
|
||||
// Ground a walk from here can end on: the spot itself, or the nearest such ground
|
||||
// when the spot is a pocket nothing links into (NavCoarse.ProbeReachable).
|
||||
target = _loadedTiles.Contains(goalLb)
|
||||
? NavCoarse.ProbeNear(g, _navMesh!, _query!, _gotoTew, _wz, _gotoTns, 40f, _tileRegions)
|
||||
: NavCoarse.ProbeFile(g, NavDataDir, _gotoTew, _wz, _gotoTns, 40f);
|
||||
? NavCoarse.ProbeReachable(g, _navMesh!, _query!, _gotoTew, _wz, _gotoTns, 40f, _tileRegions, start.Region, out moved)
|
||||
: NavCoarse.ProbeFile(g, NavDataDir, _gotoTew, _wz, _gotoTns, 40f, start.Region, out moved);
|
||||
}
|
||||
catch (Exception ex) { Host.Log($"[RynthNav] route: target tile unreadable: {ex.Message}"); }
|
||||
if (target == null) return; // no navmesh at the target: head straight, as without a graph
|
||||
if (moved && !_coarseGoalMovedSaid)
|
||||
{
|
||||
_coarseGoalMovedSaid = true;
|
||||
double off = Math.Sqrt((target.Pt.X - _gotoTew) * (target.Pt.X - _gotoTew) + (target.Pt.Z - _gotoTns) * (target.Pt.Z - _gotoTns));
|
||||
Host.Log($"[RynthNav] route: the spot itself can't be walked into (fenced-in ground, a roof or a rock); aiming at walkable ground {off:F0}u from it (region {target.Region})");
|
||||
if (off >= ArrivalUnits) Say($"goto: that exact spot can't be walked to; going to the nearest walkable ground, {off:F0} yd from it");
|
||||
}
|
||||
|
||||
NavCoarse.Request req = NavCoarse.Request.Measure(g, start, target);
|
||||
int version = _coarseVersion, here = start.Region, goal = target.Region;
|
||||
|
|
@ -209,6 +219,17 @@ public sealed partial class RynthNavPlugin
|
|||
NoLandRoute();
|
||||
return;
|
||||
}
|
||||
// On open ground (the start links to its neighbours, on a real landmass) and still no
|
||||
// route though the goal end was already moved to ground a walk can end on: the graph
|
||||
// knows of no way there. Heading straight for it then only runs into what's between
|
||||
// (11-01: a bridge, then round in circles for minutes). Stop and say so. Standing in a
|
||||
// pocket yourself (indoors, a roof), the way out may be narrower than the mesh shows:
|
||||
// head for it as before.
|
||||
if (g != null && g.RegionPortals(here).Length > 0 && g.ComponentSize(g.Component(here)) >= 8)
|
||||
{
|
||||
FinishGoto("stopped: the route graph has no walking way to that spot (nothing walkable within 96 yd of it links to where you are); pick a spot nearby");
|
||||
return;
|
||||
}
|
||||
if (!_coarseNoRouteSaid)
|
||||
{
|
||||
_coarseNoRouteSaid = true;
|
||||
|
|
|
|||
136
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs
Normal file
136
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.PathApi.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using RynthNav.Routing;
|
||||
using NavPathApi = RynthCore.Plugin.Shared.RynthNavPathApiV1;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// "RynthNav.Path" version 2 (Shared/RynthNavPathApi.cs): FindPathEx and Raycast, for RynthAi's
|
||||
// outdoor hunting (a path to a monster that keeps off portals and walls like RynthNav's own walks,
|
||||
// the reachable point nearest a monster it can't get to, the path's length, and whether a straight
|
||||
// walk is clear). Called by another plugin from its OnTick (the pump thread, as our OnTick), on the
|
||||
// same navmesh and query object the walker uses; the walking itself is the caller's. The planning
|
||||
// steps are NavPathQuery's (host-free, shared with Replan); this part loads the tiles, says whether
|
||||
// the start is on the landscape at all, and keeps FindPathEx's own portal set. Tick thread.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
/// <summary>A start this close to the player is the player's: the player's cell says whether it's on the landscape.</summary>
|
||||
private const double PathStartIsPlayerUnits = 24.0;
|
||||
|
||||
private readonly PathExResult _pathEx = new();
|
||||
|
||||
// FindPathEx's portals (PathAvoidPortals): the walker's sources (every portal object the client
|
||||
// knows, the Atlas's where no live one stands) round the query, never a step's own portal excepted.
|
||||
// Its own set, so a query never changes the walker's (or logs its "avoid:" line).
|
||||
private readonly PortalAvoid _pathAvoid = new();
|
||||
private AvoidFilter? _pathAvoidFilter;
|
||||
private readonly List<PortalAvoid.Spot> _pathLive = new(), _pathLiveNear = new(), _pathMapNear = new();
|
||||
private long _pathLiveNextMs;
|
||||
|
||||
private void ResetPathApi()
|
||||
{
|
||||
_pathLive.Clear(); _pathLiveNextMs = 0;
|
||||
_pathAvoid.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The start isn't on the landscape mesh: the player is in a dungeon (any world position then is a
|
||||
/// dungeon's, not the land's), or in a building's cells and the start is where the player stands
|
||||
/// (unless the caller says it is a spot outdoors, <paramref name="startOutdoors"/>: PathStartOutdoors, v3).
|
||||
/// </summary>
|
||||
private bool PathStartOffLandscape(double sx, double sy, bool startOutdoors = false)
|
||||
{
|
||||
if ((_cellId & 0xFFFF) < 0x100) return false; // outdoors
|
||||
if (InDungeon(_cellId) || !IsOnMap(_cellId)) return true; // a dungeon (the Atlas's, or one it doesn't know)
|
||||
if (startOutdoors) return false; // a building's doorstep (RynthAi's hunt walking out)
|
||||
double dx = sx - _wx, dy = sy - _wy;
|
||||
return dx * dx + dy * dy <= PathStartIsPlayerUnits * PathStartIsPlayerUnits;
|
||||
}
|
||||
|
||||
/// <summary>FindPathEx's portal circles for a query from (sx, sy) to (gx, gy); live objects read again at most once a second.</summary>
|
||||
private AvoidFilter PathPortals(double sx, double sy, double gx, double gy)
|
||||
{
|
||||
long now = NowMs;
|
||||
if (now >= _pathLiveNextMs)
|
||||
{
|
||||
_pathLiveNextMs = now + AvoidRefreshMs;
|
||||
_pathLive.Clear();
|
||||
LivePortalSpots(_pathLive, double.NegativeInfinity, double.NegativeInfinity, double.PositiveInfinity, double.PositiveInfinity);
|
||||
}
|
||||
double minX = Math.Min(sx, gx) - AvoidNearUnits, maxX = Math.Max(sx, gx) + AvoidNearUnits;
|
||||
double minY = Math.Min(sy, gy) - AvoidNearUnits, maxY = Math.Max(sy, gy) + AvoidNearUnits;
|
||||
_pathLiveNear.Clear(); _pathMapNear.Clear();
|
||||
foreach (PortalAvoid.Spot s in _pathLive)
|
||||
if (s.X >= minX && s.X <= maxX && s.Y >= minY && s.Y <= maxY) _pathLiveNear.Add(s);
|
||||
foreach (PortalAvoid.Spot s in AtlasPortalSpots())
|
||||
if (s.X >= minX && s.X <= maxX && s.Y >= minY && s.Y <= maxY) _pathMapNear.Add(s);
|
||||
_pathAvoid.Set(_pathLiveNear, _pathMapNear);
|
||||
return _pathAvoidFilter ??= new AvoidFilter(_pathAvoid);
|
||||
}
|
||||
|
||||
internal unsafe int InterfaceFindPathEx(double sx, double sy, double sz, double gx, double gy, double gz,
|
||||
int flags, int maxTiles, double* points, int maxPoints, int* count, double* info)
|
||||
{
|
||||
long t0 = Stopwatch.GetTimestamp();
|
||||
if (count != null) *count = 0;
|
||||
if (info != null) for (int i = 0; i < NavPathApi.InfoLength; i++) info[i] = 0;
|
||||
int tiles = NavPathQuery.ClampMaxTiles(maxTiles);
|
||||
PathExResult r = _pathEx;
|
||||
r.Reset();
|
||||
|
||||
if (points == null || maxPoints < 2) r.Fail(NavPathApi.ResultNoPath, "no room for the corners");
|
||||
else if (!_hasPose) r.Fail(NavPathApi.ResultNoMesh, "no player position yet");
|
||||
else if (!IsFinite(sx) || !IsFinite(sy) || !IsFinite(sz) || !IsFinite(gx) || !IsFinite(gy) || !IsFinite(gz)) r.Fail(NavPathApi.ResultNoPath, "not a position");
|
||||
else if (PathStartOffLandscape(sx, sy, (flags & NavPathApi.PathStartOutdoors) != 0))
|
||||
r.Fail(NavPathApi.ResultNoMesh, InDungeon(_cellId) || !IsOnMap(_cellId) ? "in a dungeon" : "in a building");
|
||||
else if (!LoadPathBox(sx, sy, gx, gy, tiles, shrinkMargin: true)) r.Fail(NavPathApi.ResultNoPath, $"farther than {tiles} tiles hold");
|
||||
else
|
||||
{
|
||||
AvoidFilter? portals = (flags & NavPathApi.PathAvoidPortals) != 0 ? PathPortals(sx, sy, gx, gy) : null;
|
||||
NavPathQuery.FindPathEx(_query, sx, sy, sz, gx, gy, gz, flags, maxPoints, portals, _wallClearance, r);
|
||||
}
|
||||
|
||||
int n = r.Code is NavPathApi.ResultOk or NavPathApi.ResultPartial ? r.Corners.Count : 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
points[i * 3] = r.Corners[i].X; // east
|
||||
points[i * 3 + 1] = r.Corners[i].Y; // north
|
||||
points[i * 3 + 2] = r.Corners[i].Z; // height
|
||||
}
|
||||
if (count != null) *count = n;
|
||||
if (info != null && n > 0)
|
||||
{
|
||||
info[0] = r.Length;
|
||||
info[1] = r.Partial ? 1 : 0;
|
||||
info[2] = r.Corners[n - 1].X; info[3] = r.Corners[n - 1].Y; info[4] = r.Corners[n - 1].Z;
|
||||
info[5] = r.EndDistance;
|
||||
}
|
||||
|
||||
if ((flags & NavPathApi.PathQuiet) == 0)
|
||||
{
|
||||
double ms = Stopwatch.GetElapsedTime(t0).TotalMilliseconds;
|
||||
string what = r.Code switch
|
||||
{
|
||||
NavPathApi.ResultOk => $"{n} corners, {r.Polys} polys, {r.Length:F0}u, ends {r.EndDistance:F1}u from the goal",
|
||||
NavPathApi.ResultPartial => $"PARTIAL{(r.Truncated ? " (cut short)" : "")}: {n} corners, {r.Polys} polys, {r.Length:F0}u, ends {r.EndDistance:F0}u from the goal",
|
||||
NavPathApi.ResultNoMesh => $"no navmesh: {r.Note}",
|
||||
_ => $"no path: {r.Note}",
|
||||
};
|
||||
string extras = "";
|
||||
if (r.Portals > 0) extras += $"; {r.Portals} portal(s) avoided{(r.FellBack ? " (no way round them: plain path)" : "")}{(r.Bent > 0 ? $", bent round {r.Bent}" : "")}";
|
||||
if (r.Pushed > 0) extras += $"; {r.Pushed} corner(s) {_wallClearance:0.#} m off the walls";
|
||||
Host.Log($"[RynthNav] path request ex (flags 0x{flags:X}): {what}{extras}; ({sx:F0},{sy:F0}) -> ({gx:F0},{gy:F0}), {_tileCount} tiles, {ms:F1} ms");
|
||||
}
|
||||
return r.Code;
|
||||
}
|
||||
|
||||
internal int InterfaceRaycast(double sx, double sy, double sz, double gx, double gy, double gz)
|
||||
{
|
||||
if (!_hasPose) return NavPathApi.ResultNoMesh;
|
||||
if (!IsFinite(sx) || !IsFinite(sy) || !IsFinite(sz) || !IsFinite(gx) || !IsFinite(gy) || !IsFinite(gz)) return NavPathApi.RayBlocked;
|
||||
if (PathStartOffLandscape(sx, sy)) return NavPathApi.ResultNoMesh;
|
||||
if (!LoadPathBox(sx, sy, gx, gy, NavPathQuery.DefaultMaxTiles, shrinkMargin: true)) return NavPathApi.RayBlocked; // too far to tell
|
||||
return NavPathQuery.Raycast(_query, sx, sy, sz, gx, gy, gz, out _);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,54 +1,44 @@
|
|||
using System;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// Turning the way RynthAi's nav does it (NavigationEngine.DriveHeading, mode 0 heading servo):
|
||||
// the heading is slewed toward the target at a capped rate rather than snapped onto it, and a big
|
||||
// turn is made standing (autorun off) and the run resumes once lined up. The numbers are RynthAi's
|
||||
// defaults (Nav Turn Rate 270 deg/s, Stop Turn Angle 20, Resume Turn Angle 10, Dead Zone 4).
|
||||
// Turning: the heading servo is WalkSteer (host-free, tested in RynthNav.RouteTests). It slews the
|
||||
// heading toward the target at a capped rate and turns standing (autorun off) for a big turn.
|
||||
// Two settings: the walk over open ground (the goto's path, the blind push, stepping round
|
||||
// something) makes corrections up to 50 degrees on the run and sends a turn at most 20 times a
|
||||
// second; the close work (the Town Network's corridors, aiming into a portal, holding off one)
|
||||
// keeps RynthAi's tight defaults (stop for anything over 20 degrees).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private const double TurnRateDegPerSec = 270.0;
|
||||
private const double TurnDeadZoneDeg = 4.0;
|
||||
private const double StopTurnAngleDeg = 20.0;
|
||||
private const double ResumeTurnAngleDeg = 10.0;
|
||||
private readonly WalkSteer _steerOpen = new();
|
||||
private readonly WalkSteer _steerTight = WalkSteer.Legacy();
|
||||
|
||||
private bool _turnInPlace;
|
||||
private long _lastTurnMs;
|
||||
/// <summary>The player's heading (0 = north, clockwise) from the pose quaternion, or NaN.</summary>
|
||||
private double PlayerHeadingDeg()
|
||||
{
|
||||
// The quaternion, not GetPlayerHeading (that one is 0 = east, counter-clockwise).
|
||||
if (Host.TryGetPlayerPose(out _, out _, out _, out _, out float qw, out _, out _, out float qz))
|
||||
return (-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) + 720.0) % 360.0;
|
||||
return double.NaN;
|
||||
}
|
||||
|
||||
/// <summary>Turn toward <paramref name="desiredDeg"/> (0 = north, clockwise) and run when lined up.</summary>
|
||||
private void DriveTo(double desiredDeg)
|
||||
private void DriveTo(double desiredDeg, WalkSteer? servo = null)
|
||||
{
|
||||
desiredDeg = ((desiredDeg % 360.0) + 360.0) % 360.0;
|
||||
double current = desiredDeg;
|
||||
if (Host.TryGetPlayerPose(out _, out _, out _, out _, out float qw, out _, out _, out float qz))
|
||||
current = (-(2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) + 720.0) % 360.0;
|
||||
|
||||
double error = desiredDeg - current;
|
||||
if (error > 180.0) error -= 360.0; else if (error < -180.0) error += 360.0;
|
||||
double abs = Math.Abs(error);
|
||||
|
||||
long now = NowMs;
|
||||
double dt = _lastTurnMs == 0 ? 33.0 : Math.Clamp(now - _lastTurnMs, 10, 200);
|
||||
_lastTurnMs = now;
|
||||
double maxStep = TurnRateDegPerSec * dt / 1000.0;
|
||||
|
||||
// Run gate with hysteresis: stop to turn when far off, run again once close.
|
||||
if (_turnInPlace) { if (abs <= ResumeTurnAngleDeg) _turnInPlace = false; }
|
||||
else if (abs > StopTurnAngleDeg) _turnInPlace = true;
|
||||
|
||||
if (abs > TurnDeadZoneDeg)
|
||||
{
|
||||
double next = current + Math.Clamp(error, -maxStep, maxStep);
|
||||
Host.TurnToHeading((float)(((next % 360.0) + 360.0) % 360.0));
|
||||
}
|
||||
AutoRun.Run(!_turnInPlace);
|
||||
servo ??= _steerTight;
|
||||
desiredDeg = WalkSteer.Norm(desiredDeg);
|
||||
double current = PlayerHeadingDeg();
|
||||
if (double.IsNaN(current)) current = desiredDeg;
|
||||
double turn = servo.Step(desiredDeg, current, NowMs, out bool run);
|
||||
if (!double.IsNaN(turn)) Host.TurnToHeading((float)turn);
|
||||
AutoRun.Run(run);
|
||||
}
|
||||
|
||||
// SetAutoRun/StopCompletely for the goto, sent when they change (AutoRunGate.cs).
|
||||
private AutoRunGate? _autoRun;
|
||||
private AutoRunGate AutoRun => _autoRun ??= new AutoRunGate(on => Host.SetAutoRun(on), () => Host.StopCompletely(), () => NowMs);
|
||||
|
||||
/// <summary>A fresh start for the turn servo (a new goto, a teleport).</summary>
|
||||
private void ResetTurn() { _turnInPlace = false; _lastTurnMs = 0; }
|
||||
/// <summary>A fresh start for the turn servo (a new goto, a new leg).</summary>
|
||||
private void ResetTurn() { _steerOpen.Reset(); _steerTight.Reset(); }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
private const int MaxTiles = 256;
|
||||
private const int MaxCorridorTiles = 220;
|
||||
private const double ArrivalUnits = 7.0;
|
||||
private const double CornerLookaheadUnits = 6.0; // a path corner is cut from this far out when the next is in plain view
|
||||
private const int PreviewMaxLandblocks = 3; // preview only targets this many landblocks away (a <= 6x6 tile box)
|
||||
private const int BlindPushTicks = 45; // ~1.5 s straight at the goal when the plan runs out short of it (crosses a seam)
|
||||
private const int NoProgressTicks = 30 * 30; // ~30 s without getting ProgressUnits closer to the leg's goal = give up
|
||||
|
|
@ -189,6 +190,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
HideMarkers("logged out");
|
||||
_meshView.Clear(); _meshDunLb = 0;
|
||||
_trip = null; _tripPath = null;
|
||||
ResetPathApi();
|
||||
OnLogoutTravel();
|
||||
}
|
||||
|
||||
|
|
@ -283,7 +285,11 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
lock (_gate) _status = _tileCount > 0 ? $"{_tileCount} tiles @ 0x{centerLb:X4}" : $"no tile for 0x{centerLb:X4} — bake it";
|
||||
}
|
||||
|
||||
// Feed the bake-ahead watcher: player landblock + goto-target landblock.
|
||||
// Feed the bake-ahead watcher: player landblock + goto-target landblock. Written only when it
|
||||
// changes (2026-11-02): every client rewrote it a few times a second, and Windows Defender scans
|
||||
// each write.
|
||||
private string _lastPosText = "";
|
||||
|
||||
private void WritePosFile()
|
||||
{
|
||||
try
|
||||
|
|
@ -291,7 +297,10 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
int pX = (int)((_cellId >> 24) & 0xFF), pY = (int)((_cellId >> 16) & 0xFF);
|
||||
int tX = pX, tY = pY;
|
||||
if (_gotoActive) { tX = (int)(_gotoTew / 192.0); tY = (int)(_gotoTns / 192.0); }
|
||||
File.WriteAllText(Path.Combine(NavDataDir, "_player.txt"), $"{pX},{pY},{tX},{tY}");
|
||||
string text = $"{pX},{pY},{tX},{tY}";
|
||||
if (text == _lastPosText) return;
|
||||
File.WriteAllText(Path.Combine(NavDataDir, "_player.txt"), text);
|
||||
_lastPosText = text;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
|
@ -314,6 +323,26 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The "RynthNav.Path" interface's tiles: the box from (sx, sy) to (gx, gy) plus a one-tile margin
|
||||
/// (<see cref="NavPathQuery.TileBox"/>; <paramref name="shrinkMargin"/>: without the margin when that
|
||||
/// alone fits). False when it's more than <paramref name="maxTiles"/>; else <see cref="_query"/> is
|
||||
/// ready (made again when a tile was added).
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.MemberNotNullWhen(true, nameof(_query))]
|
||||
private bool LoadPathBox(double sx, double sy, double gx, double gy, int maxTiles, bool shrinkMargin)
|
||||
{
|
||||
EnsureNavMesh();
|
||||
if (!NavPathQuery.TileBox(sx, sy, gx, gy, maxTiles, shrinkMargin, out int minX, out int minY, out int maxX, out int maxY)) return false;
|
||||
bool changed = false;
|
||||
for (int x = minX; x <= maxX; x++)
|
||||
for (int y = minY; y <= maxY; y++)
|
||||
changed |= !_loadedTiles.Contains((uint)((x << 8) | y)) && EnsureTile((uint)((x << 8) | y));
|
||||
if (changed || _query == null) _query = new DtNavMeshQuery(_navMesh!);
|
||||
_tileCount = _loadedTiles.Count;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Load every tile in the bounding box from player to target (the route corridor).
|
||||
private void LoadCorridorTo(double twx, double twy)
|
||||
{
|
||||
|
|
@ -712,16 +741,14 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
lock (_gotoGate) { path = _gotoPath; idx = _gotoIdx; }
|
||||
if (path != null)
|
||||
{
|
||||
while (idx < path.Count)
|
||||
{
|
||||
double ddew = path[idx].ew - _wx, ddns = path[idx].ns - _wy;
|
||||
// A corner is reached close up (cornerReachMetres); only the path's end uses
|
||||
// ArrivalUnits. 7 u for every corner turned early and cut across the inside of
|
||||
// each one, into the building it was going round (10-01 20:15).
|
||||
double reach = idx >= path.Count - 1 ? ArrivalUnits : _cornerReach;
|
||||
if (Math.Sqrt(ddew * ddew + ddns * ddns) < reach) idx++;
|
||||
else break;
|
||||
}
|
||||
// A corner is reached close up (cornerReachMetres); only the path's end uses
|
||||
// ArrivalUnits. 7 u for every corner turned early and cut across the inside of
|
||||
// each one, into the building it was going round (10-01 20:15). From
|
||||
// CornerLookaheadUnits out, a corner is also passed once the next one can be walked to
|
||||
// straight (the navmesh's raycast: the agent radius from every wall it knows, and out
|
||||
// of the portal circles): the walk turns smoothly instead of overshooting each corner
|
||||
// at run speed and turning back to it (11-01).
|
||||
idx = PathFollow.Advance(path, idx, _wx, _wy, _cornerReach, ArrivalUnits, CornerLookaheadUnits, WalkableStraight);
|
||||
lock (_gotoGate) _gotoIdx = idx;
|
||||
}
|
||||
if (path == null || idx >= path.Count)
|
||||
|
|
@ -805,6 +832,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// New leg: fresh progress watchdog, and the old leg's walkable end no longer counts.
|
||||
ResetHub();
|
||||
ResetBlocked();
|
||||
ResetTurn();
|
||||
_coarseHoldTicks = _graph != null ? CoarseHoldMaxTicks : 0;
|
||||
_nextAvoidMs = 0;
|
||||
_walkHaveLast = false; // a new leg starts where the last step's teleport put us
|
||||
|
|
@ -975,8 +1003,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// The ground we stand on first: the mesh keeps the agent radius (2 m) from walls, so close
|
||||
// up it's within that, at our height. Only then the wide search, which can pick ground on
|
||||
// the far side of a thin wall or a roof overhead, and the walk then runs into that wall.
|
||||
_query.FindNearestPoly(startP, new RcVec3f(2.5f, 4, 2.5f), filter, out long sRef, out RcVec3f sPt, out _);
|
||||
if (sRef == 0) _query.FindNearestPoly(startP, new RcVec3f(8, 64, 8), filter, out sRef, out sPt, out _);
|
||||
long sRef = NavPathQuery.SnapStart(_query, startP, filter, out RcVec3f sPt);
|
||||
// A failed plan drops the old one: StepGoto must not keep following a stale path.
|
||||
if (sRef == 0) { lock (_gate) _status = "off navmesh"; lock (_gotoGate) _gotoPath = null; return; }
|
||||
|
||||
|
|
@ -990,7 +1017,12 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// the target is too far to be loaded yet (that probe jitters and must stay a last resort).
|
||||
double aimEw = steer?.Ew ?? _gotoTew, aimNs = steer?.Ns ?? _gotoTns;
|
||||
_aimEw = aimEw; _aimNs = aimNs;
|
||||
var targetP = steer is { } st ? new RcVec3f(st.Ew, st.Up, st.Ns) : new RcVec3f((float)_gotoTew, (float)_wz, (float)_gotoTns);
|
||||
// The route's last stretch ends on the ground its search ended on: the spot itself, or the
|
||||
// nearest ground a walk can end on when the spot is fenced in (NavCoarse.ProbeReachable).
|
||||
// Planned to the spot itself, the nearest polygon is the fenced-in one again.
|
||||
var targetP = steer is { } st ? new RcVec3f(st.Ew, st.Up, st.Ns)
|
||||
: _coarse != null && !double.IsNaN(_coarse.GoalUp) ? new RcVec3f((float)_coarse.GoalEw, (float)_coarse.GoalUp, (float)_coarse.GoalNs)
|
||||
: new RcVec3f((float)_gotoTew, (float)_wz, (float)_gotoTns);
|
||||
AvoidFilter avoid = WalkFilter();
|
||||
avoid.AllowA = sRef; avoid.AllowB = 0;
|
||||
// The goal is looked up WITHOUT the portal circles: the goal's polygon is always allowed
|
||||
|
|
@ -1002,15 +1034,11 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
if (gRef == 0) gRef = FindGoalToward(aimEw, aimNs, out gPt);
|
||||
if (gRef == 0) { lock (_gate) _status = "no tile ahead — bake the route"; lock (_gotoGate) _gotoPath = null; return; }
|
||||
|
||||
Span<long> p = new long[512];
|
||||
Span<long> p = new long[NavPathQuery.MaxPolys];
|
||||
avoid.AllowB = gRef;
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, avoid, p, out int pc, 512);
|
||||
if ((pc == 0 || p[pc - 1] != gRef) && _avoid.Count > 0)
|
||||
{
|
||||
// No way round the portals to there: plan as before; steering still keeps out of them.
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, filter, p, out pc, 512);
|
||||
if (!_avoidFallbackSaid) { _avoidFallbackSaid = true; Host.Log("[RynthNav] avoid: no path round the portals here; steering round them instead"); }
|
||||
}
|
||||
// No way round the portals to there: planned as before; steering still keeps out of them.
|
||||
int pc = NavPathQuery.Corridor(_query, sRef, gRef, sPt, gPt, avoid, filter, _avoid.Count > 0, p, out bool fellBack, out _);
|
||||
if (fellBack && !_avoidFallbackSaid) { _avoidFallbackSaid = true; Host.Log("[RynthNav] avoid: no path round the portals here; steering round them instead"); }
|
||||
Span<DtStraightPath> sp = new DtStraightPath[512];
|
||||
_query.FindStraightPath(sPt, gPt, p[..pc], pc, sp, out int spc, 512, 0);
|
||||
if (spc < 2) { lock (_gate) _status = "no path"; lock (_gotoGate) _gotoPath = null; return; }
|
||||
|
|
@ -1022,49 +1050,17 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
var wps = new List<(double, double)>(spc);
|
||||
for (int i = 0; i < spc; i++) wps.Add((sp[i].pos.X, sp[i].pos.Z));
|
||||
// Round any portal the path still crosses (big open-ground polygons let it cut straight over one).
|
||||
// Every mesh test at our own height (the walker plans from where it stands).
|
||||
float wz = (float)_wz;
|
||||
if (_avoid.Count > 0)
|
||||
{
|
||||
var q = _query;
|
||||
float wz = (float)_wz;
|
||||
int before = wps.Count;
|
||||
// On the mesh = inside a polygon (the nearest point on the mesh is the point itself),
|
||||
// not merely near one; a leg is on the mesh when every metre of it is.
|
||||
bool OnMesh(double x, double y)
|
||||
{
|
||||
q.FindNearestPoly(new RcVec3f((float)x, wz, (float)y), new RcVec3f(0.5f, 24, 0.5f), filter, out long r, out RcVec3f np, out _);
|
||||
return r != 0 && Math.Abs(np.X - x) < 0.05 && Math.Abs(np.Z - y) < 0.05;
|
||||
}
|
||||
bool LegOnMesh(double ax, double ay, double bx, double by)
|
||||
{
|
||||
double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
|
||||
int n = Math.Max(1, (int)Math.Ceiling(len));
|
||||
for (int k = 1; k < n; k++)
|
||||
if (!OnMesh(ax + (bx - ax) * k / n, ay + (by - ay) * k / n)) return false;
|
||||
return true;
|
||||
}
|
||||
wps = _avoid.Bend(wps, OnMesh, 12, LegOnMesh);
|
||||
wps = NavPathQuery.BendRoundPortals(_query, _avoid, wps, filter, (_, _) => wz);
|
||||
if (wps.Count != before) Host.Log($"[RynthNav] avoid: path bent round {wps.Count - before} portal(s)");
|
||||
}
|
||||
// Walls: each corner the path turns round sits on the mesh's edge (the agent radius from a
|
||||
// building); push it out along the turn's outside bisector where the ground is walkable.
|
||||
if (_avoidWalls && _wallClearance > 0 && wps.Count > 2)
|
||||
{
|
||||
var q2 = _query;
|
||||
for (int i = 1; i < wps.Count - 1; i++)
|
||||
{
|
||||
var (px, py) = wps[i]; var (ax, ay) = wps[i - 1]; var (bx, by) = wps[i + 1];
|
||||
double ux = ax - px, uy = ay - py, ul = Math.Sqrt(ux * ux + uy * uy);
|
||||
double vx = bx - px, vy = by - py, vl = Math.Sqrt(vx * vx + vy * vy);
|
||||
if (ul < 0.5 || vl < 0.5) continue;
|
||||
double ox = -(ux / ul + vx / vl), oy = -(uy / ul + vy / vl), ol = Math.Sqrt(ox * ox + oy * oy);
|
||||
if (ol < 0.05) continue; // straight on: no corner to clear
|
||||
double nx = px + ox / ol * _wallClearance, ny = py + oy / ol * _wallClearance;
|
||||
// Only onto walkable ground itself (inside a polygon), not merely near it: near it,
|
||||
// the moved corner could sit closer to the wall than the body is wide.
|
||||
q2.FindNearestPoly(new RcVec3f((float)nx, (float)_wz, (float)ny), new RcVec3f(0.3f, 24, 0.3f), filter, out long rr, out RcVec3f rp, out _);
|
||||
if (rr != 0 && Math.Abs(rp.X - nx) < 0.05 && Math.Abs(rp.Z - ny) < 0.05) wps[i] = (nx, ny);
|
||||
}
|
||||
}
|
||||
if (_avoidWalls) NavPathQuery.PushFromWalls(_query, wps, _wallClearance, filter, (_, _) => wz);
|
||||
lock (_gotoGate) { _gotoPath = wps; _gotoIdx = 0; }
|
||||
int rem = (int)Math.Sqrt((_gotoTew - _wx) * (_gotoTew - _wx) + (_gotoTns - _wy) * (_gotoTns - _wy));
|
||||
string via = _coarse != null && _coarse.Count > 0 ? $", route {_coarse.Crossed}/{_coarse.Count}" : "";
|
||||
|
|
@ -1075,8 +1071,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
// Called by another plugin from its OnTick: the same pump thread as our OnTick, so
|
||||
// the navmesh is touched on the tick thread only. Loads the tiles covering start and
|
||||
// goal (plus a one-tile margin) and plans on the same query object goto uses.
|
||||
private const int InterfaceMaxTiles = 25; // at most a 5x5 block of tiles per call
|
||||
private const double InterfaceGoalSlackUnits = 6.0; // a path ending farther than this from the goal is partial
|
||||
// Version 2 (FindPathEx, Raycast): RynthNavPlugin.PathApi.cs.
|
||||
|
||||
internal unsafe int InterfaceFindPath(double sx, double sy, double sz, double gx, double gy, double gz,
|
||||
double* points, int maxPoints, int* count)
|
||||
|
|
@ -1088,18 +1083,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
return Shared.RynthNavPathApiV1.ResultNoPath;
|
||||
|
||||
// Tiles for both ends and everything between (plus a margin), capped.
|
||||
EnsureNavMesh();
|
||||
int sLbX = (int)(sx / 192.0), sLbY = (int)(sy / 192.0);
|
||||
int gLbX = (int)(gx / 192.0), gLbY = (int)(gy / 192.0);
|
||||
int minX = Math.Max(0, Math.Min(sLbX, gLbX) - 1), maxX = Math.Min(255, Math.Max(sLbX, gLbX) + 1);
|
||||
int minY = Math.Max(0, Math.Min(sLbY, gLbY) - 1), maxY = Math.Min(255, Math.Max(sLbY, gLbY) + 1);
|
||||
if ((maxX - minX + 1) * (maxY - minY + 1) > InterfaceMaxTiles) return Shared.RynthNavPathApiV1.ResultNoPath;
|
||||
bool changed = false;
|
||||
for (int x = minX; x <= maxX; x++)
|
||||
for (int y = minY; y <= maxY; y++)
|
||||
changed |= !_loadedTiles.Contains((uint)((x << 8) | y)) && EnsureTile((uint)((x << 8) | y));
|
||||
if (changed || _query == null) _query = new DtNavMeshQuery(_navMesh!);
|
||||
_tileCount = _loadedTiles.Count;
|
||||
if (!LoadPathBox(sx, sy, gx, gy, NavPathQuery.DefaultMaxTiles, shrinkMargin: false)) return Shared.RynthNavPathApiV1.ResultNoPath;
|
||||
|
||||
var filter = new DtQueryDefaultFilter();
|
||||
var startP = new RcVec3f((float)sx, (float)sz, (float)sy);
|
||||
|
|
@ -1120,7 +1104,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
|
||||
var last = sp[spc - 1].pos;
|
||||
double slackE = last.X - gPt.X, slackN = last.Z - gPt.Z;
|
||||
if (Math.Sqrt(slackE * slackE + slackN * slackN) > InterfaceGoalSlackUnits) return Shared.RynthNavPathApiV1.ResultNoPath;
|
||||
if (Math.Sqrt(slackE * slackE + slackN * slackN) > NavPathQuery.GoalSlackUnits) return Shared.RynthNavPathApiV1.ResultNoPath;
|
||||
|
||||
for (int i = 0; i < spc; i++)
|
||||
{
|
||||
|
|
|
|||
123
Plugins/RynthCore.Plugin.RynthNav/WalkSteer.cs
Normal file
123
Plugins/RynthCore.Plugin.RynthNav/WalkSteer.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// The goto's heading servo, host-free (RynthNavPlugin.Turn.cs feeds it the player's heading and
|
||||
/// sends what it asks for; RynthNav.RouteTests walks it along made-up paths).
|
||||
///
|
||||
/// The heading is slewed toward the wanted one at a capped rate; a big turn is made standing
|
||||
/// (autorun off) and the run resumes once lined up. Until 11-01 it stopped to turn for anything
|
||||
/// over 20 degrees and sent a turn every tick (~45 a second): every path corner and every shift
|
||||
/// of the aim stopped the run, a "bounces left and right with a lot of stopping" walk (11-01, 862
|
||||
/// turns and 21 stops in 107 s). Now: running, corrections up to <see cref="StopTurnAngleDeg"/> are
|
||||
/// made on the move, small ones (<see cref="RunDeadZoneDeg"/>) are left alone, and a turn goes
|
||||
/// out at most every <see cref="MinTurnIntervalMs"/>.
|
||||
/// </summary>
|
||||
internal sealed class WalkSteer
|
||||
{
|
||||
public double TurnRateDegPerSec = 270.0;
|
||||
public double DeadZoneDeg = 4.0; // standing: closer than this is lined up
|
||||
public double RunDeadZoneDeg = 6.0; // running: closer than this isn't worth a turn
|
||||
public double StopTurnAngleDeg = 50.0; // farther off than this: stop and turn standing
|
||||
public double ResumeTurnAngleDeg = 20.0; // ...and run again once this close
|
||||
public long MinTurnIntervalMs = 50; // at most 20 turns a second
|
||||
|
||||
public bool TurnInPlace { get; private set; }
|
||||
private long _lastTurnMs;
|
||||
|
||||
/// <summary>The servo as it was before 11-01 (for comparison in the tests).</summary>
|
||||
public static WalkSteer Legacy() => new()
|
||||
{ RunDeadZoneDeg = 4.0, StopTurnAngleDeg = 20.0, ResumeTurnAngleDeg = 10.0, MinTurnIntervalMs = 0 };
|
||||
|
||||
public void Reset() { TurnInPlace = false; _lastTurnMs = 0; _lastCallMs = 0; _held = false; }
|
||||
|
||||
/// <summary>Signed smallest difference a - b, in -180..180.</summary>
|
||||
public static double Diff(double a, double b)
|
||||
{
|
||||
double e = (a - b) % 360.0;
|
||||
if (e > 180.0) e -= 360.0; else if (e < -180.0) e += 360.0;
|
||||
return e;
|
||||
}
|
||||
|
||||
public static double Norm(double deg) => ((deg % 360.0) + 360.0) % 360.0;
|
||||
|
||||
/// <summary>
|
||||
/// One tick: wanted and current heading (0 = north, clockwise). Returns the heading to turn to
|
||||
/// now, or NaN for none; <paramref name="run"/> is whether to run.
|
||||
/// </summary>
|
||||
public double Step(double desiredDeg, double currentDeg, long nowMs, out bool run)
|
||||
{
|
||||
double error = Diff(Norm(desiredDeg), Norm(currentDeg));
|
||||
double abs = Math.Abs(error);
|
||||
|
||||
// Run gate with hysteresis: stop to turn when far off, run again once close.
|
||||
if (TurnInPlace) { if (abs <= ResumeTurnAngleDeg) TurnInPlace = false; }
|
||||
else if (abs > StopTurnAngleDeg) TurnInPlace = true;
|
||||
run = !TurnInPlace;
|
||||
|
||||
// The slew covers the time since the last call, or since the last turn when the calls in
|
||||
// between wanted one and were held back by the rate limit (as before 11-01 with no limit).
|
||||
long since = _held ? nowMs - _lastTurnMs : nowMs - _lastCallMs;
|
||||
bool first = _lastCallMs == 0;
|
||||
_lastCallMs = nowMs;
|
||||
_held = false;
|
||||
double dead = TurnInPlace ? DeadZoneDeg : RunDeadZoneDeg;
|
||||
if (abs <= dead) return double.NaN;
|
||||
if (_lastTurnMs != 0 && nowMs - _lastTurnMs < MinTurnIntervalMs) { _held = true; return double.NaN; }
|
||||
double dt = first ? 33.0 : Math.Clamp(since, 10, 200);
|
||||
_lastTurnMs = nowMs;
|
||||
double maxStep = TurnRateDegPerSec * dt / 1000.0;
|
||||
return Norm(currentDeg + Math.Clamp(error, -maxStep, maxStep));
|
||||
}
|
||||
|
||||
private long _lastCallMs;
|
||||
private bool _held;
|
||||
|
||||
/// <summary>
|
||||
/// Which way to step round something the walk ran into: away from <paramref name="headingDeg"/>
|
||||
/// on <paramref name="side"/> (+1 clockwise, -1 counter-clockwise) first, the first heading the
|
||||
/// navmesh shows open ground along (<paramref name="open"/>), else straight back. Before 11-01 it
|
||||
/// was always 120 degrees off, alternating sides, open or not (into the bank of the river beside
|
||||
/// a bridge, then back into the bridge).
|
||||
/// </summary>
|
||||
public static double UnstickHeading(double headingDeg, int side, Func<double, bool>? open)
|
||||
{
|
||||
side = side >= 0 ? 1 : -1;
|
||||
foreach (double off in new[] { 100.0, 130.0, 70.0, 160.0 })
|
||||
foreach (int s in new[] { side, -side })
|
||||
{
|
||||
double h = Norm(headingDeg + s * off);
|
||||
if (open == null || open(h)) return h;
|
||||
}
|
||||
return Norm(headingDeg + 180.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which path corner the walk heads for (host-free). A corner is passed when the walk is within
|
||||
/// <c>cornerReach</c> of it, or, from <c>lookahead</c> out, as soon as the corner after it can be
|
||||
/// walked to in a straight line (<c>clear</c>: the navmesh's raycast, which keeps the agent radius
|
||||
/// from every wall, and no portal circle on the way). Before 11-01 only the first: each corner was
|
||||
/// run to within 1.5 m, overshot at run speed and turned back to.
|
||||
/// </summary>
|
||||
internal static class PathFollow
|
||||
{
|
||||
public static int Advance(IReadOnlyList<(double X, double Y)> path, int idx, double x, double y,
|
||||
double cornerReach, double arrival, double lookahead,
|
||||
Func<double, double, double, double, bool>? clear)
|
||||
{
|
||||
while (idx < path.Count)
|
||||
{
|
||||
bool last = idx >= path.Count - 1;
|
||||
double d = Dist(path[idx].X, path[idx].Y, x, y);
|
||||
if (d < (last ? arrival : cornerReach)) { idx++; continue; }
|
||||
if (!last && clear != null && d < lookahead && clear(x, y, path[idx + 1].X, path[idx + 1].Y)) { idx++; continue; }
|
||||
break;
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
|
||||
private static double Dist(double ax, double ay, double bx, double by) => Math.Sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
|
||||
}
|
||||
Loading…
Reference in a new issue