Snapshot for release 2026.10.31.1 (internal 69b244e)

This commit is contained in:
Tom Bohar 2026-10-31 15:01:58 -04:00
commit 2546497f37
122 changed files with 22896 additions and 170 deletions

View file

@ -0,0 +1,281 @@
// ============================================================================
// RynthCore.Geometry - Cells/CellDat.cs
// Reads indoor cells from the dats: each EnvCell's frame, its cell portals
// (which cell is on the other side of which doorway polygon) and static
// objects, and the Environment's CellStruct for it (render polygons with the
// doorway polygons, physics polygons with the floors). Polygons come out
// landblock-local.
//
// Formats as in ACE (EnvCell.Unpack, Environment/CellStruct.Unpack,
// Polygon.Unpack, BSP trees); the polygon, vertex and BSP readers were ported
// from RynthAi's Raycasting/DungeonLOS.cs, which reads the same structures
// for the dungeon map and missile LOS.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/CellDat.cs (3a8075a).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Cells;
/// <summary>EnvCell / Environment readers. Stateless; see <see cref="IndoorWorld"/> for a cached, thread-safe front end.</summary>
public static class CellDat
{
/// <summary>A walkable floor: ACE's PhysicsGlobals.FloorZ (cos 48.4 degrees).</summary>
public const float FloorZ = 0.66417414f;
/// <summary>
/// Every EnvCell of landblock <paramref name="landblock"/> (0xXXYY, or any cell id 0xXXYYnnnn of it),
/// ascending by id, with geometry attached. A cell whose record does not parse is skipped; one whose
/// Environment/CellStruct does not parse is kept with <see cref="EnvCell.GeometryOk"/> false.
/// </summary>
public static List<EnvCell> LoadLandblock(DatDatabase cellDat, DatDatabase portalDat, uint landblock)
{
if (landblock > 0xFFFF) landblock >>= 16;
var envCache = new Dictionary<uint, Dictionary<uint, RawCellStruct>>();
var cells = new List<EnvCell>();
foreach (uint id in cellDat.GetLandblockCellIds(landblock))
{
byte[]? data = cellDat.GetFileData(id);
if (data == null) continue;
EnvCell? c = ParseEnvCell(data);
if (c == null) continue;
c.Id = id;
if (!envCache.TryGetValue(c.EnvironmentId, out var structs))
{
byte[]? env = portalDat.GetFileData(c.EnvironmentId);
structs = env == null ? new() : ParseEnvironmentSafe(env);
envCache[c.EnvironmentId] = structs;
}
if (structs.TryGetValue(c.CellStructure, out RawCellStruct? cs))
Attach(c, cs);
c.ComputeBounds();
cells.Add(c);
}
return cells;
}
/// <summary>A point in the cell's own frame to landblock-local.</summary>
public static Vector3 ToLandblock(EnvCell c, Vector3 local) => Vector3.Transform(local, c.Rotation) + c.Origin;
private static void Attach(EnvCell c, RawCellStruct cs)
{
c.GeometryOk = cs.PhysicsOk;
foreach (var poly in cs.Physics)
{
var w = poly.Select(v => ToLandblock(c, v)).ToArray();
Vector3 n = Normal(w);
if (n.Z >= FloorZ) c.Floors.Add(w); else c.Walls.Add(w);
}
foreach (var p in c.Portals)
if (cs.Render.TryGetValue(p.PolygonId, out var poly))
p.Polygon = poly.Select(v => ToLandblock(c, v)).ToArray();
}
/// <summary>Unit normal by the vertex order (ACE Polygon.make_plane: sum of fan cross products).</summary>
public static Vector3 Normal(IReadOnlyList<Vector3> v)
{
Vector3 n = Vector3.Zero;
for (int i = 1; i < v.Count - 1; i++)
n += Vector3.Cross(v[i] - v[0], v[i + 1] - v[0]);
float len = n.Length();
return len < 1e-6f ? Vector3.Zero : n / len;
}
// -- EnvCell ---------------------------------------------------------------
private static EnvCell? ParseEnvCell(byte[] data)
{
try
{
using var r = new BinaryReader(new MemoryStream(data));
var c = new EnvCell();
r.ReadUInt32(); // id
c.Flags = r.ReadUInt32();
r.ReadUInt32(); // id again
byte numSurfaces = r.ReadByte();
byte numPortals = r.ReadByte();
ushort numVisible = r.ReadUInt16();
for (int i = 0; i < numSurfaces; i++) r.ReadUInt16();
c.EnvironmentId = 0x0D000000u | r.ReadUInt16();
c.CellStructure = r.ReadUInt16();
c.Origin = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
c.Rotation = new Quaternion(x, y, z, w);
for (int i = 0; i < numPortals; i++)
c.Portals.Add(new CellPortal { Flags = r.ReadUInt16(), PolygonId = r.ReadUInt16(), OtherCell = r.ReadUInt16(), OtherPortal = r.ReadUInt16() });
for (int i = 0; i < numVisible; i++) c.VisibleCells.Add(r.ReadUInt16());
if ((c.Flags & 0x2) != 0)
{
uint n = r.ReadUInt32();
for (uint i = 0; i < n && i < 4096; i++)
{
// A stab's frame is landblock-local, like the cell's own (not relative to the cell).
var s = new Stab { Id = r.ReadUInt32(), Origin = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()) };
float sw = r.ReadSingle(), sx = r.ReadSingle(), sy = r.ReadSingle(), sz = r.ReadSingle();
s.Rotation = new Quaternion(sx, sy, sz, sw);
c.Stabs.Add(s);
}
}
return c;
}
catch (EndOfStreamException) { return null; }
}
// -- Environment / CellStruct ----------------------------------------------
private sealed class RawCellStruct
{
public Dictionary<ushort, Vector3[]> Render = new();
public List<Vector3[]> Physics = new();
public bool PhysicsOk;
}
// A damaged Environment must not take the landblock down: keep what parsed before the damage.
private static Dictionary<uint, RawCellStruct> ParseEnvironmentSafe(byte[] data)
{
var result = new Dictionary<uint, RawCellStruct>();
try { ParseEnvironment(data, result); }
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException or ArgumentException) { }
return result;
}
private static void ParseEnvironment(byte[] data, Dictionary<uint, RawCellStruct> result)
{
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); // id
uint n = r.ReadUInt32();
for (uint i = 0; i < n && i < 512; i++)
{
uint key = r.ReadUInt32();
var cs = ParseCellStruct(r, ms, out bool toEnd);
if (cs == null) break;
result[key] = cs;
if (!toEnd) break; // stream position unknown after this one
}
}
private static RawCellStruct? ParseCellStruct(BinaryReader r, MemoryStream ms, out bool toEnd)
{
toEnd = false;
uint numPolys = r.ReadUInt32(), numPhys = r.ReadUInt32(), numPortals = r.ReadUInt32();
if (numPolys > 5000 || numPhys > 5000) return null;
var verts = ReadVertexArray(r, ms);
if (verts == null) return null;
var cs = new RawCellStruct();
foreach (var (key, ids) in ReadPolygons(r, ms, numPolys))
cs.Render[key] = Resolve(ids, verts);
for (uint i = 0; i < numPortals; i++) r.ReadUInt16();
Align(ms);
if (!SkipBsp(r, ms, Bsp.Cell)) return cs;
foreach (var (_, ids) in ReadPolygons(r, ms, numPhys))
{
var p = Resolve(ids, verts);
if (p.Length >= 3) cs.Physics.Add(p);
}
cs.PhysicsOk = cs.Physics.Count > 0;
if (!SkipBsp(r, ms, Bsp.Physics)) return cs;
if (ms.Position + 4 <= ms.Length && r.ReadUInt32() != 0 && !SkipBsp(r, ms, Bsp.Drawing)) return cs;
Align(ms);
toEnd = true;
return cs;
}
internal static Vector3[] Resolve(List<ushort> ids, Dictionary<ushort, Vector3> verts)
{
var list = new List<Vector3>(ids.Count);
foreach (var id in ids) if (verts.TryGetValue(id, out var v)) list.Add(v);
return list.ToArray();
}
private static void Align(MemoryStream ms)
{
long a = (ms.Position + 3) & ~3L;
if (a <= ms.Length) ms.Position = a;
}
internal static Dictionary<ushort, Vector3>? ReadVertexArray(BinaryReader r, MemoryStream ms)
{
if (r.ReadInt32() != 1) return null;
uint n = r.ReadUInt32();
if (n > 50000) return null;
var verts = new Dictionary<ushort, Vector3>();
for (uint i = 0; i < n; i++)
{
ushort key = r.ReadUInt16();
ushort numUv = r.ReadUInt16();
var v = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
ms.Seek(12 + numUv * 8L, SeekOrigin.Current); // normal + UVs
verts[key] = v;
}
return verts;
}
internal static List<(ushort, List<ushort>)> ReadPolygons(BinaryReader r, MemoryStream ms, uint count)
{
var polys = new List<(ushort, List<ushort>)>();
for (uint i = 0; i < count; i++)
{
ushort key = r.ReadUInt16();
byte numPts = r.ReadByte();
byte stippling = r.ReadByte();
int sides = r.ReadInt32();
r.ReadInt16(); r.ReadInt16(); // surfaces
if (numPts == 0 || numPts > 50) throw new InvalidDataException("bad polygon");
var ids = new List<ushort>(numPts);
for (int v = 0; v < numPts; v++) ids.Add((ushort)r.ReadInt16());
if ((stippling & 0x04) == 0) ms.Seek(numPts, SeekOrigin.Current);
if (sides == 2 && (stippling & 0x08) == 0) ms.Seek(numPts, SeekOrigin.Current);
polys.Add((key, ids));
}
return polys;
}
private enum Bsp { Cell, Physics, Drawing }
private const uint PORT = 0x504F5254, LEAF = 0x4C454146, BPnn = 0x42506E6E, BPIn = 0x4250496E, BpIN = 0x4270494E,
BpnN = 0x42706E4E, BPIN = 0x4250494E, BPnN = 0x42506E4E, BPFL = 0x4250464C, BPOL = 0x42504F4C, BpIn = 0x4270496E;
private static bool SkipBsp(BinaryReader r, MemoryStream ms, Bsp t)
{
if (ms.Position + 4 > ms.Length) return false;
uint tag = r.ReadUInt32();
if (tag == LEAF || tag == PORT)
{
r.ReadInt32(); // leaf index
if (t == Bsp.Physics)
{
r.ReadInt32(); // solid
ms.Seek(16, SeekOrigin.Current); // sphere
uint np = r.ReadUInt32();
if (np > 100000) return false;
ms.Seek(np * 2L, SeekOrigin.Current);
}
return ms.Position <= ms.Length;
}
ms.Seek(16, SeekOrigin.Current); // splitting plane
switch (tag)
{
case BPnn: case BPIn: case BpIN: case BpnN:
if (!SkipBsp(r, ms, t)) return false;
break;
case BPIN: case BPnN:
if (!SkipBsp(r, ms, t) || !SkipBsp(r, ms, t)) return false;
break;
case BPFL: case BPOL: case BpIn:
break;
default:
return false;
}
if (t == Bsp.Cell) return true;
ms.Seek(16, SeekOrigin.Current); // sphere
if (t == Bsp.Physics) return true;
uint n = r.ReadUInt32();
if (n > 100000) return false;
ms.Seek(n * 2L, SeekOrigin.Current);
return ms.Position <= ms.Length;
}
}

View file

@ -0,0 +1,123 @@
// ============================================================================
// RynthCore.Geometry - Cells/EnvCell.cs
// The indoor cell model: an EnvCell (dungeon / building interior cell) with
// its frame, cell portals (doorway polygons and the cell beyond), static
// objects, and its physics polygons split into floors and walls, all in
// landblock-local coordinates. Filled by CellDat.LoadLandblock.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/CellDat.cs (3a8075a).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
namespace RynthCore.Geometry.Cells;
/// <summary>A doorway of an EnvCell: the polygon you walk through and the cell on its other side.</summary>
public sealed class CellPortal
{
/// <summary>Raw portal flags (0x2 = PortalSide).</summary>
public ushort Flags;
/// <summary>Key into the CellStruct's render polygons.</summary>
public ushort PolygonId;
/// <summary>Low 16 bits of the cell on the other side; <see cref="Outdoors"/> (0xFFFF) = leads outdoors.</summary>
public ushort OtherCell;
public ushort OtherPortal;
/// <summary>The doorway polygon, landblock-local (empty when the CellStruct did not have it).</summary>
public Vector3[] Polygon = Array.Empty<Vector3>();
/// <summary><see cref="OtherCell"/> value of a portal that leads outdoors.</summary>
public const ushort Outdoors = 0xFFFF;
public bool LeadsOutdoors => OtherCell == Outdoors;
/// <summary>
/// ACE's CellPortal.PortalSide (flag 0x2 clear): the cell behind the portal is on the front of
/// <see cref="Polygon"/> (the side its vertex-order normal, <see cref="CellDat.Normal"/>, points to) and
/// this cell on its back; when false, the other way round. Checked against the cells' floor plans for
/// every doorway of dungeon 0x6146 (GeometryTests "cells").
/// </summary>
public bool PortalSide => (Flags & 0x2) == 0;
}
/// <summary>A static object placed in a cell: a GfxObj (0x01..) or a Setup (0x02..).</summary>
public sealed class Stab
{
public uint Id;
/// <summary>Landblock-local (like the cell's own frame, not relative to the cell).</summary>
public Vector3 Origin;
public Quaternion Rotation;
}
/// <summary>
/// One indoor cell (0xLLLL0100..0xLLLLFFFD). Every position and polygon is landblock-local
/// (the same frame as ACE positions: x, y in 0..192 for the landblock, z absolute).
/// </summary>
public sealed class EnvCell
{
/// <summary>Full cell id 0xLLLLCCCC.</summary>
public uint Id;
public uint Flags;
public uint EnvironmentId;
public ushort CellStructure;
/// <summary>The cell frame, landblock-local; the CellStruct's vertices are rotated by
/// <see cref="Rotation"/> then offset by <see cref="Origin"/>.</summary>
public Vector3 Origin;
public Quaternion Rotation;
public List<CellPortal> Portals = new();
public List<ushort> VisibleCells = new();
public List<Stab> Stabs = new();
/// <summary>Physics polygons facing up (normal.Z &gt;= <see cref="CellDat.FloorZ"/>), landblock-local.</summary>
public List<Vector3[]> Floors = new();
/// <summary>Every other physics polygon (walls, ceilings, steep slopes), landblock-local.</summary>
public List<Vector3[]> Walls = new();
/// <summary>The Environment's CellStruct for this cell was found and has physics polygons.</summary>
public bool GeometryOk;
/// <summary>XY bounds of <see cref="Floors"/> (empty bounds when there are no floors).</summary>
public float MinX = float.MaxValue, MinY = float.MaxValue, MaxX = float.MinValue, MaxY = float.MinValue;
/// <summary>The low word: the cell number inside its landblock.</summary>
public ushort Short => (ushort)(Id & 0xFFFF);
/// <summary>The landblock key 0xXXYY.</summary>
public uint Landblock => Id >> 16;
/// <summary>The full id of the cell behind <paramref name="p"/> (meaningless when it leads outdoors).</summary>
public uint Neighbour(CellPortal p) => (Id & 0xFFFF0000u) | p.OtherCell;
/// <summary>Is a cell low word an indoor (EnvCell) number?</summary>
public static bool IsIndoor(uint cellId)
{
uint low = cellId & 0xFFFF;
return low >= 0x0100 && low <= 0xFFFD;
}
internal bool BoundsContain(float x, float y, float margin) =>
x >= MinX - margin && x <= MaxX + margin && y >= MinY - margin && y <= MaxY + margin;
/// <summary>
/// Is (x, y) inside the cell's plan seen from above: over one of its floors, or under one of its other
/// physics polygons that has area from above (ceilings, steep slopes), within <paramref name="eps"/>?
/// </summary>
public bool CoversXY(float x, float y, float eps = 0.05f)
{
foreach (var f in Floors)
if (Geo.InsideXY(f, x, y, eps)) return true;
foreach (var w in Walls)
if (Geo.AreaXY(w) > 0.01f && Geo.InsideXY(w, x, y, eps)) return true;
return false;
}
internal void ComputeBounds()
{
MinX = MinY = float.MaxValue; MaxX = MaxY = float.MinValue;
foreach (var f in Floors)
foreach (var v in f)
{
MinX = MathF.Min(MinX, v.X); MaxX = MathF.Max(MaxX, v.X);
MinY = MathF.Min(MinY, v.Y); MaxY = MathF.Max(MaxY, v.Y);
}
}
public override string ToString() => $"EnvCell {Id:X8} ({Floors.Count} floors, {Walls.Count} walls, {Portals.Count} portals)";
}

View file

@ -0,0 +1,216 @@
// ============================================================================
// RynthCore.Geometry - Cells/Geo.cs
// Small geometry helpers for the indoor queries: 2D tests on the floor plan
// (point in polygon seen from above, distances, plane height) and the 3D
// segment-through-polygon test used to cross cell portals.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/Geometry.cs (3a8075a);
// SegmentCrossesToward, DistToPolygon and SphereRestZ are new (2026-10-28).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
namespace RynthCore.Geometry.Cells;
/// <summary>Small geometry helpers: 2D tests on the floor plan, 3D segment-through-polygon.</summary>
public static class Geo
{
/// <summary>Is (x, y) inside the polygon's outline seen from above (edges count as inside within eps)?</summary>
public static bool InsideXY(IReadOnlyList<Vector3> poly, float x, float y, float eps = 0.01f)
{
bool inside = false;
int n = poly.Count;
for (int i = 0, j = n - 1; i < n; j = i++)
{
Vector3 a = poly[i], b = poly[j];
if ((a.Y > y) != (b.Y > y))
{
float xc = (b.X - a.X) * (y - a.Y) / (b.Y - a.Y) + a.X;
if (x < xc) inside = !inside;
}
}
if (inside || eps <= 0) return inside;
return DistToOutlineXY(poly, x, y) <= eps;
}
/// <summary>Distance from (x, y) to the polygon's outline seen from above (0 inside when filled).</summary>
public static float DistXY(IReadOnlyList<Vector3> poly, float x, float y, bool filled)
{
if (filled && poly.Count >= 3 && AreaXY(poly) > 1e-4f && InsideXY(poly, x, y, 0)) return 0;
return DistToOutlineXY(poly, x, y);
}
public static float DistToOutlineXY(IReadOnlyList<Vector3> poly, float x, float y)
{
float best = float.MaxValue;
int n = poly.Count;
for (int i = 0, j = n - 1; i < n; j = i++)
best = MathF.Min(best, DistToSegXY(poly[j].X, poly[j].Y, poly[i].X, poly[i].Y, x, y));
return best;
}
public static float DistToSegXY(float ax, float ay, float bx, float by, float px, float py)
{
float dx = bx - ax, dy = by - ay;
float len2 = dx * dx + dy * dy;
float t = len2 < 1e-12f ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / len2, 0, 1);
float ex = ax + t * dx - px, ey = ay + t * dy - py;
return MathF.Sqrt(ex * ex + ey * ey);
}
public static float AreaXY(IReadOnlyList<Vector3> poly)
{
float a = 0;
for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
a += poly[j].X * poly[i].Y - poly[i].X * poly[j].Y;
return MathF.Abs(a) * 0.5f;
}
/// <summary>Height of a (non-vertical) planar polygon's plane at (x, y).</summary>
public static float PlaneZ(IReadOnlyList<Vector3> poly, float x, float y)
{
Vector3 n = CellDat.Normal(poly);
if (MathF.Abs(n.Z) < 1e-4f) return poly[0].Z;
Vector3 p = poly[0];
return p.Z - (n.X * (x - p.X) + n.Y * (y - p.Y)) / n.Z;
}
/// <summary>Does the segment a-b pass through the planar polygon (edges included within eps)?</summary>
public static bool SegmentCrosses(IReadOnlyList<Vector3> poly, Vector3 a, Vector3 b, float eps = 0.02f)
{
if (poly.Count < 3) return false;
Vector3 n = CellDat.Normal(poly);
if (n == Vector3.Zero) return false;
float da = Vector3.Dot(n, a - poly[0]), db = Vector3.Dot(n, b - poly[0]);
if ((da > 0 && db > 0) || (da < 0 && db < 0)) return false;
float denom = da - db;
if (MathF.Abs(denom) < 1e-7f) return false; // in the plane: not a crossing
return HitsInside(poly, n, a + (b - a) * (da / denom), eps);
}
/// <summary>
/// Does the segment a-b go through the planar polygon in one direction: from its back to its front
/// (<paramref name="towardFront"/>; the front is the side the vertex-order normal points to, see
/// <see cref="CellDat.Normal"/>) or front to back? A point within <paramref name="planeTol"/> of the
/// plane still counts as on the side it is coming from, so stepping a path sample by sample, each
/// crossing is seen once, by the step that ends clearly beyond the plane.
/// </summary>
public static bool SegmentCrossesToward(IReadOnlyList<Vector3> poly, Vector3 a, Vector3 b, bool towardFront,
float eps = 0.02f, float planeTol = 0.0005f)
{
if (poly.Count < 3) return false;
Vector3 n = CellDat.Normal(poly);
if (n == Vector3.Zero) return false;
float s = towardFront ? 1f : -1f;
float da = s * Vector3.Dot(n, a - poly[0]), db = s * Vector3.Dot(n, b - poly[0]);
if (da > planeTol || db <= planeTol) return false;
float t = da >= 0 ? 0 : da / (da - db); // where it meets the plane
return HitsInside(poly, n, a + (b - a) * t, eps);
}
/// <summary>
/// Is <paramref name="p"/> clearly on one side of the planar polygon (its front when
/// <paramref name="front"/>, else its back), at most <paramref name="maxDist"/> from the plane, and does it
/// drop onto the polygon itself (not beside it) along the normal?
/// </summary>
public static bool BeyondThrough(IReadOnlyList<Vector3> poly, Vector3 p, bool front, float maxDist,
float eps = 0.02f, float planeTol = 0.0005f)
{
if (poly.Count < 3) return false;
Vector3 n = CellDat.Normal(poly);
if (n == Vector3.Zero) return false;
float d = Vector3.Dot(n, p - poly[0]);
float side = front ? d : -d;
if (side <= planeTol || side > maxDist) return false;
return HitsInside(poly, n, p - n * d, eps);
}
// Is p (on the polygon's plane) inside it? Tested in the plane, dropping the normal's dominant axis.
private static bool HitsInside(IReadOnlyList<Vector3> poly, Vector3 n, Vector3 p, float eps)
{
int drop = DominantAxis(n);
var flat = new Vector3[poly.Count];
for (int i = 0; i < flat.Length; i++) flat[i] = Flatten(poly[i], drop);
Vector3 fp = Flatten(p, drop);
return InsideXY(flat, fp.X, fp.Y, eps);
}
/// <summary>3D distance from <paramref name="p"/> to the planar polygon (its surface, edges and corners).</summary>
public static float DistToPolygon(IReadOnlyList<Vector3> poly, Vector3 p)
{
Vector3 n = CellDat.Normal(poly);
if (n != Vector3.Zero)
{
float d = Vector3.Dot(n, p - poly[0]);
Vector3 q = p - n * d;
int drop = DominantAxis(n);
var flat = new Vector3[poly.Count];
for (int i = 0; i < flat.Length; i++) flat[i] = Flatten(poly[i], drop);
Vector3 fq = Flatten(q, drop);
if (InsideXY(flat, fq.X, fq.Y, 0)) return MathF.Abs(d);
}
float best = float.MaxValue;
for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
best = MathF.Min(best, DistToSegment(poly[j], poly[i], p));
return best;
}
public static float DistToSegment(Vector3 a, Vector3 b, Vector3 p)
{
Vector3 ab = b - a;
float len2 = ab.LengthSquared();
float t = len2 < 1e-12f ? 0 : Math.Clamp(Vector3.Dot(p - a, ab) / len2, 0, 1);
return Vector3.Distance(a + ab * t, p);
}
/// <summary>
/// Where a sphere of radius <paramref name="radius"/> above (x, y) comes to rest on the polygon when
/// lowered onto it: the height of the sphere's bottom (centre - radius), or null when the polygon is not
/// under the sphere. On a flat floor that is the floor height; on a slope with normal n it is
/// radius * (1 / n.Z - 1) above the plane (the sphere touches uphill of its centre); near an edge or a
/// corner the sphere rests on that.
/// </summary>
public static float? SphereRestZ(IReadOnlyList<Vector3> poly, float x, float y, float radius)
{
if (poly.Count < 3) return null;
// A height at which the sphere's centre is within radius of the polygon: the polygon's own height
// at the point of it nearest (x, y) seen from above.
float lo;
if (InsideXY(poly, x, y, 0)) lo = PlaneZ(poly, x, y);
else
{
float best = float.MaxValue; lo = 0;
for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
{
Vector3 a = poly[j], b = poly[i];
float dx = b.X - a.X, dy = b.Y - a.Y, len2 = dx * dx + dy * dy;
float t = len2 < 1e-12f ? 0 : Math.Clamp(((x - a.X) * dx + (y - a.Y) * dy) / len2, 0, 1);
float ex = a.X + t * dx - x, ey = a.Y + t * dy - y, d = MathF.Sqrt(ex * ex + ey * ey);
if (d < best) { best = d; lo = a.Z + t * (b.Z - a.Z); }
}
if (best > radius) return null;
}
// Distance from the centre to the polygon is convex in the centre's height, so the heights within
// radius form an interval holding lo; its top is where the sphere rests.
float hi = float.MinValue;
foreach (var v in poly) hi = MathF.Max(hi, v.Z);
hi += radius + 0.01f;
for (int it = 0; it < 40 && hi - lo > 1e-4f; it++)
{
float mid = 0.5f * (lo + hi);
if (DistToPolygon(poly, new Vector3(x, y, mid)) <= radius) lo = mid; else hi = mid;
}
return lo - radius;
}
private static int DominantAxis(Vector3 n) =>
MathF.Abs(n.X) > MathF.Abs(n.Y) ? (MathF.Abs(n.X) > MathF.Abs(n.Z) ? 0 : 2) : (MathF.Abs(n.Y) > MathF.Abs(n.Z) ? 1 : 2);
private static Vector3 Flatten(Vector3 v, int drop) => drop switch
{
0 => new Vector3(v.Y, v.Z, 0),
1 => new Vector3(v.X, v.Z, 0),
_ => new Vector3(v.X, v.Y, 0),
};
}

