Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add sdf geometry: primitives, smooth union, subtract, intersect and offset meshed by surface nets

Nguyen Xuan An8ee27fad7eaa
diff --git a/changes/700.md b/changes/700.md
new file mode 100644
index 00000000..5204fce9
--- /dev/null
+++ b/changes/700.md
@@ -0,0 +1 @@
+- `sdf` geometry meshes a tree of sphere, box, round box, capsule, cylinder and torus shapes with union, subtract, intersect, smooth blends and offset by surface nets, so blobby bodies and rounded joins need no hand modeling (#700)
diff --git a/changes/700.size.md b/changes/700.size.md
new file mode 100644
index 00000000..b7f51a42
--- /dev/null
+++ b/changes/700.size.md
@@ -0,0 +1,4 @@
+- entry:modeling: signed-distance shapes with smooth union, offset and surface-nets meshing are a modeling capability agents lacked (3255 bytes gzip)
+- scene:agent-scene: the sdf geometry type, its capability text and the lazy-load marker (242 bytes gzip)
+- scene:agent-scene+lazy: the same code ships in the lazy bundle (3149 bytes gzip)
+- goal:agent-scene: the capability is worth 242 bytes gzip over the goal; lead approved growth for modeling features
diff --git a/docs/mcp.md b/docs/mcp.md
index e724ab40..e5a5a9b0 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -159,7 +159,7 @@ Every tool schema is read on every turn, so `node scripts/measure-tool-cost.mjs`
`mesh_inspect` lint adds warnings for `intersecting-parts`, `self-intersection`, `thin-wall`, `floating-part` and `asymmetric`. They never set `ok` to false, run within face budgets, and list any check they skipped in `skippedChecks`. `scene_inspect` returns a `diagnostics` list only when there is something to say: ignored material fields, blended transmission, unused materials or geometries, and for imported assets the decoder's not-drawn features, rigs with no joints or no skin, and assets with no clips. Each item has `kind`, `severity`, `target`, `message` and `fix`.
The recipe uses `format: '67js.scene'` and `schemaVersion: 1`.
-Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, `tube`, `curve`, `text`, `grid`, `terrain`, and `mesh`. The fields of `curve` and `text` are listed by `scene_capabilities` (`curveText.details`) and not repeated in every tool schema. Text uses the bundled font only; the MCP accepts no font file or URL.
+Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, `tube`, `curve`, `sdf`, `text`, `grid`, `terrain`, and `mesh`. The fields of `curve` and `text` are listed by `scene_capabilities` (`curveText.details`) and not repeated in every tool schema. Text uses the bundled font only; the MCP accepts no font file or URL.
A `mesh` geometry starts from one of the others as `base` and replays an edit log; see [mesh.md](mesh.md).
Geometry fields remain flat inside each geometry record.
Set operations use `set-node`, `set-material`, or `set-camera`, with fields directly on each command.
diff --git a/docs/parity.md b/docs/parity.md
index 93d55012..3fdad342 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -55,7 +55,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Curves | partial | The `curve` geometry sweeps a cubic Bezier chain with explicit or automatic handles, a round or custom profile, a taper along the length and flat caps. Volume, area and bounds match Blender for an open and a closed curve to 2e-5. Splines can be poly or uniform cubic NURBS (with weights), several splines share one mesh, and arc, spiral and star primitives and a trim by factor or length (open result, caps) build a curve from parameters. There is no NURBS order or knot control, no mesh to curve, no handle types, no fill for flat curves, no offset or extrude, and no separate taper or bevel object. | [curve-text](../tests/curve-text.test.js), [curve-splines](../tests/curve-splines.test.js), [Blender comparison](../tests/blender-curve-text.test.js) | #45, #701 |
| Modeling > Curves (New) | missing | No hair curves. | | #63 |
| Modeling > Surfaces | out of scope | Issue #45 records NURBS surfaces as out of scope unless demand appears. | | |
-| Modeling > Metaball | out of scope | Issue #45 records metaballs as out of scope unless demand appears. | | |
+| Modeling > Metaball | partial | The `sdf` geometry blends spheres and other primitives with a smooth union, which gives the metaball look as a mesh meshed by surface nets. There is no metaball object, no per-element stiffness and no threshold setting. | [modeling-sdf](../tests/modeling-sdf.test.js) | #700 |
| Modeling > Text | partial | The `text` geometry extrudes outlines of the bundled DejaVu Sans (printable ASCII, 20 KB loaded on demand) or of a font table registered in code, with size, depth, alignment, lines and curve resolution. One glyph and a word match Blender 5.2 with the same font to 2e-5 in volume and area. There is no kerning, no bevel, no character styles, no text on a curve, no non-ASCII glyphs in the bundled font, and no font through MCP. | [curve-text](../tests/curve-text.test.js), [Blender comparison](../tests/blender-curve-text.test.js) | #45 |
| Modeling > Point Cloud | missing | No point clouds. | | #43 |
| Modeling > Volumes | missing | Depth-clipped volume fog exists. There are no volume objects. Smoke and fire are not built, by decision: a measured CPU grid step costs 0.46 s at 64 cubed (docs/physics.md, "Decision"). | | #63 |
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 30927342..41dcfc1a 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -327,6 +327,7 @@ const shadow = z.strictObject({
function curveAndTextGeometries(id) {
return [
z.strictObject({ ...id, type: z.literal('curve'), points: z.array(z.unknown()).max(1024), closed: looseField, radius: looseField, taper: looseField, profile: looseField, resolution: looseField, radialSegments: looseField }).describe('Bezier sweep; see scene_capabilities curveText.'),
+ z.strictObject({ ...id, type: z.literal('sdf'), root: z.record(z.string(), z.unknown()), resolution: looseField }).describe('Signed-distance shapes with smooth union; see scene_capabilities curveText.'),
z.strictObject({ ...id, type: z.literal('text'), text: z.string().max(256), size: looseField, depth: looseField, font: looseField, align: looseField, curveSegments: looseField }).describe('3D text; see scene_capabilities curveText.'),
z.strictObject({ ...id, type: z.literal('terrain'), size: looseField, resolution: looseField, seed: looseField, amplitude: looseField, holes: z.array(z.unknown()).max(16).optional() }).describe('Hills with round holes; see scene_capabilities terrain.'),
];
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index fba4eb7a..2aa5ae35 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -66,6 +66,7 @@ export const CURVE_TEXT_LIMITS = Object.freeze({
export const CURVE_TEXT_DETAILS = Object.freeze({
curve: 'bends along path, 2-64 points [x,y,z] (Catmull-Rom); the coordinate along axis (x) is the distance from the path start, so model from 0.',
splines: 'Geometry curve takes points (kind bezier|poly|nurbs, weights for nurbs, closed), or shape {type arc|spiral|star} (arc: radius, startAngle, sweep radians, segments; spiral: rotations, startRadius, endRadius, height, pointsPerRotation, reverse; star: points, innerRadius, outerRadius, innerTwist), or splines: up to 64 of those in one mesh. trim {start, end, length}: factors 0-1 of the arc length, or lengths when length is true; a trimmed curve is open. See docs/modeling.md.',
+ sdf: 'Geometry sdf: root is a tree meshed by surface nets, resolution 4-128 cells along the longest side (default 32). Primitive {shape sphere|box|roundBox|capsule|cylinder|torus, radius, size, height, tubeRadius, position, rotation (Euler radians), scale (uniform)}. Operation {op union|subtract|intersect, smooth (blend radius), children: 2-16} (subtract removes the rest from the first) or {op offset, distance, child}. At most 64 nodes, 8 levels. See docs/modeling.md.',
text: 'Extruded text, baseline y=0 along +X, facing +Z. text (\n for lines), size (1), depth (0.2), align left|center|right, curveSegments, font. See docs/modeling.md.',
});
export const MATERIAL_MAPPINGS = Object.freeze(['box', 'uv']);
@@ -187,7 +188,7 @@ export const MESH_SCULPT_NOTES = Object.freeze({
export const AGENT_SCENE_CAPABILITIES = Object.freeze({
format: '67js.scene', schemaVersion: 1,
- geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'mesh']),
+ geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'sdf', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'mesh']),
camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its size. fStop (0.7-64) turns on depth of field focused on target; 1.4 or lower is full blur; effects.depthOfField.blur must stay 0. Orthographic/shifted cameras use the rasterizer.',
terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius}, no surface inside; radius a few cells or more.',
placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start; set-motion tracks move the node and scene time seeks the clip. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame (docs/vehicle.md). Max 512 placements, 16 assets, 16 animated.',
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 82d96445..fe8f6fad 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -48,7 +48,7 @@ let physicsLoader = null;
// Each test errs on the side of loading: a false positive costs a chunk, a false negative a clear error.
const MODULE_MARKERS = {
mesh: ['"type":"mesh"', '"instances"'],
- modeling: ['"type":"lathe"', '"type":"extrude"', '"type":"tube"', '"type":"curve"'],
+ modeling: ['"type":"lathe"', '"type":"extrude"', '"type":"tube"', '"type":"curve"', '"type":"sdf"'],
text: ['"type":"text"'],
motion: ['"motion":{'],
drive: ['"drive":{'],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index dc17eb25..87ec60ad 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -452,6 +452,7 @@ const GEOMETRY_FIELDS = {
lathe: ['profile', 'segments', 'startAngle', 'sweep'],
extrude: ['contour', 'holes', 'depth', 'steps', 'bevel', 'bevelThickness', 'bevelSegments'],
tube: ['path', 'radius', 'segments', 'radialSegments', 'closed'],
+ sdf: ['root', 'resolution'],
curve: ['points', 'shape', 'splines', 'closed', 'kind', 'weights', 'trim', 'radius', 'taper', 'profile', 'resolution', 'radialSegments'],
text: ['text', 'size', 'depth', 'font', 'align', 'curveSegments'],
mesh: ['base', 'edits', 'stack', 'smoothAngle', 'shapeKeys'],
@@ -486,7 +487,7 @@ function geometryEstimate(value) {
return input.length;
}
for (const field of GEOMETRY_FIELDS[value.type]) {
- if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed', 'base', 'edits', 'stack', 'shapeKeys', 'points', 'taper', 'text', 'font', 'align', 'from', 'to', 'shape', 'splines', 'kind', 'weights', 'trim'].includes(field)) {
+ if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed', 'base', 'edits', 'stack', 'shapeKeys', 'points', 'taper', 'text', 'font', 'align', 'from', 'to', 'shape', 'splines', 'kind', 'weights', 'trim', 'root'].includes(field)) {
finite(value[field], field);
}
}
@@ -533,6 +534,8 @@ function geometryEstimate(value) {
const rings = (value.closed ? knots.length : knots.length - 1) * detail('resolution', 12, 1, 64) + 1;
return rings * sides * 2 + 2 * (sides + 1);
}
+ case 'sdf':
+ return agentSceneModule('modeling').sdfVertexEstimate(value);
case 'text': {
if (typeof value.text !== 'string') throw invalidField('text', value.text, 'a string, such as "Hello"', TypeError);
const visible = [...value.text].filter(character => !/\s/.test(character)).length;
@@ -619,6 +622,8 @@ function generateGeometry(value, maxVertices) {
return agentSceneModule('modeling').extrude(value.contour, { ...value, maxVertices });
case 'tube':
return agentSceneModule('modeling').tube(value.path, { ...value, maxVertices });
+ case 'sdf':
+ return agentSceneModule('modeling').sdfGeometry(value, maxVertices);
case 'curve':
return agentSceneModule('modeling').curveGeometry(value, maxVertices);
case 'text':
diff --git a/src/mesh-remesh.js b/src/mesh-remesh.js
index cc431f6d..b719a1c0 100644
--- a/src/mesh-remesh.js
+++ b/src/mesh-remesh.js
@@ -1,6 +1,7 @@
import { createMeshData, meshBounds } from './mesh-data.js';
import { edgeCornerTable } from './mesh-topology.js';
import { createSurfaceDistance, triangulatedSurface } from './mesh-surface-distance.js';
+import { placeCellVertices, quadsAroundEdges } from './surface-nets.js';
// Voxel remesh: sample the signed distance to the surface on a grid, then place one vertex in each cell the surface
// crosses (surface nets) and join the four cells around each crossing grid edge into a quad. The result is a closed
@@ -106,91 +107,6 @@ function sampleDistances(mesh, surface, grid) {
return { distances, origin };
}
-const CELL_CORNERS = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]];
-const CELL_EDGES = [[0, 1], [2, 3], [4, 5], [6, 7], [0, 2], [1, 3], [4, 6], [5, 7], [0, 4], [1, 5], [2, 6], [3, 7]];
-
-/** One vertex per crossed cell, at the mean of the edge crossings. Returns the cell-to-vertex map and positions. */
-function placeCellVertices(distances, grid, origin) {
- const [pointsX, pointsY, pointsZ] = grid.points;
- const cellsX = pointsX - 1;
- const cellsY = pointsY - 1;
- const cellVertex = new Int32Array(cellsX * cellsY * (pointsZ - 1)).fill(-1);
- const positions = [];
- const values = new Float64Array(8);
- for (let z = 0; z < pointsZ - 1; z++) {
- for (let y = 0; y < cellsY; y++) {
- for (let x = 0; x < cellsX; x++) {
- let negative = 0;
- for (let corner = 0; corner < 8; corner++) {
- const [dx, dy, dz] = CELL_CORNERS[corner];
- values[corner] = distances[((z + dz) * pointsY + y + dy) * pointsX + x + dx];
- if (values[corner] < 0) negative++;
- }
- if (negative === 0 || negative === 8) continue;
- const sum = [0, 0, 0];
- let crossings = 0;
- for (const [start, end] of CELL_EDGES) {
- if ((values[start] < 0) === (values[end] < 0)) continue;
- const fraction = values[start] / (values[start] - values[end]);
- for (let axis = 0; axis < 3; axis++) {
- sum[axis] += CELL_CORNERS[start][axis] + fraction * (CELL_CORNERS[end][axis] - CELL_CORNERS[start][axis]);
- }
- crossings++;
- }
- cellVertex[(z * cellsY + y) * cellsX + x] = positions.length / 3;
- positions.push(
- origin[0] + (x + sum[0] / crossings) * grid.edge,
- origin[1] + (y + sum[1] / crossings) * grid.edge,
- origin[2] + (z + sum[2] / crossings) * grid.edge,
- );
- }
- }
- }
- return { cellVertex, positions };
-}
-
-// For each axis, its two other axes in cyclic order (u, v). Seen from the positive axis, the four cells around an
-// edge run counterclockwise through (-1,-1), (0,-1), (0,0), (-1,0) in (u, v).
-const AXIS_BASES = [[1, 2], [2, 0], [0, 1]];
-const QUAD_OFFSETS = [[-1, -1], [0, -1], [0, 0], [-1, 0]];
-
-/** One quad of cell vertices per grid edge that crosses the surface, wound so the normal points outward. */
-function quadsAroundEdges(distances, grid, cellVertex) {
- const cellsPerAxis = grid.points.map(count => count - 1);
- const [pointsX, pointsY, pointsZ] = grid.points;
- const strides = [1, pointsX, pointsX * pointsY];
- const quads = [];
- const point = [0, 0, 0];
- for (let z = 0; z < pointsZ; z++) {
- for (let y = 0; y < pointsY; y++) {
- for (let x = 0; x < pointsX; x++) {
- point[0] = x;
- point[1] = y;
- point[2] = z;
- const index = (z * pointsY + y) * pointsX + x;
- for (let axis = 0; axis < 3; axis++) {
- const [u, v] = AXIS_BASES[axis];
- if (point[axis] + 1 >= grid.points[axis] || point[u] === 0 || point[v] === 0) continue;
- const here = distances[index];
- if ((here < 0) === (distances[index + strides[axis]] < 0)) continue;
- const quad = QUAD_OFFSETS.map(([stepU, stepV]) => cellVertexAt(cellVertex, cellsPerAxis, point, axis, u, v, stepU, stepV));
- if (quad.includes(-1)) continue;
- quads.push(here < 0 ? quad : quad.reverse());
- }
- }
- }
- }
- return quads;
-}
-
-function cellVertexAt(cellVertex, cellsPerAxis, point, axis, u, v, stepU, stepV) {
- const cell = [point[0], point[1], point[2]];
- cell[u] += stepU;
- cell[v] += stepV;
- if (cell[0] >= cellsPerAxis[0] || cell[1] >= cellsPerAxis[1] || cell[2] >= cellsPerAxis[2]) return -1;
- return cellVertex[(cell[2] * cellsPerAxis[1] + cell[1]) * cellsPerAxis[0] + cell[0]];
-}
-
/**
* Rebuild a closed mesh as a quad surface on a grid of `voxelSize` (or `resolution` cells along the longest side).
* Returns the mesh and the grid it used.
diff --git a/src/modeling-sdf.js b/src/modeling-sdf.js
new file mode 100644
index 00000000..e737f384
--- /dev/null
+++ b/src/modeling-sdf.js
@@ -0,0 +1,302 @@
+import { placeCellVertices, quadsAroundEdges } from './surface-nets.js';
+
+// The sdf geometry: a tree of signed-distance primitives and operations, sampled on a bounded grid and meshed by surface
+// nets. Distances are negative inside. Everything is plain arithmetic in a fixed order, so the same recipe gives the same bytes.
+
+export const SDF_LIMITS = Object.freeze({ minResolution: 4, maxResolution: 128, defaultResolution: 32, maxNodes: 64, maxDepth: 8, maxChildren: 16 });
+const PADDING_VOXELS = 2;
+const PRIMITIVE_FIELDS = {
+ sphere: ['radius'],
+ box: ['size'],
+ roundBox: ['size', 'radius'],
+ capsule: ['radius', 'height'],
+ cylinder: ['radius', 'height'],
+ torus: ['radius', 'tubeRadius'],
+};
+const OPERATIONS = ['union', 'subtract', 'intersect', 'offset'];
+const PLACEMENT_FIELDS = ['position', 'rotation', 'scale'];
+
+function fail(path, value, expected) {
+ const shown = typeof value === 'object' ? JSON.stringify(value) : String(value);
+ return new RangeError(`${path} is ${shown}; pass ${expected}.`);
+}
+
+function positiveNumber(node, field, fallback, path) {
+ const value = node[field] ?? fallback;
+ if (!Number.isFinite(value) || value <= 0) throw fail(`${path}.${field}`, value, 'a positive number');
+ return value;
+}
+
+function vectorOf(value, fallback, path, { positive = false } = {}) {
+ const vector = value ?? fallback;
+ const valid = Array.isArray(vector) && vector.length === 3 && vector.every(component => Number.isFinite(component) && (!positive || component > 0));
+ if (!valid) throw fail(path, vector, positive ? 'three positive numbers, such as [1, 1, 1]' : 'three numbers, such as [0, 0, 0]');
+ return vector;
+}
+
+function checkKeys(node, allowed, path) {
+ for (const key of Object.keys(node)) {
+ if (!allowed.includes(key)) throw fail(`${path}.${key}`, node[key], `one of ${allowed.join(', ')}; remove "${key}"`);
+ }
+}
+
+// Rotation by Euler angles in radians: about X first, then Y, then Z. Stored as the 3x3 matrix, row by row.
+function rotationMatrix([x, y, z]) {
+ const cosX = Math.cos(x);
+ const sinX = Math.sin(x);
+ const cosY = Math.cos(y);
+ const sinY = Math.sin(y);
+ const cosZ = Math.cos(z);
+ const sinZ = Math.sin(z);
+ return [
+ cosZ * cosY, cosZ * sinY * sinX - sinZ * cosX, cosZ * sinY * cosX + sinZ * sinX,
+ sinZ * cosY, sinZ * sinY * sinX + cosZ * cosX, sinZ * sinY * cosX - cosZ * sinX,
+ -sinY, cosY * sinX, cosY * cosX,
+ ];
+}
+
+function length2(first, second) {
+ return Math.sqrt(first * first + second * second);
+}
+
+function length3(first, second, third) {
+ return Math.sqrt(first * first + second * second + third * third);
+}
+
+function boxDistance(x, y, z, half) {
+ const qx = Math.abs(x) - half[0];
+ const qy = Math.abs(y) - half[1];
+ const qz = Math.abs(z) - half[2];
+ return length3(Math.max(qx, 0), Math.max(qy, 0), Math.max(qz, 0)) + Math.min(Math.max(qx, qy, qz), 0);
+}
+
+// Local distance function and half extents of each primitive; capsule, cylinder and torus stand along Y.
+function primitiveShape(node, path) {
+ switch (node.shape) {
+ case 'sphere': {
+ const radius = positiveNumber(node, 'radius', 0.5, path);
+ return { half: [radius, radius, radius], distance: (x, y, z) => length3(x, y, z) - radius };
+ }
+ case 'box': {
+ const size = vectorOf(node.size, [1, 1, 1], `${path}.size`, { positive: true });
+ const half = size.map(value => value / 2);
+ return { half, distance: (x, y, z) => boxDistance(x, y, z, half) };
+ }
+ case 'roundBox': {
+ const size = vectorOf(node.size, [1, 1, 1], `${path}.size`, { positive: true });
+ const radius = node.radius ?? 0.1;
+ if (!Number.isFinite(radius) || radius < 0 || radius > Math.min(...size) / 2) {
+ throw fail(`${path}.radius`, radius, `a number from 0 to half the smallest size, ${Math.min(...size) / 2}`);
+ }
+ const half = size.map(value => value / 2);
+ const inner = half.map(value => value - radius);
+ return { half, distance: (x, y, z) => boxDistance(x, y, z, inner) - radius };
+ }
+ case 'capsule': {
+ const radius = positiveNumber(node, 'radius', 0.25, path);
+ const halfSegment = positiveNumber(node, 'height', 0.5, path) / 2;
+ return {
+ half: [radius, halfSegment + radius, radius],
+ distance: (x, y, z) => length3(x, y - Math.max(-halfSegment, Math.min(halfSegment, y)), z) - radius,
+ };
+ }
+ case 'cylinder': {
+ const radius = positiveNumber(node, 'radius', 0.5, path);
+ const halfHeight = positiveNumber(node, 'height', 1, path) / 2;
+ return {
+ half: [radius, halfHeight, radius],
+ distance: (x, y, z) => {
+ const radial = length2(x, z) - radius;
+ const vertical = Math.abs(y) - halfHeight;
+ return Math.min(Math.max(radial, vertical), 0) + length2(Math.max(radial, 0), Math.max(vertical, 0));
+ },
+ };
+ }
+ case 'torus': {
+ const radius = positiveNumber(node, 'radius', 0.5, path);
+ const tubeRadius = positiveNumber(node, 'tubeRadius', 0.15, path);
+ return {
+ half: [radius + tubeRadius, tubeRadius, radius + tubeRadius],
+ distance: (x, y, z) => length2(length2(x, z) - radius, y) - tubeRadius,
+ };
+ }
+ default:
+ throw fail(`${path}.shape`, node.shape, `one of ${Object.keys(PRIMITIVE_FIELDS).join(', ')}`);
+ }
+}
+
+function placedPrimitive(node, path) {
+ checkKeys(node, ['shape', ...PRIMITIVE_FIELDS[node.shape] ?? [], ...PLACEMENT_FIELDS], path);
+ const shape = primitiveShape(node, path);
+ const position = vectorOf(node.position, [0, 0, 0], `${path}.position`);
+ const rotation = vectorOf(node.rotation, [0, 0, 0], `${path}.rotation`);
+ const scale = node.scale ?? 1;
+ if (!Number.isFinite(scale) || scale <= 0) throw fail(`${path}.scale`, scale, 'one positive number; scale is uniform');
+ const matrix = rotationMatrix(rotation);
+ const inverseScale = 1 / scale;
+ // The point goes into the shape's frame with the transpose of the rotation; the distance comes back multiplied by the scale.
+ const distance = (x, y, z) => {
+ const dx = x - position[0];
+ const dy = y - position[1];
+ const dz = z - position[2];
+ const localX = (matrix[0] * dx + matrix[3] * dy + matrix[6] * dz) * inverseScale;
+ const localY = (matrix[1] * dx + matrix[4] * dy + matrix[7] * dz) * inverseScale;
+ const localZ = (matrix[2] * dx + matrix[5] * dy + matrix[8] * dz) * inverseScale;
+ return shape.distance(localX, localY, localZ) * scale;
+ };
+ const reach = [0, 1, 2].map(row => scale * (Math.abs(matrix[row * 3]) * shape.half[0] + Math.abs(matrix[row * 3 + 1]) * shape.half[1] + Math.abs(matrix[row * 3 + 2]) * shape.half[2]));
+ return {
+ distance,
+ bounds: { min: reach.map((value, axis) => position[axis] - value), max: reach.map((value, axis) => position[axis] + value) },
+ };
+}
+
+// Polynomial smooth minimum: it lowers the plain minimum by at most smooth / 4, and equals it when smooth is 0.
+function smoothMinimum(first, second, smooth) {
+ if (smooth === 0) return Math.min(first, second);
+ const blend = Math.max(smooth - Math.abs(first - second), 0) / smooth;
+ return Math.min(first, second) - blend * blend * smooth / 4;
+}
+
+function combine(operation, smooth) {
+ switch (operation) {
+ case 'union': return (first, second) => smoothMinimum(first, second, smooth);
+ case 'intersect': return (first, second) => -smoothMinimum(-first, -second, smooth);
+ default: return (first, second) => -smoothMinimum(-first, second, smooth);
+ }
+}
+
+function expandedBounds(bounds, amount) {
+ return { min: bounds.min.map(value => value - amount), max: bounds.max.map(value => value + amount) };
+}
+
+function combinedBounds(operation, childBounds, slack, path) {
+ if (operation === 'subtract') return childBounds[0];
+ const pick = operation === 'union' ? [Math.min, Math.max] : [Math.max, Math.min];
+ const bounds = {
+ min: [0, 1, 2].map(axis => pick[0](...childBounds.map(child => child.min[axis]))),
+ max: [0, 1, 2].map(axis => pick[1](...childBounds.map(child => child.max[axis]))),
+ };
+ if (operation === 'intersect' && bounds.min.some((value, axis) => value >= bounds.max[axis])) {
+ throw fail(path, 'children that do not overlap', 'children whose shapes overlap, or use union');
+ }
+ return operation === 'union' ? expandedBounds(bounds, slack) : bounds;
+}
+
+function compileNode(node, path, depth, counter) {
+ if (!node || typeof node !== 'object' || Array.isArray(node)) throw fail(path, node, `a primitive such as { "shape": "sphere", "radius": 0.5 } or an operation such as { "op": "union", "children": [...] }`);
+ counter.count += 1;
+ if (counter.count > SDF_LIMITS.maxNodes) throw fail(path, `more than ${SDF_LIMITS.maxNodes} nodes`, `at most ${SDF_LIMITS.maxNodes} primitives and operations in all`);
+ if (depth > SDF_LIMITS.maxDepth) throw fail(path, `nesting deeper than ${SDF_LIMITS.maxDepth}`, `at most ${SDF_LIMITS.maxDepth} levels of operations`);
+ if (node.shape !== undefined) {
+ if (node.op !== undefined) throw fail(`${path}.op`, node.op, 'either shape or op, not both');
+ return placedPrimitive(node, path);
+ }
+ if (!OPERATIONS.includes(node.op)) throw fail(`${path}.op`, node.op, `shape (${Object.keys(PRIMITIVE_FIELDS).join(', ')}) or op (${OPERATIONS.join(', ')})`);
+ if (node.op === 'offset') return compileOffset(node, path, depth, counter);
+ checkKeys(node, ['op', 'smooth', 'children'], path);
+ const smooth = node.smooth ?? 0;
+ if (!Number.isFinite(smooth) || smooth < 0) throw fail(`${path}.smooth`, smooth, 'a blend radius of 0 or more, in the units of the shapes');
+ const children = node.children;
+ if (!Array.isArray(children) || children.length < 2 || children.length > SDF_LIMITS.maxChildren) {
+ throw fail(`${path}.children`, Array.isArray(children) ? `${children.length} children` : children, `2 to ${SDF_LIMITS.maxChildren} nodes`);
+ }
+ const compiled = children.map((child, index) => compileNode(child, `${path}.children[${index}]`, depth + 1, counter));
+ const join = combine(node.op, smooth);
+ const distance = (x, y, z) => {
+ let result = compiled[0].distance(x, y, z);
+ for (let index = 1; index < compiled.length; index++) result = join(result, compiled[index].distance(x, y, z));
+ return result;
+ };
+ const slack = smooth / 4 * (compiled.length - 1);
+ return { distance, bounds: combinedBounds(node.op, compiled.map(child => child.bounds), slack, path) };
+}
+
+function compileOffset(node, path, depth, counter) {
+ checkKeys(node, ['op', 'distance', 'child'], path);
+ if (!Number.isFinite(node.distance)) throw fail(`${path}.distance`, node.distance, 'a number: positive grows the shape, negative shrinks it');
+ const child = compileNode(node.child, `${path}.child`, depth + 1, counter);
+ const bounds = node.distance > 0 ? expandedBounds(child.bounds, node.distance) : child.bounds;
+ return { distance: (x, y, z) => child.distance(x, y, z) - node.distance, bounds };
+}
+
+/** Validates an sdf geometry and returns its grid, without sampling it. */
+export function planSdf(value) {
+ const unknown = Object.keys(value).filter(key => !['id', 'type', 'root', 'resolution'].includes(key));
+ if (unknown.length) throw fail(`sdf.${unknown[0]}`, value[unknown[0]], 'only root and resolution; remove it');
+ const resolution = value.resolution ?? SDF_LIMITS.defaultResolution;
+ if (!Number.isInteger(resolution) || resolution < SDF_LIMITS.minResolution || resolution > SDF_LIMITS.maxResolution) {
+ throw fail('sdf.resolution', resolution, `a whole number of cells along the longest side, ${SDF_LIMITS.minResolution} to ${SDF_LIMITS.maxResolution}; the grid is capped at ${SDF_LIMITS.maxResolution ** 3} cells`);
+ }
+ const root = compileNode(value.root, 'sdf.root', 0, { count: 0 });
+ const extent = root.bounds.max.map((high, axis) => high - root.bounds.min[axis]);
+ const edge = Math.max(...extent) / resolution;
+ const points = extent.map(length => Math.ceil(length / edge - 1e-9) + 1 + PADDING_VOXELS * 2);
+ const origin = root.bounds.min.map(low => low - PADDING_VOXELS * edge);
+ return { root, resolution, edge, points, origin, vertexEstimate: 8 * resolution * resolution };
+}
+
+/** The vertex count to reserve for an sdf geometry: validated, not sampled. Surfaces with more detail are checked after meshing. */
+export function sdfVertexEstimate(value) {
+ return planSdf(value).vertexEstimate;
+}
+
+function sampleGrid({ root, edge, points, origin }) {
+ const [pointsX, pointsY, pointsZ] = points;
+ const distances = new Float32Array(pointsX * pointsY * pointsZ);
+ let index = 0;
+ for (let z = 0; z < pointsZ; z++) {
+ for (let y = 0; y < pointsY; y++) {
+ for (let x = 0; x < pointsX; x++) {
+ distances[index++] = root.distance(origin[0] + x * edge, origin[1] + y * edge, origin[2] + z * edge);
+ }
+ }
+ }
+ return distances;
+}
+
+function gradientAt(distance, x, y, z, step) {
+ return [
+ distance(x + step, y, z) - distance(x - step, y, z),
+ distance(x, y + step, z) - distance(x, y - step, z),
+ distance(x, y, z + step) - distance(x, y, z - step),
+ ];
+}
+
+// Two triangles per quad, split along the shorter diagonal so thin quads do not fold.
+function triangulate(quads, positions) {
+ const indices = [];
+ const gap = (first, second) => {
+ const dx = positions[first * 3] - positions[second * 3];
+ const dy = positions[first * 3 + 1] - positions[second * 3 + 1];
+ const dz = positions[first * 3 + 2] - positions[second * 3 + 2];
+ return dx * dx + dy * dy + dz * dz;
+ };
+ for (const [first, second, third, fourth] of quads) {
+ if (gap(first, third) <= gap(second, fourth)) indices.push(first, second, third, first, third, fourth);
+ else indices.push(first, second, fourth, second, third, fourth);
+ }
+ return Uint32Array.from(indices);
+}
+
+/** Mesh an sdf geometry: positions, normals from the field gradient, box-projected UVs and triangle indices. */
+export function sdfGeometry(value) {
+ const plan = planSdf(value);
+ const grid = { points: plan.points, edge: plan.edge };
+ const distances = sampleGrid(plan);
+ const { cellVertex, positions: cellPositions } = placeCellVertices(distances, grid, plan.origin);
+ const quads = quadsAroundEdges(distances, grid, cellVertex);
+ if (!quads.length) throw new RangeError('sdf has no surface: the shape is empty or smaller than a cell. Pass a larger resolution or check subtract and intersect children.');
+ const positions = Float32Array.from(cellPositions);
+ const normals = new Float32Array(positions.length);
+ const uvs = new Float32Array(positions.length / 3 * 2);
+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {
+ const gradient = gradientAt(plan.root.distance, cellPositions[vertex * 3], cellPositions[vertex * 3 + 1], cellPositions[vertex * 3 + 2], plan.edge * 0.5);
+ normals.set(gradient, vertex * 3);
+ const strongest = Math.abs(gradient[0]) >= Math.abs(gradient[1]) && Math.abs(gradient[0]) >= Math.abs(gradient[2]) ? 0 : Math.abs(gradient[1]) >= Math.abs(gradient[2]) ? 1 : 2;
+ const [u, v] = [[1, 2], [0, 2], [0, 1]][strongest];
+ uvs[vertex * 2] = cellPositions[vertex * 3 + u];
+ uvs[vertex * 2 + 1] = cellPositions[vertex * 3 + v];
+ }
+ return { positions, normals, uvs, indices: triangulate(quads, positions) };
+}
diff --git a/src/modeling.js b/src/modeling.js
index 7671b0a3..7f0c1629 100644
--- a/src/modeling.js
+++ b/src/modeling.js
@@ -1,6 +1,7 @@
import { buildLathe, buildExtrusion, buildTube } from './modeling-shapes.js';
import { sweepSamples } from './modeling-bezier.js';
import { sampleCountOf, sampleSpline, shapeToSpline, trimSamples } from './modeling-splines.js';
+import { planSdf, sdfGeometry as buildSdf } from './modeling-sdf.js';
const MAX_INPUT_POINTS = 4096;
const DEFAULT_VERTEX_LIMIT = 250_000;
@@ -455,3 +456,12 @@ export function tube(path, {
checkBudget((segments + 1) * (radialSegments + 1), maxVertices);
return meshFrom(buildTube(points, closed, radius, segments, radialSegments), maxVertices);
}
+
+/** The sdf scene geometry: signed-distance shapes meshed by surface nets. See docs/modeling.md. */
+export function sdfGeometry(value, maxVertices = DEFAULT_VERTEX_LIMIT) {
+ planSdf(value);
+ return meshFrom(buildSdf(value), maxVertices);
+}
+
+/** The vertex count reserved for an sdf geometry, validated like sdfGeometry. */
+export { sdfVertexEstimate } from './modeling-sdf.js';
diff --git a/src/surface-nets.js b/src/surface-nets.js
new file mode 100644
index 00000000..d653b13b
--- /dev/null
+++ b/src/surface-nets.js
@@ -0,0 +1,87 @@
+// Surface nets on a regular grid of signed distances (negative inside): one vertex in each cell the surface crosses,
+// one quad around each crossing grid edge. Shared by the voxel remesh and the sdf geometry.
+
+const CELL_CORNERS = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]];
+const CELL_EDGES = [[0, 1], [2, 3], [4, 5], [6, 7], [0, 2], [1, 3], [4, 6], [5, 7], [0, 4], [1, 5], [2, 6], [3, 7]];
+
+/** One vertex per crossed cell, at the mean of the edge crossings. Returns the cell-to-vertex map and positions. */
+export function placeCellVertices(distances, grid, origin) {
+ const [pointsX, pointsY, pointsZ] = grid.points;
+ const cellsX = pointsX - 1;
+ const cellsY = pointsY - 1;
+ const cellVertex = new Int32Array(cellsX * cellsY * (pointsZ - 1)).fill(-1);
+ const positions = [];
+ const values = new Float64Array(8);
+ for (let z = 0; z < pointsZ - 1; z++) {
+ for (let y = 0; y < cellsY; y++) {
+ for (let x = 0; x < cellsX; x++) {
+ let negative = 0;
+ for (let corner = 0; corner < 8; corner++) {
+ const [dx, dy, dz] = CELL_CORNERS[corner];
+ values[corner] = distances[((z + dz) * pointsY + y + dy) * pointsX + x + dx];
+ if (values[corner] < 0) negative++;
+ }
+ if (negative === 0 || negative === 8) continue;
+ const sum = [0, 0, 0];
+ let crossings = 0;
+ for (const [start, end] of CELL_EDGES) {
+ if ((values[start] < 0) === (values[end] < 0)) continue;
+ const fraction = values[start] / (values[start] - values[end]);
+ for (let axis = 0; axis < 3; axis++) {
+ sum[axis] += CELL_CORNERS[start][axis] + fraction * (CELL_CORNERS[end][axis] - CELL_CORNERS[start][axis]);
+ }
+ crossings++;
+ }
+ cellVertex[(z * cellsY + y) * cellsX + x] = positions.length / 3;
+ positions.push(
+ origin[0] + (x + sum[0] / crossings) * grid.edge,
+ origin[1] + (y + sum[1] / crossings) * grid.edge,
+ origin[2] + (z + sum[2] / crossings) * grid.edge,
+ );
+ }
+ }
+ }
+ return { cellVertex, positions };
+}
+
+// For each axis, its two other axes in cyclic order (u, v). Seen from the positive axis, the four cells around an
+// edge run counterclockwise through (-1,-1), (0,-1), (0,0), (-1,0) in (u, v).
+const AXIS_BASES = [[1, 2], [2, 0], [0, 1]];
+const QUAD_OFFSETS = [[-1, -1], [0, -1], [0, 0], [-1, 0]];
+
+/** One quad of cell vertices per grid edge that crosses the surface, wound so the normal points outward. */
+export function quadsAroundEdges(distances, grid, cellVertex) {
+ const cellsPerAxis = grid.points.map(count => count - 1);
+ const [pointsX, pointsY, pointsZ] = grid.points;
+ const strides = [1, pointsX, pointsX * pointsY];
+ const quads = [];
+ const point = [0, 0, 0];
+ for (let z = 0; z < pointsZ; z++) {
+ for (let y = 0; y < pointsY; y++) {
+ for (let x = 0; x < pointsX; x++) {
+ point[0] = x;
+ point[1] = y;
+ point[2] = z;
+ const index = (z * pointsY + y) * pointsX + x;
+ for (let axis = 0; axis < 3; axis++) {
+ const [u, v] = AXIS_BASES[axis];
+ if (point[axis] + 1 >= grid.points[axis] || point[u] === 0 || point[v] === 0) continue;
+ const here = distances[index];
+ if ((here < 0) === (distances[index + strides[axis]] < 0)) continue;
+ const quad = QUAD_OFFSETS.map(([stepU, stepV]) => cellVertexAt(cellVertex, cellsPerAxis, point, axis, u, v, stepU, stepV));
+ if (quad.includes(-1)) continue;
+ quads.push(here < 0 ? quad : quad.reverse());
+ }
+ }
+ }
+ }
+ return quads;
+}
+
+function cellVertexAt(cellVertex, cellsPerAxis, point, axis, u, v, stepU, stepV) {
+ const cell = [point[0], point[1], point[2]];
+ cell[u] += stepU;
+ cell[v] += stepV;
+ if (cell[0] >= cellsPerAxis[0] || cell[1] >= cellsPerAxis[1] || cell[2] >= cellsPerAxis[2]) return -1;
+ return cellVertex[(cell[2] * cellsPerAxis[1] + cell[1]) * cellsPerAxis[0] + cell[0]];
+}
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
index f40472b4..414fd3f7 100644
--- a/tests/mcp-tools.test.js
+++ b/tests/mcp-tools.test.js
@@ -156,7 +156,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'
assert.equal(recipeSchema.properties.materials.maxItems, 256);
assert.equal(recipeSchema.properties.geometries.maxItems, 256);
// The tool lists the common fields; the strict schema still validates and scene_capabilities serves the full outline.
- assert.deepEqual(recipeSchema.properties.geometries.items.properties.type.enum, ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'terrain', 'grid', 'plane', 'cone', 'icoSphere', 'circle', 'line', 'mesh']);
+ assert.deepEqual(recipeSchema.properties.geometries.items.properties.type.enum, ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'sdf', 'text', 'terrain', 'grid', 'plane', 'cone', 'icoSphere', 'circle', 'line', 'mesh']);
assert.ok(recipeSchema.properties.environment.properties.setup);
assert.equal(recipeSchema.properties.shadow.additionalProperties, false);
for (const topic of ['geometries', 'environment', 'effects', 'motion', 'physics', 'cloth', 'armatures', 'materialFields', 'meshEdit', 'meshStack']) {
diff --git a/tests/modeling-sdf.test.js b/tests/modeling-sdf.test.js
new file mode 100644
index 00000000..d4f98592
--- /dev/null
+++ b/tests/modeling-sdf.test.js
@@ -0,0 +1,195 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import test from 'node:test';
+import { createAgentScene } from '../src/agent-scene.js';
+import { sdfGeometry } from '../src/modeling.js';
+
+function hashOf(mesh) {
+ const hash = createHash('sha256');
+ for (const array of [mesh.positions, mesh.normals, mesh.uvs, mesh.indices]) hash.update(Buffer.from(array.buffer, array.byteOffset, array.byteLength));
+ return hash.digest('hex');
+}
+
+function volumeOf({ positions, indices }) {
+ let total = 0;
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ const [a, b, c] = [0, 1, 2].map(corner => indices[offset + corner] * 3);
+ total += (positions[a] * (positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1])
+ - positions[a + 1] * (positions[b] * positions[c + 2] - positions[b + 2] * positions[c])
+ + positions[a + 2] * (positions[b] * positions[c + 1] - positions[b + 1] * positions[c])) / 6;
+ }
+ return total;
+}
+
+// Edges that do not belong to exactly two triangles; zero means the surface is closed.
+function openEdgeCount({ indices }) {
+ const uses = new Map();
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ for (let side = 0; side < 3; side++) {
+ const from = indices[offset + side];
+ const to = indices[offset + (side + 1) % 3];
+ const key = from < to ? `${from}|${to}` : `${to}|${from}`;
+ uses.set(key, (uses.get(key) ?? 0) + 1);
+ }
+ }
+ return [...uses.values()].filter(count => count !== 2).length;
+}
+
+function boundsOf({ positions }) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], positions[offset + axis]);
+ maximum[axis] = Math.max(maximum[axis], positions[offset + axis]);
+ }
+ }
+ return { minimum, maximum };
+}
+
+const sphere = (radius, position = [0, 0, 0]) => ({ shape: 'sphere', radius, position });
+const mesh = (root, resolution = 32) => sdfGeometry({ type: 'sdf', root, resolution });
+
+// A body, a head and two arms blended with a smooth union: the character-body case of the issue.
+const CHARACTER = {
+ op: 'union',
+ smooth: 0.18,
+ children: [
+ { shape: 'capsule', radius: 0.3, height: 0.7 },
+ sphere(0.25, [0, 0.75, 0]),
+ { shape: 'capsule', radius: 0.09, height: 0.45, position: [0.45, 0.2, 0], rotation: [0, 0, -0.9] },
+ { shape: 'capsule', radius: 0.09, height: 0.45, position: [-0.45, 0.2, 0], rotation: [0, 0, 0.9] },
+ ],
+};
+
+// An L bracket with a rounded inside corner (smooth union) and a bolt hole (smooth subtract).
+const BRACKET = {
+ op: 'subtract',
+ smooth: 0.02,
+ children: [
+ {
+ op: 'union',
+ smooth: 0.12,
+ children: [
+ { shape: 'box', size: [1, 0.15, 0.5], position: [0, -0.425, 0] },
+ { shape: 'box', size: [0.15, 1, 0.5], position: [-0.425, 0, 0] },
+ ],
+ },
+ { shape: 'cylinder', radius: 0.07, height: 1, position: [0.2, -0.425, 0], rotation: [0, 0, 0] },
+ ],
+};
+
+test('a sphere and a box are closed and close to their analytic volume', () => {
+ const ball = mesh(sphere(0.5), 48);
+ assert.equal(openEdgeCount(ball), 0);
+ assert.ok(Math.abs(volumeOf(ball) / (4 / 3 * Math.PI * 0.125) - 1) < 0.02);
+ const block = mesh({ shape: 'box', size: [1, 0.6, 0.8], position: [0.13, 0.07, 0.02] }, 48);
+ assert.equal(openEdgeCount(block), 0);
+ assert.ok(Math.abs(volumeOf(block) / 0.48 - 1) < 0.02);
+ const { minimum, maximum } = boundsOf(block);
+ assert.ok(Math.abs(maximum[0] - minimum[0] - 1) < 0.05);
+});
+
+test('the surface faces outward and the normals follow the field', () => {
+ const ball = mesh(sphere(0.5), 24);
+ assert.ok(volumeOf(ball) > 0);
+ for (let vertex = 0; vertex < ball.positions.length; vertex += 3) {
+ const dot = ball.normals[vertex] * ball.positions[vertex] + ball.normals[vertex + 1] * ball.positions[vertex + 1] + ball.normals[vertex + 2] * ball.positions[vertex + 2];
+ assert.ok(dot > 0.4);
+ }
+});
+
+test('smooth union is watertight and fills more than a hard union', () => {
+ const blended = mesh({ op: 'union', smooth: 0.3, children: [sphere(0.4), sphere(0.3, [0.5, 0, 0])] }, 40);
+ const hard = mesh({ op: 'union', children: [sphere(0.4), sphere(0.3, [0.5, 0, 0])] }, 40);
+ assert.equal(openEdgeCount(blended), 0);
+ assert.equal(openEdgeCount(hard), 0);
+ assert.ok(volumeOf(blended) > volumeOf(hard));
+ assert.equal(openEdgeCount(mesh(CHARACTER, 48)), 0);
+ assert.equal(openEdgeCount(mesh(BRACKET, 48)), 0);
+});
+
+test('subtract, intersect and offset change the volume as expected', () => {
+ const big = sphere(0.5);
+ const small = sphere(0.3, [0.4, 0, 0]);
+ const whole = volumeOf(mesh(big, 40));
+ const carved = mesh({ op: 'subtract', children: [big, small] }, 40);
+ const shared = mesh({ op: 'intersect', children: [big, small] }, 40);
+ assert.equal(openEdgeCount(carved), 0);
+ assert.equal(openEdgeCount(shared), 0);
+ assert.ok(Math.abs(volumeOf(carved) + volumeOf(shared) - whole) / whole < 0.03);
+ const grown = mesh({ op: 'offset', distance: 0.1, child: big }, 40);
+ assert.ok(Math.abs(volumeOf(grown) / (4 / 3 * Math.PI * 0.6 ** 3) - 1) < 0.02);
+ const shrunk = mesh({ op: 'offset', distance: -0.1, child: big }, 40);
+ assert.ok(Math.abs(volumeOf(shrunk) / (4 / 3 * Math.PI * 0.4 ** 3) - 1) < 0.03);
+});
+
+test('every primitive meshes closed, and position, rotation and scale move it', () => {
+ for (const root of [
+ { shape: 'roundBox', size: [1, 0.5, 0.7], radius: 0.12 },
+ { shape: 'capsule' },
+ { shape: 'cylinder' },
+ { shape: 'torus' },
+ ]) {
+ assert.equal(openEdgeCount(mesh(root, 40)), 0, root.shape);
+ }
+ const moved = boundsOf(mesh({ shape: 'box', size: [1, 0.2, 0.2], position: [1, 2, 3], rotation: [0, 0, Math.PI / 2], scale: 2 }, 32));
+ assert.ok(Math.abs((moved.maximum[1] - moved.minimum[1]) - 2) < 0.15);
+ assert.ok(Math.abs((moved.maximum[0] - moved.minimum[0]) - 0.4) < 0.15);
+ assert.ok(Math.abs((moved.maximum[0] + moved.minimum[0]) / 2 - 1) < 0.05);
+ assert.ok(Math.abs((moved.maximum[1] + moved.minimum[1]) / 2 - 2) < 0.05);
+});
+
+test('the meshing is deterministic and matches the recorded geometry', () => {
+ const body = mesh(CHARACTER, 32);
+ const bracket = mesh(BRACKET, 32);
+ assert.equal(hashOf(mesh(CHARACTER, 32)), hashOf(body));
+ assert.deepEqual([body.positions.length / 3, body.indices.length / 3], [RECORDED.bodyVertices, RECORDED.bodyTriangles]);
+ assert.deepEqual([bracket.positions.length / 3, bracket.indices.length / 3], [RECORDED.bracketVertices, RECORDED.bracketTriangles]);
+ assert.equal(hashOf(body), RECORDED.bodyHash);
+ assert.equal(hashOf(bracket), RECORDED.bracketHash);
+});
+
+const RECORDED = {
+ bodyVertices: 1362, bodyTriangles: 2720, bodyHash: '98016f1be170476cad9110cc47f8e5fd4324f4bd31401436d56cb4bbe614e404',
+ bracketVertices: 2526, bracketTriangles: 5052, bracketHash: '73fab5cf025c640fe724b1422356bbf9580bcde4c4cc13be50f2dae0e35c1946',
+};
+
+test('bad input names the field and what to pass', () => {
+ const failure = (root, pattern, extra = {}) => assert.throws(() => sdfGeometry({ type: 'sdf', root, ...extra }), pattern);
+ failure({ shape: 'cone' }, /sdf\.root\.shape is cone; pass one of sphere, box/);
+ failure({ shape: 'sphere', radius: -1 }, /sdf\.root\.radius is -1; pass a positive number/);
+ failure({ shape: 'sphere', radiu: 1 }, /sdf\.root\.radiu.*remove "radiu"/);
+ failure({ shape: 'roundBox', size: [1, 1, 1], radius: 0.9 }, /radius is 0\.9; pass a number from 0 to half the smallest size, 0\.5/);
+ failure({ op: 'union', children: [sphere(1)] }, /children is 1 children; pass 2 to 16 nodes/);
+ failure({ op: 'union', smooth: -1, children: [sphere(1), sphere(1)] }, /smooth is -1; pass a blend radius/);
+ failure({ op: 'blend', children: [] }, /sdf\.root\.op is blend/);
+ failure({ op: 'offset', child: sphere(1) }, /distance is undefined; pass a number/);
+ failure({ op: 'intersect', children: [sphere(0.1), sphere(0.1, [5, 0, 0])] }, /do not overlap/);
+ failure({ shape: 'box', size: [1, 0, 1] }, /size is \[1,0,1\]; pass three positive numbers/);
+ failure({ shape: 'sphere', scale: [2, 2, 2] }, /scale is \[2,2,2\]; pass one positive number/);
+ failure(sphere(1), /resolution is 129; pass a whole number .* 2097152 cells/, { resolution: 129 });
+ failure(sphere(1), /resolution is 2\.5/, { resolution: 2.5 });
+ failure(sphere(1), /sdf\.mesh is 1; pass only root and resolution/, { mesh: 1 });
+ failure({ op: 'subtract', children: [sphere(0.1), sphere(1)] }, /sdf has no surface/);
+ let deep = sphere(1);
+ for (let level = 0; level < 9; level++) deep = { op: 'offset', distance: 0, child: deep };
+ failure(deep, /nesting deeper than 8/);
+ const wide = { op: 'union', children: Array.from({ length: 16 }, () => ({ op: 'union', children: [sphere(1), sphere(1), sphere(1), sphere(1)] })) };
+ failure(wide, /more than 64 nodes/);
+});
+
+test('a recipe sdf geometry becomes a part and respects the vertex budget', () => {
+ const recipe = (geometry, limits) => createAgentScene({
+ format: '67js.scene',
+ schemaVersion: 1,
+ materials: [{ id: 'clay', color: [0.8, 0.5, 0.4], roughness: 0.6 }],
+ geometries: [{ id: 'g', type: 'sdf', ...geometry }],
+ nodes: [{ id: 'n', geometry: 'g', material: 'clay' }],
+ }, limits);
+ const scene = recipe({ root: CHARACTER, resolution: 24 });
+ assert.ok(scene.parts[0].geometry.indices.length > 0);
+ assert.throws(() => recipe({ root: CHARACTER, resolution: 128 }, { maxVertices: 1000 }), /vertices|maxVertices/);
+ assert.throws(() => recipe({ root: { shape: 'cone' } }), /sdf\.root\.shape/);
+});