Snapshot for release 2026.10.31.1 (internal 69b244e)
This commit is contained in:
parent
8cb74c7685
commit
2546497f37
122 changed files with 22896 additions and 170 deletions
258
tools/GeometryTests/CellTests.cs
Normal file
258
tools/GeometryTests/CellTests.cs
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
// ============================================================================
|
||||
// GeometryTests - CellTests.cs
|
||||
// Indoor cells (RynthCore.Geometry.Cells) and models (RynthCore.Geometry.Models)
|
||||
// against the dats and the creature positions captured from ACE in dungeon
|
||||
// landblock 0x6146 (Vectors\dungeon-6146.txt).
|
||||
// ============================================================================
|
||||
|
||||
using System.Numerics;
|
||||
using RynthCore.Geometry.Cells;
|
||||
using RynthCore.Geometry.Dat;
|
||||
using RynthCore.Geometry.Models;
|
||||
|
||||
namespace GeometryTests;
|
||||
|
||||
internal static class CellTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("cells", Run, order: 20);
|
||||
|
||||
private const uint Dungeon = 0x6146;
|
||||
private const uint Town = 0xA9B4;
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
using var cellDat = new DatDatabase();
|
||||
using var portalDat = new DatDatabase();
|
||||
T.Check(cellDat.Open(Dats.Cell), "cell dat opens");
|
||||
T.Check(portalDat.Open(Dats.Portal), "portal dat opens");
|
||||
var world = new IndoorWorld(cellDat, portalDat);
|
||||
|
||||
LoadsLandblock(world);
|
||||
PortalSides(world);
|
||||
var vectors = Dats.Vectors("dungeon-6146.txt");
|
||||
FindsCells(world, vectors);
|
||||
TestSpot(world);
|
||||
TracksCells(world, vectors);
|
||||
TracksOutdoors(world);
|
||||
ReadsModels(world, cellDat);
|
||||
}
|
||||
|
||||
private static void LoadsLandblock(IndoorWorld world)
|
||||
{
|
||||
var cells = world.LoadLandblock(Dungeon);
|
||||
int bad = cells.Count(c => !c.GeometryOk);
|
||||
int portals = cells.Sum(c => c.Portals.Count), noPoly = cells.Sum(c => c.Portals.Count(p => p.Polygon.Length < 3));
|
||||
T.Info($"landblock {Dungeon:X4}: {cells.Count} EnvCells, {bad} without geometry, {cells.Sum(c => c.Floors.Count)} floors, " +
|
||||
$"{cells.Sum(c => c.Walls.Count)} walls, {portals} portals ({noPoly} without a polygon)");
|
||||
T.Check(cells.Count > 0, $"landblock {Dungeon:X4} has EnvCells");
|
||||
T.Check(bad == 0, $"{bad} cells of {Dungeon:X4} failed to parse geometry: " +
|
||||
string.Join(" ", cells.Where(c => !c.GeometryOk).Take(10).Select(c => c.Id.ToString("X8"))));
|
||||
T.Check(noPoly == 0, $"{noPoly} portals of {Dungeon:X4} have no doorway polygon");
|
||||
T.Check(ReferenceEquals(cells, world.LoadLandblock(Dungeon << 16 | 0x100)), "landblock cells are cached (same list by key or cell id)");
|
||||
T.Check(cells.All(c => EnvCell.IsIndoor(c.Id) && c.Landblock == Dungeon), "every cell id is an indoor cell of the landblock");
|
||||
}
|
||||
|
||||
// CellPortal.PortalSide says which side of the doorway polygon the cell behind it is on (TrackCell
|
||||
// relies on it). Check it against the cells' plans: just ahead of every wall doorway, on the side it
|
||||
// names, the neighbour covers the floor plan, and just behind it this cell does. And both cells of a
|
||||
// doorway must agree (one says front, the other back of the same polygon).
|
||||
private static void PortalSides(IndoorWorld world)
|
||||
{
|
||||
int tested = 0, ok = 0, pairs = 0, pairsOk = 0, shown = 0;
|
||||
foreach (var c in world.LoadLandblock(Dungeon))
|
||||
foreach (var p in c.Portals)
|
||||
{
|
||||
if (p.Polygon.Length < 3 || p.LeadsOutdoors) continue;
|
||||
var other = world.GetCell(c.Neighbour(p));
|
||||
if (other == null) continue;
|
||||
Vector3 n = CellDat.Normal(p.Polygon);
|
||||
// The neighbour's portal back to this cell: same polygon, so the opposite side.
|
||||
var back = other.Portals.FirstOrDefault(q => q.OtherCell == c.Short && q.Polygon.Length >= 3
|
||||
&& Vector3.Distance(q.Polygon.Aggregate(Vector3.Zero, (s, v) => s + v) / q.Polygon.Length,
|
||||
p.Polygon.Aggregate(Vector3.Zero, (s, v) => s + v) / p.Polygon.Length) < 0.05f);
|
||||
if (back != null)
|
||||
{
|
||||
pairs++;
|
||||
bool sameNormal = Vector3.Dot(CellDat.Normal(back.Polygon), n) > 0;
|
||||
if ((back.PortalSide == p.PortalSide) != sameNormal) pairsOk++;
|
||||
}
|
||||
if (MathF.Abs(n.Z) > 0.5f) continue;
|
||||
Vector3 centre = p.Polygon.Aggregate(Vector3.Zero, (s, v) => s + v) / p.Polygon.Length;
|
||||
Vector3 h = Vector3.Normalize(new Vector3(n.X, n.Y, 0)) * (p.PortalSide ? 0.25f : -0.25f);
|
||||
tested++;
|
||||
bool ahead = other.CoversXY(centre.X + h.X, centre.Y + h.Y, 0), behind = c.CoversXY(centre.X - h.X, centre.Y - h.Y, 0);
|
||||
if (ahead && behind) ok++;
|
||||
else if (shown++ < 5)
|
||||
T.Info($"portal {c.Id:X8} -> {other.Id:X8} flags {p.Flags:X}: neighbour covers ahead {ahead}, this cell behind {behind}");
|
||||
}
|
||||
T.Info($"PortalSide: {ok}/{tested} wall doorways have the neighbour ahead and this cell behind; {pairsOk}/{pairs} doorway pairs agree");
|
||||
T.Check(tested > 100 && ok >= tested * 0.98, $"PortalSide matches the cells' plans ({ok}/{tested})");
|
||||
T.Check(pairs > 100 && pairsOk == pairs, $"both cells of a doorway agree on its sides ({pairsOk}/{pairs})");
|
||||
}
|
||||
|
||||
private static void FindsCells(IndoorWorld world, List<(uint Cell, float X, float Y, float Z)> vectors)
|
||||
{
|
||||
// Creatures touch the floor with their lowest collision sphere: on a slope ACE's z (the feet) is
|
||||
// above the floor plane, so the floor plane matches z on flat floor and StandZ matches it everywhere.
|
||||
var human = world.Models.Get(ModelReader.HumanSetup);
|
||||
float radius = human.Spheres.Count > 0 ? human.Spheres.Min(s => s.Radius) : 0.48f;
|
||||
int cellOk = 0, findZOk = 0, floorOk = 0, standOk = 0, none = 0, flat = 0, flatOk = 0, shown = 0;
|
||||
float worstStand = 0;
|
||||
foreach (var v in vectors)
|
||||
{
|
||||
var found = world.FindCell(Dungeon, v.X, v.Y, v.Z);
|
||||
float? fz = world.FloorZ(v.Cell, v.X, v.Y, v.Z);
|
||||
float? sz = world.StandZ(v.Cell, v.X, v.Y, radius, v.Z);
|
||||
bool cOk = found?.cellId == v.Cell;
|
||||
bool zOk = fz != null && MathF.Abs(fz.Value - v.Z) <= 0.05f;
|
||||
bool sOk = sz != null && MathF.Abs(sz.Value - v.Z) <= 0.05f;
|
||||
if (cOk) cellOk++;
|
||||
if (found == null) none++;
|
||||
if (found != null && MathF.Abs(found.Value.floorZ - v.Z) <= 0.05f) findZOk++;
|
||||
if (zOk) floorOk++;
|
||||
if (sOk) standOk++;
|
||||
if (sz != null) worstStand = MathF.Max(worstStand, MathF.Abs(sz.Value - v.Z));
|
||||
var cell = world.GetCell(v.Cell);
|
||||
if (cell != null && cell.Floors.Where(f => Geo.InsideXY(f, v.X, v.Y, 0.6f)).All(f => CellDat.Normal(f).Z > 0.999f))
|
||||
{
|
||||
flat++;
|
||||
if (zOk) flatOk++;
|
||||
}
|
||||
if ((!cOk || !sOk) && shown++ < 15)
|
||||
T.Info($"mismatch {v.Cell:X8} ({v.X:F3},{v.Y:F3},{v.Z:F3}): FindCell " +
|
||||
(found == null ? "none" : $"{found.Value.cellId:X8} floor {found.Value.floorZ:F3}") +
|
||||
$", FloorZ(own cell) {(fz == null ? "none" : fz.Value.ToString("F3"))}, StandZ {(sz == null ? "none" : sz.Value.ToString("F3"))}");
|
||||
}
|
||||
int n = vectors.Count;
|
||||
double cellRate = (double)cellOk / n, floorRate = (double)floorOk / n, standRate = (double)standOk / n;
|
||||
double flatRate = flat == 0 ? 0 : (double)flatOk / flat;
|
||||
T.Info($"FindCell: {cellOk}/{n} cells match ({cellRate:P2}), {none} found nothing, {findZOk}/{n} with the floor plane within 0.05 m of z");
|
||||
T.Info($"FloorZ(own cell, floor plane): {floorOk}/{n} within 0.05 m ({floorRate:P2}); on flat floor (no slope within 0.6 m) {flatOk}/{flat} ({flatRate:P2})");
|
||||
T.Info($"StandZ(own cell, sphere r {radius:F2}): {standOk}/{n} within 0.05 m ({standRate:P2}), worst {worstStand:F3} m");
|
||||
T.Check(n > 1000, $"dungeon vectors loaded ({n})");
|
||||
T.Check(cellRate >= 0.95, $"FindCell matches the captured cell for >= 95% ({cellRate:P2})");
|
||||
T.Check(flatRate >= 0.95, $"FloorZ on flat floor within 0.05 m for >= 95% ({flatRate:P2})");
|
||||
T.Check(standRate >= 0.95, $"StandZ within 0.05 m for >= 95% ({standRate:P2})");
|
||||
}
|
||||
|
||||
private static void TestSpot(IndoorWorld world)
|
||||
{
|
||||
var found = world.FindCell(Dungeon, 91.617874f, -157.55351f, -11.9885f);
|
||||
T.Info($"the test character's spot (91.618,-157.554,-11.989): {(found == null ? "none" : $"{found.Value.cellId:X8} floor {found.Value.floorZ:F3}")}");
|
||||
T.Check(found?.cellId == 0x61460249, "the test character's spot is in cell 61460249");
|
||||
}
|
||||
|
||||
private static void TracksCells(IndoorWorld world, List<(uint Cell, float X, float Y, float Z)> vectors)
|
||||
{
|
||||
// Pairs of captured positions in portal-connected cells, a few metres apart: walking straight from
|
||||
// one to the other should end in the other's cell (unless the straight line goes through a wall).
|
||||
int pairs = 0, ok = 0, stayed = 0, wrong = 0, shown = 0;
|
||||
int same = 0, sameOk = 0;
|
||||
for (int i = 0; i < vectors.Count; i++)
|
||||
for (int j = 0; j < vectors.Count; j++)
|
||||
{
|
||||
if (i == j) continue;
|
||||
var p = vectors[i]; var q = vectors[j];
|
||||
var a = new Vector3(p.X, p.Y, p.Z); var b = new Vector3(q.X, q.Y, q.Z);
|
||||
float d = Vector3.Distance(a, b);
|
||||
if (d > 4f) continue;
|
||||
if (p.Cell == q.Cell)
|
||||
{
|
||||
if (same >= 2000 || d < 1f) continue;
|
||||
same++;
|
||||
uint s = world.TrackCell(p.Cell, a, b);
|
||||
if (s == p.Cell) sameOk++;
|
||||
else if (same - sameOk <= 5)
|
||||
T.Info($"track within {p.Cell:X8} ({p.X:F2},{p.Y:F2},{p.Z:F2}) -> ({q.X:F2},{q.Y:F2},{q.Z:F2}) ended in {s:X8}");
|
||||
continue;
|
||||
}
|
||||
if (!world.Neighbours(p.Cell).Contains(q.Cell)) continue;
|
||||
pairs++;
|
||||
uint got = world.TrackCell(p.Cell, a, b);
|
||||
if (got == q.Cell) ok++;
|
||||
else if (got == p.Cell)
|
||||
{
|
||||
stayed++;
|
||||
if (stayed <= 5)
|
||||
T.Info($"track {p.Cell:X8} ({p.X:F2},{p.Y:F2},{p.Z:F2}) -> {q.Cell:X8} ({q.X:F3},{q.Y:F3},{q.Z:F3}) stayed in the start cell");
|
||||
}
|
||||
else
|
||||
{
|
||||
wrong++;
|
||||
if (shown++ < 8)
|
||||
T.Info($"track {p.Cell:X8} ({p.X:F2},{p.Y:F2},{p.Z:F2}) -> {q.Cell:X8} ({q.X:F2},{q.Y:F2},{q.Z:F2}) ended in {got:X8}");
|
||||
}
|
||||
}
|
||||
double rate = pairs == 0 ? 0 : (double)ok / pairs;
|
||||
T.Info($"TrackCell, adjacent cells within 4 m: {ok}/{pairs} reach the other cell ({rate:P2}), {stayed} stayed in the start cell (blocked, or the end is on its side of the doorway), {wrong} in a third cell");
|
||||
T.Info($"TrackCell, same cell 1-4 m apart: {sameOk}/{same} stay in the cell");
|
||||
T.Check(pairs >= 50, $"enough adjacent-cell pairs ({pairs})");
|
||||
T.Check(rate >= 0.99, $"TrackCell reaches the neighbour cell for >= 99% of pairs ({rate:P2})");
|
||||
// Through a wall: from the middle of the junction cell 1F0 (floor -18, an octagon around (60,-160)
|
||||
// with doorways on its four straight sides) diagonally out through its south-east chamfer wall.
|
||||
uint walled = world.TrackCell(0x614601F0, new Vector3(60, -160, -18), new Vector3(66, -166, -18));
|
||||
T.Check(walled == 0x614601F0, $"TrackCell through a wall keeps the start cell (got {walled:X8})");
|
||||
T.Check(wrong == 0, $"TrackCell never ends in a third cell ({wrong})");
|
||||
T.Check(same > 0 && sameOk == same, $"TrackCell inside one cell stays there ({sameOk}/{same})");
|
||||
}
|
||||
|
||||
// Walk out of a town building through a doorway that leads outdoors: TrackCell gives 0.
|
||||
private static void TracksOutdoors(IndoorWorld world)
|
||||
{
|
||||
var cells = world.LoadLandblock(Town);
|
||||
int tried = 0, ok = 0;
|
||||
foreach (var c in cells)
|
||||
foreach (var p in c.Portals.Where(p => p.LeadsOutdoors && p.Polygon.Length >= 3))
|
||||
{
|
||||
Vector3 centre = p.Polygon.Aggregate(Vector3.Zero, (s, v) => s + v) / p.Polygon.Length;
|
||||
Vector3 n = CellDat.Normal(p.Polygon);
|
||||
if (MathF.Abs(n.Z) > 0.5f) continue; // a doorway in a wall
|
||||
float floor = p.Polygon.Min(v => v.Z);
|
||||
Vector3 h = Vector3.Normalize(new Vector3(n.X, n.Y, 0));
|
||||
// Inside is the side over the cell's floor.
|
||||
Vector3 inA = centre + h * 0.75f, inB = centre - h * 0.75f;
|
||||
bool aIn = IndoorWorld.CellFloorZ(c, inA.X, inA.Y) != null, bIn = IndoorWorld.CellFloorZ(c, inB.X, inB.Y) != null;
|
||||
if (aIn == bIn) continue;
|
||||
Vector3 from = aIn ? inA : inB, to = aIn ? inB : inA;
|
||||
from.Z = to.Z = floor;
|
||||
tried++;
|
||||
uint got = world.TrackCell(c.Id, from, to);
|
||||
if (got == 0) ok++;
|
||||
else if (tried - ok <= 5) T.Info($"walking out of {c.Id:X8} at ({centre.X:F2},{centre.Y:F2}) gave {got:X8}");
|
||||
}
|
||||
T.Info($"TrackCell out through outdoor doorways of {Town:X4}: {ok}/{tried} give 0 (outdoors)");
|
||||
T.Check(tried > 0 && ok == tried, $"walking out through an outdoor doorway gives 0 ({ok}/{tried})");
|
||||
}
|
||||
|
||||
private static void ReadsModels(IndoorWorld world, DatDatabase cellDat)
|
||||
{
|
||||
var human = world.Models.Get(ModelReader.HumanSetup);
|
||||
T.Info($"setup {ModelReader.HumanSetup:X8}: parsed {human.Parsed}, radius {human.Radius:F3}, height {human.Height:F3}, " +
|
||||
$"{human.Cylinders.Count} cylinders [{string.Join(", ", human.Cylinders.Select(c => $"r {c.Radius:F3} h {c.Height:F3}"))}], " +
|
||||
$"{human.Spheres.Count} spheres [{string.Join(", ", human.Spheres.Select(s => $"r {s.Radius:F3} at z {s.Center.Z:F3}"))}], {human.Polygons.Count} polygons");
|
||||
T.Check(human.Parsed, "human setup parses");
|
||||
T.Check(human.Spheres.Count + human.Cylinders.Count > 0, "human setup has collision spheres or cylinders");
|
||||
|
||||
var info = LandblockInfo.Load(cellDat, Town);
|
||||
T.Check(info != null && info.Complete, $"LandblockInfo {Town:X4}FFFE reads completely");
|
||||
if (info == null) return;
|
||||
T.Info($"LandblockInfo {info.Id:X8}: {info.NumCells} cells, {info.Objects.Count} objects, {info.Buildings.Count} buildings");
|
||||
int withPolys = 0;
|
||||
foreach (var b in info.Buildings.Take(8))
|
||||
{
|
||||
var shape = world.Models.Get(b.ModelId);
|
||||
if (shape.Polygons.Count > 0) withPolys++;
|
||||
var placed = shape.Place(b.Origin, b.Rotation).ToList();
|
||||
string span = placed.Count == 0 ? "" :
|
||||
$", z {placed.Min(p => p.Min(v => v.Z)):F1}..{placed.Max(p => p.Max(v => v.Z)):F1} at ({b.Origin.X:F1},{b.Origin.Y:F1})";
|
||||
T.Info($" building {b.ModelId:X8}: parsed {shape.Parsed}, {shape.Polygons.Count} physics polygons, " +
|
||||
$"portals to [{string.Join(" ", b.PortalCells.Select(c => c.ToString("X4")))}]{span}");
|
||||
}
|
||||
T.Check(info.Buildings.Count > 0 && withPolys > 0, "town buildings have physics polygons");
|
||||
// Building portals open into the landblock's own cells.
|
||||
var ids = world.LoadLandblock(Town).Select(c => c.Short).ToHashSet();
|
||||
int portalCells = info.Buildings.Sum(b => b.PortalCells.Count), known = info.Buildings.Sum(b => b.PortalCells.Count(ids.Contains));
|
||||
T.Check(portalCells > 0 && known == portalCells, $"building portals lead to cells of the landblock ({known}/{portalCells})");
|
||||
}
|
||||
}
|
||||
320
tools/GeometryTests/CollisionTests.cs
Normal file
320
tools/GeometryTests/CollisionTests.cs
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
// ============================================================================
|
||||
// GeometryTests - CollisionTests.cs
|
||||
// Collision/OutdoorCollision and Scenery/SceneryPlacer against the real dats
|
||||
// and the creature positions captured from ACE in five towns
|
||||
// (Vectors\outdoor-towns.txt): creatures standing on porches and platforms
|
||||
// must have a walkable object surface at their feet, creatures on the ground
|
||||
// must have none just above it, and nobody stands inside a wall.
|
||||
// ============================================================================
|
||||
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using RynthCore.Geometry.Cells;
|
||||
using RynthCore.Geometry.Collision;
|
||||
using RynthCore.Geometry.Dat;
|
||||
using RynthCore.Geometry.Models;
|
||||
using RynthCore.Geometry.Scenery;
|
||||
using RynthCore.Geometry.Terrain;
|
||||
|
||||
namespace GeometryTests;
|
||||
|
||||
internal static class CollisionTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("collision", Run, order: 30);
|
||||
|
||||
private const uint Holtburg = 0xA9B4;
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
using var cellDat = new DatDatabase();
|
||||
using var portalDat = new DatDatabase();
|
||||
T.Check(cellDat.Open(Dats.Cell), "cell dat opens");
|
||||
T.Check(portalDat.Open(Dats.Portal), "portal dat opens");
|
||||
using var terrain = new TerrainSampler(portalDat, cellDat);
|
||||
var models = new ModelReader(portalDat);
|
||||
var indoor = new IndoorWorld(cellDat, portalDat, models);
|
||||
var oc = new OutdoorCollision(cellDat, portalDat, terrain, models, indoor);
|
||||
|
||||
var outdoor = Dats.Vectors("outdoor-towns.txt").Where(v => (v.Cell & 0xFFFF) < 0x100).ToList();
|
||||
T.Check(outdoor.Count > 50, $"outdoor vectors loaded ({outdoor.Count})");
|
||||
|
||||
BuildsHoltburg(oc);
|
||||
BuildsInParallel(oc, outdoor);
|
||||
RaisedSurfaces(oc, terrain, outdoor);
|
||||
NotInsideSolids(oc, outdoor);
|
||||
Segments(oc, cellDat, outdoor);
|
||||
NeighbourEdges(oc, outdoor.Select(v => v.Cell >> 16).Distinct());
|
||||
SceneryRules(oc, terrain, cellDat, indoor, models);
|
||||
SetupTails(portalDat);
|
||||
}
|
||||
|
||||
private static void BuildsHoltburg(OutdoorCollision oc)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var c = oc.Counts(Holtburg);
|
||||
T.Info($"landblock {Holtburg:X4} built in {sw.ElapsedMilliseconds} ms: {c}");
|
||||
T.Info($"region scene tables: {oc.Scenery.Tables.SceneTypes.Count} scene types, {oc.Scenery.Tables.TerrainTypes.Count} terrain types" +
|
||||
(oc.Scenery.Tables.Scanned ? " (found by scanning)" : " (structured read)"));
|
||||
T.Check(oc.Scenery.Tables.Ready, "region scene tables read");
|
||||
T.Check(c.StaticObjects > 0 && c.StaticTris > 0, "Holtburg has static objects with collision");
|
||||
T.Check(c.Buildings > 0 && c.BuildingTris > 0, "Holtburg has building shells with collision");
|
||||
T.Check(c.BuildingCells > 0 && c.BuildingCellTris > 0, "Holtburg has building cells seen from outside");
|
||||
T.Check(c.Total == oc.Count(Holtburg), "Count equals the per-kind total");
|
||||
T.Check(ReferenceEquals(oc.Triangles(Holtburg), oc.Triangles(Holtburg << 16 | 0x0021)), "landblock is cached (same array by key or cell id)");
|
||||
|
||||
var tris = oc.Triangles(Holtburg);
|
||||
int badNormal = tris.Count(t => MathF.Abs(t.Normal.Length() - 1) > 1e-3f);
|
||||
int disagree = tris.Count(t =>
|
||||
{
|
||||
var n = Vector3.Cross(t.B - t.A, t.C - t.A);
|
||||
return n.LengthSquared() > 1e-8f && Vector3.Dot(Vector3.Normalize(n), t.Normal) < 0.99f;
|
||||
});
|
||||
T.Check(badNormal == 0, $"{badNormal} triangles without a unit normal");
|
||||
T.Check(disagree == 0, $"{disagree} triangles whose normal disagrees with their vertex order");
|
||||
T.Info($"{tris.Count(t => t.Walkable)} of {tris.Count} triangles are walkable");
|
||||
}
|
||||
|
||||
// Several landblocks built from parallel threads: each is built once and the results agree.
|
||||
private static void BuildsInParallel(OutdoorCollision oc, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
var lbs = outdoor.Select(v => v.Cell >> 16).Distinct().ToArray();
|
||||
var sw = Stopwatch.StartNew();
|
||||
var arrays = new IReadOnlyList<CollisionTri>[lbs.Length * 4];
|
||||
Parallel.For(0, arrays.Length, i => arrays[i] = oc.Triangles(lbs[i % lbs.Length]));
|
||||
bool same = true;
|
||||
for (int i = lbs.Length; i < arrays.Length; i++) same &= ReferenceEquals(arrays[i], arrays[i % lbs.Length]);
|
||||
T.Check(same, "parallel callers get the same cached triangles");
|
||||
T.Info($"{lbs.Length} landblocks built in parallel in {sw.ElapsedMilliseconds} ms: " +
|
||||
string.Join(", ", lbs.Select(lb => $"{lb:X4} {oc.Count(lb)}")));
|
||||
|
||||
// How far a landblock's triangles reach past its edge (queries look MaxOverhang into neighbours).
|
||||
float over = 0; uint worst = 0;
|
||||
foreach (uint lb in lbs)
|
||||
foreach (var t in oc.Triangles(lb))
|
||||
{
|
||||
float o = MathF.Max(MathF.Max(-t.MinX, t.MaxX - 192), MathF.Max(-t.MinY, t.MaxY - 192));
|
||||
if (o > over) { over = o; worst = t.Source; }
|
||||
}
|
||||
T.Info($"largest overhang past a landblock edge: {over:F1} m (source {worst:X8})");
|
||||
T.Check(over <= OutdoorCollision.MaxOverhang, $"overhang {over:F1} m is within MaxOverhang");
|
||||
}
|
||||
|
||||
// Creatures above the terrain stand on an object's walkable surface; creatures on the terrain have no
|
||||
// walkable surface just above the ground (a phantom floor would lift the walker).
|
||||
private static void RaisedSurfaces(OutdoorCollision oc, TerrainSampler terrain, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
int raised = 0, found = 0, ground = 0, phantom = 0, water = 0;
|
||||
foreach (var (cell, x, y, z) in outdoor)
|
||||
{
|
||||
uint lb = cell >> 16;
|
||||
float standZ = terrain.GetStandingZ(lb, x, y), meshZ = terrain.GetTerrainZ(lb, x, y);
|
||||
if (z - standZ > 0.1f && z - meshZ <= 0.1f)
|
||||
{
|
||||
// in water: above the standing Z (mesh less water depth) but not above the terrain mesh
|
||||
water++;
|
||||
T.Info($"in water {cell:X8} ({x:F2}, {y:F2}, {z:F3}): terrain mesh {meshZ:F3}, standing {standZ:F3} (not an object surface)");
|
||||
}
|
||||
if (z - standZ > 0.1f && z - meshZ > 0.1f)
|
||||
{
|
||||
raised++;
|
||||
float? s = oc.SurfaceBelow(lb, x, y, z + 0.5f, 3f);
|
||||
if (s != null && MathF.Abs(s.Value - z) <= 0.15f) found++;
|
||||
else
|
||||
{
|
||||
var near = oc.Near(lb, x, y, 1f);
|
||||
T.Info($"raised miss {cell:X8} ({x:F2}, {y:F2}, {z:F3}) terrain {standZ:F3}: surface {(s == null ? "none" : s.Value.ToString("F3"))}; " +
|
||||
$"{near.Count} tris within 1 m ({near.Count(t => t.Walkable)} walkable" +
|
||||
(near.Count > 0 ? ", sources " + string.Join(" ", near.Select(t => t.Source.ToString("X8")).Distinct().Take(6)) : "") + ")");
|
||||
}
|
||||
}
|
||||
else if (z - standZ <= 0.1f)
|
||||
{
|
||||
ground++;
|
||||
float top = z + 0.3f, lo = standZ + 0.1f;
|
||||
float? s = top > lo ? oc.SurfaceBelow(lb, x, y, top, top - lo) : null;
|
||||
if (s != null)
|
||||
{
|
||||
phantom++;
|
||||
T.Info($"phantom floor {cell:X8} ({x:F2}, {y:F2}, {z:F3}) terrain {standZ:F3}: surface {s.Value:F3}");
|
||||
}
|
||||
}
|
||||
}
|
||||
float rate = raised == 0 ? 1 : found / (float)raised;
|
||||
T.Info($"raised vectors: {found}/{raised} have a walkable surface within 0.15 m of their z ({rate:P0}); " +
|
||||
$"ground vectors: {phantom}/{ground} have a walkable surface 0.1..0.3 m above the ground; {water} in water");
|
||||
// Known misses (2026-10-28): two creatures in C6A9 at (89.47, 45.20) and (89.39, 52.51) stand 0.22 and
|
||||
// 0.26 m above the top of a crate (static Setup 0x02000275, a 0.88 x 0.88 x 1 m physics box, top
|
||||
// 43.025) with nothing else under them: most likely spawn positions that never settled.
|
||||
T.Check(raised >= 15, $"enough raised vectors ({raised})");
|
||||
T.Check(rate >= 0.9f, $"raised vectors find their surface ({found}/{raised})");
|
||||
T.Check(phantom <= ground / 20, $"few phantom floors ({phantom}/{ground})");
|
||||
}
|
||||
|
||||
// A body (radius 0.3 m, from 0.5 to 1.5 m above the feet) at a captured position touches no wall.
|
||||
private static void NotInsideSolids(OutdoorCollision oc, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
int touching = 0, within10 = 0, within20 = 0;
|
||||
foreach (var (cell, x, y, z) in outdoor)
|
||||
{
|
||||
uint lb = cell >> 16;
|
||||
float best = float.MaxValue;
|
||||
CollisionTri hit = default;
|
||||
foreach (var t in oc.Near(lb, x, y, 0.3f))
|
||||
{
|
||||
if (t.Walkable || t.MaxZ < z + 0.5f - 0.3f || t.MinZ > z + 1.5f + 0.3f) continue;
|
||||
var poly = new[] { t.A, t.B, t.C };
|
||||
for (float h = 0.5f; h <= 1.501f; h += 0.1f)
|
||||
{
|
||||
float d = Geo.DistToPolygon(poly, new Vector3(x, y, z + h));
|
||||
if (d < best) { best = d; hit = t; }
|
||||
}
|
||||
}
|
||||
if (best >= 0.3f) continue;
|
||||
touching++;
|
||||
if (best < 0.1f) within10++;
|
||||
if (best < 0.2f) within20++;
|
||||
T.Info($"near a wall {cell:X8} ({x:F2}, {y:F2}, {z:F3}): {best:F2} m from source {hit.Source:X8}, " +
|
||||
$"normal ({hit.Normal.X:F2}, {hit.Normal.Y:F2}, {hit.Normal.Z:F2}), z {hit.MinZ:F2}..{hit.MaxZ:F2}");
|
||||
}
|
||||
T.Info($"{outdoor.Count - touching}/{outdoor.Count} vectors are clear of walls (0.3 m body, 0.5..1.5 m up); " +
|
||||
$"{touching} within 0.3 m, {within20} within 0.2 m, {within10} within 0.1 m");
|
||||
T.Check(touching <= outdoor.Count / 20, $"few vectors within 0.3 m of a wall ({touching}/{outdoor.Count})");
|
||||
T.Check(within10 == 0, $"no vector within 0.1 m of a wall ({within10})");
|
||||
}
|
||||
|
||||
// A horizontal segment from a creature through the middle of a nearby building hits it; a short one in
|
||||
// open ground hits nothing.
|
||||
private static void Segments(OutdoorCollision oc, DatDatabase cellDat, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
var info = LandblockInfo.Load(cellDat, Holtburg)!;
|
||||
var here = outdoor.Where(v => v.Cell >> 16 == Holtburg).ToList();
|
||||
int tried = 0, hits = 0;
|
||||
foreach (var b in info.Buildings)
|
||||
{
|
||||
var v = here.Select(p => (p, d: Vector2.Distance(new(p.X, p.Y), new(b.Origin.X, b.Origin.Y))))
|
||||
.Where(q => q.d > 4 && q.d < 40).OrderBy(q => q.d).Select(q => q.p).FirstOrDefault();
|
||||
if (v.Cell == 0) continue;
|
||||
float z = MathF.Max(v.Z, b.Origin.Z) + 1f;
|
||||
var a = new Vector3(v.X, v.Y, z);
|
||||
var c = new Vector3(b.Origin.X, b.Origin.Y, z);
|
||||
var end = c + Vector3.Normalize(c - a) * 6f;
|
||||
tried++;
|
||||
if (oc.SegmentHit(Holtburg, a, end, out float t, out var tri))
|
||||
{
|
||||
hits++;
|
||||
var p = Vector3.Lerp(a, end, t);
|
||||
float dist = Geo.DistToPolygon(new[] { tri.A, tri.B, tri.C }, p);
|
||||
T.Check(dist < 0.01f, $"segment hit point lies on the triangle it names ({dist:F4} m)");
|
||||
}
|
||||
else T.Info($"segment to building {b.ModelId:X8} at ({b.Origin.X:F1}, {b.Origin.Y:F1}) from ({v.X:F1}, {v.Y:F1}) hits nothing");
|
||||
}
|
||||
T.Info($"segments into Holtburg buildings: {hits}/{tried} hit");
|
||||
T.Check(tried >= 3, $"enough buildings near a vector ({tried})");
|
||||
T.Check(hits >= tried - 1, $"segments into buildings hit ({hits}/{tried})");
|
||||
|
||||
// open ground: a vector with nothing within 3 m
|
||||
int open = 0, openHits = 0;
|
||||
foreach (var (cell, x, y, z) in outdoor)
|
||||
{
|
||||
uint lb = cell >> 16;
|
||||
if (oc.Near(lb, x, y, 3f).Count > 0) continue;
|
||||
open++;
|
||||
if (oc.SegmentHit(lb, new Vector3(x - 1, y, z + 1), new Vector3(x + 1, y + 0.5f, z + 1), out _, out _)) openHits++;
|
||||
}
|
||||
T.Info($"{open} vectors in open ground (nothing within 3 m)");
|
||||
T.Check(open > 0, "some vectors stand in open ground");
|
||||
T.Check(openHits == 0, $"short segments in open ground hit nothing ({openHits}/{open})");
|
||||
T.Check(!oc.SegmentHit(Holtburg, new Vector3(96, 96, 2000), new Vector3(97, 97, 2000), out _, out _), "a segment high in the air hits nothing");
|
||||
}
|
||||
|
||||
// Triangles near a landblock edge come from the neighbour too, shifted into the queried frame.
|
||||
private static void NeighbourEdges(OutdoorCollision oc, IEnumerable<uint> landblocks)
|
||||
{
|
||||
// a triangle within 6 m of a landblock edge, seen from the landblock across that edge
|
||||
int tried = 0, seen = 0;
|
||||
foreach (uint lb in landblocks)
|
||||
foreach (var (dx, dy) in new[] { (0, -1), (0, 1), (-1, 0), (1, 0) })
|
||||
{
|
||||
var t = oc.Triangles(lb).FirstOrDefault(q =>
|
||||
dy == -1 ? q.MaxY < 6 : dy == 1 ? q.MinY > 186 : dx == -1 ? q.MaxX < 6 : q.MinX > 186);
|
||||
if (t == default) continue;
|
||||
uint other = (uint)((int)(lb >> 8) + dx) << 8 | (uint)((int)(lb & 0xFF) + dy);
|
||||
var shift = new Vector3(-dx * 192f, -dy * 192f, 0); // lb's frame -> other's frame
|
||||
float cx = (t.A.X + t.B.X + t.C.X) / 3 + shift.X, cy = (t.A.Y + t.B.Y + t.C.Y) / 3 + shift.Y;
|
||||
tried++;
|
||||
if (oc.Near(other, cx, cy, 0.5f).Any(q => q.Source == t.Source && Vector3.Distance(q.A, t.A + shift) < 1e-3f)) seen++;
|
||||
else T.Info($"triangle of {lb:X4} at ({cx - shift.X:F1}, {cy - shift.Y:F1}) not seen from {other:X4}");
|
||||
}
|
||||
T.Info($"edge triangles seen from the neighbouring landblock: {seen}/{tried}");
|
||||
T.Check(tried >= 4 && seen == tried, $"edge triangles are seen from across the edge, shifted ({seen}/{tried})");
|
||||
T.Check(oc.Near(Holtburg, 96, 96, 2f).All(q => q.MinX > -1 && q.MaxX < 193 && q.MinY > -1 && q.MaxY < 193),
|
||||
"a query in the middle of a landblock sees no neighbour triangles");
|
||||
}
|
||||
|
||||
// Scenery: some per landblock, none on a road or inside a building's footprint (under a building shell
|
||||
// polygon, or on the floor of a building cell at about the scenery's height; buildings' cellars run
|
||||
// under the ground and trees above them are fine).
|
||||
private static void SceneryRules(OutdoorCollision oc, TerrainSampler terrain, DatDatabase cellDat, IndoorWorld indoor, ModelReader models)
|
||||
{
|
||||
uint[] lbs = { 0xA9B4, 0xA9B3, 0xC6A9, 0xDA55, 0x7D64, 0xC98C, 0xA9B6, 0x8A8A, 0x5C9E };
|
||||
int total = 0, onRoad = 0, inBuilding = 0;
|
||||
var counts = new List<string>();
|
||||
foreach (uint lb in lbs)
|
||||
{
|
||||
var sc = oc.SceneryOf(lb);
|
||||
total += sc.Count;
|
||||
counts.Add($"{lb:X4} {sc.Count} ({oc.Counts(lb).SceneryTris} tris)");
|
||||
var footprints = new List<Vector3[]>();
|
||||
var info = LandblockInfo.Load(cellDat, lb);
|
||||
if (info != null)
|
||||
foreach (var b in info.Buildings) footprints.AddRange(models.Get(b.ModelId).Place(b.Origin, b.Rotation));
|
||||
foreach (var c in indoor.LoadLandblock(lb))
|
||||
if ((c.Flags & 1) != 0) footprints.AddRange(c.Floors);
|
||||
foreach (var o in sc)
|
||||
{
|
||||
if (terrain.OnRoad(lb, o.Position.X, o.Position.Y)) { onRoad++; T.Info($"scenery {o.ModelId:X8} on a road in {lb:X4} at ({o.Position.X:F1}, {o.Position.Y:F1})"); }
|
||||
if (footprints.Any(f => Geo.AreaXY(f) > 0.01f && Geo.InsideXY(f, o.Position.X, o.Position.Y, 0)
|
||||
&& MathF.Abs(Geo.PlaneZ(f, o.Position.X, o.Position.Y) - o.Position.Z) < 3f))
|
||||
{
|
||||
inBuilding++;
|
||||
T.Info($"scenery {o.ModelId:X8} inside a building footprint in {lb:X4} at ({o.Position.X:F1}, {o.Position.Y:F1})");
|
||||
}
|
||||
T.Check(o.Position.X >= 0 && o.Position.X < 192 && o.Position.Y >= 0 && o.Position.Y < 192, "scenery inside its landblock");
|
||||
}
|
||||
}
|
||||
T.Info($"scenery: {string.Join(", ", counts)}");
|
||||
T.Check(total > 50, $"scenery is placed ({total} objects in {lbs.Length} landblocks)");
|
||||
T.Check(onRoad == 0, $"{onRoad} scenery objects on a road");
|
||||
T.Check(inBuilding == 0, $"{inBuilding} scenery objects inside a building footprint");
|
||||
T.Info($"Setups whose cylinders/spheres were read from the end of their record (animation hooks): {oc.TailReads} placements");
|
||||
}
|
||||
// SetupBounds reads a Setup's cylinders, spheres and sorting sphere from the end of the record when its
|
||||
// placement frames have animation hooks. Check that tail reading against the front-to-back read on every
|
||||
// Setup without hooks, and count how many with hooks it reads.
|
||||
private static void SetupTails(DatDatabase portalDat)
|
||||
{
|
||||
int plain = 0, agree = 0, hooked = 0, hookedRead = 0, broken = 0;
|
||||
var disagree = new List<uint>();
|
||||
foreach (var e in portalDat.EnumerateEntries())
|
||||
{
|
||||
if ((e.ObjectId >> 24) != 0x02) continue;
|
||||
byte[]? data = portalDat.GetFileData(e.ObjectId);
|
||||
if (data == null) continue;
|
||||
SetupBounds? fwd;
|
||||
try { fwd = SetupBounds.Parse(data, fromEnd: false); }
|
||||
catch (Exception) { broken++; continue; }
|
||||
var tail = SetupBounds.Parse(data, fromEnd: true);
|
||||
if (fwd == null) { hooked++; if (tail != null) hookedRead++; continue; }
|
||||
plain++;
|
||||
bool same = tail != null && tail.Cylinders.SequenceEqual(fwd.Cylinders) && tail.Spheres.SequenceEqual(fwd.Spheres)
|
||||
&& tail.Height == fwd.Height && tail.Radius == fwd.Radius && tail.SortCenter == fwd.SortCenter && tail.SortRadius == fwd.SortRadius;
|
||||
if (same) agree++; else if (disagree.Count < 10) disagree.Add(e.ObjectId);
|
||||
}
|
||||
T.Info($"Setups: {plain} without hooks ({agree} read the same from the end), {hooked} with hooks ({hookedRead} read from the end), {broken} unreadable" +
|
||||
(disagree.Count > 0 ? "; disagree: " + string.Join(" ", disagree.Select(i => i.ToString("X8"))) : ""));
|
||||
T.Check(plain > 1000, $"many Setups in the portal dat ({plain})");
|
||||
T.Check(agree >= plain * 0.99, $"reading from the end agrees with the front-to-back read ({agree}/{plain})");
|
||||
T.Check(hookedRead >= hooked * 0.95, $"Setups with animation hooks read from the end ({hookedRead}/{hooked})");
|
||||
}
|
||||
}
|
||||
29
tools/GeometryTests/GeometryTests.csproj
Normal file
29
tools/GeometryTests/GeometryTests.csproj
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Checks RynthCore.Geometry against the real dats (C:\Turbine\Asheron's Call, read-only) and
|
||||
against ground truth captured from the local ACE server (Vectors\: positions of creatures
|
||||
standing on terrain in five towns, and on dungeon floors in landblock 0x6146).
|
||||
Without the dats it prints SKIP and exits 0.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>GeometryTests</RootNamespace>
|
||||
<AssemblyName>GeometryTests</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="Vectors\**" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\RynthCore.Geometry\RynthCore.Geometry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
95
tools/GeometryTests/Program.cs
Normal file
95
tools/GeometryTests/Program.cs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
// ============================================================================
|
||||
// GeometryTests - RynthCore.Geometry against the real dats and captured ACE ground truth.
|
||||
// Each area has its own file (TerrainTests.cs, CellTests.cs, ...) with a Run() that uses T.
|
||||
// ============================================================================
|
||||
|
||||
namespace GeometryTests;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static int Main()
|
||||
{
|
||||
string? ac = Dats.Folder;
|
||||
if (ac == null)
|
||||
{
|
||||
Console.WriteLine("SKIP: no AC dats (client_portal.dat / client_cell_1.dat) found.");
|
||||
return 0;
|
||||
}
|
||||
Console.WriteLine($"dats: {ac}");
|
||||
|
||||
foreach (var (name, run) in Suites.All)
|
||||
{
|
||||
T.Case(name);
|
||||
try { run(); }
|
||||
catch (Exception ex) { T.Check(false, $"threw {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"{T.Checks - T.Failed}/{T.Checks} checks passed.");
|
||||
Console.WriteLine(T.Failed == 0 ? "ALL GEOMETRY TESTS PASSED." : $"{T.Failed} FAILED.");
|
||||
return T.Failed == 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The suites. Each area's file registers itself from a module initializer:
|
||||
/// [System.Runtime.CompilerServices.ModuleInitializer]
|
||||
/// internal static void Register() => Suites.Add("terrain", Run, order: 10);
|
||||
/// </summary>
|
||||
internal static class Suites
|
||||
{
|
||||
private static readonly List<(int Order, string Name, Action Run)> _all = new();
|
||||
public static void Add(string name, Action run, int order) => _all.Add((order, name, run));
|
||||
public static IEnumerable<(string Name, Action Run)> All => _all.OrderBy(s => s.Order).Select(s => (s.Name, s.Run));
|
||||
}
|
||||
|
||||
internal static class Dats
|
||||
{
|
||||
public static string? Folder { get; } = Find();
|
||||
|
||||
private static string? Find()
|
||||
{
|
||||
foreach (string dir in new[] { Environment.GetEnvironmentVariable("AC_DAT_DIR") ?? "", @"C:\Turbine\Asheron's Call" })
|
||||
if (dir.Length > 0 && File.Exists(Path.Combine(dir, "client_portal.dat")) && File.Exists(Path.Combine(dir, "client_cell_1.dat")))
|
||||
return dir;
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string Portal => Path.Combine(Folder!, "client_portal.dat");
|
||||
public static string Cell => Path.Combine(Folder!, "client_cell_1.dat");
|
||||
|
||||
/// <summary>Ground-truth positions: "cell x y z" lines.</summary>
|
||||
public static List<(uint Cell, float X, float Y, float Z)> Vectors(string file)
|
||||
{
|
||||
var list = new List<(uint, float, float, float)>();
|
||||
foreach (string line in File.ReadLines(Path.Combine(AppContext.BaseDirectory, "Vectors", file)))
|
||||
{
|
||||
if (line.StartsWith('#') || line.Trim().Length == 0) continue;
|
||||
string[] f = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
list.Add((Convert.ToUInt32(f[0], 16), float.Parse(f[1]), float.Parse(f[2]), float.Parse(f[3])));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class T
|
||||
{
|
||||
public static int Checks, Failed;
|
||||
private static string _case = "";
|
||||
|
||||
public static void Case(string name)
|
||||
{
|
||||
_case = name;
|
||||
Console.WriteLine($"-- {name}");
|
||||
}
|
||||
|
||||
public static void Check(bool ok, string what)
|
||||
{
|
||||
Checks++;
|
||||
if (ok) return;
|
||||
Failed++;
|
||||
Console.WriteLine($" FAIL [{_case}] {what}");
|
||||
}
|
||||
|
||||
public static void Info(string s) => Console.WriteLine($" info: {s}");
|
||||
}
|
||||
322
tools/GeometryTests/TerrainTests.cs
Normal file
322
tools/GeometryTests/TerrainTests.cs
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
// ============================================================================
|
||||
// GeometryTests - TerrainTests.cs
|
||||
// Terrain/TerrainSampler and Terrain/LandblockData against the real dats and
|
||||
// the outdoor ground truth in Vectors\outdoor-towns.txt (creatures standing in
|
||||
// five towns, positions from the local ACE server).
|
||||
// ============================================================================
|
||||
|
||||
using System.Numerics;
|
||||
using RynthCore.Geometry.Dat;
|
||||
using RynthCore.Geometry.Terrain;
|
||||
|
||||
namespace GeometryTests;
|
||||
|
||||
internal static class TerrainTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("terrain", Run, order: 10);
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
using var portal = new DatDatabase();
|
||||
using var cell = new DatDatabase();
|
||||
T.Check(portal.Open(Dats.Portal), "portal dat opens");
|
||||
T.Check(cell.Open(Dats.Cell), "cell dat opens");
|
||||
using var ts = new TerrainSampler(portal, cell);
|
||||
|
||||
var outdoor = Dats.Vectors("outdoor-towns.txt").Where(v => (v.Cell & 0xFFFF) < 0x100).ToList();
|
||||
T.Check(outdoor.Count > 50, $"outdoor vectors loaded ({outdoor.Count})");
|
||||
|
||||
HeightTableAndLandblocks(ts, outdoor);
|
||||
TerrainZ(ts, outdoor);
|
||||
SplitPolarity(ts, outdoor);
|
||||
Normals(ts, outdoor);
|
||||
RaycastDown(ts, outdoor);
|
||||
RaycastOblique(ts, outdoor);
|
||||
Roads(ts, outdoor);
|
||||
OpenFromFolder();
|
||||
}
|
||||
|
||||
private static void HeightTableAndLandblocks(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
var table = ts.LandHeightTable;
|
||||
bool monotonic = true;
|
||||
for (int i = 1; i < table.Count; i++) if (table[i] < table[i - 1]) monotonic = false;
|
||||
T.Check(table.Count == 256 && monotonic, "land-height table: 256 entries, non-decreasing");
|
||||
T.Check(table[0] >= 0f && table[0] < 10f && table[255] > 500f && table[255] < 5000f,
|
||||
$"land-height table range plausible ({table[0]} .. {table[255]})");
|
||||
T.Info($"land-height table {table[0]} .. {table[255]}, [64]={table[64]} [128]={table[128]}");
|
||||
|
||||
var keys = outdoor.Select(v => v.Cell >> 16).Distinct().ToList();
|
||||
foreach (uint key in keys)
|
||||
{
|
||||
var lb = ts.LoadLandblock(key);
|
||||
T.Check(lb != null, $"landblock {key:X4} loads");
|
||||
if (lb == null) continue;
|
||||
lb.GetHeightRange(out float min, out float max);
|
||||
T.Check(lb.LandblockKey == key && min >= table[0] && max <= table[255] && max - min < 400f,
|
||||
$"landblock {key:X4} heights plausible ({min:F1} .. {max:F1})");
|
||||
T.Check(lb.HasObjects, $"town landblock {key:X4} has objects");
|
||||
T.Check(ReferenceEquals(lb, ts.LoadLandblock(key)), $"landblock {key:X4} is cached");
|
||||
}
|
||||
T.Info($"town landblocks: {string.Join(" ", keys.Select(k => k.ToString("X4")))}");
|
||||
|
||||
// Cell-id form and key form name the same landblock.
|
||||
uint k0 = keys[0];
|
||||
T.Check(ReferenceEquals(ts.LoadLandblock(k0), ts.LoadLandblock((k0 << 16) | 0x0019)), "0xXXYY and 0xXXYYnnnn give the same landblock");
|
||||
|
||||
// Neighbouring landblocks share their edge vertices (checks the ix*9+iy indexing).
|
||||
int shared = 0, sharedMatch = 0;
|
||||
foreach (uint key in keys)
|
||||
{
|
||||
var a = ts.LoadLandblock(key);
|
||||
var east = ts.LoadLandblock(key + 0x0100);
|
||||
var north = ts.LoadLandblock(key + 0x0001);
|
||||
for (int i = 0; i <= 8; i++)
|
||||
{
|
||||
if (a != null && east != null) { shared++; if (a.HeightsZ[8, i] == east.HeightsZ[0, i]) sharedMatch++; }
|
||||
if (a != null && north != null) { shared++; if (a.HeightsZ[i, 8] == north.HeightsZ[i, 0]) sharedMatch++; }
|
||||
}
|
||||
}
|
||||
T.Check(shared > 0 && sharedMatch == shared, $"landblock edges match their neighbours ({sharedMatch}/{shared})");
|
||||
|
||||
// 0xFFFF is not a landblock: everything answers "no terrain" rather than throwing.
|
||||
T.Check(ts.LoadLandblock(0xFFFF) == null && float.IsNaN(ts.GetTerrainZ(0xFFFF, 10, 10))
|
||||
&& ts.GetNormal(0xFFFF, 10, 10) == Vector3.Zero && !ts.OnRoad(0xFFFF, 10, 10) && ts.TerrainType(0xFFFF, 10, 10) == -1,
|
||||
"landblock 0xFFFF: null / NaN / zero / false / -1");
|
||||
}
|
||||
|
||||
private static void TerrainZ(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
// Ground truth vs GetStandingZ (terrain mesh less the cell's water depth) and vs the bare mesh.
|
||||
// Creatures can also stand on porches, platforms and ramps; those come out above the ground
|
||||
// and can't be checked without the object geometry. Nothing may come out below it.
|
||||
var rows = new List<(float D, float DMesh, float Wd, bool Flat, uint Cell, float X, float Y, float Z, float Gz)>();
|
||||
foreach (var v in outdoor)
|
||||
{
|
||||
var lb = ts.LoadLandblock(v.Cell)!;
|
||||
float mesh = ts.GetTerrainZ(v.Cell, v.X, v.Y);
|
||||
float gz = ts.GetStandingZ(v.Cell, v.X, v.Y);
|
||||
int cx = Math.Min((int)(v.X / 24f), 7), cy = Math.Min((int)(v.Y / 24f), 7);
|
||||
float h = lb.GetVertexZ(cx, cy);
|
||||
bool flat = lb.GetVertexZ(cx + 1, cy) == h && lb.GetVertexZ(cx, cy + 1) == h && lb.GetVertexZ(cx + 1, cy + 1) == h;
|
||||
rows.Add((v.Z - gz, v.Z - mesh, ts.GetWaterDepth(v.Cell, v.X, v.Y), flat, v.Cell, v.X, v.Y, v.Z, gz));
|
||||
}
|
||||
int n = rows.Count;
|
||||
int mesh05 = rows.Count(r => MathF.Abs(r.DMesh) <= 0.05f), mesh25 = rows.Count(r => MathF.Abs(r.DMesh) <= 0.25f);
|
||||
int in05 = rows.Count(r => MathF.Abs(r.D) <= 0.05f), in25 = rows.Count(r => MathF.Abs(r.D) <= 0.25f);
|
||||
var above = rows.Where(r => r.D > 0.05f).ToList();
|
||||
var below = rows.Where(r => r.D < -0.05f).ToList();
|
||||
int wet = rows.Count(r => r.Wd > 0f), wetOk = rows.Count(r => r.Wd > 0f && MathF.Abs(r.D) <= 0.05f);
|
||||
int wetRaised = rows.Count(r => r.Wd > 0f && r.D > 0.05f);
|
||||
double pct = 100.0 * in05 / n;
|
||||
T.Info($"bare terrain mesh vs ACE: {mesh05}/{n} ({100.0 * mesh05 / n:F1}%) within 0.05 m, {mesh25}/{n} ({100.0 * mesh25 / n:F1}%) within 0.25 m");
|
||||
T.Info($"standing Z (mesh - water depth) vs ACE: {in05}/{n} ({pct:F1}%) within 0.05 m, {in25}/{n} ({100.0 * in25 / n:F1}%) within 0.25 m; " +
|
||||
$"off by > 0.05: {above.Count} above the ground ({above.Count(r => r.Flat)} of them on flat cells), {below.Count} below");
|
||||
T.Info($"water cells: {wet} vectors, {wetOk} sit exactly the water depth below the mesh, {wetRaised} higher (on an object)");
|
||||
foreach (var r in rows.OrderByDescending(r => MathF.Abs(r.D)).Take(6))
|
||||
T.Info($" worst: {r.Cell:X8} ({r.X:F2}, {r.Y:F2}) z={r.Z:F3} ground={r.Gz:F3} off={r.D:+0.000;-0.000}{(r.Flat ? " (flat cell: on an object)" : "")}");
|
||||
|
||||
T.Check(rows.All(r => !float.IsNaN(r.Gz)), "every outdoor vector's landblock has terrain");
|
||||
T.Check(below.Count == 0, $"no vector stands below the ground ({below.Count})");
|
||||
T.Check(wetOk > 0 && wetOk == wet - wetRaised, $"water depth explains every ground-level vector in a water cell ({wetOk}/{wet - wetRaised})");
|
||||
// The target was 85%, but about a fifth of the vectors (25 of 135 when written) stand on
|
||||
// objects above flat cells (equal corner heights, so neither the split nor the height
|
||||
// table can be at fault) where no terrain answer can match. Hence 80% overall, plus the
|
||||
// ground-level share below.
|
||||
T.Check(pct >= 80.0, $"at least 80% of outdoor vectors within 0.05 m of the standing Z (got {pct:F1}%)");
|
||||
int ground = n - above.Count(r => r.Flat);
|
||||
T.Check(in05 >= ground * 0.98, $"vectors not raised on objects match within 0.05 m ({in05}/{ground})");
|
||||
}
|
||||
|
||||
private static void SplitPolarity(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
double sumAsIs = 0, sumInv = 0;
|
||||
int okAsIs = 0, okInv = 0, differ = 0, differAsIs = 0, differInv = 0;
|
||||
foreach (var v in outdoor)
|
||||
{
|
||||
var lb = ts.LoadLandblock(v.Cell)!;
|
||||
float z = v.Z + TerrainSampler.GetWaterDepth(lb, v.X, v.Y);
|
||||
float a = MathF.Abs(z - TerrainSampler.GetTerrainZ(lb, v.X, v.Y, invertSplit: false));
|
||||
float b = MathF.Abs(z - TerrainSampler.GetTerrainZ(lb, v.X, v.Y, invertSplit: true));
|
||||
sumAsIs += a; sumInv += b;
|
||||
if (a <= 0.05f) okAsIs++;
|
||||
if (b <= 0.05f) okInv++;
|
||||
if (MathF.Abs(a - b) > 0.01f)
|
||||
{
|
||||
differ++;
|
||||
if (a <= 0.05f) differAsIs++;
|
||||
if (b <= 0.05f) differInv++;
|
||||
T.Info($" split matters: {v.Cell:X8} ({v.X:F2}, {v.Y:F2}) z={v.Z:F3} err as implemented {a:F3}, inverted {b:F3}");
|
||||
}
|
||||
}
|
||||
int n = outdoor.Count;
|
||||
T.Info($"split polarity: as implemented mean err {sumAsIs / n:F4} m, {okAsIs}/{n} within 0.05; inverted mean err {sumInv / n:F4} m, {okInv}/{n} within 0.05");
|
||||
T.Info($" on the {differ} vectors where the polarity matters: {differAsIs} match as implemented, {differInv} inverted");
|
||||
T.Check(differ >= 5, $"enough vectors sit where the split matters ({differ})");
|
||||
T.Check(sumAsIs < sumInv && differAsIs > differInv && differInv == 0, "implemented SwToNeCut polarity fits ACE, the inverse doesn't");
|
||||
|
||||
// About half the cells each way.
|
||||
int sw = 0, total = 0;
|
||||
foreach (uint key in outdoor.Select(v => v.Cell >> 16).Distinct())
|
||||
for (int cx = 0; cx < 8; cx++)
|
||||
for (int cy = 0; cy < 8; cy++) { total++; if (TerrainSampler.SwToNeCut(key, cx, cy)) sw++; }
|
||||
T.Info($"SW->NE cut on {sw}/{total} cells of the town landblocks");
|
||||
T.Check(sw > total / 4 && sw < total * 3 / 4, "split is roughly 50/50");
|
||||
}
|
||||
|
||||
private static void Normals(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
int bad = 0, walkable = 0, consistent = 0, tested = 0;
|
||||
foreach (var v in outdoor)
|
||||
{
|
||||
var n = ts.GetNormal(v.Cell, v.X, v.Y);
|
||||
if (!(n.Z > 0f) || MathF.Abs(n.Length() - 1f) > 1e-4f) bad++;
|
||||
if (TerrainSampler.IsWalkable(n)) walkable++;
|
||||
|
||||
// The normal is the gradient of GetTerrainZ: z = z0 - (nx*dx + ny*dy)/nz on the same triangle.
|
||||
// Step toward the triangle's interior along a tiny offset that stays on the triangle.
|
||||
var lb = ts.LoadLandblock(v.Cell)!;
|
||||
float z0 = TerrainSampler.GetTerrainZ(lb, v.X, v.Y);
|
||||
const float d = 0.01f;
|
||||
bool all = true;
|
||||
foreach (var (ox, oy) in new[] { (d, 0f), (0f, d), (-d, 0f), (0f, -d) })
|
||||
{
|
||||
if (TerrainSampler.GetNormal(lb, v.X + ox, v.Y + oy) != n) continue; // crossed onto another triangle
|
||||
float pred = z0 - (n.X * ox + n.Y * oy) / n.Z;
|
||||
if (MathF.Abs(pred - TerrainSampler.GetTerrainZ(lb, v.X + ox, v.Y + oy)) > 1e-3f) all = false;
|
||||
}
|
||||
tested++;
|
||||
if (all) consistent++;
|
||||
}
|
||||
T.Check(bad == 0, $"normals are unit length with Z > 0 ({bad} bad)");
|
||||
T.Check(consistent == tested, $"normal matches the GetTerrainZ gradient ({consistent}/{tested})");
|
||||
double pct = 100.0 * walkable / outdoor.Count;
|
||||
T.Info($"walkable ground under {walkable}/{outdoor.Count} ({pct:F1}%) town vectors");
|
||||
T.Check(pct >= 95.0, "town ground under creatures is walkable");
|
||||
T.Check(TerrainSampler.IsWalkable(Vector3.UnitZ) && TerrainSampler.IsWalkable(Vector3.Normalize(new Vector3(1, 0, 1))),
|
||||
"IsWalkable: flat and 45 degrees yes");
|
||||
T.Check(!TerrainSampler.IsWalkable(Vector3.Normalize(new Vector3(1.2f, 0, 1))), "IsWalkable: 50 degrees no");
|
||||
}
|
||||
|
||||
private static void RaycastDown(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
int hits = 0, good = 0;
|
||||
float worst = 0f;
|
||||
foreach (var v in outdoor)
|
||||
{
|
||||
float tz = ts.GetTerrainZ(v.Cell, v.X, v.Y);
|
||||
bool hit = ts.RaycastTerrain(v.Cell, new Vector3(v.X, v.Y, v.Z + 10f), -Vector3.UnitZ, 100f, out float dist, out var n);
|
||||
if (!hit) continue;
|
||||
hits++;
|
||||
float expect = 10f + (v.Z - tz); // from z+10 down to the terrain
|
||||
float err = MathF.Max(MathF.Abs(dist - expect), MathF.Abs((v.Z + 10f - dist) - tz));
|
||||
worst = MathF.Max(worst, err);
|
||||
if (err <= 0.01f && Vector3.Distance(n, ts.GetNormal(v.Cell, v.X, v.Y)) < 1e-4f) good++;
|
||||
}
|
||||
T.Check(hits == outdoor.Count, $"vertical raycast hits terrain under every vector ({hits}/{outdoor.Count})");
|
||||
T.Check(good == hits, $"vertical raycast distance/normal agree with GetTerrainZ/GetNormal within 0.01 ({good}/{hits}, worst {worst:F5})");
|
||||
|
||||
var v0 = outdoor[0];
|
||||
T.Check(!ts.RaycastTerrain(v0.Cell, new Vector3(v0.X, v0.Y, v0.Z + 10f), Vector3.UnitZ, 100f, out _, out _), "ray pointing up misses");
|
||||
T.Check(!ts.RaycastTerrain(v0.Cell, new Vector3(v0.X, v0.Y, v0.Z + 10f), -Vector3.UnitZ, 5f, out _, out _), "ray shorter than the drop misses");
|
||||
}
|
||||
|
||||
private static void RaycastOblique(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
// Rays from above the town vectors in random downward directions, long enough to cross
|
||||
// several cells and often a landblock edge. The hit must lie on the terrain, and the ray
|
||||
// must stay above the terrain before it.
|
||||
var rng = new Random(12345);
|
||||
int rays = 0, hits = 0, onGround = 0, clear = 0, crossed = 0;
|
||||
float worst = 0f;
|
||||
foreach (var v in outdoor)
|
||||
{
|
||||
for (int k = 0; k < 4; k++)
|
||||
{
|
||||
double ang = rng.NextDouble() * Math.PI * 2;
|
||||
float down = 0.05f + (float)rng.NextDouble() * 0.4f; // shallow: long horizontal runs
|
||||
var dir = Vector3.Normalize(new Vector3((float)Math.Cos(ang), (float)Math.Sin(ang), -down));
|
||||
var o = new Vector3(v.X, v.Y, v.Z + 5f + (float)rng.NextDouble() * 20f);
|
||||
rays++;
|
||||
if (!ts.RaycastTerrain(v.Cell, o, dir, 600f, out float dist, out var n)) continue;
|
||||
hits++;
|
||||
var p = o + dir * dist;
|
||||
float z = WorldZ(ts, v.Cell, p.X, p.Y, out bool otherLb);
|
||||
if (otherLb) crossed++;
|
||||
float err = MathF.Abs(p.Z - z);
|
||||
worst = MathF.Max(worst, err);
|
||||
if (err <= 0.01f && n.Z > 0f && MathF.Abs(n.Length() - 1f) < 1e-4f) onGround++;
|
||||
|
||||
bool above = true;
|
||||
for (float s = 0.25f; s < dist - 0.05f; s += 0.25f)
|
||||
{
|
||||
var q = o + dir * s;
|
||||
if (q.Z < WorldZ(ts, v.Cell, q.X, q.Y, out _) - 0.005f) { above = false; break; }
|
||||
}
|
||||
if (above) clear++;
|
||||
}
|
||||
}
|
||||
T.Info($"oblique rays: {hits}/{rays} hit, {crossed} hits in a neighbouring landblock, worst hit-point error {worst:F5} m");
|
||||
T.Check(hits > rays * 3 / 4, "most oblique rays hit the ground");
|
||||
T.Check(onGround == hits, $"oblique hit points lie on the terrain within 0.01 ({onGround}/{hits})");
|
||||
T.Check(clear == hits, $"oblique rays stay above the terrain before the hit ({clear}/{hits})");
|
||||
T.Check(crossed > 0, "some oblique hits land past the starting landblock");
|
||||
}
|
||||
|
||||
/// <summary>Terrain Z at a point given relative to <paramref name="cell"/>'s landblock, which may lie in a neighbour.</summary>
|
||||
private static float WorldZ(TerrainSampler ts, uint cell, float lx, float ly, out bool otherLandblock)
|
||||
{
|
||||
uint key = cell >> 16;
|
||||
int bx = (int)((key >> 8) & 0xFF) + (int)MathF.Floor(lx / 192f);
|
||||
int by = (int)(key & 0xFF) + (int)MathF.Floor(ly / 192f);
|
||||
float x = lx - MathF.Floor(lx / 192f) * 192f, y = ly - MathF.Floor(ly / 192f) * 192f;
|
||||
uint nk = (uint)((bx << 8) | by);
|
||||
otherLandblock = nk != key;
|
||||
return ts.GetTerrainZ(nk, x, y);
|
||||
}
|
||||
|
||||
private static void Roads(TerrainSampler ts, List<(uint Cell, float X, float Y, float Z)> outdoor)
|
||||
{
|
||||
int roadVerts = 0, roadOk = 0, noRoadCells = 0, noRoadOk = 0;
|
||||
foreach (uint key in outdoor.Select(v => v.Cell >> 16).Distinct())
|
||||
{
|
||||
var lb = ts.LoadLandblock(key)!;
|
||||
for (int ix = 0; ix < 8; ix++)
|
||||
for (int iy = 0; iy < 8; iy++)
|
||||
{
|
||||
float x = ix * 24f + 0.1f, y = iy * 24f + 0.1f;
|
||||
if (TerrainSampler.RoadBits(lb, ix, iy) != 0)
|
||||
{
|
||||
roadVerts++;
|
||||
if (TerrainSampler.OnRoad(lb, x, y)) roadOk++;
|
||||
}
|
||||
if (TerrainSampler.RoadBits(lb, ix, iy) == 0 && TerrainSampler.RoadBits(lb, ix + 1, iy) == 0
|
||||
&& TerrainSampler.RoadBits(lb, ix, iy + 1) == 0 && TerrainSampler.RoadBits(lb, ix + 1, iy + 1) == 0)
|
||||
{
|
||||
noRoadCells++;
|
||||
if (!ts.OnRoad(key, ix * 24f + 12f, iy * 24f + 12f)) noRoadOk++;
|
||||
}
|
||||
}
|
||||
}
|
||||
int onRoad = outdoor.Count(v => ts.OnRoad(v.Cell, v.X, v.Y));
|
||||
T.Info($"roads: {roadVerts} road vertices in the town landblocks; {onRoad}/{outdoor.Count} vectors on a road");
|
||||
T.Check(roadVerts > 0, "town landblocks have roads");
|
||||
T.Check(roadOk == roadVerts, $"a point just inside a road vertex is on the road ({roadOk}/{roadVerts})");
|
||||
T.Check(noRoadOk == noRoadCells, $"cells with no road corners have no road ({noRoadOk}/{noRoadCells})");
|
||||
|
||||
var types = outdoor.Select(v => ts.TerrainType(v.Cell, v.X, v.Y)).ToList();
|
||||
T.Check(types.All(t => t >= 0 && t < 32), "terrain types in 0..31");
|
||||
T.Info($"terrain types under the vectors: {string.Join(" ", types.GroupBy(t => t).OrderByDescending(g => g.Count()).Select(g => $"{g.Key}x{g.Count()}"))}");
|
||||
}
|
||||
|
||||
private static void OpenFromFolder()
|
||||
{
|
||||
using var ts = TerrainSampler.Open(Dats.Folder!);
|
||||
var v = Dats.Vectors("outdoor-towns.txt")[0];
|
||||
T.Check(MathF.Abs(ts.GetTerrainZ(v.Cell, v.X, v.Y) - v.Z) < 0.25f, "TerrainSampler.Open(folder) works");
|
||||
bool threw = false;
|
||||
try { TerrainSampler.Open(Path.GetTempPath()).Dispose(); } catch (FileNotFoundException) { threw = true; }
|
||||
T.Check(threw, "Open on a folder without dats throws FileNotFoundException");
|
||||
}
|
||||
}
|
||||
1401
tools/GeometryTests/Vectors/dungeon-6146.txt
Normal file
1401
tools/GeometryTests/Vectors/dungeon-6146.txt
Normal file
File diff suppressed because it is too large
Load diff
136
tools/GeometryTests/Vectors/outdoor-towns.txt
Normal file
136
tools/GeometryTests/Vectors/outdoor-towns.txt
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
# cell x y z (outdoor creatures standing in 5 towns: CreateObject positions with gravity, and grounded UpdatePositions; captured from the local ACE server)
|
||||
A9B40019 84.000 7.100 94.006
|
||||
A9B40019 78.096 1.676 93.973
|
||||
A9B30006 18.079 125.216 93.992
|
||||
A9B30010 28.052 175.548 92.747
|
||||
A9B4002A 124.794 31.515 94.010
|
||||
A9B40029 128.520 4.955 94.005
|
||||
A9B40021 115.251 6.488 94.005
|
||||
A9B4001A 91.519 37.745 94.000
|
||||
A9B40029 122.227 11.951 94.000
|
||||
A9B40032 154.569 36.201 96.005
|
||||
A9B40021 101.926 20.412 94.005
|
||||
A9B40019 83.300 14.036 94.005
|
||||
A9B40022 97.000 27.000 94.005
|
||||
A9B40022 112.238 46.380 94.000
|
||||
A9B40022 114.644 46.356 94.005
|
||||
DA55001D 84.800 99.000 20.006
|
||||
D955003D 175.883 104.590 20.005
|
||||
DA55001D 93.831 98.497 19.973
|
||||
DA55001D 73.579 98.226 20.005
|
||||
DA55001D 75.507 116.917 20.010
|
||||
DA55001F 93.743 148.683 20.005
|
||||
DA550032 154.009 44.961 20.005
|
||||
DA550002 20.403 39.743 20.005
|
||||
DA550008 13.727 172.056 20.005
|
||||
DA55001F 75.740 153.489 25.005
|
||||
DA55001D 84.822 109.282 20.005
|
||||
DA550025 115.172 103.375 20.005
|
||||
DA550038 154.914 170.884 20.000
|
||||
DA55000C 39.224 82.093 20.000
|
||||
DA550007 12.238 151.614 20.000
|
||||
DA550012 54.482 37.256 20.000
|
||||
DA55002E 124.598 127.401 20.000
|
||||
DA55001D 86.340 104.570 20.005
|
||||
DA55001D 82.000 102.000 20.005
|
||||
7D64000D 31.900 104.600 11.906
|
||||
7C640026 119.472 143.944 -0.103
|
||||
7C640034 144.734 95.263 0.186
|
||||
7C64003B 168.512 71.781 6.089
|
||||
7D650001 0.500 0.500 11.992
|
||||
7D64001E 85.920 138.564 15.605
|
||||
7D64001B 78.387 51.565 12.010
|
||||
7D640018 62.303 173.546 12.000
|
||||
7D64001D 86.636 105.347 12.005
|
||||
7D64001B 81.841 63.649 15.605
|
||||
7D64001B 78.763 64.290 15.605
|
||||
7D640018 66.199 183.290 12.005
|
||||
7D64002C 140.955 87.873 15.497
|
||||
7D64001B 85.052 65.269 20.805
|
||||
7D64001C 90.563 90.580 12.005
|
||||
7D640015 60.374 116.128 12.000
|
||||
7D640024 100.928 84.661 12.000
|
||||
7D64001F 85.618 148.353 12.000
|
||||
7D64001D 95.773 113.577 12.000
|
||||
7D64001E 95.772 132.065 12.000
|
||||
7D64000D 39.203 102.204 12.005
|
||||
7D640015 58.000 106.000 12.005
|
||||
7D640022 106.470 32.042 11.992
|
||||
7D64002E 139.691 134.168 14.452
|
||||
7D64000D 30.148 111.945 11.156
|
||||
C6A90009 46.805 4.219 42.011
|
||||
C5A80036 156.578 138.985 41.992
|
||||
C6A80015 52.798 102.910 42.005
|
||||
C6A9001C 81.350 94.862 42.005
|
||||
C6A90019 79.758 22.932 43.041
|
||||
C6A9000B 27.440 66.958 42.005
|
||||
C6A9000B 28.855 65.493 42.005
|
||||
C6A90019 77.195 22.920 43.032
|
||||
C6A9000B 30.486 64.544 42.005
|
||||
C6A9000B 32.375 64.493 42.005
|
||||
C6A9000B 34.818 64.519 42.005
|
||||
C6A90019 82.369 22.988 43.027
|
||||
C6A9001A 89.352 29.061 43.102
|
||||
C6A9001A 89.369 27.142 43.155
|
||||
C6A9001A 89.394 30.969 43.169
|
||||
C6A9001A 89.385 32.920 43.155
|
||||
C6A9001A 89.382 43.356 43.088
|
||||
C6A9001A 89.467 45.201 43.249
|
||||
C6A9001A 89.430 46.973 43.075
|
||||
C6A9001B 89.407 48.832 43.022
|
||||
C6A9001B 89.420 50.715 43.022
|
||||
C6A9001B 89.387 52.505 43.289
|
||||
C6A9001B 89.408 54.351 43.022
|
||||
C6A9001B 89.388 56.113 43.022
|
||||
C6A90014 70.695 80.516 42.005
|
||||
C6A90022 102.932 39.494 42.005
|
||||
C6A90022 102.900 35.586 42.005
|
||||
C6A9001C 85.691 94.233 42.005
|
||||
C6A9001C 79.591 94.927 42.005
|
||||
C6A9001C 88.291 86.716 42.005
|
||||
C6A90024 107.600 75.233 42.005
|
||||
C6A9001B 92.510 61.022 71.174
|
||||
C6A9000B 43.174 66.804 42.005
|
||||
C6A9001A 74.834 46.387 42.005
|
||||
C98C0028 113.666 190.259 22.011
|
||||
C98D0001 18.872 2.470 3.550
|
||||
C98D0009 30.081 2.246 3.550
|
||||
C98D0002 23.909 37.389 3.550
|
||||
C98D000A 29.282 44.763 3.550
|
||||
C98D0003 20.924 54.795 3.550
|
||||
C98D0003 18.426 48.139 3.550
|
||||
C98D000C 31.589 75.195 3.550
|
||||
C98D0009 24.756 4.202 3.550
|
||||
C98D001C 94.907 83.491 14.939
|
||||
C98D0025 100.322 109.610 9.938
|
||||
C98D002B 133.213 66.673 21.992
|
||||
C98D002C 139.178 89.631 21.992
|
||||
C98C0028 107.834 179.356 25.005
|
||||
C98C0028 102.229 188.555 22.005
|
||||
C98C000E 30.760 123.202 3.550
|
||||
C98C0006 18.672 142.042 3.550
|
||||
C98C000F 28.457 149.060 3.550
|
||||
C98C000F 24.882 162.099 3.550
|
||||
C98C000F 24.995 156.887 3.550
|
||||
C98C0007 17.326 152.303 3.550
|
||||
C98C000F 30.828 165.435 3.550
|
||||
C98C0007 17.991 165.103 3.550
|
||||
C98D002C 138.968 89.764 21.992
|
||||
C98D002C 138.698 89.868 21.992
|
||||
C98D002C 138.304 90.093 21.992
|
||||
C98D002C 138.033 90.195 21.992
|
||||
A9B40029 133.604 17.392 94.011
|
||||
A9B4003D 176.730 106.375 65.278
|
||||
A9B40029 133.604 22.392 94.003
|
||||
A9B40029 133.604 17.792 94.011
|
||||
A9B40029 133.604 18.292 94.011
|
||||
A9B40029 133.604 18.728 94.011
|
||||
A9B40029 133.604 19.072 94.011
|
||||
A9B40029 133.604 22.214 94.003
|
||||
A9B40029 133.604 21.590 94.003
|
||||
A9B40029 133.604 20.535 94.003
|
||||
A9B40029 133.604 20.636 94.003
|
||||
A9B40029 133.604 19.472 94.011
|
||||
A9B40029 133.604 19.908 94.011
|
||||
A9B40029 133.604 20.338 94.011
|
||||
A9B40029 133.604 21.438 94.100
|
||||
285
tools/GeometryTests/WalkTests.cs
Normal file
285
tools/GeometryTests/WalkTests.cs
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
// ============================================================================
|
||||
// WalkTests - the kinematic walker (RynthCore.Geometry/Walking/Walker.cs) on the real dats,
|
||||
// checked against positions ACE reported (Vectors\).
|
||||
// ============================================================================
|
||||
|
||||
using System.Numerics;
|
||||
using RynthCore.Geometry.Cells;
|
||||
using RynthCore.Geometry.Collision;
|
||||
using RynthCore.Geometry.Dat;
|
||||
using RynthCore.Geometry.Models;
|
||||
using RynthCore.Geometry.Terrain;
|
||||
using RynthCore.Geometry.Walking;
|
||||
|
||||
namespace GeometryTests;
|
||||
|
||||
internal static class WalkTests
|
||||
{
|
||||
[System.Runtime.CompilerServices.ModuleInitializer]
|
||||
internal static void Register() => Suites.Add("walk", Run, order: 40);
|
||||
|
||||
private static void Run()
|
||||
{
|
||||
using var portal = new DatDatabase();
|
||||
using var cell = new DatDatabase();
|
||||
T.Check(portal.Open(Dats.Portal) && cell.Open(Dats.Cell), "dats open");
|
||||
var terrain = new TerrainSampler(portal, cell);
|
||||
var indoor = new IndoorWorld(cell, portal, new ModelReader(portal));
|
||||
var walker = new Walker(terrain, indoor);
|
||||
var world = new OutdoorCollision(cell, portal, terrain, indoor.Models, indoor);
|
||||
var withObstacles = new Walker(terrain, indoor, new StaticObstacles(world));
|
||||
|
||||
Dungeon(walker, indoor);
|
||||
Outdoors(walker, terrain, indoor);
|
||||
ObstacleWalks(withObstacles, terrain, indoor, world);
|
||||
IntoBuilding(withObstacles, indoor, terrain);
|
||||
Planner(withObstacles, terrain);
|
||||
}
|
||||
|
||||
/// <summary>Pairs of town points whose straight walk is blocked: the local planner finds a way and walking it arrives.</summary>
|
||||
private static void Planner(Walker walker, TerrainSampler terrain)
|
||||
{
|
||||
var v = Dats.Vectors("outdoor-towns.txt")
|
||||
.Where(p => MathF.Abs(terrain.GetStandingZ(p.Cell >> 16, p.X, p.Y) - p.Z) < 0.05f).ToList();
|
||||
var planner = new LocalPlanner(walker);
|
||||
int blockedPairs = 0, planned = 0, walked = 0;
|
||||
long ms = 0;
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
foreach (var a in v)
|
||||
{
|
||||
foreach (var b in v.Where(b => b.Cell >> 16 == a.Cell >> 16 && Dist2(a, b) is > 15 and < 40))
|
||||
{
|
||||
var start = new PathPoint(a.Cell, new Vector3(a.X, a.Y, a.Z));
|
||||
var straight = WalkTo(walker, a.Cell, start.Position, new Vector2(b.X, b.Y));
|
||||
if (Vector2.Distance(new Vector2(straight.Position.X, straight.Position.Y), new Vector2(b.X, b.Y)) < 0.5f) continue;
|
||||
blockedPairs++;
|
||||
sw.Restart();
|
||||
var path = planner.Find(start, new Vector2(b.X, b.Y), 0.5f);
|
||||
ms += sw.ElapsedMilliseconds;
|
||||
if (path == null) continue;
|
||||
planned++;
|
||||
// Follow the path with the walker.
|
||||
var r = new StepResult(a.Cell, start.Position, false);
|
||||
foreach (var pt in path.Skip(1))
|
||||
{
|
||||
var target = LocalPlanner.InFrame(a.Cell >> 16, pt.Cell, pt.Position);
|
||||
var here = LocalPlanner.InFrame(a.Cell >> 16, r.Cell, r.Position);
|
||||
r = walker.Step(r.Cell, r.Position, target.X - here.X, target.Y - here.Y);
|
||||
if (r.Blocked) break;
|
||||
}
|
||||
if (!r.Blocked && Vector2.Distance(LocalPlanner.InFrame(a.Cell >> 16, r.Cell, r.Position), new Vector2(b.X, b.Y)) < 0.6f) walked++;
|
||||
if (blockedPairs >= 25) break;
|
||||
}
|
||||
if (blockedPairs >= 25) break;
|
||||
}
|
||||
T.Info($"planner: {blockedPairs} blocked pairs, {planned} planned ({(planned > 0 ? ms / planned : 0)} ms each), {walked} walked to the goal");
|
||||
T.Check(blockedPairs >= 5, "there are blocked pairs to plan around");
|
||||
T.Check(planned >= blockedPairs * 0.7, $"most blocked pairs get a path ({planned}/{blockedPairs})");
|
||||
T.Check(walked == planned, $"every planned path walks to the goal ({walked}/{planned})");
|
||||
}
|
||||
|
||||
private static void Dungeon(Walker walker, IndoorWorld indoor)
|
||||
{
|
||||
var v = Dats.Vectors("dungeon-6146.txt");
|
||||
var byCell = v.GroupBy(p => p.Cell).ToDictionary(g => g.Key, g => g.ToList());
|
||||
|
||||
// Walk from a captured position to one in a neighbouring cell (up to 4 m away, roughly level).
|
||||
int pairs = 0, arrived = 0, rightCell = 0, rightZ = 0;
|
||||
var misses = new List<string>();
|
||||
var rng = new Random(7);
|
||||
foreach (var a in v.OrderBy(_ => rng.Next()).Take(600))
|
||||
{
|
||||
foreach (uint n in indoor.Neighbours(a.Cell))
|
||||
{
|
||||
if (!byCell.TryGetValue(n, out var list)) continue;
|
||||
var b = list.FirstOrDefault(p => Dist2(a, p) < 4 && Dist2(a, p) > 0.5f && MathF.Abs(p.Z - a.Z) < 0.3f);
|
||||
if (b.Cell == 0) continue;
|
||||
pairs++;
|
||||
var r = WalkTo(walker, a.Cell, new Vector3(a.X, a.Y, a.Z), new Vector2(b.X, b.Y));
|
||||
bool there = Vector2.Distance(new Vector2(r.Position.X, r.Position.Y), new Vector2(b.X, b.Y)) < 0.05f;
|
||||
if (there) arrived++;
|
||||
if (there && r.Cell == b.Cell) rightCell++;
|
||||
if (there && MathF.Abs(r.Position.Z - b.Z) < 0.15f) rightZ++;
|
||||
if ((!there || r.Cell != b.Cell) && misses.Count < 8)
|
||||
misses.Add($"{a.Cell:X8} ({a.X:F2},{a.Y:F2}) -> {b.Cell:X8} ({b.X:F2},{b.Y:F2}): ended {r.Cell:X8} ({r.Position.X:F2},{r.Position.Y:F2}) {r.Why}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
T.Info($"dungeon neighbour walks: {pairs} pairs, {arrived} arrived, {rightCell} in the right cell, {rightZ} at ACE's height (0.15 m)");
|
||||
foreach (string m in misses) T.Info(" " + m);
|
||||
T.Check(pairs > 100, "enough neighbour pairs");
|
||||
T.Check(arrived >= pairs * 0.85, $"most straight walks between neighbouring cells get there ({arrived}/{pairs})");
|
||||
T.Check(rightCell >= arrived * 0.97, $"and end in ACE's cell ({rightCell}/{arrived})");
|
||||
T.Check(rightZ >= arrived * 0.9, $"at ACE's height ({rightZ}/{arrived})");
|
||||
|
||||
// Long walks in random directions: never end outside a cell, the cell agrees with FindCell.
|
||||
int walks = 0, consistent = 0, blocked = 0;
|
||||
foreach (var a in v.OrderBy(_ => rng.Next()).Take(200))
|
||||
{
|
||||
float ang = (float)(rng.NextDouble() * Math.PI * 2);
|
||||
var r = walker.Step(a.Cell, new Vector3(a.X, a.Y, a.Z), MathF.Cos(ang) * 30, MathF.Sin(ang) * 30);
|
||||
walks++;
|
||||
if (r.Blocked) blocked++;
|
||||
var found = indoor.FindCell(0x6146, r.Position.X, r.Position.Y, r.Position.Z);
|
||||
if (r.Cell >> 16 == 0x6146 && indoor.GetCell(r.Cell)?.CoversXY(r.Position.X, r.Position.Y) == true && found?.cellId == r.Cell) consistent++;
|
||||
}
|
||||
T.Info($"30 m walks: {walks}, {blocked} stopped by walls, {consistent} end in a consistent cell");
|
||||
T.Check(consistent >= walks * 0.97, $"walks end where FindCell agrees ({consistent}/{walks})");
|
||||
|
||||
// The test character's spot.
|
||||
var start = new Vector3(91.617874f, -157.55351f, -11.9885f);
|
||||
var rb = walker.Step(0x61460249, start, 1.5f, 0);
|
||||
T.Check(!rb.Blocked || rb.Why != null, "a step from the test character's spot resolves");
|
||||
|
||||
SlopedDoorway(walker);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Matron hive (0x6346): tunnel 0x01A5 opens into room 0x01A6 through a doorway that slopes up over the
|
||||
/// tunnel's end, so the doorway is crossed above the feet before the room's floor begins. A 4Hives
|
||||
/// route walks straight through it (2026-10-29: the walker stopped at the tunnel's end until TrackCell
|
||||
/// learned sloping doorways).
|
||||
/// </summary>
|
||||
private static void SlopedDoorway(Walker walker)
|
||||
{
|
||||
var east = WalkTo(walker, 0x634601A5, new Vector3(136f, -10f, -24f), new Vector2(151.5f, -10f));
|
||||
T.Check(east.Cell == 0x634601B1 && MathF.Abs(east.Position.X - 151.5f) < 0.3f,
|
||||
$"hive tunnel -> room -> loot room through the sloping doorway (ended {east.Cell:X8} x {east.Position.X:F1})");
|
||||
var west = WalkTo(walker, 0x634601B1, new Vector3(150f, -10f, -24f), new Vector2(136f, -10f));
|
||||
T.Check(west.Cell == 0x634601A5 && MathF.Abs(west.Position.X - 136f) < 0.3f,
|
||||
$"and back out under it (ended {west.Cell:X8} x {west.Position.X:F1})");
|
||||
var beside = WalkTo(walker, 0x634601A6, new Vector3(142f, -6f, -24f), new Vector2(136f, -6f));
|
||||
T.Check(beside.Cell != 0x634601A5, $"beside the tunnel mouth the room's ramp is not the tunnel (ended {beside.Cell:X8})");
|
||||
}
|
||||
|
||||
private static void Outdoors(Walker walker, TerrainSampler terrain, IndoorWorld indoor)
|
||||
{
|
||||
var v = Dats.Vectors("outdoor-towns.txt")
|
||||
.Where(p => MathF.Abs(terrain.GetStandingZ(p.Cell >> 16, p.X, p.Y) - p.Z) < 0.05f).ToList();
|
||||
int walks = 0, onGround = 0, cellOk = 0;
|
||||
var rng = new Random(11);
|
||||
foreach (var a in v.Take(60))
|
||||
{
|
||||
float ang = (float)(rng.NextDouble() * Math.PI * 2);
|
||||
var r = walker.Step(a.Cell, new Vector3(a.X, a.Y, a.Z), MathF.Cos(ang) * 10, MathF.Sin(ang) * 10);
|
||||
walks++;
|
||||
uint lb = r.Cell >> 16;
|
||||
if (EnvCell.IsIndoor(r.Cell))
|
||||
{
|
||||
// Walked in through a ground-level doorway: fine if the cell agrees.
|
||||
bool ok = indoor.FindCell(lb, r.Position.X, r.Position.Y, r.Position.Z)?.cellId == r.Cell;
|
||||
if (ok) { onGround++; cellOk++; }
|
||||
else T.Info($" entered {r.Cell:X8} but FindCell disagrees");
|
||||
continue;
|
||||
}
|
||||
float g = terrain.GetStandingZ(lb, r.Position.X, r.Position.Y);
|
||||
if (MathF.Abs(g - r.Position.Z) < 0.01f) onGround++;
|
||||
if (r.Cell == Walker.OutdoorCell(lb, r.Position.X, r.Position.Y)) cellOk++;
|
||||
else T.Info($" land cell miss: from {a.Cell:X8} ({a.X:F2},{a.Y:F2}) ended {r.Cell:X8} ({r.Position.X:F2},{r.Position.Y:F2}) blocked {r.Blocked} {r.Why}");
|
||||
}
|
||||
T.Info($"outdoor 10 m walks (no obstacles loaded, ground-level doors count when the cell agrees): {walks}, {onGround} on the terrain, {cellOk} with the right land cell");
|
||||
T.Check(onGround == walks && cellOk == walks, "outdoor walks follow the terrain and land cells");
|
||||
|
||||
// Across a landblock edge: Holtburg 0xA9B4 east edge -> 0xAAB4.
|
||||
float z0 = terrain.GetStandingZ(0xA9B4, 190f, 100f);
|
||||
var e = walker.Step(Walker.OutdoorCell(0xA9B4, 190f, 100f), new Vector3(190f, 100f, z0), 5f, 0f);
|
||||
T.Check(!e.Blocked && e.Cell >> 16 == 0xAAB4 && MathF.Abs(e.Position.X - 3f) < 0.01f,
|
||||
$"crossing east into 0xAAB4 (ended 0x{e.Cell:X8} x {e.Position.X:F2}{(e.Blocked ? ", " + e.Why : "")})");
|
||||
T.Check(MathF.Abs(e.Position.Z - terrain.GetStandingZ(0xAAB4, e.Position.X, e.Position.Y)) < 0.01f, "and on its terrain");
|
||||
}
|
||||
|
||||
/// <summary>Outdoor walks among buildings, statics and scenery: feet on terrain or a walkable surface, never in a wall.</summary>
|
||||
private static void ObstacleWalks(Walker walker, TerrainSampler terrain, IndoorWorld indoor, OutdoorCollision world)
|
||||
{
|
||||
var v = Dats.Vectors("outdoor-towns.txt")
|
||||
.Where(p => MathF.Abs(terrain.GetStandingZ(p.Cell >> 16, p.X, p.Y) - p.Z) < 0.05f).ToList();
|
||||
int walks = 0, grounded = 0, clear = 0, blocked = 0;
|
||||
var rng = new Random(13);
|
||||
foreach (var a in v.Take(70))
|
||||
{
|
||||
float ang = (float)(rng.NextDouble() * Math.PI * 2);
|
||||
var r = walker.Step(a.Cell, new Vector3(a.X, a.Y, a.Z), MathF.Cos(ang) * 15, MathF.Sin(ang) * 15);
|
||||
walks++;
|
||||
if (r.Blocked) blocked++;
|
||||
uint lb = r.Cell >> 16;
|
||||
var q = r.Position;
|
||||
bool ok;
|
||||
if (EnvCell.IsIndoor(r.Cell))
|
||||
{
|
||||
// Inside: the cell index agrees, or we stopped on the threshold just past the doorway's
|
||||
// plane (ACE changes cells at that plane too) before the cell's floor starts.
|
||||
ok = indoor.FindCell(lb, q.X, q.Y, q.Z)?.cellId == r.Cell
|
||||
|| (indoor.GetCell(r.Cell)?.Portals.Any(cp => cp.LeadsOutdoors && cp.Polygon.Length >= 3
|
||||
&& RynthCore.Geometry.Cells.Geo.DistToPolygon(cp.Polygon, q + new Vector3(0, 0, 0.6f)) < 1.0f) ?? false);
|
||||
}
|
||||
else
|
||||
{
|
||||
float g = terrain.GetStandingZ(lb, q.X, q.Y);
|
||||
float? s = world.SurfaceBelow(lb, q.X, q.Y, q.Z + 0.01f, 0.05f);
|
||||
ok = MathF.Abs(g - q.Z) < 0.01f || (s is { } sz && MathF.Abs(sz - q.Z) < 0.01f);
|
||||
}
|
||||
if (ok) grounded++;
|
||||
else T.Info($" not grounded: from {a.Cell:X8} ({a.X:F2},{a.Y:F2},{a.Z:F2}) ended {r.Cell:X8} ({q.X:F2},{q.Y:F2},{q.Z:F2}) terrain {terrain.GetStandingZ(lb, q.X, q.Y):F2} surface {world.SurfaceBelow(lb, q.X, q.Y, q.Z + 1, 3)?.ToString("F2") ?? "-"} {r.Why}");
|
||||
bool inWall = !EnvCell.IsIndoor(r.Cell) && world.Near(lb, q.X, q.Y, 0.3f)
|
||||
.Any(t => !t.Walkable && RynthCore.Geometry.Cells.Geo.DistToPolygon(new[] { t.A, t.B, t.C }, q + new Vector3(0, 0, 1.0f)) < 0.3f);
|
||||
if (!inWall) clear++;
|
||||
}
|
||||
T.Info($"15 m walks among obstacles: {walks}, {blocked} stopped, {grounded} standing on terrain or a surface, {clear} clear of walls");
|
||||
T.Check(grounded == walks, $"feet always on terrain, an object surface or a cell floor ({grounded}/{walks})");
|
||||
T.Check(clear == walks, $"never ends inside a wall ({clear}/{walks})");
|
||||
}
|
||||
|
||||
private static void IntoBuilding(Walker walker, IndoorWorld indoor, TerrainSampler terrain)
|
||||
{
|
||||
int tried = 0, entered = 0, windows = 0;
|
||||
var misses = new List<string>();
|
||||
foreach (EnvCell c in indoor.LoadLandblock(0xA9B4))
|
||||
{
|
||||
if ((c.Flags & 1) == 0) continue;
|
||||
foreach (CellPortal p in c.Portals.Where(p => p.LeadsOutdoors && p.Polygon.Length >= 3))
|
||||
{
|
||||
Vector3 centre = p.Polygon.Aggregate(Vector3.Zero, (s, q) => s + q) / p.Polygon.Length;
|
||||
Vector3 n = CellDat.Normal(p.Polygon);
|
||||
var flat = Vector2.Normalize(new Vector2(n.X, n.Y));
|
||||
if (float.IsNaN(flat.X)) continue;
|
||||
// Outward = toward the side PortalSide names (the way TrackCell leaves the cell).
|
||||
Vector2 outward = p.PortalSide ? flat : -flat;
|
||||
var outside = new Vector2(centre.X, centre.Y) + outward * 3f;
|
||||
var inside = new Vector2(centre.X, centre.Y) - outward * 1.2f;
|
||||
float z = terrain.GetStandingZ(0xA9B4, outside.X, outside.Y);
|
||||
// Windows are outdoor portals too: skip openings whose sill is more than a step above the ground.
|
||||
float sill = p.Polygon.Min(q => q.Z);
|
||||
float ground = terrain.GetStandingZ(0xA9B4, centre.X + outward.X * 0.6f, centre.Y + outward.Y * 0.6f);
|
||||
if (sill - ground > walker.StepUp + 0.1f) { windows++; continue; }
|
||||
tried++;
|
||||
var r = WalkTo(walker, Walker.OutdoorCell(0xA9B4, outside.X, outside.Y), new Vector3(outside, z), inside);
|
||||
if (r.Cell == c.Id || (EnvCell.IsIndoor(r.Cell) && r.Cell >> 16 == 0xA9B4)) entered++;
|
||||
else if (misses.Count < 6) misses.Add($"door of {c.Id:X8}: ended {r.Cell:X8} ({r.Position.X:F1},{r.Position.Y:F1},{r.Position.Z:F2}) {r.Why}");
|
||||
}
|
||||
}
|
||||
T.Info($"Holtburg doorways: {tried} tried, {entered} walked inside ({windows} windows skipped)");
|
||||
foreach (string m in misses) T.Info(" " + m);
|
||||
T.Check(tried > 5, "Holtburg has buildings with outdoor doorways");
|
||||
T.Check(entered >= tried * 0.8, $"walking through a doorway enters the building ({entered}/{tried})");
|
||||
}
|
||||
|
||||
/// <summary>Steps toward a point in 0.4 m pieces until there, blocked, or 100 steps.</summary>
|
||||
private static StepResult WalkTo(Walker w, uint cell, Vector3 pos, Vector2 goal)
|
||||
{
|
||||
var r = new StepResult(cell, pos, false);
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
var d = goal - new Vector2(r.Position.X, r.Position.Y);
|
||||
float len = d.Length();
|
||||
if (len < 0.01f) break;
|
||||
float s = Math.Min(len, 0.4f);
|
||||
var n = w.Step(r.Cell, r.Position, d.X / len * s, d.Y / len * s);
|
||||
if (n.Blocked) return n;
|
||||
r = n;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
private static float Dist2((uint Cell, float X, float Y, float Z) a, (uint Cell, float X, float Y, float Z) b)
|
||||
=> MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
|
||||
}
|
||||
Loading…
Reference in a new issue