View file

@ -0,0 +1,217 @@
// ============================================================================
// RynthCore.Geometry - Cells/Indoor.cs
// An indoor world for walk planning: a set of EnvCells plus solid footprints
// (walls, static objects, NPCs) and portal objects to keep clear of. Queries:
// floor height in a cell, doorways between cells, a floor-following trace of
// a straight segment through cell portals, and clearance from solids.
// For the cached per-landblock queries (FindCell, TrackCell) see IndoorWorld.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/Indoor.cs (3a8075a).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
namespace RynthCore.Geometry.Cells;
/// <summary>Something solid seen from above: a polygon outline (or a disc), between two heights.</summary>
public sealed class Footprint
{
public Vector3[] Poly = Array.Empty<Vector3>();
/// <summary>The outline has area: inside counts as touching.</summary>
public bool Filled;
/// <summary>A disc when <see cref="Poly"/> is empty.</summary>
public Vector2 Center; public float Radius;
public float ZMin, ZMax;
public string Source = "";
public float MinX, MinY, MaxX, MaxY;
public float Dist(float x, float y) =>
Poly.Length == 0 ? MathF.Max(0, Vector2.Distance(Center, new Vector2(x, y)) - Radius) : Geo.DistXY(Poly, x, y, Filled);
/// <summary>Does it stand in the way of someone whose feet are at z (step over below +0.45, head at +1.8)?</summary>
public bool Blocks(float z) => ZMax > z + Indoor.StepUp && ZMin < z + Indoor.BodyHeight;
public void Bounds()
{
if (Poly.Length == 0) { MinX = Center.X - Radius; MaxX = Center.X + Radius; MinY = Center.Y - Radius; MaxY = Center.Y + Radius; return; }
MinX = Poly.Min(v => v.X); MaxX = Poly.Max(v => v.X); MinY = Poly.Min(v => v.Y); MaxY = Poly.Max(v => v.Y);
}
public static Footprint FromPolygon(Vector3[] p, string source)
{
var f = new Footprint { Poly = p, Filled = Geo.AreaXY(p) > 0.01f, ZMin = p.Min(v => v.Z), ZMax = p.Max(v => v.Z), Source = source };
f.Bounds();
return f;
}
public static Footprint Disc(float x, float y, float r, float zmin, float zmax, string source)
{
var f = new Footprint { Center = new Vector2(x, y), Radius = r, ZMin = zmin, ZMax = zmax, Source = source };
f.Bounds();
return f;
}
}
/// <summary>A portal object inside the network: walking into it uses it, so the walks keep clear of all but their own.</summary>
public sealed class PortalZone
{
public string Guid = "";
public string Name = "";
public uint Cell;
public Vector3 Pos;
/// <summary>Its collision radius.</summary>
public float Radius;
}
/// <summary>The indoor world walks are planned in: cells, solid things, portal objects.</summary>
public sealed class Indoor
{
public const float StepUp = 0.45f;
public const float BodyHeight = 1.8f;
/// <summary>Largest height change between neighbouring floor samples.</summary>
public const float StepZ = 0.45f;
public readonly Dictionary<uint, EnvCell> Cells = new();
public readonly List<Footprint> Solids = new();
public readonly List<PortalZone> Portals = new();
public float AgentRadius = 0.5f;
public readonly List<string> Notes = new();
public EnvCell Cell(uint id) => Cells[id];
/// <summary>
/// The floor height of a cell at (x, y), or null when (x, y) is not on its floor. With several floors
/// there, the one nearest <paramref name="near"/>; without <paramref name="near"/>, the first found.
/// </summary>
public static float? FloorZ(EnvCell c, float x, float y, float? near = null, float eps = 0.01f)
{
float? best = null;
foreach (var f in c.Floors)
{
if (!Geo.InsideXY(f, x, y, eps)) continue;
float z = Geo.PlaneZ(f, x, y);
if (best == null || (near != null && MathF.Abs(z - near.Value) < MathF.Abs(best.Value - near.Value))) best = z;
}
return best;
}
/// <summary>The portal polygons of cell a that open into cell b.</summary>
public static IEnumerable<Vector3[]> Doorways(EnvCell a, uint b)
{
ushort bs = (ushort)(b & 0xFFFF);
foreach (var p in a.Portals)
if (p.OtherCell == bs && p.Polygon.Length >= 3) yield return p.Polygon;
}
public static uint Full(EnvCell from, ushort other) => (from.Id & 0xFFFF0000u) | other;
/// <summary>
/// Follows the straight segment a-b along the floor from cell <paramref name="start"/>, sampling every
/// <paramref name="step"/>: every sample must be on the floor of the cell it is in, and the walk may only
/// change cell where the segment passes through a doorway (cell portal) between the two. Returns the cells
/// visited, or null with a reason when the segment leaves the floor or goes through a wall.
/// </summary>
public List<uint>? Trace(Vector3 a, Vector3 b, uint start, out string why, float step = 0.05f) =>
Trace(Cells, a, b, start, out why, step);
/// <summary><see cref="Trace(Vector3, Vector3, uint, out string, float)"/> over any cell set.</summary>
public static List<uint>? Trace(IReadOnlyDictionary<uint, EnvCell> cellsById, Vector3 a, Vector3 b, uint start, out string why, float step = 0.05f)
{
why = "";
var cells = new List<uint> { start };
if (!cellsById.TryGetValue(start, out EnvCell? cur)) { why = $"cell {start:X8} is not loaded"; return null; }
float len = Vector2.Distance(new Vector2(a.X, a.Y), new Vector2(b.X, b.Y));
int n = Math.Max(1, (int)MathF.Ceiling(len / step));
Vector3 prev = a;
float prevZ = FloorZ(cur, a.X, a.Y, a.Z, 0.02f) ?? float.NaN;
if (float.IsNaN(prevZ)) { why = $"start ({a.X:F2},{a.Y:F2}) is not on the floor of {start:X8}"; return null; }
for (int i = 1; i <= n; i++)
{
Vector3 p = Vector3.Lerp(a, b, i / (float)n);
// A doorway crossed between the last sample and this one moves us into the next cell.
EnvCell? next = null;
float lift = 0.6f;
var pa = new Vector3(prev.X, prev.Y, prevZ + lift);
foreach (var cp in cur.Portals)
{
if (cp.OtherCell == 0xFFFF || cp.Polygon.Length < 3) continue;
uint oid = Full(cur, cp.OtherCell);
if (!cellsById.TryGetValue(oid, out var other)) continue;
float? oz = FloorZ(other, p.X, p.Y, prevZ, 0.02f);
if (oz == null || MathF.Abs(oz.Value - prevZ) > StepZ) continue;
if (Geo.SegmentCrosses(cp.Polygon, pa, new Vector3(p.X, p.Y, oz.Value + lift))) { next = other; break; }
}
if (next != null)
{
cur = next;
cells.Add(cur.Id);
prevZ = FloorZ(cur, p.X, p.Y, prevZ, 0.02f)!.Value;
}
else
{
float? z = FloorZ(cur, p.X, p.Y, prevZ, 0.02f);
if (z == null) { why = $"({p.X:F2},{p.Y:F2}) is off the floor of {cur.Id:X8}"; return null; }
if (MathF.Abs(z.Value - prevZ) > StepZ) { why = $"({p.X:F2},{p.Y:F2}) height jump {prevZ:F2} -> {z:F2} in {cur.Id:X8}"; return null; }
prevZ = z.Value;
}
prev = p;
}
return cells;
}
/// <summary>The nearest solid thing (that blocks at the floor height z) to (x, y), within limit.</summary>
public float SolidDist(float x, float y, float z, float limit, out Footprint? which)
{
which = null;
float best = limit;
if (_buckets == null) Index();
int bx0 = (int)MathF.Floor((x - limit) / Bucket), bx1 = (int)MathF.Floor((x + limit) / Bucket);
int by0 = (int)MathF.Floor((y - limit) / Bucket), by1 = (int)MathF.Floor((y + limit) / Bucket);
var seen = new HashSet<Footprint>();
for (int bx = bx0; bx <= bx1; bx++)
for (int by = by0; by <= by1; by++)
{
if (!_buckets!.TryGetValue((bx, by), out var list)) continue;
foreach (var f in list)
{
if (!seen.Add(f)) continue;
if (x < f.MinX - best || x > f.MaxX + best || y < f.MinY - best || y > f.MaxY + best) continue;
if (!f.Blocks(z)) continue;
float d = f.Dist(x, y);
if (d < best) { best = d; which = f; }
}
}
return best;
}
private const float Bucket = 4f;
private Dictionary<(int, int), List<Footprint>>? _buckets;
/// <summary>A coarse spatial index of the solids (call again after changing <see cref="Solids"/>).</summary>
public void Index()
{
_buckets = new();
foreach (var f in Solids)
for (int bx = (int)MathF.Floor(f.MinX / Bucket); bx <= (int)MathF.Floor(f.MaxX / Bucket); bx++)
for (int by = (int)MathF.Floor(f.MinY / Bucket); by <= (int)MathF.Floor(f.MaxY / Bucket); by++)
{
if (!_buckets.TryGetValue((bx, by), out var l)) _buckets[(bx, by)] = l = new List<Footprint>();
l.Add(f);
}
}
/// <summary>Clearance from portal objects other than <paramref name="except"/>: distance minus the portal's radius.</summary>
public float PortalDist(float x, float y, float z, string? except, out PortalZone? which)
{
which = null;
float best = float.MaxValue;
foreach (var p in Portals)
{
if (p.Guid == except || MathF.Abs(p.Pos.Z - z) > 2.5f) continue;
float d = Vector2.Distance(new Vector2(p.Pos.X, p.Pos.Y), new Vector2(x, y)) - p.Radius;
if (d < best) { best = d; which = p; }
}
return best;
}
}

View file

@ -0,0 +1,303 @@
// ============================================================================
// RynthCore.Geometry - Cells/IndoorWorld.cs
// The indoor cell index: EnvCells loaded per landblock on first use and kept
// (one load per landblock, thread-safe), with the queries a client needs to
// keep its indoor cell id right:
// FindCell - which cell a landblock-local position stands in;
// FloorZ - the floor height of a cell at (x, y);
// TrackCell - the cell after moving a -> b, following cell portals;
// Floors / Walls / ObjectPolygons - the cell's geometry for collision.
//
// Why it matters: ACE trusts the client's cell id for indoor positions and
// never corrects it, so a wrong cell id is not fixed up by the server.
// Indoor cell ids are 0x0100..0xFFFD in the landblock's low word; a cell
// portal whose OtherCell is 0xFFFF leads outdoors.
//
// Written for RynthCore (MIT) on 2026-10-28, on the EnvCell readers and the
// Trace walk moved from RynthSuite Tools/RynthNav.TownNet (3a8075a).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
namespace RynthCore.Geometry.Cells;
/// <summary>
/// Indoor cells by landblock, loaded lazily from the dats and cached. All coordinates are landblock-local
/// (ACE position frame). Safe to share between threads: each landblock is loaded once (other callers for
/// the same landblock wait for that load) and the loaded cells are never changed afterwards.
/// </summary>
public sealed class IndoorWorld
{
/// <summary>FindCell: a floor up to this far above the feet still counts (steps, rounding).</summary>
public const float FindAbove = 0.5f;
/// <summary>FindCell: floors further below the feet than this are ignored.</summary>
public const float FindBelow = 3.0f;
/// <summary>TrackCell: sample spacing along the move.</summary>
public const float TrackStep = 0.05f;
/// <summary>TrackCell: the move is tested this far above the feet, so it passes through doorways, not their sills.</summary>
public const float PortalLift = 0.6f;
private const float FloorEps = 0.02f; // edge tolerance of floor point-in-polygon tests
private const float TieZ = 0.02f; // floors this close in height are the same level
private const float InCellEps = 0.05f; // TrackCell: still in the cell this close to its outline
private const float SlopedDoorwayReach = 2.0f; // TrackCell: how far past a sloping doorway's plane it still counts
private readonly DatDatabase _cellDat;
private readonly DatDatabase _portalDat;
private readonly ConcurrentDictionary<uint, Lazy<Landblock>> _landblocks = new();
/// <summary>Models for the cells' static objects (shared cache).</summary>
public ModelReader Models { get; }
public IndoorWorld(DatDatabase cellDat, DatDatabase portalDat, ModelReader? models = null)
{
_cellDat = cellDat;
_portalDat = portalDat;
Models = models ?? new ModelReader(portalDat);
}
private sealed class Landblock
{
public readonly IReadOnlyList<EnvCell> Cells;
public readonly Dictionary<uint, EnvCell> ById;
public Landblock(List<EnvCell> cells)
{
Cells = cells;
ById = cells.ToDictionary(c => c.Id);
}
}
private static uint Key(uint landblockOrCell) => landblockOrCell > 0xFFFF ? landblockOrCell >> 16 : landblockOrCell;
private Landblock Get(uint landblockOrCell) =>
_landblocks.GetOrAdd(Key(landblockOrCell), lb => new Lazy<Landblock>(
() => new Landblock(CellDat.LoadLandblock(_cellDat, _portalDat, lb)),
LazyThreadSafetyMode.ExecutionAndPublication)).Value;
/// <summary>
/// The EnvCells of a landblock (0xXXYY, or any cell id 0xXXYYnnnn of it), ascending by id; empty for a
/// landblock with no indoor cells. Loaded on first use and cached.
/// </summary>
public IReadOnlyList<EnvCell> LoadLandblock(uint landblock) => Get(landblock).Cells;
/// <summary>Forgets a landblock's cells (they are loaded again on next use).</summary>
public void Unload(uint landblock) => _landblocks.TryRemove(Key(landblock), out _);
/// <summary>The cell with full id <paramref name="cellId"/>, or null when it is not an indoor cell in the dats.</summary>
public EnvCell? GetCell(uint cellId)
{
if (!EnvCell.IsIndoor(cellId)) return null;
return Get(cellId).ById.TryGetValue(cellId, out var c) ? c : null;
}
/// <summary>
/// The indoor cell a landblock-local position (x, y, z = feet) stands in, and its floor height there.
/// <para>
/// Every cell floor polygon whose outline (seen from above) contains (x, y) is a candidate if its height
/// there is at most <see cref="FindAbove"/> above z and at most <see cref="FindBelow"/> below it; the
/// highest candidate wins (the floor nearest at-or-below the feet). Floors at the same height (within
/// 2 cm, e.g. two cells meeting at a doorway) are settled by the point being strictly inside, then by
/// its distance from the polygon's edge.
/// </para>
/// <para>
/// Overhangs: where cells are stacked (a bridge or upper floor above a lower room), a floor more than
/// 0.5 m above the feet is ignored, so someone under a bridge stays in the lower cell, and someone on
/// the bridge gets the bridge cell because it is the highest floor at or below their feet. A floor less
/// than 0.5 m above the feet (a thin overhang right above someone's head is never that low; a step is)
/// would win, and someone falling past several stacked floors gets the highest one at or below them.
/// More than 3 m above any floor (high in the air, or off the floor plan) gives null.
/// </para>
/// </summary>
public (uint cellId, float floorZ)? FindCell(uint landblock, float x, float y, float z)
{
EnvCell? best = null;
float bestZ = 0, bestMargin = 0;
foreach (var c in Get(landblock).Cells)
{
if (!c.BoundsContain(x, y, FloorEps)) continue;
foreach (var f in c.Floors)
{
if (!Geo.InsideXY(f, x, y, FloorEps)) continue;
float fz = Geo.PlaneZ(f, x, y);
if (fz > z + FindAbove || fz < z - FindBelow) continue;
float edge = Geo.DistToOutlineXY(f, x, y);
float margin = Geo.InsideXY(f, x, y, 0) ? edge : -edge;
bool better = best == null
|| fz > bestZ + TieZ
|| (fz >= bestZ - TieZ && margin > bestMargin);
if (better) { best = c; bestZ = fz; bestMargin = margin; }
}
}
return best == null ? null : (best.Id, bestZ);
}
/// <summary>
/// The floor height of cell <paramref name="cellId"/> at (x, y), or null when (x, y) is not over its floor
/// (or the cell is unknown). Where the cell has several floors over (x, y), the one nearest
/// <paramref name="near"/>, or the highest when <paramref name="near"/> is null.
/// </summary>
public float? FloorZ(uint cellId, float x, float y, float? near = null)
{
var c = GetCell(cellId);
return c == null ? null : CellFloorZ(c, x, y, near, FloorEps);
}
/// <summary><see cref="FloorZ(uint, float, float, float?)"/> for a cell already in hand.</summary>
public static float? CellFloorZ(EnvCell c, float x, float y, float? near = null, float eps = FloorEps)
{
float? best = null;
foreach (var f in c.Floors)
{
if (!Geo.InsideXY(f, x, y, eps)) continue;
float z = Geo.PlaneZ(f, x, y);
bool better = best == null || (near != null
? MathF.Abs(z - near.Value) < MathF.Abs(best.Value - near.Value)
: z > best.Value);
if (better) best = z;
}
return best;
}
/// <summary>
/// The height of the feet of someone standing in cell <paramref name="cellId"/> at (x, y), whose body
/// touches the floor with a sphere of radius <paramref name="radius"/> (the human Setup 0x02000001 uses
/// 0.48 m; see <see cref="ModelReader"/>). This is the z ACE reports for a grounded creature: equal to
/// <see cref="FloorZ"/> on flat floor, but above the floor plane on a slope (radius * (1 / n.Z - 1),
/// about 0.12 m on a 37 degree ramp) and where a ramp meets a flat floor. Null when (x, y) is not over
/// the cell's floor.
/// <para>The sphere rests on the highest floor polygon under it among those at the level picked by
/// <see cref="FloorZ"/> (with <paramref name="near"/>): from 0.5 m below to <see cref="FindAbove"/>
/// above that floor.</para>
/// </summary>
public float? StandZ(uint cellId, float x, float y, float radius, float? near = null)
{
var c = GetCell(cellId);
return c == null ? null : CellStandZ(c, x, y, radius, near);
}
/// <summary><see cref="StandZ"/> for a cell already in hand.</summary>
public static float? CellStandZ(EnvCell c, float x, float y, float radius, float? near = null)
{
float? level = CellFloorZ(c, x, y, near);
if (level == null) return null;
float best = level.Value;
foreach (var f in c.Floors)
{
float? rz = Geo.SphereRestZ(f, x, y, radius);
if (rz == null || rz.Value < level.Value - 0.5f || rz.Value > level.Value + FindAbove) continue;
best = MathF.Max(best, rz.Value);
}
return best;
}
/// <summary>
/// The cell someone is in after moving in a straight line from <paramref name="a"/> to <paramref name="b"/>
/// (landblock-local feet positions), starting in indoor cell <paramref name="fromCell"/>.
/// <para>
/// The move is sampled every <see cref="TrackStep"/> and tested <see cref="PortalLift"/> above the feet.
/// Each step that passes through one of the current cell's portal polygons outward (toward the side
/// <see cref="CellPortal.PortalSide"/> gives the other cell) moves into the cell behind it, any number
/// of cells along the way. A point exactly on a doorway's plane (within 0.5 mm) stays in the cell it
/// came from, so a stop right in a doorway does not flip cells.
/// </para>
/// <para>
/// Against ACE (dungeon 0x6146): for 19476 pairs of captured positions in neighbouring cells up to 4 m
/// apart, 19473 end in the other position's cell; the 3 others end at one position that lies 2 mm on
/// the near side of a doorway's plane although ACE puts it in the far cell.
/// </para>
/// Returns:
/// <list type="bullet">
/// <item>the final cell's id (<paramref name="fromCell"/> itself when no portal was crossed);</item>
/// <item>0 when the move goes out through a portal whose OtherCell is 0xFFFF: the walker is outdoors and
/// the caller computes the outdoor land cell from the position;</item>
/// <item><paramref name="fromCell"/> when the move cannot be followed: a sample leaves the current cell's
/// floor plan (its physics polygons seen from above) without passing a portal - through a wall, or
/// geometry missing - or <paramref name="fromCell"/> is not a known indoor cell. Treat that as "blocked or
/// unknown": keep the old cell, and re-check with <see cref="FindCell"/> if in doubt.</item>
/// </list>
/// </summary>
public uint TrackCell(uint fromCell, Vector3 a, Vector3 b)
{
if (!EnvCell.IsIndoor(fromCell)) return fromCell;
var lb = Get(fromCell);
if (!lb.ById.TryGetValue(fromCell, out var cur)) return fromCell;
float len = Vector3.Distance(a, b);
int n = Math.Max(1, (int)MathF.Ceiling(len / TrackStep));
var lift = new Vector3(0, 0, PortalLift);
Vector3 prev = a;
for (int i = 1; i <= n; i++)
{
Vector3 p = Vector3.Lerp(a, b, i / (float)n);
EnvCell? next = null;
foreach (var cp in cur.Portals)
{
if (cp.Polygon.Length < 3) continue;
if (!Geo.SegmentCrossesToward(cp.Polygon, prev + lift, p + lift, cp.PortalSide)) continue;
if (cp.LeadsOutdoors) return 0;
if (lb.ById.TryGetValue(cur.Neighbour(cp), out var other)) { next = other; break; }
}
if (next != null)
{
// A sloping doorway (a tunnel mouth under a slanted roof, dungeon 0x6346) is crossed this high
// above the feet before the floor beyond it starts: until it does, stay on this cell's floor.
if (next.CoversXY(p.X, p.Y, InCellEps) || !cur.CoversXY(p.X, p.Y, InCellEps)) cur = next;
}
else if (!cur.CoversXY(p.X, p.Y, InCellEps))
{
// Off this floor: into the cell behind a sloping doorway passed (above the feet) earlier.
EnvCell? beyond = BeyondSlopedDoorway(lb, cur, p, p + lift);
if (beyond == null) return fromCell;
cur = beyond;
}
prev = p;
}
return cur.Id;
}
// The neighbour whose floor plan covers p, behind one of cur's doorways that the feet or the lifted point
// are already through: beyond the doorway's plane (by less than a step) and over the doorway itself, not
// the wall beside it. Walking down under a sloping doorway the lifted point passes it first; walking up
// out from under it, the feet do.
private static EnvCell? BeyondSlopedDoorway(Landblock lb, EnvCell cur, Vector3 p, Vector3 lifted)
{
foreach (var cp in cur.Portals)
{
if (cp.Polygon.Length < 3 || cp.LeadsOutdoors) continue;
if (!lb.ById.TryGetValue(cur.Neighbour(cp), out var other)) continue;
if (!other.CoversXY(p.X, p.Y, InCellEps)) continue;
if (Geo.BeyondThrough(cp.Polygon, lifted, cp.PortalSide, SlopedDoorwayReach)
|| Geo.BeyondThrough(cp.Polygon, p, cp.PortalSide, SlopedDoorwayReach))
return other;
}
return null;
}
/// <summary>The cell's floor polygons (walkable physics polygons), landblock-local; empty for an unknown cell.</summary>
public IReadOnlyList<Vector3[]> Floors(uint cellId) => GetCell(cellId)?.Floors ?? (IReadOnlyList<Vector3[]>)Array.Empty<Vector3[]>();
/// <summary>The cell's other physics polygons (walls, ceilings, steep slopes), landblock-local; empty for an unknown cell.</summary>
public IReadOnlyList<Vector3[]> Walls(uint cellId) => GetCell(cellId)?.Walls ?? (IReadOnlyList<Vector3[]>)Array.Empty<Vector3[]>();
/// <summary>The physics polygons of the cell's static objects, placed landblock-local (objects without physics give none).</summary>
public IEnumerable<Vector3[]> ObjectPolygons(uint cellId)
{
var c = GetCell(cellId);
if (c == null) yield break;
foreach (var s in c.Stabs)
foreach (var p in Models.Get(s.Id).Place(s.Origin, s.Rotation))
yield return p;
}
/// <summary>The cells next to <paramref name="cellId"/> through its portals (full ids; outdoors not included).</summary>
public IEnumerable<uint> Neighbours(uint cellId)
{
var c = GetCell(cellId);
if (c == null) yield break;
foreach (var p in c.Portals)
if (!p.LeadsOutdoors) yield return c.Neighbour(p);
}
}

