Retire dead evaluation harnesses and RealtimeCSG native bridge

This commit is contained in:
Meta Vens 2026-12-03 21:50:57 +01:00
commit 2078daef92
20 changed files with 7 additions and 6826 deletions

View file

@ -57,33 +57,6 @@ or:
.\tools\run_csg_perf.ps1 -ReferenceCommand "path\to\reference-perf.exe"
```
To run the native RealtimeCSG C++ plugin directly through the public P/Invoke
surface mirrored by its managed Unity library:
```powershell
.\tools\run_csg_perf.ps1 -UseRealtimeCsgCpp
```
To test the native bridge without running the full timing suite:
```powershell
.\tools\run_realtimecsg_cpp_perf.ps1 -OutputPath .\experiments\generated\realtimecsg-cpp-health-latest.jsonl -Health
```
That path builds `tools/realtimecsg_native_bridge`, copies
`RealtimeCSG[1_559].dll` beside the bridge executable, calls only exported
functions already declared by the plugin's managed P/Invoke layer, and writes
native timing records to `experiments/generated/realtimecsg-cpp-perf-latest.jsonl`.
It fails closed if the native plugin emits no mesh descriptions; zero-geometry
timings are poison, not data.
Current direct-DLL status: the bridge successfully loads the native plugin,
creates brush meshes, brushes, and trees, verifies bounds, outlines, raycasts,
and now extracts generated mesh descriptions. The fragile part was construction
discipline: build child nodes before the tree, insert them through the public
Foundation range-insert path, and avoid eagerly setting default brush operation
or flag state.
The reference executable must emit JSONL with the same scenario names. Until
that harness exists, the script appends a `kernel=reference,status=missing`
record instead of faking a comparison. Sad, but hygienic.
@ -91,8 +64,7 @@ record instead of faking a comparison. Sad, but hygienic.
The public `LogicalError/Realtime-CSG-demo` source still exposes the relevant
algorithmic surface: half-edge control meshes, polygon bounds, visible flags,
inside/outside/aligned/reverse-aligned categories, crossing polygon splits, and
logical routing tables. Use it as readable doctrine. Use the native bridge as
the performance target.
logical routing tables. Use it as readable doctrine.
CultGeometry CSG reports the first demand-frontier counters. These are not yet a
new kernel path; they expose the ordered brush stream as affected source/operator
@ -147,7 +119,7 @@ checkpoint path.
## Latest Local Baseline
Captured on 2026-05-07 with `.\tools\run_csg_perf.ps1 -UseRealtimeCsgCpp`:
Captured on 2026-05-07 (historical baseline before the native bridge was retired):
This baseline predates the `candidate_pairs`/`rejected_pairs` fields. New
fixture runs include them; keep the old block until a fresh C++ comparison is

View file

@ -1,6 +1,7 @@
# Aetheris evaluation (2026-10-14)
Serves the operator's request to evaluate https://github.com/yuechen-li-dev/Aetheris (a C# AGPL-3.0 B-rep kernel) for capability and ideas, campaign brush-tree, session self-2026-10-14-ag. Facts only, measured at Aetheris 335dfb07df on Yggdrasil; Self's reading is in the conversation, not here. The torture harness is in `harness/`.
Serves the operator's request to evaluate https://github.com/yuechen-li-dev/Aetheris (a C# AGPL-3.0 B-rep kernel) for capability and ideas, campaign brush-tree, session self-2026-10-14-ag. Facts only, measured at Aetheris 335dfb07df on Yggdrasil; Self's reading is in the conversation, not here.
Note: the raw probe harness (`harness/`) was retired from git while preserving all measured findings below.
# Aetheris evaluation facts

View file

@ -1,13 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<AssemblyName>Aetheris.Kernel.Core.Tests</AssemblyName>
<RootNamespace>Harness</RootNamespace>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="/src/Aetheris.Kernel.Core/Aetheris.Kernel.Core.csproj" />
</ItemGroup>
</Project>

View file

@ -1,161 +0,0 @@
using System.Diagnostics;
using System.Text.Json;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Boolean;
using Aetheris.Kernel.Core.Brep.Verification;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Geometry.Curves;
using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Core.Topology;
using Aetheris.Kernel.Core.Diagnostics;
static class P
{
static (double c, double s) CS(double deg)
{
var d = ((deg % 360) + 360) % 360;
if (d == 0) return (1, 0);
if (d == 90) return (0, 1);
if (d == 180) return (-1, 0);
if (d == 270) return (0, -1);
var r = deg * Math.PI / 180;
return (Math.Cos(r), Math.Sin(r));
}
static Transform3D Make(double rxDeg, double ryDeg, double[] p)
{
var (cx, sx) = CS(rxDeg);
var (cy, sy) = CS(ryDeg);
var rx = Transform3D.FromRowMajor(new double[] { 1, 0, 0, 0, 0, cx, sx, 0, 0, -sx, cx, 0, 0, 0, 0, 1 });
var ry = Transform3D.FromRowMajor(new double[] { cy, 0, -sy, 0, 0, 1, 0, 0, sy, 0, cy, 0, 0, 0, 0, 1 });
var t = Transform3D.CreateTranslation(new Vector3D(p[0], p[1], p[2]));
return rx * ry * t;
}
static BrepBody Tr(BrepBody body, Transform3D t)
{
var g = new BrepGeometryStore();
foreach (var c in body.Geometry.Curves)
{
g.AddCurve(c.Key, c.Value.Kind switch
{
CurveGeometryKind.Line3 => CurveGeometry.FromLine(new Line3Curve(t.Apply(c.Value.Line3!.Value.Origin), t.Apply(c.Value.Line3.Value.Direction))),
CurveGeometryKind.Circle3 => CurveGeometry.FromCircle(new Circle3Curve(t.Apply(c.Value.Circle3!.Value.Center), t.Apply(c.Value.Circle3.Value.Normal), c.Value.Circle3.Value.Radius, t.Apply(c.Value.Circle3.Value.XAxis))),
_ => c.Value
});
}
foreach (var s in body.Geometry.Surfaces)
{
g.AddSurface(s.Key, s.Value.Kind switch
{
SurfaceGeometryKind.Plane => SurfaceGeometry.FromPlane(new PlaneSurface(t.Apply(s.Value.Plane!.Value.Origin), t.Apply(s.Value.Plane.Value.Normal), t.Apply(s.Value.Plane.Value.UAxis))),
SurfaceGeometryKind.Cylinder => SurfaceGeometry.FromCylinder(new CylinderSurface(t.Apply(s.Value.Cylinder!.Value.Origin), t.Apply(s.Value.Cylinder.Value.Axis), s.Value.Cylinder.Value.Radius, t.Apply(s.Value.Cylinder.Value.XAxis))),
SurfaceGeometryKind.Sphere => SurfaceGeometry.FromSphere(new SphereSurface(t.Apply(s.Value.Sphere!.Value.Center), t.Apply(s.Value.Sphere.Value.Axis), s.Value.Sphere.Value.Radius, t.Apply(s.Value.Sphere.Value.XAxis))),
SurfaceGeometryKind.Torus => SurfaceGeometry.FromTorus(new TorusSurface(t.Apply(s.Value.Torus!.Value.Center), t.Apply(s.Value.Torus.Value.Axis), s.Value.Torus.Value.MajorRadius, s.Value.Torus.Value.MinorRadius, t.Apply(s.Value.Torus.Value.XAxis))),
_ => s.Value
});
}
var vp = new Dictionary<VertexId, Point3D>();
foreach (var v in body.Topology.Vertices)
if (body.TryGetVertexPoint(v.Id, out var pt)) vp[v.Id] = t.Apply(pt);
return new BrepBody(body.Topology, g, body.Bindings, vp, body.SafeBooleanComposition);
}
static KernelResult<BrepBody> Prim(JsonElement e)
{
var k = e.GetProperty("k").GetString()!;
var d = e.GetProperty("d").EnumerateArray().Select(x => x.GetDouble()).ToArray();
var p = e.GetProperty("p").EnumerateArray().Select(x => x.GetDouble()).ToArray();
var rx = e.GetProperty("rx").GetDouble();
var ry = e.GetProperty("ry").GetDouble();
KernelResult<BrepBody> r;
if (k == "box") r = BrepPrimitives.CreateBox(d[0], d[1], d[2]);
else if (k == "cyl") r = BrepPrimitives.CreateCylinder(d[0], d[1]);
else if (k == "sph") r = BrepPrimitives.CreateSphere(d[0]);
else if (k == "tor") r = BrepPrimitives.CreateTorus(d[0], d[1]);
else throw new Exception("kind " + k);
if (!r.IsSuccess) return r;
if (rx == 0 && ry == 0 && p.All(x => x == 0)) return r;
return KernelResult<BrepBody>.Success(Tr(r.Value, Make(rx, ry, p)));
}
static string Short(IEnumerable<KernelDiagnostic> ds, int n = 3)
=> string.Join(" || ", ds.Take(n).Select(d => "[" + d.Severity + "/" + d.Code + "] " + d.Message)).Replace("\n", " ");
static int Main(string[] a)
{
var cases = JsonDocument.Parse(File.ReadAllText(a[0])).RootElement;
var outDir = a[1];
Directory.CreateDirectory(outDir);
var only = a.Length > 2 ? a[2] : null;
foreach (var c in cases.EnumerateArray())
{
var name = c.GetProperty("name").GetString()!;
if (only != null && !name.StartsWith(only)) continue;
var line = new Dictionary<string, object?> { ["name"] = name };
var sw = Stopwatch.StartNew();
var cc = c;
var task = Task.Run(() =>
{
var cur = Prim(cc.GetProperty("a"));
if (!cur.IsSuccess) throw new Exception("PRIM(a): " + Short(cur.Diagnostics));
var op = cc.GetProperty("op").GetString();
int i = 0;
int n = cc.GetProperty("bs").GetArrayLength();
foreach (var b in cc.GetProperty("bs").EnumerateArray())
{
var rb = Prim(b);
if (!rb.IsSuccess) throw new Exception("PRIM(b" + i + "): " + Short(rb.Diagnostics));
if (op == "union") cur = BrepBoolean.Union(cur.Value, rb.Value);
else if (op == "subtract") cur = BrepBoolean.Subtract(cur.Value, rb.Value);
else cur = BrepBoolean.Intersect(cur.Value, rb.Value);
i++;
if (!cur.IsSuccess) { line["failedAtStep"] = i + "/" + n; return cur; }
}
line["stepsDone"] = i + "/" + n;
return cur;
});
try
{
if (!task.Wait(TimeSpan.FromSeconds(180))) { line["status"] = "TIMEOUT"; }
else
{
var r = task.Result;
if (!r.IsSuccess) { line["status"] = "REFUSED"; line["msg"] = Short(r.Diagnostics); }
else
{
line["status"] = "OK";
line["warn"] = Short(r.Diagnostics.Where(d => d.Severity != KernelDiagnosticSeverity.Info), 2);
try
{
var m = BrepMassProperties.Evaluate(r.Value);
line["vol"] = m.Status + ":" + m.AbsoluteVolume.ToString("R") + ":" + m.EvaluationMethod;
}
catch (Exception ex) { line["vol"] = "EX " + ex.GetType().Name; }
try
{
var s = Step242Exporter.ExportBody(r.Value);
if (s.IsSuccess) { File.WriteAllText(Path.Combine(outDir, name + ".step"), s.Value); line["step"] = "exported"; }
else line["step"] = "EXPORT_REFUSED " + Short(s.Diagnostics);
}
catch (Exception ex) { line["step"] = "EXPORT_CRASH " + ex.GetType().Name + ": " + ex.Message; }
}
}
}
catch (AggregateException ex)
{
var m = ex.InnerException?.Message ?? ex.Message;
bool prim = m.StartsWith("PRIM");
line["status"] = prim ? "HARNESS_PRIM_FAIL" : "CRASH";
line["msg"] = (ex.InnerException?.GetType().Name + ": " + m).Replace("\n", " ");
if (!prim) line["stack"] = (ex.InnerException?.StackTrace ?? "").Split('\n').Take(3).Select(s => s.Trim()).ToArray();
}
line["ms"] = sw.ElapsedMilliseconds;
Console.WriteLine("RESULT " + JsonSerializer.Serialize(line));
}
return 0;
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,9 +0,0 @@
import sys, re, collections
for f in sys.argv[1:]:
t = open(f).read()
ec = set(re.findall(r"#(\d+)=EDGE_CURVE", t))
uses = collections.Counter()
for m in re.finditer(r"ORIENTED_EDGE\([^,]*,\*,\*,#(\d+),", t):
uses[m.group(1)] += 1
hist = collections.Counter(uses.values())
print("EDGES", f.split("/")[-1], "edge_curves", len(ec), "oriented_edge_uses_per_edge_histogram", dict(hist), "edges_never_used", len(ec - set(uses)))

View file

@ -1,29 +0,0 @@
import sys, re, collections, math
from OCP.STEPControl import STEPControl_Reader
from OCP.TopAbs import TopAbs_SOLID, TopAbs_SHELL, TopAbs_FACE, TopAbs_COMPOUND
from OCP.TopExp import TopExp_Explorer
from OCP.BRepCheck import BRepCheck_Analyzer
from OCP.GProp import GProp_GProps
from OCP.BRepGProp import BRepGProp
from OCP.ShapeAnalysis import ShapeAnalysis_FreeBounds
from OCP.TopoDS import TopoDS
def vol(s):
p = GProp_GProps(); BRepGProp.VolumeProperties_s(s, p); return round(p.Mass(), 6)
KEYS = ["MANIFOLD_SOLID_BREP","BREP_WITH_VOIDS","CLOSED_SHELL","OPEN_SHELL","ORIENTED_CLOSED_SHELL","SHELL_BASED_SURFACE_MODEL","ADVANCED_FACE","SPHERICAL_SURFACE","CYLINDRICAL_SURFACE","PLANE","FACE_BOUND","FACE_OUTER_BOUND"]
for f in sys.argv[1:]:
t = open(f).read()
ents = collections.Counter(re.findall(r"=\s*([A-Z_0-9]+)\s*\(", t))
print("INSPECT", f.split("/")[-1], {k: ents[k] for k in KEYS if ents[k]})
rd = STEPControl_Reader(); rd.ReadFile(f); rd.TransferRoots(); s = rd.OneShape()
print(" OCCT shape type", s.ShapeType(), "valid", BRepCheck_Analyzer(s).IsValid(), "vol", vol(s))
for kind, nm in ((TopAbs_SOLID, "solid"), (TopAbs_SHELL, "shell")):
ex = TopExp_Explorer(s, kind); i = 0
while ex.More():
sh = ex.Current()
try:
fb = ShapeAnalysis_FreeBounds(sh)
nopen = fb.GetOpenWires().NbChildren() if hasattr(fb.GetOpenWires(), "NbChildren") else "?"
except Exception as e:
nopen = "err"
print(" ", nm, i, "vol", vol(sh), "valid", BRepCheck_Analyzer(sh).IsValid(), "freeOpenWires", nopen)
i += 1; ex.Next()

View file

@ -10,6 +10,7 @@ Measured at truck commit `88ed005249e5e3a6b07f62425399435905cd3ab6` (master, 202
Tags: [V] measured or read this pass; [S] stated by the repo's own docs only; [M] marketing claim.
Logs: `eyes-truck\jobs\job1.log` (truck's own tests), `job2.log` (first harness run, tol 0.05), `job4.log` (harness: 35 cases x tol 0.05/0.01/0.2, OCCT checks, truck reading OCCT STEP), `job5.log` (licences, wasm, determinism), `job6.log` (STEP entity census, case-25 stage timing, tolerance sweep). `jobs\analyze.py` digests job4.
Harness (mine, not truck's): `eyes-truck\harness\` = local git repo (`src\main.rs`, `check.py`, `cases.json` copied unchanged from the Aetheris harness, `job.sh`, `job5.sh`, `job6.sh`); depends on truck by git rev 88ed0052. Built `--release`.
Note: the raw probe harness (`harness/`) was retired from git while preserving all measured findings below.
## Q1 Shape

View file

@ -1,2 +0,0 @@
target
Cargo.lock

View file

@ -1,11 +0,0 @@
[package]
name = "trucktorture"
version = "0.0.0"
edition = "2021"
[dependencies]
truck-modeling = { git = "https://github.com/ricosjp/truck", rev = "88ed005249e5e3a6b07f62425399435905cd3ab6" }
truck-shapeops = { git = "https://github.com/ricosjp/truck", rev = "88ed005249e5e3a6b07f62425399435905cd3ab6" }
truck-meshalgo = { git = "https://github.com/ricosjp/truck", rev = "88ed005249e5e3a6b07f62425399435905cd3ab6" }
truck-stepio = { git = "https://github.com/ricosjp/truck", rev = "88ed005249e5e3a6b07f62425399435905cd3ab6" }
serde_json = "1"

File diff suppressed because it is too large Load diff

View file

@ -1,151 +0,0 @@
"""Independent checks of truck output with OpenCASCADE (cadquery-ocp) and plain-python OBJ analysis.
modes:
ref <cases.json> <outdir> OCCT reference boolean per case: volume + writes ref_NN.step
one <file.step> BRepCheck / counts / volume of one STEP (own process; OCCT may segfault)
obj <file.obj> watertightness and volume of an OBJ mesh
all <dir> run `one` per *.step and `obj` per *.obj in subprocesses
"""
import sys, json, subprocess, math, os, glob
def vol_of(shape):
from OCP.GProp import GProp_GProps
from OCP.BRepGProp import BRepGProp
p = GProp_GProps()
BRepGProp.VolumeProperties_s(shape, p)
return p.Mass()
def count(shape, kind):
from OCP.TopExp import TopExp_Explorer
e = TopExp_Explorer(shape, kind)
n = 0
while e.More():
n += 1
e.Next()
return n
def one(path):
from OCP.STEPControl import STEPControl_Reader
from OCP.IFSelect import IFSelect_RetDone
from OCP.BRepCheck import BRepCheck_Analyzer
from OCP.TopAbs import TopAbs_SOLID, TopAbs_SHELL, TopAbs_FACE
r = STEPControl_Reader()
st = r.ReadFile(path)
out = {"file": os.path.basename(path), "read_ok": st == IFSelect_RetDone}
if st != IFSelect_RetDone:
print("RES " + json.dumps(out)); return
nroots = r.TransferRoots()
s = r.OneShape()
out.update({"roots": nroots, "null": s.IsNull()})
if not s.IsNull():
out.update({"valid": BRepCheck_Analyzer(s).IsValid(), "solids": count(s, TopAbs_SOLID),
"shells": count(s, TopAbs_SHELL), "faces": count(s, TopAbs_FACE), "volume": vol_of(s)})
print("RES " + json.dumps(out))
def objcheck(path):
pts, tris = [], []
for line in open(path):
t = line.split()
if not t:
continue
if t[0] == "v":
pts.append((float(t[1]), float(t[2]), float(t[3])))
elif t[0] == "f":
idx = [int(x.split("/")[0]) - 1 for x in t[1:]]
for i in range(1, len(idx) - 1):
tris.append((idx[0], idx[i], idx[i + 1]))
key = {}
remap = []
for p in pts:
k = (round(p[0] / 1e-6), round(p[1] / 1e-6), round(p[2] / 1e-6))
remap.append(key.setdefault(k, len(key)))
edges = {}
vol = 0.0
degenerate = 0
for a, b, c in tris:
pa, pb, pc = pts[a], pts[b], pts[c]
vol += (pa[0] * (pb[1] * pc[2] - pb[2] * pc[1]) - pa[1] * (pb[0] * pc[2] - pb[2] * pc[0]) + pa[2] * (pb[0] * pc[1] - pb[1] * pc[0])) / 6.0
ra, rb, rc = remap[a], remap[b], remap[c]
if len({ra, rb, rc}) < 3:
degenerate += 1
continue
for u, v in ((ra, rb), (rb, rc), (rc, ra)):
edges[(u, v)] = edges.get((u, v), 0) + 1
unmatched = sum(1 for (u, v), n in edges.items() if edges.get((v, u), 0) != n)
multi = sum(1 for n in edges.values() if n > 1)
print("RES " + json.dumps({"file": os.path.basename(path), "tris": len(tris), "welded_vertices": len(key),
"degenerate_after_weld": degenerate, "unmatched_directed_edges": unmatched,
"multi_edges": multi, "watertight_oriented": unmatched == 0 and multi == 0,
"volume": vol}))
def build_ref(cases_path, outdir):
from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinder, BRepPrimAPI_MakeSphere, BRepPrimAPI_MakeTorus
from OCP.BRepAlgoAPI import BRepAlgoAPI_Fuse, BRepAlgoAPI_Cut, BRepAlgoAPI_Common
from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
from OCP.gp import gp_Trsf, gp_Ax1, gp_Ax2, gp_Pnt, gp_Dir, gp_Vec
from OCP.STEPControl import STEPControl_Writer, STEPControl_AsIs
from OCP.BRepCheck import BRepCheck_Analyzer
cases = json.load(open(cases_path))
o = gp_Pnt(0, 0, 0)
z = gp_Dir(0, 0, 1)
def prim(e):
d, k = e["d"], e["k"]
if k == "box":
s = BRepPrimAPI_MakeBox(gp_Pnt(-d[0] / 2, -d[1] / 2, -d[2] / 2), d[0], d[1], d[2]).Shape()
elif k == "cyl":
s = BRepPrimAPI_MakeCylinder(gp_Ax2(gp_Pnt(0, 0, -d[1] / 2), z), d[0], d[1]).Shape()
elif k == "sph":
s = BRepPrimAPI_MakeSphere(o, d[0]).Shape()
else:
s = BRepPrimAPI_MakeTorus(gp_Ax2(o, z), d[0], d[1]).Shape()
for axis, key in ((gp_Dir(1, 0, 0), "rx"), (gp_Dir(0, 1, 0), "ry")):
if e[key]:
t = gp_Trsf(); t.SetRotation(gp_Ax1(o, axis), math.radians(e[key]))
s = BRepBuilderAPI_Transform(s, t, True).Shape()
t = gp_Trsf(); t.SetTranslation(gp_Vec(*e["p"]))
return BRepBuilderAPI_Transform(s, t, True).Shape()
for i, c in enumerate(cases):
rec = {"case": c["name"], "idx": i, "exp": c["exp"]}
try:
cur = prim(c["a"])
for b in c["bs"]:
bb = prim(b)
alg = {"union": BRepAlgoAPI_Fuse, "subtract": BRepAlgoAPI_Cut, "intersect": BRepAlgoAPI_Common}[c["op"]](cur, bb)
cur = alg.Shape()
rec["occt_volume"] = vol_of(cur)
rec["occt_valid"] = BRepCheck_Analyzer(cur).IsValid()
w = STEPControl_Writer(); w.Transfer(cur, STEPControl_AsIs)
w.Write(os.path.join(outdir, "ref_%02d.step" % (i + 1)))
except Exception as ex:
rec["error"] = str(ex)[:200]
print("RES " + json.dumps(rec))
if __name__ == "__main__":
m = sys.argv[1]
if m == "one":
one(sys.argv[2])
elif m == "obj":
objcheck(sys.argv[2])
elif m == "ref":
build_ref(sys.argv[2], sys.argv[3])
elif m == "all":
for f in sorted(glob.glob(sys.argv[2] + "/*.step")) + sorted(glob.glob(sys.argv[2] + "/*.obj")):
if os.path.basename(f).startswith("ref_"):
continue
mode = "one" if f.endswith(".step") else "obj"
try:
r = subprocess.run([sys.executable, "-I", __file__, mode, f], capture_output=True, text=True, timeout=180)
lines = [l for l in r.stdout.splitlines() if l.startswith("RES ")]
if r.returncode != 0 or not lines:
print("RES " + json.dumps({"file": os.path.basename(f), "rc": r.returncode, "stderr_tail": r.stderr[-300:]}))
else:
print(lines[0])
except subprocess.TimeoutExpired:
print("RES " + json.dumps({"file": os.path.basename(f), "timeout": True}))

View file

@ -1,38 +0,0 @@
#!/usr/bin/env bash
# usage: job.sh <tol> (runs inside the stopgap rust container, cwd = repo root)
TOLS="${*:-0.05}"
set -u
OUT=/tmp/out; mkdir -p $OUT
echo "== build"
cargo build --release 2>&1 | tail -30
BIN=target/release/trucktorture
[ -x $BIN ] || { echo BUILD-FAILED; exit 1; }
echo "== prims"
$BIN prims 2>&1 | tail -8
N=$(grep -c '"name"' cases.json)
echo "cases=$N"
for TOL in $TOLS; do
echo "== cases tol=$TOL"
for i in $(seq 0 $((N-1))); do
s=$(date +%s.%N)
timeout ${CASE_TIMEOUT:-150} $BIN run cases.json $i $TOL $OUT > /tmp/case_$i.out 2> /tmp/case_$i.err
rc=$?
e=$(date +%s.%N)
echo "CASE idx=$i rc=$rc wall=$(echo "$e - $s" | bc 2>/dev/null || echo ?)"
grep -h '^RES' /tmp/case_$i.out | cut -c1-1500
if [ $rc -ne 0 ]; then echo "STDERR-TAIL idx=$i: $(tail -c 400 /tmp/case_$i.err | tr '\n' ' ')"; fi
done
done
echo "== python/ocp"
apt-get update -qq 2>&1 | tail -2
apt-get install -y -qq python3 python3-pip libgl1 libglu1-mesa libxrender1 2>&1 | tail -3
PY=python3
$PY -m pip install -q --break-system-packages cadquery-ocp 2>&1 | tail -3
$PY -c "import OCP; print('OCP ok')" 2>&1 | tail -2
echo "== ref (OCCT reference booleans)"
$PY check.py ref cases.json $OUT 2>&1 | cut -c1-400
echo "== check truck output (STEP via OCCT, OBJ independent)"
$PY check.py all $OUT 2>&1 | cut -c1-500
echo "== truck reads OCCT-written STEP"
for f in $OUT/ref_*.step; do timeout 120 $BIN readstep $f 2>&1 | grep -h '^RES' | cut -c1-500 || echo "READSTEP-FAIL $f"; done
echo "== done"

View file

@ -1,40 +0,0 @@
#!/usr/bin/env bash
# second probe batch: STEP entity census, determinism, tolerance sweep, licences, wasm
set -u
echo "== build"; cargo build --release 2>&1 | tail -2
BIN=target/release/trucktorture
OUT=/tmp/out5; mkdir -p $OUT
apt-get update -qq 2>&1 | tail -1; apt-get install -y -qq python3 2>&1 | tail -1
echo "== step census"
for spec in "25 0.2" "12 0.05" "29 0.05" "27 0.2"; do set -- $spec
timeout 150 $BIN run cases.json $1 $2 $OUT > /tmp/o.txt 2>/dev/null
f=$(ls $OUT/$(printf %02d $(($1+1)))_t$2.step 2>/dev/null)
echo "-- case idx=$1 tol=$2 file=$f"
[ -n "$f" ] && { grep -ho '^#[0-9]*= *[A-Z_0-9]*' $f | sed 's/#[0-9]*= *//' | sort | uniq -c | sort -rn | head -22 | tr '\n' ';'; echo; grep -m3 -n 'FILE_SCHEMA\|FILE_NAME\|MANIFOLD_SOLID_BREP\|CLOSED_SHELL' $f | cut -c1-120; }
done
echo "== determinism (3 runs each, tol 0.05)"
for idx in 10 12 25 27 29; do for r in 1 2 3; do
timeout 150 $BIN run cases.json $idx 0.05 $OUT 2>/dev/null | grep '^RES' | grep -o '"status":"[a-z_]*"\|"faces":[0-9]*\|"vol":[-0-9.e]*' | head -4 | tr '\n' ' '; echo " idx=$idx run=$r"
done; done
echo "== tolerance sweep"
for idx in 0 20 24 25 26 16; do for t in 0.5 0.1 0.02 0.005; do
/usr/bin/time -f "wall=%es rss=%MKB" timeout 200 $BIN run cases.json $idx $t $OUT > /tmp/o.txt 2> /tmp/e.txt
echo "idx=$idx tol=$t rc=$? $(grep '^RES' /tmp/o.txt | grep -o '"status":"[a-z_]*"\|"steps_done":[0-9]*\|"boolean_ms_total":[0-9.]*' | tr '\n' ' ') $(tail -1 /tmp/e.txt)"
done; done
echo "== licences (transitive deps of harness)"
cargo metadata --format-version 1 > /tmp/md.json 2>/dev/null
python3 -c "
import json,collections
d=json.load(open('/tmp/md.json'));c=collections.Counter();odd=[]
for p in d['packages']:
c[p.get('license') or 'NONE']+=1
if not p.get('license') or 'GPL' in (p.get('license') or '') or 'MPL' in (p.get('license') or ''): odd.append((p['name'],p.get('license')))
print('n_packages',len(d['packages']));print(c.most_common(12));print('odd',odd)
"
echo "== wasm build of truck-js"
rustup target add wasm32-unknown-unknown 2>&1 | tail -1
D=$(ls -d /usr/local/cargo/git/checkouts/truck-*/88ed005 | head -1); echo "checkout=$D"
cd $D && (time cargo build --release --target wasm32-unknown-unknown -p truck-js 2>&1 | tail -4)
ls -la target/wasm32-unknown-unknown/release/*.wasm 2>&1 | head -3
cd $D && grep -c "wasm_bindgen" truck-js/src/*.rs | tr '\n' ' '
echo "== done"

View file

@ -1,32 +0,0 @@
#!/usr/bin/env bash
# third probe batch: STEP entity census, case-25 stage timing, tolerance sweep
set -u
echo "== build"; cargo build --release 2>&1 | tail -2
BIN=target/release/trucktorture
OUT=/tmp/out6; mkdir -p $OUT
echo "== step census"
for spec in "25 0.2" "12 0.05" "29 0.05" "27 0.2" "10 0.05"; do
set -- $spec
timeout 150 $BIN run cases.json $1 $2 $OUT > /tmp/o.txt 2>/dev/null
f=$(ls $OUT/$(printf %02d $(($1+1)))_t$2.step 2>/dev/null)
echo "-- case idx=$1 tol=$2 file=$f"
if [ -n "$f" ]; then
grep -ho '^#[0-9]* *= *[A-Z_0-9]*' $f | sed 's/#[0-9]* *= *//' | sort | uniq -c | sort -rn | head -24 | tr '\n' ';'
echo
fi
done
echo "== case 25 stage timing x3"
for r in 1 2 3; do
timeout 200 $BIN run cases.json 24 0.05 $OUT 2>&1 >/dev/null | grep STAGE | tr '\n' ' '
echo " run=$r"
done
echo "== tolerance sweep"
for idx in 0 20 24 25 26 16; do
for t in 0.5 0.1 0.02 0.005; do
s0=$(date +%s%N)
timeout 200 $BIN run cases.json $idx $t $OUT > /tmp/o.txt 2> /tmp/e.txt
rc=$?
echo "idx=$idx tol=$t rc=$rc wall=$(( ($(date +%s%N)-s0)/1000000 ))ms $(grep '^RES' /tmp/o.txt | grep -o '"status":"[a-z_]*"\|"steps_done":[0-9]*\|"boolean_ms_total":[0-9.]*' | tr '\n' ' ')"
done
done
echo "== done"

View file

@ -1,263 +0,0 @@
// Torture harness for truck (ricosjp/truck), mirrors the Aetheris harness cases (cases.json).
use serde_json::{json, Value};
use std::f64::consts::PI;
use std::io::BufWriter;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Mutex;
use std::time::Instant;
use truck_meshalgo::prelude::*;
use truck_modeling::*;
use truck_stepio::out;
static PANIC: Mutex<String> = Mutex::new(String::new());
fn take_panic() -> String {
let mut g = PANIC.lock().unwrap();
let s = g.clone();
g.clear();
s.chars().take(300).collect()
}
fn box_(d: &[f64]) -> Solid {
let v = builder::vertex(Point3::origin());
let e = builder::tsweep(&v, Vector3::unit_x());
let f = builder::tsweep(&e, Vector3::unit_y());
let c: Solid = builder::tsweep(&f, Vector3::unit_z());
let c = builder::scaled(&c, Point3::origin(), Vector3::new(d[0], d[1], d[2]));
builder::translated(&c, Vector3::new(-d[0] / 2.0, -d[1] / 2.0, -d[2] / 2.0))
}
fn cyl(r: f64, h: f64) -> Solid {
let v = builder::vertex(Point3::new(r, 0.0, -h / 2.0));
let circle = builder::rsweep(&v, Point3::new(0.0, 0.0, -h / 2.0), Vector3::unit_z(), Rad(7.0), 2);
let disk = builder::try_attach_plane(&[circle]).unwrap();
builder::tsweep(&disk, Vector3::new(0.0, 0.0, h))
}
fn sph(r: f64) -> Solid {
let v0 = builder::vertex(Point3::new(0.0, r, 0.0));
let wire: Wire = builder::rsweep(&v0, Point3::origin(), Vector3::unit_x(), Rad(PI), 3);
let shell = builder::cone(&wire, Vector3::unit_y(), Rad(7.0), 4);
Solid::new(vec![shell])
}
fn tor(big: f64, small: f64) -> Solid {
let v = builder::vertex(Point3::new(big, 0.0, small));
let w = builder::rsweep(&v, Point3::new(big, 0.0, 0.0), Vector3::unit_y(), Rad(7.0), 2);
let shell = builder::rsweep(&w, Point3::origin(), Vector3::unit_z(), Rad(7.0), 2);
Solid::new(vec![shell])
}
fn mesh_of(s: &Solid, tol: f64) -> PolygonMesh {
let mut m = s.triangulation(tol).to_polygon();
m.put_together_same_attrs(TOLERANCE * 50.0).remove_degenerate_faces();
m
}
fn orient(mut s: Solid) -> Solid {
if mesh_of(&s, 0.05).volume() < 0.0 {
s.not();
}
s
}
fn nums(v: &Value) -> Vec<f64> {
v.as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect()
}
fn prim(e: &Value) -> Solid {
let d = nums(&e["d"]);
let s = match e["k"].as_str().unwrap() {
"box" => box_(&d),
"cyl" => cyl(d[0], d[1]),
"sph" => sph(d[0]),
"tor" => tor(d[0], d[1]),
k => panic!("kind {k}"),
};
let mut s = orient(s);
let rx = e["rx"].as_f64().unwrap();
let ry = e["ry"].as_f64().unwrap();
if rx != 0.0 {
s = builder::rotated(&s, Point3::origin(), Vector3::unit_x(), Rad(rx.to_radians()));
}
if ry != 0.0 {
s = builder::rotated(&s, Point3::origin(), Vector3::unit_y(), Rad(ry.to_radians()));
}
let p = nums(&e["p"]);
builder::translated(&s, Vector3::new(p[0], p[1], p[2]))
}
fn apply(op: &str, a: &Solid, b: &Solid, tol: f64) -> Option<Solid> {
match op {
"union" => truck_shapeops::or(a, b, tol),
"intersect" => truck_shapeops::and(a, b, tol),
"subtract" => {
let mut nb = b.clone();
nb.not();
truck_shapeops::and(a, &nb, tol)
}
o => panic!("op {o}"),
}
}
fn mesh_stats(s: &Solid, tol: f64, objpath: Option<&str>) -> Value {
let t = Instant::now();
let r = catch_unwind(AssertUnwindSafe(|| mesh_of(s, tol)));
let ms = t.elapsed().as_secs_f64() * 1e3;
match r {
Ok(m) => {
if let Some(p) = objpath {
let f = std::fs::File::create(p).unwrap();
let _ = truck_meshalgo::rexport_polymesh::obj::write(&m, BufWriter::new(f));
}
json!({"tol": tol, "ms": ms, "tris": m.faces().triangle_iter().count(), "faces": m.faces().len(),
"closed": format!("{:?}", m.shell_condition()), "vol": m.volume()})
}
Err(_) => json!({"tol": tol, "panic": take_panic()}),
}
}
fn step_string(s: &Solid) -> String {
let c = s.compress();
let repr = out::StepDesign::from_model(out::StepModel::from(&c));
out::StepDisplay::new(
out::StepHeaderDescriptor { organization_system: "trucktorture".to_owned(), ..Default::default() },
repr,
)
.to_string()
}
fn reread(text: &str) -> Value {
use truck_stepio::r#in::*;
let r = catch_unwind(AssertUnwindSafe(|| {
let table = Table::from_step(text).ok_or("parse failed")?;
let mut shells = vec![];
for (_, sh) in table.shell.iter() {
match table.to_compressed_shell(sh) {
Ok(cs) => {
let mut m = cs.triangulation(0.01).to_polygon();
m.put_together_same_attrs(TOLERANCE * 50.0).remove_degenerate_faces();
shells.push(json!({"closed": format!("{:?}", m.shell_condition()), "vol": m.volume(),
"tris": m.faces().triangle_iter().count()}));
}
Err(e) => shells.push(json!({"err": format!("{e:?}").chars().take(200).collect::<String>()})),
}
}
Ok::<_, &str>(json!({"shells": shells}))
}));
match r {
Ok(Ok(v)) => v,
Ok(Err(e)) => json!({"err": e}),
Err(_) => json!({"panic": take_panic()}),
}
}
fn run_case(cases: &Value, idx: usize, tol: f64, out_dir: &str) {
let c = &cases[idx];
let name = c["name"].as_str().unwrap();
let op = c["op"].as_str().unwrap();
let bs = c["bs"].as_array().unwrap();
let t0 = Instant::now();
let mut step_ms: Vec<f64> = vec![];
let r = catch_unwind(AssertUnwindSafe(|| {
let mut cur = prim(&c["a"]);
for b in bs {
let bb = prim(b);
let t = Instant::now();
let n = apply(op, &cur, &bb, tol);
step_ms.push(t.elapsed().as_secs_f64() * 1e3);
match n {
Some(n) => cur = n,
None => return None,
}
}
Some(cur)
}));
let total = t0.elapsed().as_secs_f64() * 1e3;
eprintln!("STAGE boolean done {:.0}ms", total);
let maxstep = step_ms.iter().cloned().fold(0.0, f64::max);
let mut res = json!({"case": name, "idx": idx, "tol": tol, "steps_done": step_ms.len(), "steps_total": bs.len(),
"boolean_ms_total": total, "boolean_ms_max_step": maxstep, "exp": c["exp"]});
match r {
Err(_) => {
res["status"] = json!("panic");
res["panic"] = json!(take_panic());
}
Ok(None) => res["status"] = json!("refused_none"),
Ok(Some(s)) => {
res["status"] = json!("ok");
res["shells"] = json!(s.boundaries().len());
res["faces"] = json!(s.boundaries().iter().map(|b| b.len()).sum::<usize>());
let tag = format!("{}/{:02}_t{}", out_dir, idx + 1, tol);
res["mesh"] = json!([
mesh_stats(&s, 0.1, None),
mesh_stats(&s, 0.01, Some(&format!("{tag}.obj"))),
mesh_stats(&s, 0.001, None)
]);
eprintln!("STAGE meshes done {:.0}ms", t0.elapsed().as_secs_f64() * 1e3);
let t = Instant::now();
let sr = catch_unwind(AssertUnwindSafe(|| step_string(&s)));
match sr {
Ok(text) => {
res["step_ms"] = json!(t.elapsed().as_secs_f64() * 1e3);
res["step_bytes"] = json!(text.len());
std::fs::write(format!("{tag}.step"), &text).unwrap();
eprintln!("STAGE step written {:.0}ms", t0.elapsed().as_secs_f64() * 1e3);
res["step_reread"] = reread(&text);
eprintln!("STAGE reread done {:.0}ms", t0.elapsed().as_secs_f64() * 1e3);
}
Err(_) => res["step_panic"] = json!(take_panic()),
}
}
}
println!("RES {}", res);
}
fn read_step(path: &str) {
let text = std::fs::read_to_string(path).unwrap();
let t = Instant::now();
let mut v = reread(&text);
v["file"] = json!(path);
v["ms"] = json!(t.elapsed().as_secs_f64() * 1e3);
println!("RES {}", v);
}
fn prims() {
for (n, s, exp) in [
("box 10x10x10", box_(&[10.0, 10.0, 10.0]), 1000.0),
("cyl r5 h10", cyl(5.0, 10.0), PI * 25.0 * 10.0),
("sph r5", sph(5.0), 4.0 / 3.0 * PI * 125.0),
("tor 10,3", tor(10.0, 3.0), 2.0 * PI * PI * 10.0 * 9.0),
] {
let raw = mesh_of(&s, 0.01).volume();
let o = orient(s.clone());
println!(
"RES {}",
json!({"prim": n, "analytic": exp, "mesh_vol_raw_orientation": raw,
"mesh_vol_after_orient": mesh_of(&o, 0.01).volume()})
);
}
}
fn main() {
std::panic::set_hook(Box::new(|i| {
let bt = std::backtrace::Backtrace::force_capture().to_string();
let frames: Vec<String> = bt
.lines()
.filter(|l| l.contains("truck_") && !l.trim_start().starts_with("at "))
.map(|l| l.trim().chars().take(70).collect::<String>())
.take(6)
.collect();
*PANIC.lock().unwrap() = format!("{i}").replace('\n', " | ") + " || " + &frames.join(" ; ");
}));
let a: Vec<String> = std::env::args().collect();
match a[1].as_str() {
"run" => {
let cases: Value = serde_json::from_str(&std::fs::read_to_string(&a[2]).unwrap()).unwrap();
run_case(&cases, a[3].parse().unwrap(), a[4].parse().unwrap(), &a[5]);
}
"readstep" => read_step(&a[2]),
"prims" => prims(),
_ => panic!("mode"),
}
}

View file

@ -1,593 +0,0 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
const int WarmupIterations = 8;
const int MeasureIterations = 64;
var debugNative = args.Any(arg => arg == "--debug-native");
var healthOnly = args.Any(arg => arg == "--health");
var outputArg = args.FirstOrDefault(arg => arg != "--debug-native" && arg != "--health");
var output = outputArg is not null
? outputArg
: Path.GetFullPath(Path.Combine("experiments", "generated", "realtimecsg-cpp-perf-latest.jsonl"));
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
Native.RegisterNoopUnityMethods();
if (healthOnly)
{
using var healthWriter = new StreamWriter(output, false);
healthWriter.WriteLine(RunHealthProbe());
return;
}
var cases = new PerfCase[]
{
new("single_center_cut", 2, SingleCenterCut),
new("room_grid_8x8_doors", 192, RoomGrid8x8Doors),
new("rotated_cut_stack_64", 65, RotatedCutStack64),
new("common_box_chain_64", 64, CommonBoxChain64),
new("distant_cutters_512", 513, DistantCutters512),
};
using var writer = new StreamWriter(output, false);
foreach (var perfCase in cases)
{
writer.WriteLine(RunCase(perfCase));
}
string RunCase(PerfCase perfCase)
{
var timings = new List<long>(MeasureIterations);
var triangles = 0;
var vertices = 0;
var meshDescriptions = 0;
Native.ClearAllNodes();
var tree = perfCase.Build();
if (tree == 0)
throw new InvalidOperationException($"Failed to build native RealtimeCSG tree for {perfCase.Name}");
Native.RebuildAll();
if (debugNative)
DumpTree(perfCase.Name, tree);
if (Native.GetBrushCount() != perfCase.Brushes)
throw new InvalidOperationException($"Native brush count mismatch for {perfCase.Name}: expected {perfCase.Brushes}, got {Native.GetBrushCount()}, nodes={Native.GetNodeCount()}, trees={Native.GetTreeCount()}, brushMeshes={Native.GetBrushMeshCount()}");
for (var i = 0; i < WarmupIterations; i++)
MeasureOnce(tree, out triangles, out vertices, out meshDescriptions);
if (meshDescriptions == 0)
{
DumpTree(perfCase.Name, tree);
throw new InvalidOperationException($"Native generated no mesh descriptions for {perfCase.Name}: nodes={Native.GetNodeCount()}, brushes={Native.GetBrushCount()}, trees={Native.GetTreeCount()}, brushMeshes={Native.GetBrushMeshCount()}, treeBrushes={Native.GetNumberOfBrushesInTree(tree)}, treeChildren={Native.GetChildNodeCount(tree)}, treeDirty={Native.IsNodeDirty(tree)}");
}
for (var i = 0; i < MeasureIterations; i++)
{
var stopwatch = Stopwatch.StartNew();
MeasureOnce(tree, out triangles, out vertices, out meshDescriptions);
stopwatch.Stop();
timings.Add(stopwatch.ElapsedTicks);
}
Native.ClearAllNodes();
timings.Sort();
var mean = timings.Sum() / timings.Count;
return
$"{{\"kernel\":\"realtime_csg_cpp\",\"scenario\":\"{perfCase.Name}\",\"brushes\":{perfCase.Brushes},\"iterations\":{MeasureIterations},\"warmup_iterations\":{WarmupIterations},\"mean_ns\":{TicksToNs(mean)},\"min_ns\":{TicksToNs(timings[0])},\"p50_ns\":{TicksToNs(timings[(timings.Count - 1) * 50 / 100])},\"p95_ns\":{TicksToNs(timings[(timings.Count - 1) * 95 / 100])},\"max_ns\":{TicksToNs(timings[^1])},\"triangles\":{triangles},\"vertices\":{vertices},\"mesh_descriptions\":{meshDescriptions}}}";
}
static string RunHealthProbe()
{
Native.ClearAllNodes();
var tree = TreeFrom(() => new[]
{
Brush("native_health_cube", Vec3.Zero, Vec3.Splat(4), Mat4.Identity, Operation.Additive),
});
Native.RebuildAll();
var updateOk = Native.UpdateAllTreeMeshes();
var child = Native.GetChildNodeAtIndex(tree, 0);
var bounds = new Aabb();
var boundsOk = Native.GetBrushBounds(child, ref bounds);
var outlineOk = Native.GetBrushOutlineSizes(child, out var outlineVertices, out var visibleOuter, out var visibleInner, out var invisibleOuter, out var invisibleInner, out var invalid);
var rayStart = new Vec3(-8, 0, 0);
var rayEnd = new Vec3(8, 0, 0);
var matrix = Mat4.Identity;
var rayHits = Native.RayCastIntoTreeMultiCount(tree, ref rayStart, ref rayEnd, ref matrix, 0, false, IntPtr.Zero, 0);
var meshTypes = MeshQuery.RenderOnlyTypes;
var meshTypesHandle = GCHandle.Alloc(meshTypes, GCHandleType.Pinned);
var generated = Native.GenerateMeshDescriptions(tree, meshTypes.Length, meshTypesHandle.AddrOfPinnedObject(), VertexChannelFlags.All, out var meshDescriptions);
meshTypesHandle.Free();
var heartbeat = updateOk && Native.GetTreeEnabled(tree) && Native.GetChildNodeCount(tree) == 1 && boundsOk && outlineOk && rayHits > 0;
var meshExtractionReady = generated && meshDescriptions > 0;
var json =
$"{{\"kernel\":\"realtime_csg_cpp\",\"scenario\":\"native_health_cube\",\"heartbeat\":{JsonBool(heartbeat)},\"mesh_extraction_ready\":{JsonBool(meshExtractionReady)},\"update_ok\":{JsonBool(updateOk)},\"tree\":{tree},\"tree_enabled\":{JsonBool(Native.GetTreeEnabled(tree))},\"nodes\":{Native.GetNodeCount()},\"brushes\":{Native.GetBrushCount()},\"trees\":{Native.GetTreeCount()},\"brush_meshes\":{Native.GetBrushMeshCount()},\"tree_children\":{Native.GetChildNodeCount(tree)},\"tree_brushes\":{Native.GetNumberOfBrushesInTree(tree)},\"tree_dirty\":{JsonBool(Native.IsNodeDirty(tree))},\"child_type\":{Native.GetTypeOfNode(child)},\"child_tree\":{Native.GetTreeOfNode(child)},\"child_mesh\":{Native.GetBrushMeshID(child)},\"child_operation\":{Native.GetBrushOperationType(child)},\"bounds_ok\":{JsonBool(boundsOk)},\"bounds_min\":[{bounds.MinX},{bounds.MinY},{bounds.MinZ}],\"bounds_max\":[{bounds.MaxX},{bounds.MaxY},{bounds.MaxZ}],\"outline_ok\":{JsonBool(outlineOk)},\"outline_vertices\":{outlineVertices},\"visible_outer_lines\":{visibleOuter},\"visible_inner_lines\":{visibleInner},\"invisible_outer_lines\":{invisibleOuter},\"invisible_inner_lines\":{invisibleInner},\"invalid_lines\":{invalid},\"raycast_hits\":{rayHits},\"mesh_descriptions_generated\":{JsonBool(generated)},\"mesh_descriptions\":{meshDescriptions}}}";
Native.ClearAllNodes();
return json;
}
static void DumpTree(string name, int tree)
{
Native.RebuildAll();
var updated = Native.UpdateAllTreeMeshes();
Console.Error.WriteLine($"native debug {name}: updated={updated} tree={tree} type={Native.GetTypeOfNode(tree)} enabled={Native.GetTreeEnabled(tree)} children={Native.GetChildNodeCount(tree)} dirty={Native.IsNodeDirty(tree)} nodes={Native.GetNodeCount()} brushes={Native.GetBrushCount()} trees={Native.GetTreeCount()} brushMeshes={Native.GetBrushMeshCount()}");
for (var i = 0; i < Native.GetChildNodeCount(tree); i++)
{
var child = Native.GetChildNodeAtIndex(tree, i);
var bounds = new Aabb();
var boundsOk = Native.GetBrushBounds(child, ref bounds);
var outlineOk = Native.GetBrushOutlineSizes(child, out var outlineVertices, out var visibleOuter, out var visibleInner, out var invisibleOuter, out var invisibleInner, out var invalid);
Console.Error.WriteLine($" child[{i}] id={child} type={Native.GetTypeOfNode(child)} tree={Native.GetTreeOfNode(child)} mesh={Native.GetBrushMeshID(child)} op={Native.GetBrushOperationType(child)} dirty={Native.IsNodeDirty(child)} boundsOk={boundsOk} bounds=({bounds.MinX},{bounds.MinY},{bounds.MinZ})..({bounds.MaxX},{bounds.MaxY},{bounds.MaxZ}) outlineOk={outlineOk} outlineVertices={outlineVertices} visibleOuter={visibleOuter} visibleInner={visibleInner} invisibleOuter={invisibleOuter} invisibleInner={invisibleInner} invalid={invalid}");
}
var rayStart = new Vec3(-8, 0, 0);
var rayEnd = new Vec3(8, 0, 0);
var matrix = Mat4.Identity;
var rayHits = Native.RayCastIntoTreeMultiCount(tree, ref rayStart, ref rayEnd, ref matrix, 0, false, IntPtr.Zero, 0);
Console.Error.WriteLine($" raycast hits={rayHits}");
ProbeGeneratedMesh(tree);
}
static void ProbeGeneratedMesh(int tree)
{
var indices = new int[8192];
var positions = new Vec3[8192];
var indexHandle = GCHandle.Alloc(indices, GCHandleType.Pinned);
var positionHandle = GCHandle.Alloc(positions, GCHandleType.Pinned);
var ok = Native.GetGeneratedMesh(tree, 0, 0, indices.Length, indexHandle.AddrOfPinnedObject(), positions.Length, positionHandle.AddrOfPinnedObject(), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, out var center, out var size);
positionHandle.Free();
indexHandle.Free();
Console.Error.WriteLine($" direct mesh probe ok={ok} boundsCenter=({center.X},{center.Y},{center.Z}) boundsSize=({size.X},{size.Y},{size.Z}) firstIndex={indices[0]} firstPos=({positions[0].X},{positions[0].Y},{positions[0].Z})");
}
static long TicksToNs(long ticks) => (long)(ticks * (1_000_000_000.0 / Stopwatch.Frequency));
static string JsonBool(bool value) => value ? "true" : "false";
static void MeasureOnce(int tree, out int triangles, out int vertices, out int meshDescriptions)
{
Native.UpdateAllTreeMeshes();
var meshTypes = MeshQuery.RenderOnlyTypes;
var meshTypesHandle = GCHandle.Alloc(meshTypes, GCHandleType.Pinned);
var generated = Native.GenerateMeshDescriptions(tree, meshTypes.Length, meshTypesHandle.AddrOfPinnedObject(), VertexChannelFlags.All, out meshDescriptions);
if (!generated || meshDescriptions == 0)
{
meshTypesHandle.Free();
triangles = 0;
vertices = 0;
return;
}
meshTypesHandle.Free();
var descriptions = new GeneratedMeshDescription[meshDescriptions];
var descriptionsHandle = GCHandle.Alloc(descriptions, GCHandleType.Pinned);
var ok = Native.GetMeshDescriptions(tree, meshDescriptions, descriptionsHandle.AddrOfPinnedObject());
descriptionsHandle.Free();
if (!ok)
{
triangles = 0;
vertices = 0;
return;
}
triangles = 0;
vertices = 0;
foreach (var description in descriptions)
{
if (description.VertexCount <= 0 || description.IndexCount <= 0)
continue;
var indices = new int[description.IndexCount];
var positions = new Vec3[description.VertexCount];
var indexHandle = GCHandle.Alloc(indices, GCHandleType.Pinned);
var positionHandle = GCHandle.Alloc(positions, GCHandleType.Pinned);
ok = Native.GetGeneratedMesh(
tree,
description.MeshQueryIndex,
description.SubMeshQueryIndex,
description.IndexCount,
indexHandle.AddrOfPinnedObject(),
description.VertexCount,
positionHandle.AddrOfPinnedObject(),
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
out _,
out _);
positionHandle.Free();
indexHandle.Free();
if (ok)
{
triangles += description.IndexCount / 3;
vertices += description.VertexCount;
}
}
}
static int SingleCenterCut()
{
return TreeFrom(() => new[]
{
Brush("source", Vec3.Zero, Vec3.Splat(4), Mat4.Identity, Operation.Additive),
Brush("void", Vec3.Zero, Vec3.Splat(2), Mat4.Identity, Operation.Subtractive),
});
}
static int RoomGrid8x8Doors()
{
var nodes = new List<int>();
const float cell = 6.0f;
for (var y = 0; y < 8; y++)
for (var x = 0; x < 8; x++)
{
var center = new Vec3((x - 3.5f) * cell, (y - 3.5f) * cell, 0);
nodes.Add(Brush("floor", center + new Vec3(0, 0, -0.1f), new Vec3(5.6f, 5.6f, 0.2f), Mat4.Identity, Operation.Additive));
nodes.Add(Brush("north_wall", center + new Vec3(0, 2.8f, 1.5f), new Vec3(5.6f, 0.25f, 3.0f), Mat4.Identity, Operation.Additive));
nodes.Add(Brush("door", center + new Vec3(0, 2.8f, 1.0f), new Vec3(1.2f, 0.5f, 2.0f), Mat4.Identity, Operation.Subtractive));
}
return Tree(nodes.ToArray());
}
static int RotatedCutStack64()
{
var nodes = new List<int> { Brush("slab", Vec3.Zero, new Vec3(32, 32, 4), Mat4.Identity, Operation.Additive) };
for (var index = 0; index < 64; index++)
{
var angle = index * 0.173f;
var radius = 11.0f + (index % 7) * 0.35f;
var center = new Vec3(MathF.Cos(angle) * radius, MathF.Sin(angle) * radius, 0);
nodes.Add(Brush("rotated_void", center, new Vec3(1.0f + (index % 3) * 0.3f, 8.0f, 5.0f), Mat4.RotationZ(angle), Operation.Subtractive));
}
return Tree(nodes.ToArray());
}
static int CommonBoxChain64()
{
var nodes = new List<int> { Brush("source", Vec3.Zero, new Vec3(32, 16, 8), Mat4.Identity, Operation.Additive) };
for (var index = 1; index < 64; index++)
{
var t = index / 63.0f;
var center = new Vec3((t - 0.5f) * 6.0f, MathF.Sin(t * MathF.Tau) * 1.5f, 0);
nodes.Add(Brush("common", center, new Vec3(30.0f - t * 8.0f, 14.0f, 7.0f), Mat4.RotationZ(t * 0.2f), Operation.Intersecting));
}
return Tree(nodes.ToArray());
}
static int DistantCutters512()
{
var nodes = new List<int> { Brush("source", Vec3.Zero, Vec3.Splat(8), Mat4.Identity, Operation.Additive) };
for (var index = 0; index < 512; index++)
{
var row = index / 32;
var col = index % 32;
nodes.Add(Brush("far_void", new Vec3(1000.0f + col * 4.0f, 1000.0f + row * 4.0f, 0), Vec3.Splat(1), Mat4.Identity, Operation.Subtractive));
}
return Tree(nodes.ToArray());
}
static int Tree(params int[] children)
{
return TreeFrom(() => children);
}
static int TreeFrom(Func<int[]> buildChildren)
{
var children = buildChildren();
if (!Native.GenerateTree(0, out var tree))
return 0;
if (!Native.SetTreeEnabled(tree, true) || !Native.GetTreeEnabled(tree))
throw new InvalidOperationException($"SetTreeEnabled failed for tree {tree}");
if (!InsertChildNodes(tree, children))
throw new InvalidOperationException($"InsertChildNodes failed for tree {tree} with {children.Length} children");
foreach (var child in children)
Native.SetDirty(child);
Native.SetDirty(tree);
return tree;
}
static int Brush(string name, Vec3 center, Vec3 size, Mat4 rotation, Operation operation)
{
var mesh = Cube(size);
var meshId = CreateBrushMesh(mesh, name.GetHashCode());
if (meshId == 0 || !Native.GenerateBrush(name.GetHashCode(), out var brush))
throw new InvalidOperationException($"Failed to create brush {name}: meshId={meshId}");
if (!Native.IsBrushMeshIDValid(meshId))
throw new InvalidOperationException($"Native rejected brush mesh {name}/{meshId}");
var transform = rotation.WithTranslation(center);
if (!Native.SetNodeLocalTransformation(brush, ref transform))
throw new InvalidOperationException($"SetNodeLocalTransformation failed for brush {name}/{brush}");
if (!Native.SetBrushMeshID(brush, meshId))
throw new InvalidOperationException($"SetBrushMeshID failed for brush {name}/{brush}, mesh={meshId}");
if (operation != Operation.Additive && !Native.SetBrushOperationType(brush, operation))
throw new InvalidOperationException($"SetBrushOperationType failed for brush {name}/{brush}, op={operation}");
if (Native.GetBrushMeshID(brush) != meshId)
throw new InvalidOperationException($"Brush {name}/{brush} did not retain mesh id {meshId}");
Native.SetDirty(brush);
return brush;
}
static bool InsertChildNodes(int node, int[] children)
{
var handle = GCHandle.Alloc(children, GCHandleType.Pinned);
var ok = Native.InsertChildNodeRange(node, 0, children.Length, handle.AddrOfPinnedObject());
handle.Free();
return ok;
}
static int CreateBrushMesh(BrushMesh mesh, int userId)
{
var vh = GCHandle.Alloc(mesh.Vertices, GCHandleType.Pinned);
var eh = GCHandle.Alloc(mesh.HalfEdges, GCHandleType.Pinned);
var ph = GCHandle.Alloc(mesh.Polygons, GCHandleType.Pinned);
var id = Native.CreateBrushMesh(userId, mesh.Vertices.Length, vh.AddrOfPinnedObject(), mesh.HalfEdges.Length, eh.AddrOfPinnedObject(), mesh.Polygons.Length, ph.AddrOfPinnedObject());
ph.Free();
eh.Free();
vh.Free();
return id;
}
static BrushMesh Cube(Vec3 size)
{
var min = size * -0.5f;
var max = size * 0.5f;
var layers = new SurfaceLayers { LayerUsage = LayerUsageFlags.RenderReceiveCastShadows | LayerUsageFlags.Collidable };
var surfaces = new[]
{
new SurfaceDescription { UV0 = new UvMatrix(new Vec4(-1, 0, 0, -min.X), new Vec4(0, 1, 0, min.Y)) },
new SurfaceDescription { UV0 = new UvMatrix(new Vec4( 1, 0, 0, min.X), new Vec4(0, 1, 0, min.Y)) },
new SurfaceDescription { UV0 = new UvMatrix(new Vec4( 0, 0, 1, min.Z), new Vec4(0, 1, 0, min.Y)) },
new SurfaceDescription { UV0 = new UvMatrix(new Vec4( 0, 0, -1, -min.Z), new Vec4(0, 1, 0, min.Y)) },
new SurfaceDescription { UV0 = new UvMatrix(new Vec4(-1, 0, 0, -min.X), new Vec4(0, 0, -1, -min.Z)) },
new SurfaceDescription { UV0 = new UvMatrix(new Vec4( 1, 0, 0, min.X), new Vec4(0, 0, -1, -min.Z)) },
};
return new BrushMesh(
new[]
{
new Vec3(min.X, min.Y, min.Z), new Vec3(min.X, max.Y, min.Z),
new Vec3(max.X, max.Y, min.Z), new Vec3(max.X, min.Y, min.Z),
new Vec3(min.X, min.Y, max.Z), new Vec3(max.X, min.Y, max.Z),
new Vec3(max.X, max.Y, max.Z), new Vec3(min.X, max.Y, max.Z),
},
new[]
{
new HalfEdge(0,17), new HalfEdge(1,8), new HalfEdge(2,20), new HalfEdge(3,13),
new HalfEdge(4,10), new HalfEdge(5,19), new HalfEdge(6,15), new HalfEdge(7,22),
new HalfEdge(0,1), new HalfEdge(4,16), new HalfEdge(7,4), new HalfEdge(1,21),
new HalfEdge(3,18), new HalfEdge(2,3), new HalfEdge(6,23), new HalfEdge(5,6),
new HalfEdge(0,9), new HalfEdge(3,0), new HalfEdge(5,12), new HalfEdge(4,5),
new HalfEdge(1,2), new HalfEdge(7,11), new HalfEdge(6,7), new HalfEdge(2,14),
},
new[]
{
new Polygon(0,4,0,surfaces[0],layers), new Polygon(4,4,1,surfaces[1],layers),
new Polygon(8,4,2,surfaces[2],layers), new Polygon(12,4,3,surfaces[3],layers),
new Polygon(16,4,4,surfaces[4],layers), new Polygon(20,4,5,surfaces[5],layers),
});
}
record PerfCase(string Name, int Brushes, Func<int> Build);
record BrushMesh(Vec3[] Vertices, HalfEdge[] HalfEdges, Polygon[] Polygons);
enum Operation : byte { Additive = 0, Subtractive = 1, Intersecting = 2 }
enum BrushFlags : int { Default = 0, Infinite = 1 }
enum VertexChannelFlags : byte { Position = 0, Tangent = 2, Normal = 4, UV0 = 8, All = 14 }
enum LayerUsageFlags : int
{
None = 0,
Renderable = 1,
CastShadows = 2,
ReceiveShadows = 4,
RenderCastShadows = Renderable | CastShadows,
RenderReceiveShadows = Renderable | ReceiveShadows,
RenderReceiveCastShadows = Renderable | CastShadows | ReceiveShadows,
Collidable = 8,
Culled = 1 << 23,
}
enum LayerParameterIndex : byte { None = 0, LayerParameter1 = 1, LayerParameter2 = 2, LayerParameter3 = 3 }
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct Vec2 { public float X, Y; }
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct Vec3(float x, float y, float z)
{
public float X = x;
public float Y = y;
public float Z = z;
public static Vec3 Zero => new(0, 0, 0);
public static Vec3 Splat(float value) => new(value, value, value);
public static Vec3 operator +(Vec3 a, Vec3 b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
public static Vec3 operator *(Vec3 a, float s) => new(a.X * s, a.Y * s, a.Z * s);
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct Vec4(float x, float y, float z, float w) { public float X = x, Y = y, Z = z, W = w; }
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct Mat4
{
public float M00, M10, M20, M30;
public float M01, M11, M21, M31;
public float M02, M12, M22, M32;
public float M03, M13, M23, M33;
public static Mat4 Identity => new() { M00 = 1, M11 = 1, M22 = 1, M33 = 1 };
public static Mat4 RotationZ(float radians)
{
var c = MathF.Cos(radians);
var s = MathF.Sin(radians);
return new Mat4 { M00 = c, M10 = s, M01 = -s, M11 = c, M22 = 1, M33 = 1 };
}
public Mat4 WithTranslation(Vec3 t)
{
var m = this;
m.M03 = t.X; m.M13 = t.Y; m.M23 = t.Z; m.M33 = 1;
return m;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct UvMatrix(Vec4 u, Vec4 v) { public Vec4 U = u; public Vec4 V = v; }
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct SurfaceDescription
{
public uint SmoothingGroup;
public int SurfaceFlags;
public UvMatrix UV0;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct SurfaceLayers
{
public LayerUsageFlags LayerUsage;
public int LayerParameter1;
public int LayerParameter2;
public int LayerParameter3;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct Aabb
{
public float MinX, MaxX;
public float MinY, MaxY;
public float MinZ, MaxZ;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct Polygon(int firstEdge, int edgeCount, int polygonId, SurfaceDescription surface, SurfaceLayers layers)
{
public int FirstEdge = firstEdge;
public int EdgeCount = edgeCount;
public int PolygonId = polygonId;
public SurfaceDescription Surface = surface;
public SurfaceLayers Layers = layers;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct HalfEdge(int vertexIndex, int twinIndex)
{
public int VertexIndex = vertexIndex;
public int TwinIndex = twinIndex;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct MeshQuery
{
const int BitShift = 24;
public uint Layers;
public uint MaskAndChannels;
public static MeshQuery RenderableAll => new(LayerUsageFlags.Renderable, LayerUsageFlags.RenderReceiveCastShadows, LayerParameterIndex.LayerParameter1, VertexChannelFlags.All);
public static MeshQuery[] SimpleTypes => new[]
{
new MeshQuery(LayerUsageFlags.Renderable, LayerUsageFlags.Renderable, LayerParameterIndex.None, VertexChannelFlags.Position),
new MeshQuery(LayerUsageFlags.RenderReceiveCastShadows, LayerUsageFlags.RenderReceiveCastShadows, LayerParameterIndex.None, VertexChannelFlags.Position),
new MeshQuery(LayerUsageFlags.Renderable, LayerUsageFlags.RenderReceiveCastShadows, LayerParameterIndex.None, VertexChannelFlags.All),
new MeshQuery(LayerUsageFlags.RenderReceiveCastShadows, LayerUsageFlags.RenderReceiveCastShadows, LayerParameterIndex.LayerParameter1, VertexChannelFlags.All),
new MeshQuery(LayerUsageFlags.None, LayerUsageFlags.None, LayerParameterIndex.None, VertexChannelFlags.Position),
new MeshQuery(LayerUsageFlags.Culled, LayerUsageFlags.Culled, LayerParameterIndex.None, VertexChannelFlags.Position),
};
public static MeshQuery[] RenderOnlyTypes => new[]
{
new MeshQuery(LayerUsageFlags.CastShadows, LayerUsageFlags.RenderCastShadows, LayerParameterIndex.LayerParameter1, VertexChannelFlags.All),
new MeshQuery(LayerUsageFlags.Renderable, LayerUsageFlags.RenderReceiveCastShadows, LayerParameterIndex.LayerParameter1, VertexChannelFlags.All),
new MeshQuery(LayerUsageFlags.RenderCastShadows, LayerUsageFlags.RenderReceiveCastShadows, LayerParameterIndex.LayerParameter1, VertexChannelFlags.All),
new MeshQuery(LayerUsageFlags.RenderReceiveShadows, LayerUsageFlags.RenderReceiveCastShadows, LayerParameterIndex.LayerParameter1, VertexChannelFlags.All),
new MeshQuery(LayerUsageFlags.RenderReceiveCastShadows, LayerUsageFlags.RenderReceiveCastShadows, LayerParameterIndex.LayerParameter1, VertexChannelFlags.All),
new MeshQuery(LayerUsageFlags.None, LayerUsageFlags.Renderable, LayerParameterIndex.None, VertexChannelFlags.Position),
new MeshQuery(LayerUsageFlags.CastShadows, LayerUsageFlags.None, LayerParameterIndex.None, VertexChannelFlags.Position),
new MeshQuery(LayerUsageFlags.ReceiveShadows, LayerUsageFlags.None, LayerParameterIndex.None, VertexChannelFlags.Position),
new MeshQuery(LayerUsageFlags.Culled, LayerUsageFlags.None, LayerParameterIndex.None, VertexChannelFlags.Position),
};
public MeshQuery(LayerUsageFlags query, LayerUsageFlags mask, LayerParameterIndex parameterIndex, VertexChannelFlags vertexChannels)
{
if (mask == LayerUsageFlags.None)
mask = query;
Layers = (uint)query;
Layers |= (uint)parameterIndex << BitShift;
MaskAndChannels = (uint)mask | ((uint)vertexChannels << BitShift);
}
public int UsedVertexChannels => (int)(MaskAndChannels >> BitShift);
}
[StructLayout(LayoutKind.Sequential, Pack = 8)]
struct GeneratedMeshDescription
{
public MeshQuery MeshQuery;
public int SurfaceParameter;
public int MeshQueryIndex;
public int SubMeshQueryIndex;
public long GeometryHashValue;
public long SurfaceHashValue;
public int VertexCount;
public int IndexCount;
}
static partial class Native
{
const string Dll = "RealtimeCSG[1_559]";
static readonly StringLog Log = (message, userId) => Console.Error.WriteLine($"native[{userId}]: {message}");
static readonly ReturnString NameForUserId = _ => "<native-bridge>";
public static void RegisterNoopUnityMethods()
{
var methods = new UnityMethods
{
DebugLog = Log,
DebugLogError = Log,
DebugLogWarning = Log,
NameForUserID = NameForUserId,
};
RegisterMethods(ref methods);
}
public delegate void StringLog([MarshalAs(UnmanagedType.LPStr)] string text, int uniqueObjectID);
[return: MarshalAs(UnmanagedType.LPStr)]
public delegate string ReturnString(int uniqueObjectID);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 4)]
struct UnityMethods
{
public StringLog DebugLog;
public StringLog DebugLogError;
public StringLog DebugLogWarning;
public ReturnString NameForUserID;
}
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] static extern void RegisterMethods(ref UnityMethods unityMethods);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern void ClearAllNodes();
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool UpdateAllTreeMeshes();
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern void RebuildAll();
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetNodeCount();
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetBrushCount();
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetTreeCount();
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetBrushMeshCount();
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GenerateTree(int userID, out int generatedTreeNodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetNumberOfBrushesInTree(int nodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetDirty(int nodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool ClearDirty(int nodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool IsNodeDirty(int nodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetChildNodeCount(int nodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetChildNodeAtIndex(int nodeID, int index);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetTreeOfNode(int nodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern byte GetTypeOfNode(int nodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetTreeEnabled(int modelNodeID, bool isEnabled);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetTreeEnabled(int modelNodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GenerateBrush(int userID, out int generatedNodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GenerateBranch(int userID, out int generatedOperationNodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetBranchOperationType(int branchNodeID, Operation operation);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetBrushOperationType(int brushNodeID, Operation operation);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetBrushFlags(int brushNodeID, BrushFlags flags);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetBrushOperationType(int brushNodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetBrushMeshID(int brushNodeID, int brushMeshID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int GetBrushMeshID(int brushNodeID);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetBrushBounds(int brushNodeID, ref Aabb bounds);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetBrushOutlineSizes(int brushNodeID, out int vertexCount, out int visibleOuterLineCount, out int visibleInnerLineCount, out int invisibleOuterLineCount, out int invisibleInnerLineCount, out int invalidLineCount);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetNodeLocalTransformation(int brushNodeID, ref Mat4 brushToTreeSpace);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool SetChildNodes(int nodeID, int childCount, IntPtr childrenNodeIDs);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool InsertChildNodeRange(int nodeID, int index, int childCount, IntPtr childrenNodeIDs);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int CreateBrushMesh(int userID, int vertexCount, IntPtr vertices, int halfEdgeCount, IntPtr halfEdges, int polygonCount, IntPtr polygons);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool UpdateBrushMesh(int brushMeshIndex, int vertexCount, IntPtr vertices, int halfEdgeCount, IntPtr halfEdges, int polygonCount, IntPtr polygons);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool IsBrushMeshIDValid(int brushMeshIndex);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GenerateMeshDescriptions(int treeNodeID, int meshTypeCount, IntPtr meshTypes, VertexChannelFlags vertexChannelMask, out int meshDescriptionCount);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetMeshDescriptions(int treeNodeID, int meshDescriptionCount, IntPtr meshDescriptions);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetGeneratedMesh(int treeNodeID, int meshIndex, int subMeshIndex, int indexCount, IntPtr indices, int vertexCount, IntPtr positions, IntPtr tangents, IntPtr normals, IntPtr uvs, out Vec3 boundsCenter, out Vec3 boundsSize);
[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)] public static extern int RayCastIntoTreeMultiCount(int modelNodeID, ref Vec3 worldRayStart, ref Vec3 worldRayEnd, ref Mat4 modelLocalToWorldMatrix, int inFilterLayerParameter0, bool ignoreInvisiblePolygons, IntPtr ignoreNodeIds, int ignoreNodeIdCount);
}

View file

@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>RealtimeCsgNativeBridge</AssemblyName>
</PropertyGroup>
</Project>

View file

@ -1,7 +1,6 @@
param(
[string]$OutputPath = ".\experiments\generated\csg-perf-latest.jsonl",
[string]$ReferenceCommand = $env:GAMECULT_GEOMETRY_CSG_REFERENCE_PERF,
[switch]$UseRealtimeCsgCpp
[string]$ReferenceCommand = $env:GAMECULT_GEOMETRY_CSG_REFERENCE_PERF
)
$ErrorActionPreference = "Stop"
@ -28,14 +27,7 @@ try {
throw "CultGeometry CSG perf fixture failed with exit code $LASTEXITCODE"
}
if ($UseRealtimeCsgCpp) {
$nativeOutput = ".\experiments\generated\realtimecsg-cpp-perf-latest.jsonl"
& (Join-Path $root ".\tools\run_realtimecsg_cpp_perf.ps1") -OutputPath $nativeOutput | Out-Host
if ($LASTEXITCODE -ne 0) {
throw "RealtimeCSG C++ perf fixture failed with exit code $LASTEXITCODE"
}
Get-Content -Path $nativeOutput | Add-Content -Path $resolvedOutput -Encoding utf8
} elseif ($ReferenceCommand) {
if ($ReferenceCommand) {
$referenceOutput = & cmd /c $ReferenceCommand
foreach ($line in $referenceOutput) {
Add-Content -Path $resolvedOutput -Value $line -Encoding utf8

View file

@ -1,38 +0,0 @@
param(
[string]$OutputPath = ".\experiments\generated\realtimecsg-cpp-perf-latest.jsonl",
[string]$PluginDll = ".\experiments\source-repos\realtime-CSG-for-unity\Plugins\Editor\External\x64\RealtimeCSG[1_559].dll",
[switch]$Health,
[switch]$DebugNative
)
$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot
$project = Join-Path $root "tools\realtimecsg_native_bridge"
$resolvedOutput = Join-Path $root $OutputPath
$resolvedDll = Join-Path $root $PluginDll
$releaseDir = Join-Path $project "bin\Release\net10.0"
if (!(Test-Path -LiteralPath $resolvedDll)) {
throw "RealtimeCSG native DLL not found: $resolvedDll"
}
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $resolvedOutput) | Out-Null
dotnet build $project -c Release | Out-Host
if ($LASTEXITCODE -ne 0) {
throw "RealtimeCSG native bridge build failed with exit code $LASTEXITCODE"
}
Copy-Item -LiteralPath $resolvedDll -Destination (Join-Path $releaseDir "RealtimeCSG[1_559].dll") -Force
$bridgeArgs = @($resolvedOutput)
if ($Health) {
$bridgeArgs += "--health"
}
if ($DebugNative) {
$bridgeArgs += "--debug-native"
}
& (Join-Path $releaseDir "RealtimeCsgNativeBridge.exe") @bridgeArgs
if ($LASTEXITCODE -ne 0) {
Remove-Item -LiteralPath $resolvedOutput -ErrorAction SilentlyContinue
throw "RealtimeCSG native bridge failed with exit code $LASTEXITCODE"
}
Get-Content -Path $resolvedOutput