View file

@ -0,0 +1,88 @@
// ============================================================================
// RynthCore.Geometry - Collision/CollisionTri.cs
// One solid triangle of the outdoor world (a face of a static object, a
// building shell, a building cell or a piece of scenery), landblock-local,
// with its unit normal by vertex order and the id of what it came from; and
// the segment-vs-triangle test the collision queries use.
//
// Logic from RynthSuite Tools/RynthNav.Baker/CollisionGeometry.cs (d4ae46a),
// Tri and Tri.Hit. Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
namespace RynthCore.Geometry.Collision;
/// <summary>
/// A solid triangle, landblock-local (x, y in the frame of the landblock that was queried, z absolute).
/// <see cref="Normal"/> is the unit normal by vertex order (A, B, C counter-clockwise seen from the side it
/// points to; for a fanned polygon, the whole polygon's normal as ACE's Polygon.make_plane computes it).
/// <see cref="Source"/> is the model id (GfxObj 0x01.. / Setup 0x02..) it belongs to, or the EnvCell id
/// (0xXXYY01nn..) for a building cell's own walls and floors.
/// </summary>
public readonly record struct CollisionTri(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal, uint Source)
{
/// <summary>Can it be stood on: normal.Z at least ACE's FloorZ (0.66417414, about 48 degrees)?</summary>
public bool Walkable => Normal.Z >= CellDat.FloorZ;
public float MinX => MathF.Min(A.X, MathF.Min(B.X, C.X));
public float MaxX => MathF.Max(A.X, MathF.Max(B.X, C.X));
public float MinY => MathF.Min(A.Y, MathF.Min(B.Y, C.Y));
public float MaxY => MathF.Max(A.Y, MathF.Max(B.Y, C.Y));
public float MinZ => MathF.Min(A.Z, MathF.Min(B.Z, C.Z));
public float MaxZ => MathF.Max(A.Z, MathF.Max(B.Z, C.Z));
/// <summary>The same triangle moved by <paramref name="d"/>.</summary>
public CollisionTri Shifted(Vector3 d) => this with { A = A + d, B = B + d, C = C + d };
/// <summary>
/// Segment <paramref name="p0"/> to <paramref name="p1"/> against the triangle, from either side
/// (Moller-Trumbore). <paramref name="t"/> is the fraction along the segment, 0..1.
/// </summary>
public bool Hit(Vector3 p0, Vector3 p1, out float t)
{
t = 0;
Vector3 d = p1 - p0, e1 = B - A, e2 = C - A;
Vector3 h = Vector3.Cross(d, e2);
float det = Vector3.Dot(e1, h);
if (MathF.Abs(det) < 1e-12f) return false;
float inv = 1f / det;
Vector3 s = p0 - A;
float u = Vector3.Dot(s, h) * inv;
if (u < 0 || u > 1) return false;
Vector3 q = Vector3.Cross(s, e1);
float v = Vector3.Dot(d, q) * inv;
if (v < 0 || u + v > 1) return false;
t = Vector3.Dot(e2, q) * inv;
return t >= 0 && t <= 1;
}
/// <summary>Is (x, y) inside the triangle seen from above (within <paramref name="eps"/> metres of it)?</summary>
public bool ContainsXY(float x, float y, float eps = 0.001f)
{
float d1 = Edge(A, B, x, y), d2 = Edge(B, C, x, y), d3 = Edge(C, A, x, y);
bool neg = d1 < 0 || d2 < 0 || d3 < 0, pos = d1 > 0 || d2 > 0 || d3 > 0;
if (!(neg && pos)) return true;
return Geo.DistToSegXY(A.X, A.Y, B.X, B.Y, x, y) <= eps
|| Geo.DistToSegXY(B.X, B.Y, C.X, C.Y, x, y) <= eps
|| Geo.DistToSegXY(C.X, C.Y, A.X, A.Y, x, y) <= eps;
}
/// <summary>The height of the triangle's plane at (x, y); NaN for a vertical triangle.</summary>
public float PlaneZ(float x, float y)
{
if (MathF.Abs(Normal.Z) < 1e-6f) return float.NaN;
return A.Z - (Normal.X * (x - A.X) + Normal.Y * (y - A.Y)) / Normal.Z;
}
/// <summary>Distance seen from above from (x, y) to the triangle (0 inside).</summary>
public float DistXY(float x, float y)
{
if (ContainsXY(x, y, 0)) return 0;
return MathF.Min(Geo.DistToSegXY(A.X, A.Y, B.X, B.Y, x, y),
MathF.Min(Geo.DistToSegXY(B.X, B.Y, C.X, C.Y, x, y), Geo.DistToSegXY(C.X, C.Y, A.X, A.Y, x, y)));
}
private static float Edge(Vector3 a, Vector3 b, float x, float y) => (b.X - a.X) * (y - a.Y) - (b.Y - a.Y) * (x - a.X);
}

View file

@ -0,0 +1,97 @@
// ============================================================================
// RynthCore.Geometry - Collision/ModelTriangles.cs
// A placed model as collision triangles, with the shape ACE's
// PhysicsObj.FindObjCollisions collides with: the physics polygons of its
// parts when any part has a physics BSP; otherwise a Setup's collision
// cylinders, or failing those its spheres, each as a closed 8-sided prism.
// Also: a polygon (an EnvCell wall or floor) fanned into triangles.
//
// Logic from RynthSuite Tools/RynthNav.Baker/CollisionGeometry.cs (d4ae46a),
// AppendModel / AddPolys / AddPrism. Written for RynthCore (MIT).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Scenery;
namespace RynthCore.Geometry.Collision;
internal sealed class ModelTriangles
{
private readonly ModelReader _models;
private readonly DatDatabase _portal;
private readonly ConcurrentDictionary<uint, SetupBounds?> _bounds = new();
public ModelTriangles(ModelReader models, DatDatabase portal)
{
_models = models;
_portal = portal;
}
/// <summary>Setups that collide with cylinders or spheres read from the end of their record (diagnostics).</summary>
public int TailReads;
/// <summary>Adds model <paramref name="model"/> placed at <paramref name="origin"/> / <paramref name="rotation"/> / <paramref name="scale"/>.</summary>
public void Append(uint model, Vector3 origin, Quaternion rotation, float scale, List<CollisionTri> into)
{
var shape = _models.Get(model);
if (shape.Polygons.Count > 0)
{
foreach (var poly in shape.Place(origin, rotation, scale)) AppendPolygon(poly, model, into);
return;
}
if ((model >> 24) != 0x02) return;
var b = _bounds.GetOrAdd(model, id => SetupBounds.Read(_portal, id));
if (b == null) return;
if (b.FromTail && (b.Cylinders.Count > 0 || b.Spheres.Count > 0)) Interlocked.Increment(ref TailReads);
Vector3 World(Vector3 p) => Vector3.Transform(p, rotation) + origin;
if (b.Cylinders.Count > 0)
foreach (var c in b.Cylinders)
AppendPrism(c.Origin * scale, c.Radius * scale, 0, c.Height * scale, World, model, into);
else
foreach (var s in b.Spheres)
AppendPrism(s.Center * scale, s.Radius * scale, -s.Radius * scale, s.Radius * scale, World, model, into);
}
/// <summary>A convex polygon fanned into triangles that share its normal (by vertex order); degenerate ones are dropped.</summary>
public static void AppendPolygon(IReadOnlyList<Vector3> poly, uint source, List<CollisionTri> into)
{
if (poly.Count < 3) return;
Vector3 n = CellDat.Normal(poly);
if (n == Vector3.Zero || !float.IsFinite(n.X)) return;
Vector3 a = poly[0];
for (int i = 1; i < poly.Count - 1; i++)
{
Vector3 b = poly[i], c = poly[i + 1];
if (Vector3.Cross(b - a, c - a).LengthSquared() < 1e-10f) continue;
into.Add(new CollisionTri(a, b, c, n, source));
}
}
/// <summary>A closed 8-sided prism (sides, top and bottom), outward normals, standing in for a cylinder or sphere.</summary>
private static void AppendPrism(Vector3 center, float radius, float z0, float z1, Func<Vector3, Vector3> world, uint source, List<CollisionTri> into)
{
if (!(radius > 0.01f) || !(z1 > z0)) return;
const int N = 8;
var lo = new Vector3[N];
var hi = new Vector3[N];
for (int i = 0; i < N; i++)
{
float a = i * MathF.PI * 2 / N;
float x = center.X + radius * MathF.Cos(a), y = center.Y + radius * MathF.Sin(a);
lo[i] = world(new Vector3(x, y, center.Z + z0));
hi[i] = world(new Vector3(x, y, center.Z + z1));
}
Vector3 cl = world(new Vector3(center.X, center.Y, center.Z + z0)), ch = world(new Vector3(center.X, center.Y, center.Z + z1));
for (int i = 0; i < N; i++)
{
int j = (i + 1) % N;
AppendPolygon(new[] { lo[i], lo[j], hi[j], hi[i] }, source, into);
AppendPolygon(new[] { ch, hi[i], hi[j] }, source, into);
AppendPolygon(new[] { cl, lo[j], lo[i] }, source, into);
}
}
}

View file

@ -0,0 +1,310 @@
// ============================================================================
// RynthCore.Geometry - Collision/OutdoorCollision.cs
// What an outdoor walker collides with besides the terrain: per landblock,
// the static objects and building shells of its LandblockInfo, the walls,
// floors and objects of its building cells (EnvCells flagged SeenOutside),
// and the scenery the server places. Each landblock's triangles are built
// on first use, kept, and indexed on a 4 m grid; queries near a landblock
// edge also see the neighbouring landblocks' triangles, shifted into the
// queried landblock's frame.
//
// Logic from RynthSuite Tools/RynthNav.Baker/CollisionGeometry.cs (d4ae46a):
// AppendStatics, AppendBuildingCells, AppendScenery. RaiseIfLow is left out:
// it raises low objects into walls for the navmesh baker's 1 m climb, which
// a walker that steps like the client does not need.
// Written for RynthCore (MIT).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Scenery;
using RynthCore.Geometry.Terrain;
namespace RynthCore.Geometry.Collision;
/// <summary>Where a landblock's collision triangles came from (diagnostics).</summary>
public readonly record struct CollisionCounts(
int StaticObjects, int StaticTris,
int Buildings, int BuildingTris,
int BuildingCells, int BuildingCellTris,
int CellObjects, int CellObjectTris,
int Scenery, int SceneryTris)
{
public int Total => StaticTris + BuildingTris + BuildingCellTris + CellObjectTris + SceneryTris;
public override string ToString() =>
$"{Total} tris: statics {StaticObjects} ({StaticTris}), buildings {Buildings} ({BuildingTris}), " +
$"building cells {BuildingCells} ({BuildingCellTris}), cell objects {CellObjects} ({CellObjectTris}), scenery {Scenery} ({SceneryTris})";
}
/// <summary>
/// Outdoor collision geometry (everything solid but the terrain), landblock by landblock.
/// <para>Coordinates: every query names a landblock (0xXXYY or any 0xXXYYnnnn id) and takes and returns
/// positions in that landblock's frame (x, y in 0..192 from its SW corner, z absolute). Near an edge the
/// neighbouring landblocks' triangles are included, moved into that frame.</para>
/// <para>Thread-safe: each landblock is built once (other callers wait for that build) and never changed.</para>
/// </summary>
public sealed class OutdoorCollision
{
/// <summary>Grid bucket size, metres.</summary>
public const float Bucket = 4f;
/// <summary>How far a landblock's triangles may reach past its edge for a query to look at that neighbour.</summary>
public const float MaxOverhang = 24f;
/// <summary>ACE's FloorZ: a triangle with normal.Z at least this can be stood on.</summary>
public const float FloorZ = CellDat.FloorZ;
private const int Side = (int)(LandblockData.BlockLength / Bucket); // 48 buckets a side
private readonly DatDatabase _cell;
private readonly TerrainSampler _terrain;
private readonly IndoorWorld _indoor;
private readonly ModelTriangles _shapes;
private readonly ConcurrentDictionary<uint, Lazy<Block>> _blocks = new();
/// <summary>The scenery placer this uses (its tables are shared).</summary>
public SceneryPlacer Scenery { get; }
public OutdoorCollision(DatDatabase cell, DatDatabase portal, TerrainSampler terrain, ModelReader models, IndoorWorld indoor)
{
_cell = cell;
_terrain = terrain;
_indoor = indoor;
_shapes = new ModelTriangles(models, portal);
Scenery = new SceneryPlacer(cell, portal, terrain, models);
}
/// <summary>Setups whose cylinders/spheres had to be read from the end of their record (diagnostics).</summary>
public int TailReads => _shapes.TailReads;
// ---- per-landblock build ----------------------------------------------------------
private sealed class Block
{
public CollisionTri[] Tris = Array.Empty<CollisionTri>();
public float[] MinX = Array.Empty<float>(), MaxX = Array.Empty<float>(), MinY = Array.Empty<float>(), MaxY = Array.Empty<float>();
public int[][] Grid = Array.Empty<int[]>();
public float BMinX, BMinY, BMaxX, BMaxY; // XY bounds of all triangles (empty: Min > Max)
public CollisionCounts Counts;
public IReadOnlyList<SceneryObject> Scenery = Array.Empty<SceneryObject>();
}
private static uint Key(uint landblock) => LandblockData.KeyOf(landblock);
private Block Get(uint landblock) =>
_blocks.GetOrAdd(Key(landblock), k => new Lazy<Block>(() => Build(k), LazyThreadSafetyMode.ExecutionAndPublication)).Value;
/// <summary>Forgets a landblock's triangles (built again on next use).</summary>
public void Unload(uint landblock) => _blocks.TryRemove(Key(landblock), out _);
private Block Build(uint lb)
{
var tris = new List<CollisionTri>();
int statics = 0, staticTris = 0, buildings = 0, buildingTris = 0, cells = 0, cellTris = 0, cellObjs = 0, cellObjTris = 0;
var info = LandblockInfo.Load(_cell, lb);
if (info != null)
{
foreach (var s in info.Objects)
{
int n0 = tris.Count;
_shapes.Append(s.Id, s.Origin, s.Rotation, 1f, tris);
statics++; staticTris += tris.Count - n0;
}
foreach (var b in info.Buildings)
{
int n0 = tris.Count;
_shapes.Append(b.ModelId, b.Origin, b.Rotation, 1f, tris);
buildings++; buildingTris += tris.Count - n0;
}
}
// Building interiors: the EnvCells seen from outside (dungeon cells are not).
if (info == null || info.NumCells > 0)
{
foreach (var c in _indoor.LoadLandblock(lb))
{
if ((c.Flags & 0x01) == 0) continue;
cells++;
int n0 = tris.Count;
foreach (var f in c.Floors) ModelTriangles.AppendPolygon(f, c.Id, tris);
foreach (var w in c.Walls) ModelTriangles.AppendPolygon(w, c.Id, tris);
cellTris += tris.Count - n0;
foreach (var s in c.Stabs)
{
n0 = tris.Count;
_shapes.Append(s.Id, s.Origin, s.Rotation, 1f, tris);
cellObjs++; cellObjTris += tris.Count - n0;
}
}
}
var scenery = Scenery.Place(lb);
int sceneryTris0 = tris.Count;
foreach (var o in scenery) _shapes.Append(o.ModelId, o.Position, o.Rotation, o.Scale, tris);
var block = new Block
{
Tris = tris.ToArray(),
Scenery = scenery,
Counts = new CollisionCounts(statics, staticTris, buildings, buildingTris, cells, cellTris, cellObjs, cellObjTris,
scenery.Count, tris.Count - sceneryTris0),
};
Index(block);
return block;
}
private static int Cell(float v) => Math.Clamp((int)MathF.Floor(v / Bucket), 0, Side - 1);
private static void Index(Block b)
{
int n = b.Tris.Length;
b.MinX = new float[n]; b.MaxX = new float[n]; b.MinY = new float[n]; b.MaxY = new float[n];
b.BMinX = b.BMinY = float.MaxValue; b.BMaxX = b.BMaxY = float.MinValue;
var lists = new List<int>?[Side * Side];
for (int i = 0; i < n; i++)
{
var t = b.Tris[i];
b.MinX[i] = t.MinX; b.MaxX[i] = t.MaxX; b.MinY[i] = t.MinY; b.MaxY[i] = t.MaxY;
b.BMinX = MathF.Min(b.BMinX, t.MinX); b.BMaxX = MathF.Max(b.BMaxX, t.MaxX);
b.BMinY = MathF.Min(b.BMinY, t.MinY); b.BMaxY = MathF.Max(b.BMaxY, t.MaxY);
for (int gx = Cell(t.MinX); gx <= Cell(t.MaxX); gx++)
for (int gy = Cell(t.MinY); gy <= Cell(t.MaxY); gy++)
(lists[gx * Side + gy] ??= new List<int>()).Add(i);
}
b.Grid = lists.Select(l => l?.ToArray() ?? Array.Empty<int>()).ToArray();
}
/// <summary>
/// Calls <paramref name="visit"/> once for every triangle of <paramref name="b"/> whose XY bounds overlap
/// the box (in <paramref name="b"/>'s own frame). Each triangle is reported from one bucket only: the first
/// bucket of the overlap of its bounds and the box.
/// </summary>
private static void Visit(Block b, float x0, float y0, float x1, float y1, Action<int> visit)
{
if (b.Tris.Length == 0 || x1 < b.BMinX || x0 > b.BMaxX || y1 < b.BMinY || y0 > b.BMaxY) return;
int gx0 = Cell(x0), gx1 = Cell(x1), gy0 = Cell(y0), gy1 = Cell(y1);
for (int gx = gx0; gx <= gx1; gx++)
for (int gy = gy0; gy <= gy1; gy++)
foreach (int i in b.Grid[gx * Side + gy])
{
if (b.MaxX[i] < x0 || b.MinX[i] > x1 || b.MaxY[i] < y0 || b.MinY[i] > y1) continue;
if (Math.Max(Cell(b.MinX[i]), gx0) != gx || Math.Max(Cell(b.MinY[i]), gy0) != gy) continue;
visit(i);
}
}
/// <summary>
/// Runs <paramref name="each"/> for the landblock itself and every neighbour whose triangles may reach the
/// box (given in <paramref name="landblock"/>'s frame), with that block and the shift from its frame into
/// the landblock's (neighbour position + shift = position in the queried frame).
/// </summary>
private void ForBlocks(uint landblock, float x0, float y0, float x1, float y1, Action<Block, Vector3> each)
{
uint key = Key(landblock);
int lx = (int)(key >> 8), ly = (int)(key & 0xFF);
const float L = LandblockData.BlockLength;
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
{
int nx = lx + dx, ny = ly + dy;
if (nx < 0 || ny < 0 || nx > 0xFF || ny > 0xFF) continue;
float sx = dx * L, sy = dy * L;
if (dx != 0 || dy != 0)
{
// the box in the neighbour's frame must come within MaxOverhang of its square
float bx0 = x0 - sx, bx1 = x1 - sx, by0 = y0 - sy, by1 = y1 - sy;
if (bx1 < -MaxOverhang || bx0 > L + MaxOverhang || by1 < -MaxOverhang || by0 > L + MaxOverhang) continue;
}
each(Get((uint)(nx << 8 | ny)), new Vector3(sx, sy, 0));
}
}
// ---- queries ----------------------------------------------------------------------
/// <summary>The triangles of a landblock and its neighbours whose XY bounds come within <paramref name="radius"/> of (x, y).</summary>
public IReadOnlyList<CollisionTri> Near(uint landblock, float x, float y, float radius)
{
var result = new List<CollisionTri>();
float r2 = radius * radius;
ForBlocks(landblock, x - radius, y - radius, x + radius, y + radius, (b, shift) =>
{
float qx = x - shift.X, qy = y - shift.Y;
Visit(b, qx - radius, qy - radius, qx + radius, qy + radius, i =>
{
float ex = MathF.Max(0, MathF.Max(b.MinX[i] - qx, qx - b.MaxX[i]));
float ey = MathF.Max(0, MathF.Max(b.MinY[i] - qy, qy - b.MaxY[i]));
if (ex * ex + ey * ey > r2) return;
result.Add(shift == Vector3.Zero ? b.Tris[i] : b.Tris[i].Shifted(shift));
});
});
return result;
}
/// <summary>
/// The nearest triangle the segment <paramref name="a"/> to <paramref name="b"/> hits (either face), and
/// where: <paramref name="t"/> is the fraction along the segment (0..1). False when it hits nothing.
/// </summary>
public bool SegmentHit(uint landblock, Vector3 a, Vector3 b, out float t, out CollisionTri tri)
{
float bestT = float.MaxValue;
CollisionTri best = default;
float x0 = MathF.Min(a.X, b.X), x1 = MathF.Max(a.X, b.X), y0 = MathF.Min(a.Y, b.Y), y1 = MathF.Max(a.Y, b.Y);
float zLo = MathF.Min(a.Z, b.Z), zHi = MathF.Max(a.Z, b.Z);
ForBlocks(landblock, x0, y0, x1, y1, (blk, shift) =>
{
Vector3 pa = a - shift, pb = b - shift;
Visit(blk, x0 - shift.X, y0 - shift.Y, x1 - shift.X, y1 - shift.Y, i =>
{
var tr = blk.Tris[i];
if (tr.MaxZ < zLo || tr.MinZ > zHi) return;
if (tr.Hit(pa, pb, out float ht) && ht < bestT)
{
bestT = ht;
best = shift == Vector3.Zero ? tr : tr.Shifted(shift);
}
});
});
t = bestT == float.MaxValue ? 0 : bestT;
tri = best;
return bestT != float.MaxValue;
}
/// <summary>
/// The highest walkable (normal.Z &gt;= FloorZ) object or building triangle under (x, y) whose height
/// there is at most <paramref name="zTop"/> and above <paramref name="zTop"/> - <paramref name="maxDrop"/>;
/// null when there is none. The terrain is not included (take the max with the terrain yourself).
/// </summary>
public float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop)
{
float? best = null;
float lo = zTop - maxDrop;
ForBlocks(landblock, x, y, x, y, (b, shift) =>
{
float qx = x - shift.X, qy = y - shift.Y;
Visit(b, qx, qy, qx, qy, i =>
{
var tr = b.Tris[i];
if (!tr.Walkable || tr.MinZ > zTop || tr.MaxZ <= lo) return;
if (!tr.ContainsXY(qx, qy)) return;
float z = tr.PlaneZ(qx, qy);
if (z > zTop || z <= lo) return;
if (best == null || z > best.Value) best = z;
});
});
return best;
}
/// <summary>The number of collision triangles of the landblock itself (no neighbours).</summary>
public int Count(uint landblock) => Get(landblock).Tris.Length;
/// <summary>Where the landblock's triangles came from.</summary>
public CollisionCounts Counts(uint landblock) => Get(landblock).Counts;
/// <summary>The landblock's own triangles, in its frame (no neighbours).</summary>
public IReadOnlyList<CollisionTri> Triangles(uint landblock) => Get(landblock).Tris;
/// <summary>The scenery placed in the landblock (as used for its collision).</summary>
public IReadOnlyList<SceneryObject> SceneryOf(uint landblock) => Get(landblock).Scenery;
}

View file

@ -0,0 +1,515 @@
// ============================================================================
// RynthCore.Geometry - Dat/DatDatabase.cs (moved from RynthSuite Shared/RynthCore.TerrainData, 2f49195)
// Read-only access to Asheron's Call .dat archives (client_portal.dat,
// client_cell_1.dat, ...). Written for RynthCore (MIT) on 2026-10-05.
//
// Written from the dat container format as it is publicly documented, with
// Chorizite's DatReaderWriter (MIT, notice below) used as the format reference:
// - file header at byte 0x140: magic, block size, file size, data set,
// subset, free head / tail / count, then the byte offset of the root
// B-tree node (all little-endian uint32);
// - storage is fixed-size blocks; a block's first uint32 is the byte offset
// of the next block of the same chain (0 ends the chain), the remaining
// BlockSize - 4 bytes are payload;
// - the directory is a B-tree whose nodes are stored as block chains: 62
// uint32 child offsets, a uint32 entry count (at most 61), then the
// entries, 24 bytes each: flags/version, id, byte offset of the file's
// first block, size, timestamp, iteration. Entries are sorted by id,
// child i holds the ids between entry i-1 and entry i, and a node whose
// first child offset is 0 is a leaf.
//
// Nothing is indexed up front: lookups descend the tree from the root. Every
// interior node is kept once read (about 1 node in 62, a few hundred KB for
// client_cell_1.dat) and leaves go through a small LRU, so a lookup usually
// costs one leaf read and neighbouring ids (adjacent landblocks) none. The
// public API (null when a file or the database is missing) is the one
// RynthAi, RynthVision, RynthJuice and the RynthNav tools already use.
//
// Thread-safety: every stream read and cache access holds one lock, so one
// database can be shared between threads. NativeAOT/trimming safe (no
// reflection).
//
// Chorizite DatReaderWriter notice (format reference):
// Copyright 2024 ACClientLib
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions: The above copyright notice and this permission
// notice shall be included in all copies or substantial portions of the
// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// ============================================================================
// The API returns null for "not there" without annotations; its callers
// (RynthAi, RynthJuice, RynthVision) are written against that.
#nullable disable
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Geometry.Dat
{
/// <summary>
/// A read-only .dat archive. <see cref="Open"/> reads the header and checks
/// the root directory node; files are then found by id
/// (<see cref="FindFile"/>, <see cref="GetFileData"/>) by searching the
/// on-disk B-tree. Methods return null / empty when the database isn't open
/// or the file isn't there; nothing throws for a missing or damaged file.
/// </summary>
public class DatDatabase : IDisposable
{
// ---- container layout ----
private const long HeaderOffset = 0x140;
private const int HeaderBytes = 9 * 4; // magic .. root offset
private const int ChildSlots = 62;
private const int MaxEntriesPerNode = 61;
private const int EntryBytes = 24;
private const int CountOffset = ChildSlots * 4; // 248
private const int EntriesOffset = CountOffset + 4; // 252
private const int NodeBytes = EntriesOffset + MaxEntriesPerNode * EntryBytes; // 1716
// A real tree is 4 levels deep at most; this only stops a damaged child
// pointer from sending a search round in circles.
private const int DepthLimit = 16;
// Cache budget: all interior nodes (capped), a 128-leaf LRU.
private const int LeafLruSize = 128;
private const int InteriorCap = 4096;
private readonly object _gate = new object();
private FileStream _file;
private long _length;
private byte[] _nodeBuf; // one node's bytes, reused (under _gate)
private readonly Dictionary<uint, Node> _interior = new Dictionary<uint, Node>();
private readonly LruCache<uint, Node> _leaves = new LruCache<uint, Node>(LeafLruSize);
private int _count = -1;
/// <summary>Header word at 0x140 (the dat magic).</summary>
public uint FileType { get; private set; }
/// <summary>Block size in bytes (1024 in the retail dats).</summary>
public uint BlockSize { get; private set; }
/// <summary>File size recorded in the header.</summary>
public uint FileSize { get; private set; }
/// <summary>The header's data set (database type) word.</summary>
public uint DataSet { get; private set; }
/// <summary>Byte offset of the root directory node.</summary>
public uint BTreeRoot { get; private set; }
/// <summary>True between a successful <see cref="Open"/> and <see cref="Close"/>.</summary>
public bool IsLoaded { get; private set; }
/// <summary>The path last passed to <see cref="Open"/>.</summary>
public string FilePath { get; private set; }
/// <summary>Diagnostics from Open and failed reads (first 100 lines).</summary>
public List<string> DiagLog { get; } = new List<string>();
/// <summary>
/// Number of files in the dat. Counted on first use from the directory
/// nodes' entry counts (only the first bytes of each node are read) and
/// remembered until <see cref="Close"/>; 0 when not open.
/// </summary>
public int RecordCount
{
get
{
lock (_gate)
{
if (!IsLoaded) return 0;
if (_count < 0) _count = CountUnder(BTreeRoot, 0);
return _count;
}
}
}
private sealed class Node
{
public uint[] Children; // entry count + 1 offsets; null for a leaf
public DatBTreeEntry[] Entries; // ascending ObjectId
}
// ------------------------------------------------------------------ open / close
/// <summary>Opens <paramref name="path"/> read-only. False (and a DiagLog line) on any failure.</summary>
public bool Open(string path)
{
lock (_gate)
{
CloseLocked();
FilePath = path;
try
{
if (!File.Exists(path)) { Log($"Not found: {path}"); return false; }
// acclient.exe keeps its own handles on the dats and may open
// them after us (RynthAi opens at plugin init), so share
// everything, including delete: the client's open asks for
// delete-rename access and fails ("cannot access the data
// files") if an earlier handle refuses it.
_file = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
_length = _file.Length;
Span<byte> h = stackalloc byte[HeaderBytes];
if (!ReadAt(HeaderOffset, h)) { Log("Header is short"); CloseLocked(); return false; }
FileType = BinaryPrimitives.ReadUInt32LittleEndian(h);
BlockSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(4));
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(8));
DataSet = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(12));
BTreeRoot = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(32));
Log($"Header: type=0x{FileType:X8} blockSize={BlockSize} fileSize={FileSize} dataSet=0x{DataSet:X8} root=0x{BTreeRoot:X8} (file {_length} bytes)");
if (BlockSize <= 4 || BlockSize > 0x10000) { Log($"Bad block size {BlockSize}"); CloseLocked(); return false; }
if (BTreeRoot == 0 || BTreeRoot >= _length) { Log($"Bad root offset 0x{BTreeRoot:X8}"); CloseLocked(); return false; }
_nodeBuf = new byte[NodeBytes];
IsLoaded = true;
if (GetNode(BTreeRoot) == null)
{
Log($"Root node at 0x{BTreeRoot:X8} doesn't parse");
CloseLocked();
return false;
}
Log($"Opened {Path.GetFileName(path)}");
return true;
}
catch (Exception ex)
{
Log($"Open failed: {ex.Message}");
CloseLocked();
return false;
}
}
}
/// <summary>Closes the file and drops the cached directory nodes.</summary>
public void Close()
{
lock (_gate) CloseLocked();
}
public void Dispose() { Close(); }
private void CloseLocked()
{
IsLoaded = false;
_file?.Dispose();
_file = null;
_length = 0;
_nodeBuf = null;
_interior.Clear();
_leaves.Clear();
_count = -1;
}
// ------------------------------------------------------------------ lookups
/// <summary>The directory entry for <paramref name="fileId"/>, or null.</summary>
public DatBTreeEntry FindFile(uint fileId)
{
lock (_gate)
{
if (!IsLoaded) return null;
uint at = BTreeRoot;
for (int depth = 0; depth < DepthLimit && at != 0; depth++)
{
Node n = GetNode(at);
if (n == null) return null;
int i = LowerBound(n.Entries, fileId);
if (i < n.Entries.Length && n.Entries[i].ObjectId == fileId) return n.Entries[i];
if (n.Children == null) return null;
at = n.Children[i];
}
return null;
}
}
/// <summary>The bytes of the file <paramref name="entry"/> describes, or null.</summary>
public byte[] ReadFileData(DatBTreeEntry entry)
{
if (entry == null) return null;
lock (_gate)
{
if (!IsLoaded) return null;
if (entry.FileSize > _length) { Log($"0x{entry.ObjectId:X8}: size {entry.FileSize} exceeds the file"); return null; }
var data = new byte[entry.FileSize];
if (ReadChain(entry.FileOffset, data) != data.Length)
{
Log($"0x{entry.ObjectId:X8}: block chain at 0x{entry.FileOffset:X8} is broken");
return null;
}
return data;
}
}
/// <summary><see cref="FindFile"/> then <see cref="ReadFileData"/>.</summary>
public byte[] GetFileData(uint fileId) => ReadFileData(FindFile(fileId));
/// <summary>
/// The interior (EnvCell) ids 0xXXYY0100-0xXXYYFFFD of landblock
/// <paramref name="landblockKey"/> (0xXXYY), ascending. Only the nodes
/// whose id range overlaps the landblock are read.
/// </summary>
public List<uint> GetLandblockCellIds(uint landblockKey)
{
var found = new List<uint>();
lock (_gate)
{
if (!IsLoaded) return found;
uint lo = (landblockKey << 16) | 0x0100;
uint hi = (landblockKey << 16) | 0xFFFD;
CollectRange(BTreeRoot, lo, hi, found, 0);
}
return found;
}
// In-order walk of the part of the subtree at `at` holding ids in [lo, hi].
private void CollectRange(uint at, uint lo, uint hi, List<uint> into, int depth)
{
if (at == 0 || depth >= DepthLimit) return;
Node n = GetNode(at);
if (n == null) return;
var e = n.Entries;
for (int i = 0; i <= e.Length; i++)
{
// Child i spans (e[i-1], e[i]); visit it if that overlaps [lo, hi].
if (n.Children != null)
{
bool aboveLo = i == e.Length || e[i].ObjectId > lo;
bool belowHi = i == 0 || e[i - 1].ObjectId < hi;
if (aboveLo && belowHi) CollectRange(n.Children[i], lo, hi, into, depth + 1);
}
if (i == e.Length) break;
uint id = e[i].ObjectId;
if (id > hi) break;
if (id >= lo) into.Add(id);
}
}
/// <summary>
/// Every entry, ascending by id, read from the tree as it goes (nothing
/// is kept afterwards). Reads every node of the dat: for diagnostics and
/// offline tools, not for lookups.
/// </summary>
public IEnumerable<DatBTreeEntry> EnumerateEntries()
{
Node root;
lock (_gate)
{
if (!IsLoaded) yield break;
root = GetNodeUncached(BTreeRoot);
}
if (root == null) yield break;
// Explicit stack (no recursion through iterators); the lock is taken
// per node read, never held across a yield.
var stack = new Stack<(Node node, int next)>();
stack.Push((root, 0));
DescendLeft(stack);
while (stack.Count > 0)
{
var (node, next) = stack.Pop();
if (next >= node.Entries.Length) continue;
yield return node.Entries[next];
stack.Push((node, next + 1));
if (node.Children != null)
{
Node child = ReadForWalk(node.Children[next + 1], stack.Count);
if (child != null) { stack.Push((child, 0)); DescendLeft(stack); }
}
}
}
// Pushes the leftmost path below the node on top of the stack.
private void DescendLeft(Stack<(Node node, int next)> stack)
{
while (true)
{
var top = stack.Peek().node;
if (top.Children == null) return;
Node child = ReadForWalk(top.Children[0], stack.Count);
if (child == null) return;
stack.Push((child, 0));
}
}
private Node ReadForWalk(uint at, int depth)
{
if (at == 0 || depth >= DepthLimit) return null;
lock (_gate)
{
if (!IsLoaded) return null;
return GetNodeUncached(at);
}
}
/// <summary>The lowest file ids in the dat (up to <paramref name="maxCount"/>), for diagnostics.</summary>
public List<uint> GetSampleIds(int maxCount = 20)
{
var ids = new List<uint>();
if (maxCount <= 0) return ids;
foreach (var e in EnumerateEntries())
{
ids.Add(e.ObjectId);
if (ids.Count >= maxCount) break;
}
return ids;
}
// ------------------------------------------------------------------ nodes
// First entry index whose id is >= id (Length when none).
private static int LowerBound(DatBTreeEntry[] e, uint id)
{
int a = 0, b = e.Length;
while (a < b)
{
int m = (a + b) >> 1;
if (e[m].ObjectId < id) a = m + 1; else b = m;
}
return a;
}
// Cached node. Caller holds _gate.
private Node GetNode(uint at)
{
if (_interior.TryGetValue(at, out Node n)) return n;
if (_leaves.TryGet(at, out n)) return n;
n = ParseNode(at);
if (n == null) return null;
if (n.Children != null)
{
if (_interior.Count < InteriorCap) _interior[at] = n;
}
else _leaves.Set(at, n);
return n;
}
// For full walks: use a cached node if there is one, but don't fill the
// caches with the whole tree. Caller holds _gate.
private Node GetNodeUncached(uint at)
{
if (_interior.TryGetValue(at, out Node n)) return n;
if (_leaves.TryGet(at, out n)) return n;
return ParseNode(at);
}
// Reads and decodes the node at byte offset `at`. Caller holds _gate.
private Node ParseNode(uint at)
{
byte[] buf = _nodeBuf;
int got = ReadChain(at, buf);
if (got < EntriesOffset) return null;
ReadOnlySpan<byte> s = buf;
int count = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(CountOffset));
if (count < 0 || count > MaxEntriesPerNode || got < EntriesOffset + count * EntryBytes) return null;
var entries = new DatBTreeEntry[count];
for (int i = 0; i < count; i++)
{
var r = s.Slice(EntriesOffset + i * EntryBytes, EntryBytes);
entries[i] = new DatBTreeEntry
{
BitFlags = BinaryPrimitives.ReadUInt32LittleEndian(r),
ObjectId = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(4)),
FileOffset = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(8)),
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(12)),
};
}
uint[] children = null;
if (BinaryPrimitives.ReadUInt32LittleEndian(s) != 0)
{
children = new uint[count + 1];
for (int i = 0; i <= count; i++)
children[i] = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(i * 4));
}
return new Node { Children = children, Entries = entries };
}
// Node entry counts under `at`, reading only each node's first bytes
// (child table + count). Caller holds _gate.
private int CountUnder(uint at, int depth)
{
if (at == 0 || depth >= DepthLimit) return 0;
Span<byte> head = stackalloc byte[EntriesOffset];
if (ReadChain(at, head) != EntriesOffset) return 0;
int count = BinaryPrimitives.ReadInt32LittleEndian(head.Slice(CountOffset));
if (count < 0 || count > MaxEntriesPerNode) return 0;
int total = count;
if (BinaryPrimitives.ReadUInt32LittleEndian(head) != 0)
{
// Copy the child offsets out: the recursion reuses the stack.
Span<uint> kids = stackalloc uint[count + 1];
for (int i = 0; i <= count; i++) kids[i] = BinaryPrimitives.ReadUInt32LittleEndian(head.Slice(i * 4));
for (int i = 0; i <= count; i++) total += CountUnder(kids[i], depth + 1);
}
return total;
}
// ------------------------------------------------------------------ blocks
// Copies the block chain starting at byte offset `first` into `dest`
// and returns how many bytes it filled: dest.Length, or less when the
// chain ends (a 0 link) first; -1 when a link points outside the file.
// Caller holds _gate.
private int ReadChain(uint first, Span<byte> dest)
{
int payload = (int)BlockSize - 4;
long block = first;
int done = 0;
Span<byte> link = stackalloc byte[4];
while (done < dest.Length)
{
if (block == 0) return done;
if (block + 4 > _length) return -1;
int take = Math.Min(payload, dest.Length - done);
if (!ReadAt(block, link) || !ReadAt(block + 4, dest.Slice(done, take))) return -1;
done += take;
block = BinaryPrimitives.ReadUInt32LittleEndian(link);
}
return done;
}
// Caller holds _gate (or is Open, before anything else can see the file).
private bool ReadAt(long offset, Span<byte> into)
{
if (offset < 0 || offset + into.Length > _length) return false;
_file.Position = offset;
int got = 0;
while (got < into.Length)
{
int n = _file.Read(into.Slice(got));
if (n <= 0) return false;
got += n;
}
return true;
}
private void Log(string msg)
{
string line = "[DatDB] " + msg;
System.Diagnostics.Debug.WriteLine(line);
if (DiagLog.Count < 100) DiagLog.Add(line);
}
}
/// <summary>One directory entry: a file's id, flags, first block and size.</summary>
public class DatBTreeEntry
{
public uint BitFlags;
public uint ObjectId;
public uint FileOffset; // byte offset of the file's first block
public uint FileSize;
}
}

View file

@ -0,0 +1,62 @@
using System.Collections.Generic;
namespace RynthCore.Geometry.Dat;
/// <summary>
/// Small fixed-capacity least-recently-used map. Not thread-safe: callers hold
/// their own lock. A hit moves the entry to the front without allocating; only
/// an insert allocates (one list node), and the oldest entry is dropped when
/// the map is full.
/// </summary>
internal sealed class LruCache<TKey, TValue> where TKey : notnull
{
private readonly int _capacity;
private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> _map;
private readonly LinkedList<KeyValuePair<TKey, TValue>> _order = new();
public LruCache(int capacity)
{
_capacity = capacity < 1 ? 1 : capacity;
_map = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(_capacity);
}
public int Count => _map.Count;
public bool TryGet(TKey key, out TValue value)
{
if (_map.TryGetValue(key, out var node))
{
if (node != _order.First)
{
_order.Remove(node);
_order.AddFirst(node);
}
value = node.Value.Value;
return true;
}
value = default!;
return false;
}
public void Set(TKey key, TValue value)
{
if (_map.TryGetValue(key, out var existing))
{
_order.Remove(existing);
_map.Remove(key);
}
else if (_map.Count >= _capacity)
{
var oldest = _order.Last!;
_order.RemoveLast();
_map.Remove(oldest.Value.Key);
}
_map[key] = _order.AddFirst(new KeyValuePair<TKey, TValue>(key, value));
}
public void Clear()
{
_map.Clear();
_order.Clear();
}
}

View file

@ -0,0 +1,110 @@
// ============================================================================
// RynthCore.Geometry - Models/LandblockInfo.cs
// The outdoor objects of a landblock, from its LandblockInfo record in the
// cell dat (0xXXYYFFFE): static objects (Stabs) and buildings, each a model
// id with a landblock-local frame, plus each building's portals (the indoor
// cells its doorways open into).
//
// Format as in ACE (LandblockInfo.Unpack, BuildInfo.Unpack, CBldPortal.Unpack):
// uint Id, uint NumCells, uint count + Stab[] (uint id, frame),
// ushort numBuildings, ushort packMask,
// BuildInfo[]: uint ModelId, frame, uint NumLeaves, uint count + CBldPortal[]
// (ushort flags, otherCell, otherPortal, numStabs, ushort[numStabs], align 4),
// (packMask & 1) restriction table (not read).
// A frame is origin x, y, z then rotation w, x, y, z.
//
// Written for RynthCore (MIT) on 2026-10-28.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Models;
/// <summary>A building placed on a landblock, and the cells its doorways open into.</summary>
public sealed class BuildingInfo
{
/// <summary>Its model: a GfxObj (0x01..) or a Setup (0x02..).</summary>
public uint ModelId;
/// <summary>Landblock-local.</summary>
public Vector3 Origin;
public Quaternion Rotation;
public uint NumLeaves;
/// <summary>Low words of the indoor cells behind the building's doorways.</summary>
public List<ushort> PortalCells = new();
}
/// <summary>A landblock's LandblockInfo (0xXXYYFFFE): its outdoor static objects and buildings.</summary>
public sealed class LandblockInfo
{
public uint Id;
public uint NumCells;
/// <summary>Static objects, landblock-local frames.</summary>
public List<Stab> Objects = new();
public List<BuildingInfo> Buildings = new();
/// <summary>The whole record (objects and buildings) was read.</summary>
public bool Complete;
/// <summary>
/// Reads landblock <paramref name="landblock"/>'s LandblockInfo (0xXXYY, or any cell id 0xXXYYnnnn of it);
/// null when the record is missing. A damaged record returns what parsed, with <see cref="Complete"/> false.
/// </summary>
public static LandblockInfo? Load(DatDatabase cellDat, uint landblock)
{
if (landblock > 0xFFFF) landblock >>= 16;
byte[]? data = cellDat.GetFileData((landblock << 16) | 0xFFFE);
return data == null ? null : Parse(data);
}
public static LandblockInfo Parse(byte[] data)
{
var info = new LandblockInfo();
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
try
{
info.Id = r.ReadUInt32();
info.NumCells = r.ReadUInt32();
uint numObjects = r.ReadUInt32();
for (uint i = 0; i < numObjects && i < 10000; i++)
{
var s = new Stab { Id = r.ReadUInt32() };
(s.Origin, s.Rotation) = ReadFrame(r);
info.Objects.Add(s);
}
ushort numBuildings = r.ReadUInt16();
r.ReadUInt16(); // pack mask
for (int b = 0; b < numBuildings; b++)
{
var bi = new BuildingInfo { ModelId = r.ReadUInt32() };
(bi.Origin, bi.Rotation) = ReadFrame(r);
bi.NumLeaves = r.ReadUInt32();
uint numPortals = r.ReadUInt32();
if (numPortals > 1000) throw new InvalidDataException("bad building portal count");
for (uint p = 0; p < numPortals; p++)
{
r.ReadUInt16(); // flags
bi.PortalCells.Add(r.ReadUInt16()); // other cell
r.ReadUInt16(); // other portal
ushort numStabs = r.ReadUInt16();
ms.Seek(numStabs * 2L, SeekOrigin.Current);
long a = (ms.Position + 3) & ~3L;
if (a > ms.Length) throw new EndOfStreamException();
ms.Position = a;
}
info.Buildings.Add(bi);
}
info.Complete = true;
}
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException) { }
return info;
}
private static (Vector3, Quaternion) ReadFrame(BinaryReader r)
{
var o = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
return (o, new Quaternion(x, y, z, w));
}
}

View file

@ -0,0 +1,174 @@
// ============================================================================
// RynthCore.Geometry - Models/ModelReader.cs
// The solid shape of a model (a Setup 0x02.. or a GfxObj 0x01..) in its own
// frame: the physics polygons of its parts, its collision cylinders and
// spheres, and the Setup's own radius and height. Formats as in ACE
// (SetupModel.Unpack, GfxObj.Unpack); a model with no physics has no
// polygons. Shapes are cached per id; the reader is thread-safe.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/Models.cs (3a8075a).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Models;
/// <summary>A model's solid shape in model space. Treat as read-only once returned by <see cref="ModelReader.Get"/>.</summary>
public sealed class ModelShape
{
/// <summary>Physics polygons of every part, in model space (part frames and scales applied).</summary>
public List<Vector3[]> Polygons = new();
/// <summary>Collision cylinders: base centre (model space), radius, height.</summary>
public List<(Vector3 Origin, float Radius, float Height)> Cylinders = new();
/// <summary>Collision spheres: centre (model space), radius.</summary>
public List<(Vector3 Center, float Radius)> Spheres = new();
/// <summary>The Setup's own (selection) radius and height; 0 for a GfxObj, or when the hooks stopped the read.</summary>
public float Radius, Height;
/// <summary>The model's record was found and read.</summary>
public bool Parsed;
public bool IsEmpty => Polygons.Count == 0 && Cylinders.Count == 0 && Spheres.Count == 0;
/// <summary>The polygons placed in the world: scaled, rotated, then moved to <paramref name="origin"/>.</summary>
public IEnumerable<Vector3[]> Place(Vector3 origin, Quaternion rotation, float scale = 1f)
{
foreach (var poly in Polygons)
{
var p = new Vector3[poly.Length];
for (int i = 0; i < p.Length; i++) p[i] = Vector3.Transform(poly[i] * scale, rotation) + origin;
yield return p;
}
}
}
/// <summary>Reads <see cref="ModelShape"/>s from the portal dat, caching each id.</summary>
public sealed class ModelReader
{
private readonly DatDatabase _portal;
private readonly Dictionary<uint, ModelShape> _cache = new();
private readonly object _gate = new();
public ModelReader(DatDatabase portalDat) { _portal = portalDat; }
/// <summary>The player's model (a human Setup): its collision spheres give the walker's radius.</summary>
public const uint HumanSetup = 0x02000001;
/// <summary>The shape of a GfxObj (0x01..) or Setup (0x02..); an empty, unparsed shape for anything else.</summary>
public ModelShape Get(uint id)
{
lock (_gate)
{
if (_cache.TryGetValue(id, out var s)) return s;
}
var shape = new ModelShape();
try
{
if ((id >> 24) == 0x01) { shape.Parsed = ReadGfxObj(id, shape.Polygons, Matrix4x4.Identity); }
else if ((id >> 24) == 0x02) { shape.Parsed = ReadSetup(id, shape); }
}
catch (Exception) { shape.Parsed = false; }
lock (_gate)
{
if (_cache.TryGetValue(id, out var s)) return s; // another thread won the race
_cache[id] = shape;
return shape;
}
}
private bool ReadGfxObj(uint id, List<Vector3[]> into, Matrix4x4 m)
{
byte[]? data = _portal.GetFileData(id);
if (data == null) return false;
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint flags = r.ReadUInt32();
uint numSurfaces = ReadCompressed(r);
ms.Seek(numSurfaces * 4L, SeekOrigin.Current);
var verts = CellDat.ReadVertexArray(r, ms);
if (verts == null) return false;
if ((flags & 1) == 0) return true; // no physics: walk through it
uint numPhys = ReadCompressed(r);
foreach (var (_, ids) in CellDat.ReadPolygons(r, ms, numPhys))
{
var p = CellDat.Resolve(ids, verts);
if (p.Length >= 3) into.Add(p.Select(v => Vector3.Transform(v, m)).ToArray());
}
return true;
}
private bool ReadSetup(uint id, ModelShape s)
{
byte[]? data = _portal.GetFileData(id);
if (data == null) return false;
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint flags = r.ReadUInt32();
uint numParts = r.ReadUInt32();
if (numParts > 1000) return false;
var parts = new uint[numParts];
for (int i = 0; i < numParts; i++) parts[i] = r.ReadUInt32();
if ((flags & 1) != 0) ms.Seek(numParts * 4L, SeekOrigin.Current); // parents
var scale = Enumerable.Repeat(Vector3.One, (int)numParts).ToArray();
if ((flags & 2) != 0)
for (int i = 0; i < numParts; i++) scale[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
SkipLocations(r, ms); // holding locations
SkipLocations(r, ms); // connection points
int placements = r.ReadInt32();
Matrix4x4[]? frames = null;
bool hooksSeen = false;
for (int p = 0; p < placements && !hooksSeen; p++)
{
int key = r.ReadInt32();
var f = new Matrix4x4[numParts];
for (int i = 0; i < numParts; i++) f[i] = ReadFrame(r);
if (frames == null || key == 0) frames = f;
if (r.ReadUInt32() != 0) hooksSeen = true; // variable-size hooks: stop here
}
for (int i = 0; i < numParts; i++)
{
Matrix4x4 m = Matrix4x4.CreateScale(scale[i]) * (frames != null ? frames[i] : Matrix4x4.Identity);
if ((parts[i] >> 24) == 0x01) ReadGfxObj(parts[i], s.Polygons, m);
}
if (hooksSeen) return true;
uint numCyl = r.ReadUInt32();
for (uint i = 0; i < numCyl && i < 64; i++)
s.Cylinders.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle(), r.ReadSingle()));
uint numSph = r.ReadUInt32();
for (uint i = 0; i < numSph && i < 64; i++)
s.Spheres.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle()));
s.Height = r.ReadSingle();
s.Radius = r.ReadSingle();
return true;
}
private static Matrix4x4 ReadFrame(BinaryReader r)
{
var o = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
var q = new Quaternion(x, y, z, w);
if (q.LengthSquared() < 1e-6f) q = Quaternion.Identity;
return Matrix4x4.CreateFromQuaternion(Quaternion.Normalize(q)) * Matrix4x4.CreateTranslation(o);
}
private static void SkipLocations(BinaryReader r, MemoryStream ms)
{
int n = r.ReadInt32();
if (n < 0 || n > 1000) throw new InvalidDataException("bad location table");
ms.Seek(n * 36L, SeekOrigin.Current); // key, part id, frame
}
private static uint ReadCompressed(BinaryReader r)
{
byte b0 = r.ReadByte();
if ((b0 & 0x80) == 0) return b0;
byte b1 = r.ReadByte();
if ((b0 & 0x40) == 0) return (uint)(((b0 & 0x7F) << 8) | b1);
ushort s = r.ReadUInt16();
return (uint)((((b0 & 0x3F) << 8 | b1) << 16) | s);
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthCore.Geometry: the AC world's shape, read from the dats. Dat access, terrain
heights/normals, indoor cells (EnvCells, portals, floors), model physics polygons, and a
collision query for walking. Shared by RynthCore.Headless now; meant to replace the
copies in RynthSuite (Shared/RynthCore.TerrainData, RynthAi Raycasting, RynthNav tools).
Pure managed code, no host, no Windows APIs.
-->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthCore.Geometry</RootNamespace>
<AssemblyName>RynthCore.Geometry</AssemblyName>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="GeometryTests" />
<InternalsVisibleTo Include="RynthCore.Headless" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,211 @@
// ============================================================================
// RynthCore.Geometry - Scenery/SceneryPlacer.cs
// The scenery (trees, rocks, bushes) of a landblock, placed as ACE's
// Landblock.get_land_scenes places it on the server: per terrain vertex the
// pseudo-random scene pick, each object's frequency and displacement, then
// the rules that drop one: a weenie object, outside the landblock, on a
// road (ACE OnRoad), in a 24 m land cell that holds a building, on a slope
// outside the object's MinSlope..MaxSlope, or poking out of the landblock
// (PhysicsObj.obj_within_block). Then the heading (slope-aligned or random),
// and the object's scale (ObjectDesc.ScaleObj).
//
// Logic from RynthSuite Tools/RynthNav.Baker/Scenery.cs (d4ae46a), on the
// region tables of Plugins/RynthCore.Plugin.RynthAi/Raycasting/ScatterSystem.cs
// (4b29610). Written for RynthCore (MIT).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Terrain;
namespace RynthCore.Geometry.Scenery;
/// <summary>
/// A piece of scenery placed in a landblock. <see cref="Position"/> is landblock-local (z on the terrain);
/// <see cref="Rotation"/> is the full placement rotation (from <see cref="Heading"/> when the object is
/// turned, else the Scene's base rotation); <see cref="Heading"/> is in AC degrees (0 = north, clockwise),
/// NaN when the object keeps its base rotation.
/// </summary>
public readonly record struct SceneryObject(uint ModelId, Vector3 Position, Quaternion Rotation, float Heading, float Scale);
/// <summary>Places a landblock's scenery. Thread-safe; nothing is cached per landblock (callers cache).</summary>
public sealed class SceneryPlacer
{
private readonly DatDatabase _cell;
private readonly DatDatabase _portal;
private readonly TerrainSampler _terrain;
private readonly ModelReader _models;
private readonly Lazy<SceneryTables> _tables;
private readonly ConcurrentDictionary<uint, ShapeInfo> _shapes = new();
public SceneryPlacer(DatDatabase cell, DatDatabase portal, TerrainSampler terrain, ModelReader models)
{
_cell = cell;
_portal = portal;
_terrain = terrain;
_models = models;
_tables = new Lazy<SceneryTables>(() => new SceneryTables(portal), LazyThreadSafetyMode.ExecutionAndPublication);
}
/// <summary>The region's scene tables (read on first use).</summary>
public SceneryTables Tables => _tables.Value;
/// <summary>
/// The scenery of landblock <paramref name="landblock"/> (0xXXYY or any 0xXXYYnnnn id); empty when the
/// landblock or the region tables are missing.
/// </summary>
public List<SceneryObject> Place(uint landblock)
{
uint lb = LandblockData.KeyOf(landblock);
var result = new List<SceneryObject>();
var tables = Tables;
var land = _terrain.LoadLandblock(lb);
if (!tables.Ready || land == null) return result;
var buildingCells = new HashSet<int>();
var info = LandblockInfo.Load(_cell, lb);
if (info != null)
foreach (var b in info.Buildings)
buildingCells.Add(Math.Clamp((int)(b.Origin.X / 24f), 0, 7) * 8 + Math.Clamp((int)(b.Origin.Y / 24f), 0, 7));
ushort[] terrain = land.TerrainWords;
uint blockX = ((lb >> 8) & 0xFF) * 8, blockY = (lb & 0xFF) * 8;
unchecked
{
for (uint i = 0; i < 81; i++)
{
int terrainType = (terrain[i] >> 2) & 0x1F;
int sceneType = terrain[i] >> 11;
if (terrainType >= tables.TerrainTypes.Count) continue;
var tt = tables.TerrainTypes[terrainType];
if (sceneType >= tt.Count) continue;
int sceneInfo = (int)tt[sceneType];
if (sceneInfo < 0 || sceneInfo >= tables.SceneTypes.Count) continue;
var scenes = tables.SceneTypes[sceneInfo];
if (scenes.Count == 0) continue;
uint cellX = i / 9, cellY = i % 9;
uint gx = cellX + blockX, gy = cellY + blockY;
uint cellMat = gy * (712977289u * gx + 1813693831u) - 1109124029u * gx + 2139937281u;
double offset = cellMat * 2.3283064e-10;
int sceneIdx = (int)(scenes.Count * offset);
if (sceneIdx >= scenes.Count || sceneIdx < 0) sceneIdx = 0;
var objs = tables.Scene(scenes[sceneIdx]);
uint cellXMat = 0u - 1109124029u * gx;
uint cellYMat = 1813693831u * gy;
uint cellMat2 = 1360117743u * gx * gy + 1888038839u;
for (uint j = 0; j < objs.Count; j++)
{
var obj = objs[(int)j];
double noise = (uint)(cellXMat + cellYMat - cellMat2 * (23399u + j)) * 2.3283064e-10;
if (!(noise < obj.Freq) || obj.WeenieObj != 0) continue;
var pos = Displace(obj, gx, gy, j);
float lx = cellX * 24f + pos.X, ly = cellY * 24f + pos.Y;
if (lx < 0 || ly < 0 || lx >= 192f || ly >= 192f || TerrainSampler.OnRoad(land, lx, ly)) continue;
int cx = Math.Min((int)(lx / 24f), 7), cy = Math.Min((int)(ly / 24f), 7);
if (buildingCells.Contains(cx * 8 + cy)) continue;
Vector3 n = TerrainSampler.GetNormal(land, lx, ly);
if (!(n.Z >= obj.MinSlope && n.Z <= obj.MaxSlope)) continue;
float z = TerrainSampler.GetTerrainZ(land, lx, ly);
float heading = float.NaN;
if (obj.Align != 0) heading = Heading(-n.X, -n.Y);
else if (obj.MaxRotation > 0f)
heading = (float)((uint)(1813693831u * gy - (j + 63127u) * (1360117743u * gy * gx + 1888038839u) - 1109124029u * gx)
* 2.3283064e-10 * obj.MaxRotation);
// AFrame.set_heading: heading 0 = north (+Y), clockwise: a rotation about Z by -heading.
Quaternion rot = float.IsNaN(heading)
? obj.BaseRotation
: Quaternion.CreateFromAxisAngle(Vector3.UnitZ, -heading * MathF.PI / 180f);
var origin = new Vector3(lx, ly, z);
if (!WithinBlock(origin, rot, Shape(obj.ObjId))) continue;
result.Add(new SceneryObject(obj.ObjId, origin, rot, heading, ScaleObj(obj, gx, gy, j)));
}
}
}
return result;
}
// ---- ACE ObjectDesc maths (uint arithmetic wraps, as in the client) -------------
private static Vector3 Displace(SceneObjectDesc obj, uint ix, uint iy, uint iq)
{
unchecked
{
float x = obj.DisplaceX <= 0 ? obj.BaseOrigin.X
: (float)((uint)(1813693831u * iy - (iq + 45773u) * (1360117743u * iy * ix + 1888038839u) - 1109124029u * ix) * 2.3283064e-10 * obj.DisplaceX + obj.BaseOrigin.X);
float y = obj.DisplaceY <= 0 ? obj.BaseOrigin.Y
: (float)((uint)(1813693831u * iy - (iq + 72719u) * (1360117743u * iy * ix + 1888038839u) - 1109124029u * ix) * 2.3283064e-10 * obj.DisplaceY + obj.BaseOrigin.Y);
float z = obj.BaseOrigin.Z;
double quadrant = (uint)(1813693831u * iy - ix * (1870387557u * iy + 1109124029u) - 402451965u) * 2.3283064e-10;
if (quadrant >= 0.75) return new Vector3(y, -x, z);
if (quadrant >= 0.5) return new Vector3(-x, -y, z);
if (quadrant >= 0.25) return new Vector3(-y, x, z);
return new Vector3(x, y, z);
}
}
private static float ScaleObj(SceneObjectDesc obj, uint x, uint y, uint k)
{
if (obj.MinScale == obj.MaxScale) return obj.MaxScale;
unchecked
{
double t = (uint)(1813693831u * y - (k + 32593u) * (1360117743u * y * x + 1888038839u) - 1109124029u * x) * 2.3283064e-10;
return (float)(Math.Pow(obj.MaxScale / obj.MinScale, t) * obj.MinScale);
}
}
/// <summary>Vector3.get_heading: degrees, 0 = +Y (north), clockwise.</summary>
private static float Heading(float x, float y)
{
float len = MathF.Sqrt(x * x + y * y);
if (len < 1e-6f) return 0;
return (450f - MathF.Atan2(y / len, x / len) * 180f / MathF.PI) % 360f;
}
// ---- obj_within_block ---------------------------------------------------------
/// <summary>What obj_within_block needs of a model: sorting sphere, physics BSP or not, cylinders, spheres.</summary>
private readonly record struct ShapeInfo(Vector3 Center, float Radius, bool Bsp, (Vector3 Low, float R)[] Cylinders, bool Spheres);
private ShapeInfo Shape(uint model) => _shapes.GetOrAdd(model, ReadShape);
private ShapeInfo ReadShape(uint model)
{
var none = Array.Empty<(Vector3, float)>();
var shape = _models.Get(model);
if ((model >> 24) == 0x01)
{
if (shape.Polygons.Count == 0) return new ShapeInfo(Vector3.Zero, 0, false, none, false);
Vector3 mn = new(float.MaxValue), mx = new(float.MinValue);
foreach (var p in shape.Polygons) foreach (var v in p) { mn = Vector3.Min(mn, v); mx = Vector3.Max(mx, v); }
return new ShapeInfo((mn + mx) / 2, (mx - mn).Length() / 2, true, none, false);
}
var b = SetupBounds.Read(_portal, model);
if (b == null) return new ShapeInfo(Vector3.Zero, 0, shape.Polygons.Count > 0, none, false);
return new ShapeInfo(b.SortCenter, b.SortRadius, shape.Polygons.Count > 0,
b.Cylinders.Select(c => (c.Origin, c.Radius)).ToArray(), b.Spheres.Count > 0);
}
/// <summary>PhysicsObj.obj_within_block (ACE), before scaling, as the server checks it.</summary>
private static bool WithinBlock(Vector3 origin, Quaternion rot, ShapeInfo s)
{
Vector3 G(Vector3 p) => Vector3.Transform(p, rot) + origin;
bool Inside(Vector3 c, float r) => c.X >= r && c.Y >= r && c.X < 192f - r && c.Y < 192f - r;
if (s.Bsp) return Inside(G(s.Center), s.Radius);
if (s.Cylinders.Length > 0)
{
foreach (var (low, r) in s.Cylinders)
if (!Inside(G(low), r)) return false;
return true;
}
if (s.Spheres) return Inside(G(s.Center), s.Radius);
return origin.X >= 0 && origin.Y >= 0 && origin.X < 192f && origin.Y < 192f;
}
}

View file

@ -0,0 +1,232 @@
// ============================================================================
// RynthCore.Geometry - Scenery/SceneryTables.cs
// The tables scenery placement reads from the portal dat: the region's
// scene types (each a list of Scene files 0x12..) and terrain types (each a
// list of scene-type indices), from RegionDesc 0x13000000, and the object
// descriptions (ObjectDesc) of each Scene file.
//
// RegionDesc layout as in ACE (RegionDesc.Unpack): Id, RegionNumber, Version,
// RegionName (PString), LandDefs (8 values + 256-float height table),
// GameTime, PartsMask, (0x10) SkyDesc, (0x01) SoundDesc, (0x02) SceneDesc,
// TerrainDesc, ... A PString is a ushort length + bytes, aligned to 4.
// If the walk through it fails a sanity check, the scene and terrain tables
// are found by scanning (as RynthSuite's ScatterSystem does).
//
// Logic from RynthSuite Plugins/RynthCore.Plugin.RynthAi/Raycasting/
// ScatterSystem.cs (4b29610: ParseRegionDesc, ParseSceneDesc, ParseTerrainDesc,
// ScanForTables) and Tools/RynthNav.Baker/Scenery.cs (d4ae46a: Scene).
// Written for RynthCore (MIT).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Scenery;
/// <summary>One object of a Scene file (ACE ObjectDesc): what to place, where in the cell, how often, how big.</summary>
public sealed record SceneObjectDesc(
uint ObjId, Vector3 BaseOrigin, Quaternion BaseRotation, float Freq, float DisplaceX, float DisplaceY,
float MinScale, float MaxScale, float MaxRotation, float MinSlope, float MaxSlope, uint Align, uint Orient, uint WeenieObj);
/// <summary>The region's terrain -> scene-type -> Scene tables, and the Scene files' objects (cached, thread-safe).</summary>
public sealed class SceneryTables
{
public const uint RegionDescId = 0x13000000;
private readonly DatDatabase _portal;
private readonly ConcurrentDictionary<uint, IReadOnlyList<SceneObjectDesc>> _scenes = new();
/// <summary>Per terrain type (0..31): indices into <see cref="SceneTypes"/>.</summary>
public IReadOnlyList<IReadOnlyList<uint>> TerrainTypes { get; private set; } = Array.Empty<IReadOnlyList<uint>>();
/// <summary>Per scene type: its Scene file ids (0x12..).</summary>
public IReadOnlyList<IReadOnlyList<uint>> SceneTypes { get; private set; } = Array.Empty<IReadOnlyList<uint>>();
/// <summary>Both tables were read.</summary>
public bool Ready => TerrainTypes.Count > 0 && SceneTypes.Count > 0;
/// <summary>The tables came from the scan fallback, not the structured walk (diagnostics).</summary>
public bool Scanned { get; private set; }
public SceneryTables(DatDatabase portal)
{
_portal = portal;
byte[]? data = portal.GetFileData(RegionDescId);
if (data == null) return;
if (!Walk(data)) Scanned = Scan(data);
}
/// <summary>The objects of Scene file <paramref name="sceneId"/> (empty when missing).</summary>
public IReadOnlyList<SceneObjectDesc> Scene(uint sceneId) => _scenes.GetOrAdd(sceneId, ReadScene);
private IReadOnlyList<SceneObjectDesc> ReadScene(uint sceneId)
{
var list = new List<SceneObjectDesc>();
byte[]? data = _portal.GetFileData(sceneId);
if (data == null || data.Length < 8) return list;
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint n = r.ReadUInt32();
for (uint i = 0; i < n && ms.Position + 76 <= ms.Length; i++)
{
uint obj = r.ReadUInt32();
var o = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
list.Add(new SceneObjectDesc(obj, o, new Quaternion(x, y, z, w),
r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(),
r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadUInt32(), r.ReadUInt32(), r.ReadUInt32()));
}
return list;
}
// ---- structured walk -----------------------------------------------------
private bool Walk(byte[] data)
{
try
{
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadUInt32(); r.ReadUInt32(); // id, region number, version
PString(r, ms); // region name
ms.Seek(8 * 4 + 256 * 4, SeekOrigin.Current); // LandDefs
// GameTime
r.ReadDouble(); r.ReadUInt32(); r.ReadSingle(); r.ReadUInt32();
PString(r, ms);
uint n = Count(r, 100);
for (uint i = 0; i < n; i++) { r.ReadSingle(); r.ReadUInt32(); PString(r, ms); }
n = Count(r, 100);
for (uint i = 0; i < n; i++) PString(r, ms);
n = Count(r, 100);
for (uint i = 0; i < n; i++) { r.ReadUInt32(); PString(r, ms); }
uint parts = r.ReadUInt32();
if ((parts & 0x10) != 0) // SkyDesc
{
r.ReadDouble(); r.ReadDouble();
uint groups = Count(r, 1000);
for (uint g = 0; g < groups; g++)
{
r.ReadSingle();
PString(r, ms);
ms.Seek(Count(r, 10000) * 36L, SeekOrigin.Current); // SkyObjects
uint times = Count(r, 10000);
for (uint t = 0; t < times; t++)
{
ms.Seek(44, SeekOrigin.Current);
ms.Seek(Count(r, 10000) * 24L, SeekOrigin.Current); // SkyObjectReplace
}
}
}
if ((parts & 0x01) != 0) // SoundDesc
{
uint stbs = Count(r, 10000);
for (uint s = 0; s < stbs; s++)
{
r.ReadUInt32();
ms.Seek(Count(r, 10000) * 20L, SeekOrigin.Current);
}
}
if ((parts & 0x02) == 0) return false;
var scenes = ReadSceneTypes(r);
if (scenes == null) return false;
var terrain = ReadTerrainTypes(r, ms);
if (terrain == null) return false;
SceneTypes = scenes;
TerrainTypes = terrain;
return true;
}
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException or ArgumentException)
{
return false;
}
}
private static List<IReadOnlyList<uint>>? ReadSceneTypes(BinaryReader r)
{
uint n = Count(r, 1000);
if (n == 0) return null;
var list = new List<IReadOnlyList<uint>>();
for (uint i = 0; i < n; i++)
{
r.ReadUInt32(); // STB index
uint k = Count(r, 1000);
var ids = new uint[k];
for (uint s = 0; s < k; s++)
{
ids[s] = r.ReadUInt32();
if ((ids[s] >> 24) != 0x12) return null;
}
list.Add(ids);
}
return list;
}
private static List<IReadOnlyList<uint>>? ReadTerrainTypes(BinaryReader r, MemoryStream ms)
{
uint n = Count(r, 100);
if (n < 5) return null;
var list = new List<IReadOnlyList<uint>>();
for (uint i = 0; i < n; i++)
{
ushort len = r.ReadUInt16();
if (len > 200) return null;
byte[] name = r.ReadBytes(len);
if (name.Any(b => b < 32 || b > 126)) return null;
Align(ms);
r.ReadUInt32(); // terrain colour
uint k = Count(r, 200);
var idx = new uint[k];
for (uint s = 0; s < k; s++) idx[s] = r.ReadUInt32();
list.Add(idx);
}
return list;
}
// ---- scan fallback ----------------------------------------------------------
private bool Scan(byte[] data)
{
for (int pos = 100; pos + 8 < data.Length; pos += 4)
{
uint count = BitConverter.ToUInt32(data, pos);
if (count < 20 || count > 200) continue;
try
{
var ms = new MemoryStream(data) { Position = pos };
using var r = new BinaryReader(ms);
var scenes = ReadSceneTypes(r);
if (scenes == null || scenes.Sum(s => s.Count) < 10) continue;
var terrain = ReadTerrainTypes(r, ms);
if (terrain == null) continue;
SceneTypes = scenes;
TerrainTypes = terrain;
return true;
}
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException or ArgumentException) { }
}
return false;
}
// ---- helpers ------------------------------------------------------------------
private static uint Count(BinaryReader r, uint max)
{
uint n = r.ReadUInt32();
if (n > max) throw new InvalidDataException("bad list count");
return n;
}
private static void PString(BinaryReader r, MemoryStream ms)
{
ushort len = r.ReadUInt16();
if (ms.Position + len > ms.Length) throw new EndOfStreamException();
ms.Seek(len, SeekOrigin.Current);
Align(ms);
}
private static void Align(MemoryStream ms)
{
long a = (ms.Position + 3) & ~3L;
if (a > ms.Length) throw new EndOfStreamException();
ms.Position = a;
}
}

View file

@ -0,0 +1,152 @@
// ============================================================================
// RynthCore.Geometry - Scenery/SetupBounds.cs
// The tail of a Setup (0x02..) record: its collision cylinders and spheres,
// height and radius, and its sorting sphere (the sphere obj_within_block
// checks). ModelReader stops reading a Setup whose placement frames carry
// animation hooks (variable size); this reader finds the tail from the end
// of the record instead, so those Setups keep their cylinders.
//
// Setup layout as in ACE (SetupModel.Unpack):
// Id, Flags, NumParts, Parts[], (Flags&1) Parents[], (Flags&2) Scales[],
// HoldingLocations, ConnectionPoints (count + 36-byte entries),
// PlacementFrames (count + key, numParts frames, numHooks, hooks[]),
// CylSpheres (count + 20 bytes), Spheres (count + 16 bytes),
// Height, Radius, StepUpHeight, StepDownHeight,
// SortingSphere (16), SelectionSphere (16),
// Lights (count + key 4 + LightInfo 44), 5 default ids (20).
//
// Written for RynthCore (MIT) on 2026-10-28; the tail scan follows RynthSuite
// Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs SetupInfo
// (4b29610).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Scenery;
/// <summary>A Setup's collision cylinders and spheres, height, radius and sorting sphere, in model space.</summary>
internal sealed class SetupBounds
{
public readonly List<(Vector3 Origin, float Radius, float Height)> Cylinders = new();
public readonly List<(Vector3 Center, float Radius)> Spheres = new();
public float Height, Radius, StepUp, StepDown;
public Vector3 SortCenter;
public float SortRadius;
/// <summary>Found from the end of the record (the placement frames had animation hooks).</summary>
public bool FromTail;
private const int LightBytes = 4 + 44;
/// <summary>The bounds of Setup <paramref name="id"/>, or null when the record is missing or does not parse.</summary>
public static SetupBounds? Read(DatDatabase portal, uint id)
{
if ((id >> 24) != 0x02) return null;
byte[]? data = portal.GetFileData(id);
if (data == null || data.Length < 16) return null;
try { return Forward(data) ?? FromEnd(data); }
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException or ArgumentException)
{
return FromEnd(data);
}
}
/// <summary>Reads a Setup record front to back (null when it has animation hooks), or from its end (tests compare the two).</summary>
internal static SetupBounds? Parse(byte[] data, bool fromEnd) => fromEnd ? FromEnd(data) : Forward(data);
// Reads front to back; null when the placement frames have hooks (variable size, not skipped).
private static SetupBounds? Forward(byte[] data)
{
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint flags = r.ReadUInt32();
uint numParts = r.ReadUInt32();
if (numParts > 1000) throw new InvalidDataException("bad part count");
ms.Seek(numParts * 4L, SeekOrigin.Current);
if ((flags & 1) != 0) ms.Seek(numParts * 4L, SeekOrigin.Current);
if ((flags & 2) != 0) ms.Seek(numParts * 12L, SeekOrigin.Current);
for (int t = 0; t < 2; t++)
{
int n = r.ReadInt32();
if (n < 0 || n > 1000) throw new InvalidDataException("bad location table");
ms.Seek(n * 36L, SeekOrigin.Current);
}
int placements = r.ReadInt32();
if (placements < 0 || placements > 1000) throw new InvalidDataException("bad placement count");
for (int p = 0; p < placements; p++)
{
r.ReadInt32();
ms.Seek(numParts * 28L, SeekOrigin.Current);
if (r.ReadUInt32() != 0) return null;
}
var b = new SetupBounds();
uint numCyl = r.ReadUInt32();
if (numCyl > 256) throw new InvalidDataException("bad cylinder count");
for (uint i = 0; i < numCyl; i++)
b.Cylinders.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle(), r.ReadSingle()));
uint numSph = r.ReadUInt32();
if (numSph > 256) throw new InvalidDataException("bad sphere count");
for (uint i = 0; i < numSph; i++)
b.Spheres.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle()));
b.Height = r.ReadSingle(); b.Radius = r.ReadSingle(); b.StepUp = r.ReadSingle(); b.StepDown = r.ReadSingle();
b.SortCenter = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
b.SortRadius = r.ReadSingle();
return b;
}
// The record ends: sorting sphere, selection sphere, light count + lights, 5 ids. Find the light count
// that fits, then walk back over Height..StepDown, the sphere list and the cylinder list.
private static SetupBounds? FromEnd(byte[] data)
{
for (int lights = 0; lights <= 16; lights++)
{
int countAt = data.Length - 20 - lights * LightBytes - 4;
if (countAt < 16 + 32 + 16 + 8) break;
if (BitConverter.ToUInt32(data, countAt) != (uint)lights) continue;
int sortAt = countAt - 32, heightAt = sortAt - 16;
float sortR = BitConverter.ToSingle(data, sortAt + 12);
if (!float.IsFinite(sortR) || sortR < 0 || sortR > 10000) continue;
for (int k = 0; k <= 64; k++)
{
int sphCountAt = heightAt - 16 * k - 4;
if (sphCountAt < 16) break;
if (BitConverter.ToUInt32(data, sphCountAt) != (uint)k) continue;
for (int m = 0; m <= 64; m++)
{
int cylCountAt = sphCountAt - 20 * m - 4;
if (cylCountAt < 16) break;
if (BitConverter.ToUInt32(data, cylCountAt) != (uint)m) continue;
var b = new SetupBounds { FromTail = true };
for (int i = 0; i < m; i++)
{
int o = cylCountAt + 4 + 20 * i;
b.Cylinders.Add((V(data, o), F(data, o + 12), F(data, o + 16)));
}
for (int i = 0; i < k; i++)
{
int o = sphCountAt + 4 + 16 * i;
b.Spheres.Add((V(data, o), F(data, o + 12)));
}
b.Height = F(data, heightAt); b.Radius = F(data, heightAt + 4);
b.StepUp = F(data, heightAt + 8); b.StepDown = F(data, heightAt + 12);
b.SortCenter = V(data, sortAt); b.SortRadius = sortR;
if (Plausible(b)) return b;
}
}
}
return null;
}
private static bool Plausible(SetupBounds b)
{
static bool Ok(float f) => float.IsFinite(f) && MathF.Abs(f) < 10000;
if (!Ok(b.Height) || !Ok(b.Radius) || b.Height < 0 || b.Radius < 0) return false;
foreach (var c in b.Cylinders) if (!Ok(c.Origin.Length()) || !Ok(c.Radius) || !Ok(c.Height) || c.Radius < 0 || c.Height < 0) return false;
foreach (var s in b.Spheres) if (!Ok(s.Center.Length()) || !Ok(s.Radius) || s.Radius < 0) return false;
return Ok(b.SortCenter.Length());
}
private static float F(byte[] d, int o) => BitConverter.ToSingle(d, o);
private static Vector3 V(byte[] d, int o) => new(F(d, o), F(d, o + 4), F(d, o + 8));
}

View file

@ -0,0 +1,153 @@
// ============================================================================
// RynthCore.Geometry - Terrain/LandblockData.cs
// One outdoor landblock's terrain as the cell dat stores it: the 9x9 vertex
// grid of terrain words (road bits, terrain type, scene type) and height
// indices, plus the heights decoded through the region's land-height table.
// Pure data: the triangle math (split-aware Z, normals, raycast, roads) lives
// in TerrainSampler so there is exactly one implementation of it.
//
// Moved from RynthSuite Shared/RynthCore.TerrainData/LandblockData.cs (72b9e26).
// Changes on the move: namespace, nullable annotations, System.Numerics; the
// old GetTerrainZLocal / RaycastTerrainLocal, which always split cells SW->NE
// (wrong on about half the cells), were dropped in favour of the split-aware
// TerrainSampler.GetTerrainZ / RaycastTerrain.
// ============================================================================
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Terrain;
/// <summary>
/// Parsed CellLandblock (cell dat file 0xXXYYFFFF): the terrain heightmap and terrain words of
/// one 192 x 192 m landblock.
///
/// File layout:
/// uint Id (0xXXYYFFFF)
/// uint HasObjects (nonzero if the matching 0xXXYYFFFE LandblockInfo exists)
/// ushort Terrain[81] 9x9 grid: roadBits (bits 0-1) | terrainType &lt;&lt; 2 (bits 2-6) | sceneType &lt;&lt; 11
/// byte Height[81] 9x9 grid, indices into RegionDesc's LandHeightTable
///
/// Vertex indexing: idx = ix * 9 + iy, ix = 0..8 west to east, iy = 0..8 south to north.
/// Vertex (ix, iy) sits at landblock-local (ix * 24, iy * 24). Heights are absolute world Z.
/// </summary>
public sealed class LandblockData
{
public const int VertexDim = 9;
public const int BlockSide = 8;
public const float CellLength = 24.0f;
public const float BlockLength = 192.0f;
/// <summary>0xXXYY landblock key (no cell word).</summary>
public uint LandblockKey { get; }
/// <summary>The landblock has a 0xXXYYFFFE LandblockInfo (buildings / static objects).</summary>
public bool HasObjects { get; }
/// <summary>81 terrain words, idx = ix * 9 + iy.</summary>
public ushort[] TerrainWords { get; }
/// <summary>81 raw height indices (into the land-height table), idx = ix * 9 + iy.</summary>
public byte[] HeightIndices { get; }
/// <summary>Decoded world Z of every vertex, HeightsZ[ix, iy].</summary>
public float[,] HeightsZ { get; }
/// <summary>World X of vertex (0, 0), the SW corner of the landblock (landblock X * 192).</summary>
public float WorldOriginX => ((LandblockKey >> 8) & 0xFF) * BlockLength;
/// <summary>World Y of vertex (0, 0), the SW corner of the landblock (landblock Y * 192).</summary>
public float WorldOriginY => (LandblockKey & 0xFF) * BlockLength;
private LandblockData(uint key, bool hasObjects, ushort[] terrain, byte[] heights, float[,] heightsZ)
{
LandblockKey = key;
HasObjects = hasObjects;
TerrainWords = terrain;
HeightIndices = heights;
HeightsZ = heightsZ;
}
/// <summary>
/// The 0xXXYY key of any landblock or cell id: 0xXXYYnnnn gives 0xXXYY, a value that already
/// fits in 16 bits is taken as the key itself. (So cell ids of landblock 0x0000, open ocean
/// at the world corner, can't be passed this way; pass the key 0 instead.)
/// </summary>
public static uint KeyOf(uint landblockOrCellId) => landblockOrCellId > 0xFFFF ? landblockOrCellId >> 16 : landblockOrCellId;
/// <summary>
/// Loads and parses the 0xXXYYFFFF CellLandblock. <paramref name="landblock"/> is the 0xXXYY key
/// or any 0xXXYYnnnn id (see <see cref="KeyOf"/>). Returns null if the file is missing or short.
/// </summary>
public static LandblockData? Load(DatDatabase cellDat, uint landblock, float[] landHeightTable)
{
ArgumentNullException.ThrowIfNull(cellDat);
ArgumentNullException.ThrowIfNull(landHeightTable);
uint key = KeyOf(landblock);
byte[]? data = cellDat.GetFileData((key << 16) | 0xFFFF);
return data == null ? null : Parse(key, data, landHeightTable);
}
/// <summary>
/// Parses a CellLandblock record (the bytes of 0xXXYYFFFF). Returns null if it's too short.
/// </summary>
public static LandblockData? Parse(uint landblockKey, ReadOnlySpan<byte> data, float[] landHeightTable)
{
// 4 (Id) + 4 (HasObjects) + 81*2 (terrain) + 81 (heights) = 251
const int Needed = 4 + 4 + 81 * 2 + 81;
if (data.Length < Needed) return null;
bool hasObjects = BitConverter.ToUInt32(data.Slice(4, 4)) != 0;
var terrain = new ushort[81];
for (int i = 0; i < 81; i++)
terrain[i] = BitConverter.ToUInt16(data.Slice(8 + i * 2, 2));
var heights = data.Slice(8 + 81 * 2, 81).ToArray();
var heightsZ = new float[VertexDim, VertexDim];
for (int ix = 0; ix < VertexDim; ix++)
for (int iy = 0; iy < VertexDim; iy++)
{
byte h = heights[ix * VertexDim + iy];
heightsZ[ix, iy] = h < landHeightTable.Length ? landHeightTable[h] : 0f;
}
return new LandblockData(KeyOf(landblockKey), hasObjects, terrain, heights, heightsZ);
}
/// <summary>Vertex Z at grid coords (0..8, 0..8); 0 outside the grid.</summary>
public float GetVertexZ(int ix, int iy)
{
if ((uint)ix > BlockSide || (uint)iy > BlockSide) return 0f;
return HeightsZ[ix, iy];
}
/// <summary>Terrain word at grid coords (0..8, 0..8); 0 outside the grid.</summary>
public ushort GetTerrainWord(int ix, int iy)
{
if ((uint)ix > BlockSide || (uint)iy > BlockSide) return 0;
return TerrainWords[ix * VertexDim + iy];
}
/// <summary>
/// Z of the nearest grid vertex for a landblock-local position; coordinates outside the block
/// are clamped to the edge. (A coarse lookup; TerrainSampler.GetTerrainZ is the exact one.)
/// </summary>
public float GetNearestVertexHeightLocal(float lx, float ly)
{
int ix = Math.Clamp((int)MathF.Round(lx / CellLength), 0, BlockSide);
int iy = Math.Clamp((int)MathF.Round(ly / CellLength), 0, BlockSide);
return HeightsZ[ix, iy];
}
/// <summary>Min and max vertex Z across the landblock.</summary>
public void GetHeightRange(out float min, out float max)
{
min = float.PositiveInfinity;
max = float.NegativeInfinity;
foreach (float z in HeightsZ)
{
if (z < min) min = z;
if (z > max) max = z;
}
}
}

View file

@ -0,0 +1,569 @@
// ============================================================================
// RynthCore.Geometry - Terrain/TerrainSampler.cs
// Outdoor ground queries on AC's landscape mesh: terrain Z, triangle normal,
// walkability, road test, terrain type and a ray-vs-terrain cast, all on the
// triangle the game actually uses for each 24 m cell (the per-cell diagonal
// split, ACE LandblockStruct.ConstructPolygons / FSplitNESW). Reads the land-
// height table from RegionDesc 0x13000000 in the portal dat and keeps parsed
// landblocks (cell dat 0xXXYYFFFF) in a small thread-safe LRU.
//
// Moved from RynthSuite Shared/RynthCore.TerrainData/TerrainSampler.cs (8777fac),
// with TerrainNormal and OnRoad from Tools/RynthNav.Baker/Scenery.cs (d4ae46a).
// Changes on the move: built on caller-supplied (shareable) DatDatabase
// instances instead of opening its own, System.Numerics.Vector3, the split-
// aware raycast (the old LandblockData.RaycastTerrainLocal always split SW->NE)
// now crosses into neighbouring landblocks.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Terrain;
/// <summary>
/// Terrain queries for AC's outdoor landscape.
///
/// Coordinates: a landblock is named by its 0xXXYY key, or by any 0xXXYYnnnn landblock/cell id
/// (the high word is used, see <see cref="LandblockData.KeyOf"/>). Positions are landblock-local:
/// X east and Y north in 0..192 from the landblock's SW corner, Z absolute (the same Z as
/// server positions). Each landblock is 8 x 8 cells of 24 m; each cell is two triangles, cut
/// along the diagonal <see cref="SwToNeCut"/> picks.
///
/// Thread-safety: all members can be called from any thread. The landblock cache is behind a
/// lock; the DatDatabase instances are thread-safe themselves.
/// </summary>
public sealed class TerrainSampler : IDisposable
{
/// <summary>
/// AC's walkable threshold (ACE PhysicsGlobals.FloorZ): a surface whose unit normal has Z
/// below this is too steep to stand on (is_valid_walkable). About 48.4 degrees.
/// </summary>
public const float FloorZ = 0.66417414618662751f;
/// <summary>RegionDesc record in the portal dat that holds the land-height table.</summary>
public const uint RegionDescId = 0x13000000;
private const float Cell = LandblockData.CellLength;
private const float Block = LandblockData.BlockLength;
private readonly DatDatabase _portal;
private readonly DatDatabase _cell;
private readonly bool _ownsDats;
private readonly float[] _landHeightTable;
// Parsed landblocks (null = not in the dat), least recently used out first. A load runs
// outside the lock; two threads missing the same key both parse it and the later Set wins,
// which is harmless.
private readonly object _cacheGate = new();
private readonly LruCache<uint, LandblockData?> _cache;
/// <summary>
/// A sampler over already-open dats, which stay the caller's (Dispose doesn't close them).
/// Throws InvalidDataException if RegionDesc's land-height table can't be read.
/// </summary>
public TerrainSampler(DatDatabase portal, DatDatabase cell, int cacheCapacity = 64)
: this(portal, cell, cacheCapacity, ownsDats: false) { }
private TerrainSampler(DatDatabase portal, DatDatabase cell, int cacheCapacity, bool ownsDats)
{
ArgumentNullException.ThrowIfNull(portal);
ArgumentNullException.ThrowIfNull(cell);
_portal = portal;
_cell = cell;
_ownsDats = ownsDats;
_landHeightTable = ReadLandHeightTable(portal)
?? throw new InvalidDataException($"RegionDesc 0x{RegionDescId:X8} land-height table not readable from {portal.FilePath}");
// The default holds a 7x7-landblock window (an overlay of radius 3 landblocks) plus headroom.
_cache = new LruCache<uint, LandblockData?>(cacheCapacity);
}
/// <summary>
/// Opens client_portal.dat (or portal.dat) and client_cell_1.dat (or cell.dat) in
/// <paramref name="acFolder"/> read-only; the sampler owns them and closes them on Dispose.
/// Throws FileNotFoundException / InvalidDataException with the reason on failure.
/// </summary>
public static TerrainSampler Open(string acFolder, int cacheCapacity = 64)
{
string portalPath = FindDat(acFolder, "client_portal.dat", "portal.dat")
?? throw new FileNotFoundException($"no client_portal.dat / portal.dat in {acFolder}");
string cellPath = FindDat(acFolder, "client_cell_1.dat", "cell.dat")
?? throw new FileNotFoundException($"no client_cell_1.dat / cell.dat in {acFolder}");
var portal = new DatDatabase();
var cell = new DatDatabase();
try
{
if (!portal.Open(portalPath)) throw new InvalidDataException($"can't open {portalPath}: {Last(portal)}");
if (!cell.Open(cellPath)) throw new InvalidDataException($"can't open {cellPath}: {Last(cell)}");
return new TerrainSampler(portal, cell, cacheCapacity, ownsDats: true);
}
catch
{
portal.Dispose();
cell.Dispose();
throw;
}
static string Last(DatDatabase d) => d.DiagLog.Count > 0 ? d.DiagLog[^1] : "unknown error";
}
/// <summary>The 256-entry land-height table (height index to world Z).</summary>
public IReadOnlyList<float> LandHeightTable => _landHeightTable;
public DatDatabase PortalDat => _portal;
public DatDatabase CellDat => _cell;
/// <summary>Parsed landblock (heights + terrain words), cached. Null if the dat doesn't have it.</summary>
public LandblockData? LoadLandblock(uint landblock)
{
uint key = LandblockData.KeyOf(landblock);
lock (_cacheGate)
{
if (_cache.TryGet(key, out var cached)) return cached;
}
LandblockData? data = LandblockData.Load(_cell, key, _landHeightTable);
lock (_cacheGate) _cache.Set(key, data);
return data;
}
// ------------------------------------------------------------------ height
/// <summary>Terrain Z at landblock-local (lx, ly), clamped to the block. NaN if the landblock isn't in the dat.</summary>
public float GetTerrainZ(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb == null ? float.NaN : GetTerrainZ(lb, localX, localY);
}
/// <summary>
/// Terrain Z at landblock-local (lx, ly) in [0, 192], on the triangle AC uses for that cell
/// (<see cref="SwToNeCut"/>). Coordinates are clamped to the block.
/// </summary>
public static float GetTerrainZ(LandblockData lb, float localX, float localY)
=> GetTerrainZ(lb, localX, localY, invertSplit: false);
/// <summary>GetTerrainZ with the split polarity optionally flipped (the tests use it to check the polarity).</summary>
internal static float GetTerrainZ(LandblockData lb, float localX, float localY, bool invertSplit)
{
Locate(localX, localY, out int cx, out int cy, out float u, out float v);
float h00 = lb.GetVertexZ(cx, cy); // SW
float h10 = lb.GetVertexZ(cx + 1, cy); // SE
float h01 = lb.GetVertexZ(cx, cy + 1); // NW
float h11 = lb.GetVertexZ(cx + 1, cy + 1); // NE
if (SwToNeCut(lb.LandblockKey, cx, cy) != invertSplit)
{
// SE half (SW,SE,NE) when v <= u, NW half (SW,NE,NW) otherwise.
return v <= u
? h00 + u * (h10 - h00) + v * (h11 - h10)
: h00 + v * (h01 - h00) + u * (h11 - h01);
}
// SW half (SW,SE,NW) when u + v <= 1, NE half (SE,NE,NW) otherwise.
return u + v <= 1f
? h00 + u * (h10 - h00) + v * (h01 - h00)
: h11 + (1f - u) * (h01 - h11) + (1f - v) * (h10 - h11);
}
// ------------------------------------------------------------------ normal / slope
/// <summary>Unit upward (Z &gt; 0) normal of the terrain triangle under (lx, ly). Zero vector if the landblock isn't in the dat.</summary>
public Vector3 GetNormal(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb == null ? Vector3.Zero : GetNormal(lb, localX, localY);
}
/// <summary>
/// Unit upward normal of the terrain triangle under landblock-local (lx, ly), on AC's per-cell
/// split (Scenery.TerrainNormal in the RynthNav baker). Coordinates are clamped to the block.
/// </summary>
public static Vector3 GetNormal(LandblockData lb, float localX, float localY)
{
Locate(localX, localY, out int cx, out int cy, out float u, out float v);
bool swToNe = SwToNeCut(lb.LandblockKey, cx, cy);
int tri = swToNe ? (v <= u ? 0 : 1) : (u + v <= 1f ? 0 : 1);
CellTriangle(lb, cx, cy, swToNe, tri, out var a, out var b, out var c);
return UpNormal(a, b, c);
}
/// <summary>True if a surface with this unit normal is flat enough to stand on (normal.Z &gt;= <paramref name="floorZ"/>).</summary>
public static bool IsWalkable(Vector3 normal, float floorZ = FloorZ) => normal.Z >= floorZ;
/// <summary>
/// Walkability of the two triangles of cell (cx, cy), 0..7. Which halves tri1/tri2 are depends
/// on the split: swToNeCut true gives tri1 = SE half (SW,SE,NE), tri2 = NW half (SW,NE,NW);
/// false gives tri1 = SW half (SW,SE,NW), tri2 = NE half (SE,NE,NW).
/// </summary>
public static void GetTrianglePassability(LandblockData lb, int cx, int cy, bool swToNeCut,
out bool tri1Passable, out bool tri2Passable, float floorZ = FloorZ)
{
CellTriangle(lb, cx, cy, swToNeCut, 0, out var a, out var b, out var c);
tri1Passable = UpNormal(a, b, c).Z >= floorZ;
CellTriangle(lb, cx, cy, swToNeCut, 1, out a, out b, out c);
tri2Passable = UpNormal(a, b, c).Z >= floorZ;
}
/// <summary>GetTrianglePassability on the cell's own split.</summary>
public static void GetTrianglePassability(LandblockData lb, int cx, int cy,
out bool tri1Passable, out bool tri2Passable, float floorZ = FloorZ)
=> GetTrianglePassability(lb, cx, cy, SwToNeCut(lb.LandblockKey, cx, cy),
out tri1Passable, out tri2Passable, floorZ);
// ------------------------------------------------------------------ split
/// <summary>
/// AC's per-cell diagonal split (ACE LandblockStruct.ConstructPolygons / FSplitNESW). True: the
/// cell is cut SW to NE (triangles SW-SE-NE and SW-NE-NW); false: cut SE to NW (triangles
/// SW-SE-NW and SE-NE-NW). Roughly half the cells each way.
///
/// The PRNG inputs are the cell's vertex-grid coordinates (landblock index * 8 + cell index),
/// matching ACE's blockid_to_lcoord (LandblockShift = 3), not raw landblock indices.
/// <paramref name="landblock"/> is the 0xXXYY key or any 0xXXYYnnnn id.
/// </summary>
public static bool SwToNeCut(uint landblock, int cellX, int cellY)
{
uint key = LandblockData.KeyOf(landblock);
int lbX = (int)((key >> 8) & 0xFF);
int lbY = (int)(key & 0xFF);
int vertexX = (lbX << 3) + cellX;
int vertexY = (lbY << 3) + cellY;
unchecked
{
uint magicA = (uint)vertexX * 214614067u + 1813693831u;
uint magicB = (uint)vertexX * 1109124029u;
uint splitDir = (uint)vertexY * magicA - magicB - 1369149221u;
return (splitDir & 0x80000000u) != 0;
}
}
// ------------------------------------------------------------------ roads / terrain type
/// <summary>True if (lx, ly) is on a road (ACE Landblock.OnRoad). False if the landblock isn't in the dat.</summary>
public bool OnRoad(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb != null && OnRoad(lb, localX, localY);
}
/// <summary>
/// ACE Landblock.OnRoad: from the road bits of the four corners of the 24 m cell under
/// (lx, ly), with a 5 m road width. Used by the server to keep scenery off roads.
/// </summary>
public static bool OnRoad(LandblockData lb, float localX, float localY)
{
const float rMin = 5f, rMax = Cell - rMin;
int x = (int)(localX / Cell), y = (int)(localY / Cell);
uint r0 = RoadBits(lb, x, y), r1 = RoadBits(lb, x, y + 1), r2 = RoadBits(lb, x + 1, y), r3 = RoadBits(lb, x + 1, y + 1);
if (r0 == 0 && r1 == 0 && r2 == 0 && r3 == 0) return false;
float dx = localX - x * Cell, dy = localY - y * Cell;
if (r0 > 0)
{
if (r1 > 0)
{
if (r2 > 0) return r3 > 0 || dx < rMin || dy < rMin;
return r3 > 0 ? (dx < rMin || dy > rMax) : dx < rMin;
}
if (r2 > 0) return r3 > 0 ? (dx > rMax || dy < rMin) : dy < rMin;
return r3 > 0 ? MathF.Abs(dx - dy) < rMin : dx + dy < rMin;
}
if (r1 > 0)
{
if (r2 > 0) return r3 > 0 ? (dx > rMax || dy > rMax) : MathF.Abs(dx + dy - Cell) < rMin;
return r3 > 0 ? dy > rMax : Cell + dx - dy < rMin;
}
if (r2 > 0) return r3 > 0 ? dx > rMax : Cell - dx + dy < rMin;
return r3 > 0 && Cell * 2f - dx - dy < rMin;
}
/// <summary>Road bits (terrain word bits 0-1) of vertex (ix, iy); 0 outside 0..8.</summary>
public static uint RoadBits(LandblockData lb, int ix, int iy) => (uint)(lb.GetTerrainWord(ix, iy) & 3);
/// <summary>
/// Terrain type (0-31: grass, water types, ...) of the grid vertex nearest (lx, ly).
/// -1 if the landblock isn't in the dat.
/// </summary>
public int TerrainType(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
if (lb == null) return -1;
int ix = Math.Clamp((int)MathF.Round(localX / Cell), 0, LandblockData.BlockSide);
int iy = Math.Clamp((int)MathF.Round(localY / Cell), 0, LandblockData.BlockSide);
return TerrainType(lb, ix, iy);
}
/// <summary>Terrain type (terrain word bits 2-6) of vertex (ix, iy), 0..8; -1 outside the grid.</summary>
public static int TerrainType(LandblockData lb, int ix, int iy)
{
if ((uint)ix > LandblockData.BlockSide || (uint)iy > LandblockData.BlockSide) return -1;
return (lb.GetTerrainWord(ix, iy) >> 2) & 0x1F;
}
// ------------------------------------------------------------------ water
/// <summary>True for the water terrain types: WaterRunning (16) .. WaterDeepSea (20).</summary>
public static bool IsWaterTerrain(int terrainType) => terrainType >= 16 && terrainType <= 20;
/// <summary>
/// Water type of land cell (cx, cy), 0..7, from its four corner vertices (ACE
/// LandblockStruct.CalcCellWater): all four water terrain = EntirelyWater, some = PartiallyWater.
/// </summary>
public static WaterType GetWaterType(LandblockData lb, int cx, int cy)
{
int water = 0;
if (IsWaterTerrain(TerrainType(lb, cx, cy))) water++;
if (IsWaterTerrain(TerrainType(lb, cx + 1, cy))) water++;
if (IsWaterTerrain(TerrainType(lb, cx, cy + 1))) water++;
if (IsWaterTerrain(TerrainType(lb, cx + 1, cy + 1))) water++;
return water == 0 ? WaterType.NotWater : water == 4 ? WaterType.EntirelyWater : WaterType.PartiallyWater;
}
/// <summary>
/// How far an object standing in the land cell under (lx, ly) sinks below the terrain mesh
/// (ACE ObjCell.get_water_depth): 0 on dry cells, 0.45 m in a partially-water cell, 0.9 m in
/// an entirely-water cell. 0 if the landblock isn't in the dat.
/// </summary>
public float GetWaterDepth(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb == null ? 0f : GetWaterDepth(lb, localX, localY);
}
/// <inheritdoc cref="GetWaterDepth(uint, float, float)"/>
public static float GetWaterDepth(LandblockData lb, float localX, float localY)
{
Locate(localX, localY, out int cx, out int cy, out _, out _);
return GetWaterType(lb, cx, cy) switch
{
WaterType.EntirelyWater => 0.9f,
WaterType.PartiallyWater => 0.45f,
_ => 0f,
};
}
/// <summary>
/// Z at which an object stands on open ground at (lx, ly): the terrain mesh Z less the cell's
/// water depth. (Buildings, porches and other objects can hold it higher; they aren't tested.)
/// NaN if the landblock isn't in the dat.
/// </summary>
public float GetStandingZ(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb == null ? float.NaN : GetTerrainZ(lb, localX, localY) - GetWaterDepth(lb, localX, localY);
}
// ------------------------------------------------------------------ raycast
/// <summary>
/// Nearest hit of a ray with the terrain mesh. <paramref name="localOrigin"/> is relative to
/// <paramref name="landblock"/>'s SW corner (X/Y local, normally 0..192 but may lie outside;
/// Z absolute). <paramref name="dir"/> needn't be unit length; <paramref name="dist"/> is in
/// metres along it. The ray walks the 24 m cell grid (2D DDA) and tests the two triangles of
/// each cell on the cell's real split (Moller-Trumbore, both faces). It is not limited to the
/// starting landblock: cells past the edge are looked up in the neighbouring landblocks, and
/// a landblock missing from the dat (or off the world) is passed over as having no ground.
/// <paramref name="normal"/> is the unit upward normal of the triangle hit.
/// Terrain only: buildings, objects and dungeon cells are not tested.
/// </summary>
public bool RaycastTerrain(uint landblock, Vector3 localOrigin, Vector3 dir, float maxDist,
out float dist, out Vector3 normal)
{
dist = 0f;
normal = Vector3.Zero;
float len = dir.Length();
if (!(len > 1e-12f) || !(maxDist > 0f) || !float.IsFinite(localOrigin.X + localOrigin.Y + localOrigin.Z)) return false;
dir /= len;
uint key = LandblockData.KeyOf(landblock);
int lbX = (int)((key >> 8) & 0xFF), lbY = (int)(key & 0xFF);
float px = localOrigin.X, py = localOrigin.Y;
int cx = (int)MathF.Floor(px / Cell);
int cy = (int)MathF.Floor(py / Cell);
int stepX = dir.X > 0 ? 1 : (dir.X < 0 ? -1 : 0);
int stepY = dir.Y > 0 ? 1 : (dir.Y < 0 ? -1 : 0);
float tMaxX = float.PositiveInfinity, tDeltaX = float.PositiveInfinity;
float tMaxY = float.PositiveInfinity, tDeltaY = float.PositiveInfinity;
if (stepX != 0)
{
tMaxX = ((stepX > 0 ? cx + 1 : cx) * Cell - px) / dir.X;
tDeltaX = Cell / MathF.Abs(dir.X);
}
if (stepY != 0)
{
tMaxY = ((stepY > 0 ? cy + 1 : cy) * Cell - py) / dir.Y;
tDeltaY = Cell / MathF.Abs(dir.Y);
}
// Cells a ray of this length can cross, plus slack for float error at the boundaries.
float span = maxDist * (MathF.Abs(dir.X) + MathF.Abs(dir.Y)) / Cell;
int iterLimit = (int)MathF.Min(span, 1_000_000f) + 4;
float bestT = maxDist;
bool found = false;
LandblockData? lb = null;
int lbCurX = int.MinValue, lbCurY = int.MinValue;
while (iterLimit-- > 0)
{
int dlx = FloorDiv(cx, LandblockData.BlockSide), dly = FloorDiv(cy, LandblockData.BlockSide);
int nx = lbX + dlx, ny = lbY + dly;
if (nx != lbCurX || ny != lbCurY)
{
lbCurX = nx;
lbCurY = ny;
lb = (uint)nx <= 0xFF && (uint)ny <= 0xFF ? LoadLandblock((uint)((nx << 8) | ny)) : null;
}
if (lb != null)
{
int lcx = cx - dlx * LandblockData.BlockSide, lcy = cy - dly * LandblockData.BlockSide;
bool swToNe = SwToNeCut(lb.LandblockKey, lcx, lcy);
// Cell-local frame (SW vertex at the origin) keeps the float math small.
float baseZ = lb.GetVertexZ(lcx, lcy);
var o = new Vector3(px - cx * Cell, py - cy * Cell, localOrigin.Z - baseZ);
for (int tri = 0; tri < 2; tri++)
{
CellTriangle(lb, lcx, lcy, swToNe, tri, out var a, out var b, out var c);
a.Z -= baseZ; b.Z -= baseZ; c.Z -= baseZ;
if (RayTriangle(o, dir, a, b, c, out float t) && t <= bestT)
{
bestT = t;
normal = UpNormal(a, b, c);
found = true;
}
}
}
float tNext = MathF.Min(tMaxX, tMaxY);
// A hit in this cell lies before the ray leaves it, so it's the nearest one.
if (found && bestT <= tNext + 1e-4f) break;
if (tNext > maxDist) break;
if (stepX == 0 && stepY == 0) break; // vertical ray: one cell
if (tMaxX < tMaxY) { tMaxX += tDeltaX; cx += stepX; }
else { tMaxY += tDeltaY; cy += stepY; }
}
if (!found) { normal = Vector3.Zero; return false; }
dist = bestT;
return true;
}
// ------------------------------------------------------------------ height table
/// <summary>
/// The 256-entry land-height table from RegionDesc 0x13000000: header (id, region number,
/// version), the region name (PString), the eight LandDefs scalars, then 256 floats.
/// Null if the record is missing or short.
/// </summary>
public static float[]? ReadLandHeightTable(DatDatabase portal)
{
byte[]? data = portal.GetFileData(RegionDescId);
// 12 (header) + >=2 (PString) + 32 (LandDefs prefix) + 256*4 (table)
if (data == null || data.Length < 12 + 2 + 32 + 256 * 4) return null;
int pos = 12; // id, regionNumber, version
int nameLen = BitConverter.ToUInt16(data, pos); // RegionName: ushort length + bytes,
pos = (pos + 2 + nameLen + 3) & ~3; // padded to 4 bytes
pos += 32; // LandDefs: NumBlockLength, NumBlockWidth, SquareLength, LBlockLength,
// VertexPerCell, MaxObjHeight, SkyHeight, RoadWidth
if (pos + 256 * 4 > data.Length) return null;
var table = new float[256];
for (int i = 0; i < 256; i++) table[i] = BitConverter.ToSingle(data, pos + i * 4);
return table;
}
// ------------------------------------------------------------------ helpers
private static void Locate(float lx, float ly, out int cx, out int cy, out float u, out float v)
{
lx = float.IsNaN(lx) ? 0f : Math.Clamp(lx, 0f, Block);
ly = float.IsNaN(ly) ? 0f : Math.Clamp(ly, 0f, Block);
cx = Math.Min((int)(lx / Cell), LandblockData.BlockSide - 1);
cy = Math.Min((int)(ly / Cell), LandblockData.BlockSide - 1);
u = (lx - cx * Cell) / Cell;
v = (ly - cy * Cell) / Cell;
}
/// <summary>
/// Triangle <paramref name="tri"/> (0 or 1) of cell (cx, cy), in the cell's local XY (0 or 24)
/// with absolute Z, wound counter-clockwise seen from above. swToNe: 0 = SE half (SW,SE,NE),
/// 1 = NW half (SW,NE,NW); otherwise 0 = SW half (SW,SE,NW), 1 = NE half (SE,NE,NW).
/// </summary>
private static void CellTriangle(LandblockData lb, int cx, int cy, bool swToNe, int tri,
out Vector3 a, out Vector3 b, out Vector3 c)
{
var sw = new Vector3(0f, 0f, lb.GetVertexZ(cx, cy));
var se = new Vector3(Cell, 0f, lb.GetVertexZ(cx + 1, cy));
var nw = new Vector3(0f, Cell, lb.GetVertexZ(cx, cy + 1));
var ne = new Vector3(Cell, Cell, lb.GetVertexZ(cx + 1, cy + 1));
if (swToNe)
{
if (tri == 0) { a = sw; b = se; c = ne; } else { a = sw; b = ne; c = nw; }
}
else
{
if (tri == 0) { a = sw; b = se; c = nw; } else { a = se; b = ne; c = nw; }
}
}
private static Vector3 UpNormal(Vector3 a, Vector3 b, Vector3 c)
{
var n = Vector3.Normalize(Vector3.Cross(b - a, c - a));
return n.Z < 0 ? -n : n;
}
// Moller-Trumbore, both faces; t along a unit direction.
private static bool RayTriangle(Vector3 origin, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t)
{
t = 0f;
const float Epsilon = 1e-7f;
Vector3 edge1 = v1 - v0;
Vector3 edge2 = v2 - v0;
Vector3 h = Vector3.Cross(dir, edge2);
float a = Vector3.Dot(edge1, h);
if (a > -Epsilon && a < Epsilon) return false;
float f = 1f / a;
Vector3 s = origin - v0;
float u = f * Vector3.Dot(s, h);
if (u < 0f || u > 1f) return false;
Vector3 q = Vector3.Cross(s, edge1);
float v = f * Vector3.Dot(dir, q);
if (v < 0f || u + v > 1f) return false;
t = f * Vector3.Dot(edge2, q);
return t >= 0f;
}
private static int FloorDiv(int a, int b) => a >= 0 ? a / b : -((-a + b - 1) / b);
private static string? FindDat(string folder, params string[] names)
{
foreach (var n in names)
{
string p = Path.Combine(folder, n);
if (File.Exists(p)) return p;
}
return null;
}
/// <summary>Drops the cache; closes the dats only if <see cref="Open"/> opened them.</summary>
public void Dispose()
{
lock (_cacheGate) _cache.Clear();
if (_ownsDats)
{
_portal.Dispose();
_cell.Dispose();
}
}
}
/// <summary>Water in a 24 m land cell (ACE LandDefs.WaterType).</summary>
public enum WaterType
{
NotWater = 0,
PartiallyWater = 1,
EntirelyWater = 2,
}

View file

@ -0,0 +1,146 @@
// ============================================================================
// RynthCore.Geometry - Walking/LocalPlanner.cs
// A short-range path around obstacles (a building corner, a fence, a doorway), for
// when a straight walk is blocked. Not a navigator: long routes come from RynthNav.
//
// A* over a grid (Grid metres) anchored at the start, where an edge exists only if
// the Walker itself can make that step (so walls, slopes, drops, doors, deep water and
// cell changes are all respected, indoors and out) and ends where it was aimed. Search
// is bounded (MaxNodes). The raw grid path is then shortened by string-pulling: from
// each kept point, the farthest later point the walker reaches in a straight line.
//
// Positions are in the start's landblock frame; a step into a neighbouring landblock
// is shifted back into that frame for the grid key, and every returned point carries
// its real cell and landblock-local position.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
namespace RynthCore.Geometry.Walking;
public readonly record struct PathPoint(uint Cell, Vector3 Position);
public sealed class LocalPlanner
{
public float Grid { get; init; } = 1.0f;
public int MaxNodes { get; init; } = 6000;
private readonly Walker _walker;
public LocalPlanner(Walker walker) => _walker = walker;
private sealed class Node
{
public required (int X, int Y) Key;
public required PathPoint At;
public Vector2 Frame; // position in the start landblock's frame
public float G;
public Node? Parent;
}
private static readonly (int X, int Y)[] Dirs = { (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1) };
/// <summary>
/// A walkable path from <paramref name="start"/> to within <paramref name="stop"/> of
/// <paramref name="goal"/> (goal's x/y in the start landblock's frame), or null.
/// The first point is the start; the last is where the path ends. With
/// <paramref name="bestEffort"/>, an unreachable goal gives the path to the reachable point
/// nearest it instead of null.
/// </summary>
public List<PathPoint>? Find(PathPoint start, Vector2 goal, float stop, bool bestEffort = false)
{
uint lb0 = start.Cell >> 16;
var origin = new Vector2(start.Position.X, start.Position.Y);
var startNode = new Node { Key = (0, 0), At = start, Frame = origin, G = 0 };
var best = new Dictionary<(int, int), Node> { [(0, 0)] = startNode };
var open = new PriorityQueue<Node, float>();
open.Enqueue(startNode, Vector2.Distance(origin, goal));
float reach = Math.Max(stop, Grid * 0.75f);
int expanded = 0;
Node? found = null, closest = startNode;
float closestD = Vector2.Distance(origin, goal);
while (open.TryDequeue(out Node? n, out _))
{
if (best[n.Key] != n) continue; // stale entry
float dn = Vector2.Distance(n.Frame, goal);
if (dn <= reach) { found = n; break; }
if (dn < closestD) { closestD = dn; closest = n; }
if (++expanded > MaxNodes) break;
foreach (var (dx, dy) in Dirs)
{
var key = (n.Key.X + dx, n.Key.Y + dy);
var target = origin + new Vector2(key.Item1, key.Item2) * Grid;
Vector2 step = target - n.Frame;
StepResult r = _walker.Step(n.At.Cell, n.At.Position, step.X, step.Y);
if (r.Blocked) continue;
Vector2 landed = InFrame(lb0, r.Cell, r.Position);
if (Vector2.Distance(landed, target) > 0.1f) continue; // slid somewhere else
float g = n.G + step.Length() + MathF.Abs(r.Position.Z - n.At.Position.Z) * 0.5f;
if (best.TryGetValue(key, out Node? old) && old.G <= g) continue;
var m = new Node { Key = key, At = new PathPoint(r.Cell, r.Position), Frame = landed, G = g, Parent = n };
best[key] = m;
open.Enqueue(m, g + Vector2.Distance(landed, goal));
}
}
if (found == null)
{
// Best effort: the reachable point nearest the goal, if it is clearly nearer than the start.
if (!bestEffort || closest == startNode || closestD > Vector2.Distance(origin, goal) - 0.5f) return null;
found = closest;
}
var raw = new List<PathPoint>();
for (Node? p = found; p != null; p = p.Parent) raw.Add(p.At);
raw.Reverse();
// The last bit, from the final grid point toward the goal itself, if it can be walked.
PathPoint last = raw[^1];
Vector2 lastFrame = InFrame(lb0, last.Cell, last.Position);
Vector2 toGoal = goal - lastFrame;
float left = toGoal.Length() - stop;
if (left > 0.05f)
{
Vector2 d = toGoal / toGoal.Length() * left;
StepResult r = _walker.Step(last.Cell, last.Position, d.X, d.Y);
if (!r.Blocked) raw.Add(new PathPoint(r.Cell, r.Position));
}
return Smooth(raw, lb0);
}
/// <summary>Keeps only the turning points: each kept point walks straight to the next.</summary>
private List<PathPoint> Smooth(List<PathPoint> raw, uint lb0)
{
var path = new List<PathPoint> { raw[0] };
int i = 0;
while (i < raw.Count - 1)
{
int j = raw.Count - 1;
for (; j > i + 1; j--)
if (StraightReaches(raw[i], raw[j], lb0)) break;
path.Add(raw[j]);
i = j;
}
return path;
}
private bool StraightReaches(PathPoint a, PathPoint b, uint lb0)
{
Vector2 fa = InFrame(lb0, a.Cell, a.Position), fb = InFrame(lb0, b.Cell, b.Position);
Vector2 d = fb - fa;
StepResult r = _walker.Step(a.Cell, a.Position, d.X, d.Y);
if (r.Blocked || r.Slid) return false;
return Vector2.Distance(InFrame(lb0, r.Cell, r.Position), fb) < 0.1f && MathF.Abs(r.Position.Z - b.Position.Z) < 0.3f
&& (EnvCell.IsIndoor(b.Cell) == EnvCell.IsIndoor(r.Cell));
}
/// <summary>A landblock-local position expressed in landblock lb0's frame (0xXXYY).</summary>
public static Vector2 InFrame(uint lb0, uint cell, Vector3 p)
{
uint lb = cell >> 16;
float ox = ((int)(lb >> 8) - (int)(lb0 >> 8)) * 192f, oy = ((int)(lb & 0xFF) - (int)(lb0 & 0xFF)) * 192f;
return new Vector2(p.X + ox, p.Y + oy);
}
}

View file

@ -0,0 +1,98 @@
// ============================================================================
// RynthCore.Geometry - Walking/Obstacles.cs
// IObstacles sources for the walker: the static outdoor world (OutdoorCollision:
// buildings, statics, building cells, scenery), objects placed at run time (closed
// doors and the like, given as placed models), and a composite of both.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Collision;
namespace RynthCore.Geometry.Walking;
/// <summary>The dats' outdoor world as walker obstacles.</summary>
public sealed class StaticObstacles : IObstacles
{
private readonly OutdoorCollision _world;
public StaticObstacles(OutdoorCollision world) => _world = world;
public IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> Near(uint landblock, float x, float y, float radius)
{
foreach (CollisionTri t in _world.Near(landblock, x, y, radius))
yield return (t.A, t.B, t.C, t.Normal);
}
public float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop)
=> _world.SurfaceBelow(landblock, x, y, zTop, maxDrop);
}
/// <summary>Several obstacle sources as one.</summary>
public sealed class CompositeObstacles : IObstacles
{
private readonly IObstacles[] _parts;
public CompositeObstacles(params IObstacles[] parts) => _parts = parts;
public IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> Near(uint landblock, float x, float y, float radius)
=> _parts.SelectMany(p => p.Near(landblock, x, y, radius));
public float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop)
{
float? best = null;
foreach (IObstacles p in _parts)
if (p.SurfaceBelow(landblock, x, y, zTop, maxDrop) is { } z && (best == null || z > best)) best = z;
return best;
}
}
/// <summary>
/// Triangles that come and go (closed doors, ...), keyed by the object they belong to, in
/// landblock-local coordinates of the landblock given when set. Thread-safe.
/// </summary>
public sealed class DynamicObstacles : IObstacles
{
private readonly object _gate = new();
private readonly Dictionary<uint, (uint Landblock, (Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)[] Tris)> _byObject = new();
public int Count { get { lock (_gate) return _byObject.Count; } }
public void Set(uint objectId, uint landblock, IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> tris)
{
var arr = tris.ToArray();
lock (_gate) _byObject[objectId] = ((landblock >> 16) == 0 ? landblock : landblock >> 16, arr);
}
public void Remove(uint objectId)
{
lock (_gate) _byObject.Remove(objectId);
}
public IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> Near(uint landblock, float x, float y, float radius)
{
uint lb = (landblock >> 16) == 0 ? landblock : landblock >> 16;
List<(Vector3, Vector3, Vector3, Vector3)> hits = new();
lock (_gate)
{
foreach (var (olb, tris) in _byObject.Values)
{
// Shift a neighbouring landblock's triangles into this frame.
float ox = ((int)(olb >> 8) - (int)(lb >> 8)) * 192f, oy = ((int)(olb & 0xFF) - (int)(lb & 0xFF)) * 192f;
if (MathF.Abs(ox) > 192 || MathF.Abs(oy) > 192) continue;
var off = new Vector3(ox, oy, 0);
foreach (var t in tris)
{
Vector3 a = t.A + off, b = t.B + off, c = t.C + off;
float minX = MathF.Min(a.X, MathF.Min(b.X, c.X)), maxX = MathF.Max(a.X, MathF.Max(b.X, c.X));
float minY = MathF.Min(a.Y, MathF.Min(b.Y, c.Y)), maxY = MathF.Max(a.Y, MathF.Max(b.Y, c.Y));
if (x < minX - radius || x > maxX + radius || y < minY - radius || y > maxY + radius) continue;
hits.Add((a, b, c, t.Normal));
}
}
}
return hits;
}
/// <summary>Dynamic objects are not stood on (doors are walls).</summary>
public float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop) => null;
}

View file

@ -0,0 +1,289 @@
// ============================================================================
// RynthCore.Geometry - Walking/Walker.cs
// Where a walking step lands: a kinematic walker over the dats. Not ACE's physics
// (no sphere sweep / BSP transitions); what a bot needs to move in ways the server and
// other players find sensible:
//
// - the body is the human Setup's two collision spheres (r 0.48 at 0.475 and 1.35 m);
// walls block a step that moves a sphere into them (moving away is always allowed);
// the lower test sits high enough (bottom at StepUp) that stairs and kerbs don't block;
// - a move is cut into sub-steps of at most SubStep metres, so StepUp (0.45 m) and the
// walkable slope (FloorZ) agree: a 0.4 m step on the steepest walkable ground rises
// ~0.45 m;
// - indoors: the cell follows the doorways crossed (IndoorWorld.TrackCell); leaving a
// cell's floor plan without a doorway is a wall; the feet height is where the body's
// sphere rests on the floor (StandZ), which is what ACE reports;
// - outdoors: the feet are on the terrain (less water depth) or on a walkable object
// surface (porches, platforms) within StepUp; terrain steeper than walkable can't be
// climbed; deep water (all four corners water) is not entered; crossing a building's
// outdoor doorway inward enters that EnvCell;
// - drops of more than MaxDrop are refused (a bot shouldn't walk off cliffs).
// When a step is blocked the walker tries sliding: the same step turned by 25, 50 and
// 75 degrees either way (shortened by the cosine).
//
// Coordinates: positions are landblock-local (x, y in 0..192 of the cell's landblock,
// z absolute). An outdoor step may leave the landblock; the result is re-expressed in
// the new landblock with the new cell id.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Terrain;
namespace RynthCore.Geometry.Walking;
/// <summary>Static and dynamic obstacles outdoors (buildings, statics, scenery, doors), landblock-local.</summary>
public interface IObstacles
{
/// <summary>Triangles within <paramref name="radius"/> of (x, y) on the ground plane, in <paramref name="landblock"/>'s frame.</summary>
IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> Near(uint landblock, float x, float y, float radius);
/// <summary>The highest walkable object surface under (x, y) between zTop - maxDrop and zTop, not terrain.</summary>
float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop);
}
public readonly record struct StepResult(uint Cell, Vector3 Position, bool Blocked, string? Why = null, bool Slid = false);
public sealed class Walker
{
public const float FloorZ = 0.66417414618662751f;
public float Radius { get; init; } = 0.48f;
/// <summary>Sphere centres above the feet used for wall tests.</summary>
public float LowSphere { get; init; } = 0.93f;
public float HighSphere { get; init; } = 1.35f;
public float StepUp { get; init; } = 0.45f;
public float MaxDrop { get; init; } = 2.5f;
public float SubStep { get; init; } = 0.4f;
private readonly TerrainSampler _terrain;
private readonly IndoorWorld _indoor;
private readonly IObstacles? _obstacles;
public Walker(TerrainSampler terrain, IndoorWorld indoor, IObstacles? obstacles = null)
{
_terrain = terrain;
_indoor = indoor;
_obstacles = obstacles;
}
/// <summary>Moves from <paramref name="pos"/> in <paramref name="cell"/> by (dx, dy) on the ground plane.</summary>
public StepResult Step(uint cell, Vector3 pos, float dx, float dy)
{
float len = MathF.Sqrt(dx * dx + dy * dy);
if (len < 1e-5f) return new StepResult(cell, pos, false);
int n = Math.Max(1, (int)MathF.Ceiling(len / SubStep));
float sx = dx / n, sy = dy / n;
bool slid = false;
for (int i = 0; i < n; i++)
{
StepResult r = SubStepWithSlide(cell, pos, sx, sy);
if (r.Blocked) return r with { Slid = slid || r.Slid };
slid |= r.Slid;
cell = r.Cell;
pos = r.Position;
}
return new StepResult(cell, pos, false, null, slid);
}
private static readonly float[] SlideAngles = { 25, -25, 50, -50, 75, -75 };
private StepResult SubStepWithSlide(uint cell, Vector3 pos, float dx, float dy)
{
StepResult r = TryMove(cell, pos, dx, dy);
if (!r.Blocked) return r;
foreach (float deg in SlideAngles)
{
float a = deg * MathF.PI / 180f, c = MathF.Cos(a), s = MathF.Sin(a);
float rx = (dx * c - dy * s) * c, ry = (dx * s + dy * c) * c;
StepResult t = TryMove(cell, pos, rx, ry);
if (!t.Blocked) return t with { Slid = true };
}
return r;
}
/// <summary>One straight sub-step, no sliding.</summary>
public StepResult TryMove(uint cell, Vector3 pos, float dx, float dy)
{
var to = new Vector3(pos.X + dx, pos.Y + dy, pos.Z);
return EnvCell.IsIndoor(cell) ? MoveIndoor(cell, pos, to) : MoveOutdoor(cell, pos, to);
}
// ── indoors ─────────────────────────────────────────────────────────────
private StepResult MoveIndoor(uint cell, Vector3 from, Vector3 to)
{
EnvCell? cur = _indoor.GetCell(cell);
if (cur == null) return Blocked(cell, from, "unknown cell");
uint next = _indoor.TrackCell(cell, from, to);
if (next == 0)
{
// Out through a doorway to the outdoors.
uint lb = cell >> 16;
float gz = OutdoorGround(lb, to.X, to.Y, from.Z, out string? why);
if (why != null) return Blocked(cell, from, why);
var outside = new Vector3(to.X, to.Y, gz);
if (BlockedByObstacles(lb, from, outside)) return Blocked(cell, from, "obstacle");
return Relocated(lb, outside);
}
if (next == cell && !cur.CoversXY(to.X, to.Y)) return Blocked(cell, from, "wall");
float? z = _indoor.StandZ(next, to.X, to.Y, Radius, from.Z);
if (z is not { } fz) return Blocked(cell, from, "no floor");
if (fz - from.Z > StepUp) return Blocked(cell, from, "step too high");
if (from.Z - fz > MaxDrop) return Blocked(cell, from, "drop");
var p = new Vector3(to.X, to.Y, fz);
if (BlockedIndoors(next, from, p)) return Blocked(cell, from, "wall");
return new StepResult(next, p, false);
}
private bool BlockedIndoors(uint cell, Vector3 from, Vector3 to)
{
foreach (uint c in CellAndNeighbours(cell))
{
foreach (Vector3[] wall in _indoor.Walls(c))
if (IntoPolygon(wall, from, to)) return true;
foreach (Vector3[] obj in _indoor.ObjectPolygons(c))
if (CellDat.Normal(obj).Z < FloorZ && IntoPolygon(obj, from, to)) return true;
}
return false;
}
private IEnumerable<uint> CellAndNeighbours(uint cell)
{
yield return cell;
foreach (uint n in _indoor.Neighbours(cell)) yield return n;
}
// ── outdoors ────────────────────────────────────────────────────────────
private StepResult MoveOutdoor(uint cell, Vector3 from, Vector3 to)
{
uint lb = cell >> 16;
// Into a building through one of its outdoor doorways?
foreach (EnvCell c in _indoor.LoadLandblock(lb))
{
if ((c.Flags & 1) == 0) continue; // only cells seen from outside have outdoor doorways
foreach (CellPortal p in c.Portals)
{
if (!p.LeadsOutdoors || p.Polygon.Length < 3) continue;
var lift = new Vector3(0, 0, IndoorWorld.PortalLift);
if (!Geo.SegmentCrossesToward(p.Polygon, from + lift, to + lift, !p.PortalSide)) continue;
// Just past the threshold the floor plan may not start yet: keep the height until it does.
float fz = _indoor.StandZ(c.Id, to.X, to.Y, Radius, from.Z) ?? from.Z;
if (fz - from.Z > StepUp) return Blocked(cell, from, "step too high");
var inside = new Vector3(to.X, to.Y, fz);
if (BlockedIndoors(c.Id, from, inside)) return Blocked(cell, from, "wall");
return new StepResult(c.Id, inside, false);
}
}
float gz = OutdoorGround(lb, to.X, to.Y, from.Z, out string? why);
if (why != null) return Blocked(cell, from, why);
var at = new Vector3(to.X, to.Y, gz);
if (BlockedByObstacles(lb, from, at)) return Blocked(cell, from, "obstacle");
return Relocated(lb, at);
}
/// <summary>Feet height outdoors at (x, y) in landblock lb's frame (x/y may be outside 0..192). why != null = not allowed.</summary>
private float OutdoorGround(uint lb, float x, float y, float fromZ, out string? why)
{
why = null;
(uint tlb, float lx, float ly) = Normalize(lb, x, y);
LandblockData? land = _terrain.LoadLandblock(tlb);
if (land == null) { why = "no terrain"; return fromZ; }
int cx = Math.Clamp((int)(lx / 24), 0, 7), cy = Math.Clamp((int)(ly / 24), 0, 7);
if (TerrainSampler.GetWaterType(land, cx, cy) == WaterType.EntirelyWater) { why = "deep water"; return fromZ; }
float terrainZ = TerrainSampler.GetTerrainZ(land, lx, ly) - TerrainSampler.GetWaterDepth(land, lx, ly);
float z = terrainZ;
if (_obstacles?.SurfaceBelow(tlb, lx, ly, fromZ + StepUp, MaxDrop + StepUp) is { } s && s > z) z = s;
if (z - fromZ > StepUp)
{
// Climbing: allowed on walkable terrain (sub-steps keep the rise per step small), not on objects.
bool onTerrain = z == terrainZ;
if (!onTerrain || !TerrainSampler.IsWalkable(TerrainSampler.GetNormal(land, lx, ly))) { why = onTerrain ? "too steep" : "step too high"; return fromZ; }
}
if (fromZ - z > MaxDrop) { why = "drop"; return fromZ; }
return z;
}
private bool BlockedByObstacles(uint lb, Vector3 from, Vector3 to)
{
if (_obstacles == null) return false;
foreach (var t in _obstacles.Near(lb, to.X, to.Y, Radius + 0.5f))
{
if (t.Normal.Z >= FloorZ) continue;
if (IntoPolygon(new[] { t.A, t.B, t.C }, from, to)) return true;
}
return false;
}
/// <summary>
/// Could the body stand at <paramref name="p"/> (landblock-local, in <paramref name="cell"/>)?
/// Indoors: the cell has a floor there. Outdoors: there is ground (not deep water, not too
/// far below or above p.Z) and no wall within the body's radius.
/// </summary>
public bool CanStand(uint cell, Vector3 p)
{
if (EnvCell.IsIndoor(cell))
return _indoor.StandZ(cell, p.X, p.Y, Radius, p.Z) is { } z && MathF.Abs(z - p.Z) < 2f;
uint lb = cell >> 16;
float gz = OutdoorGround(lb, p.X, p.Y, p.Z + 1f, out string? why);
if (why != null || MathF.Abs(gz - p.Z) > 2f) return false;
if (_obstacles == null) return true;
var at = new Vector3(p.X, p.Y, gz);
foreach (var t in _obstacles.Near(lb, p.X, p.Y, Radius + 0.5f))
{
if (t.Normal.Z >= FloorZ) continue;
var tri = new[] { t.A, t.B, t.C };
if (Geo.DistToPolygon(tri, at + new Vector3(0, 0, LowSphere)) < Radius * 0.8f
|| Geo.DistToPolygon(tri, at + new Vector3(0, 0, HighSphere)) < Radius * 0.8f) return false;
}
return true;
}
// ── shared ──────────────────────────────────────────────────────────────
/// <summary>Does moving the body from -> to push one of its spheres into the polygon?</summary>
private bool IntoPolygon(IReadOnlyList<Vector3> poly, Vector3 from, Vector3 to)
{
foreach (float h in new[] { LowSphere, HighSphere })
{
var b = new Vector3(to.X, to.Y, to.Z + h);
float after = Geo.DistToPolygon(poly, b);
if (after >= Radius) continue;
float before = Geo.DistToPolygon(poly, new Vector3(from.X, from.Y, from.Z + h));
if (after < before - 1e-4f) return true;
}
return false;
}
private static StepResult Blocked(uint cell, Vector3 at, string why) => new(cell, at, true, why);
/// <summary>An outdoor position given in landblock lb's frame (0xXXYY), re-expressed in the landblock that contains it.</summary>
private static StepResult Relocated(uint lb, Vector3 p)
{
(uint l, float x, float y) = Normalize(lb, p.X, p.Y);
return new StepResult(OutdoorCell(l, x, y), new Vector3(x, y, p.Z), false);
}
private static (uint lb, float x, float y) Normalize(uint lb, float x, float y)
{
int bx = (int)(lb >> 8) & 0xFF, by = (int)lb & 0xFF;
while (x < 0 && bx > 0) { x += 192; bx--; }
while (x >= 192 && bx < 254) { x -= 192; bx++; }
while (y < 0 && by > 0) { y += 192; by--; }
while (y >= 192 && by < 254) { y -= 192; by++; }
return ((uint)((bx << 8) | by), Math.Clamp(x, 0, 191.999f), Math.Clamp(y, 0, 191.999f));
}
/// <summary>The outdoor land cell (1..64) containing (x, y) of landblock lb (x/y may be outside 0..192).</summary>
public static uint OutdoorCell(uint lb, float x, float y)
{
(uint l, float lx, float ly) = Normalize(lb, x, y);
return (l << 16) | (uint)((int)(lx / 24) * 8 + (int)(ly / 24) + 1);
}
}