Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add field rotation math, curve instances with fillet and resample, bounding box and convex hull (issue #615)

Nguyen Xuan Anbe0df5a559c7
diff --git a/changes/615-field-math.md b/changes/615-field-math.md
new file mode 100644
index 00000000..adb3c4a2
--- /dev/null
+++ b/changes/615-field-math.md
@@ -0,0 +1 @@
+- Field math and curves: field expressions gain `rotate`, `align` and `transform` for rotation and matrix math. Instances take a `curve` source (`points`, `count`, `closed`, `fillet`) that places points at equal arc length, rounds corners and, with `alignToNormal`, turns each instance along the curve. The `bounding_box` and `convex_hull` modifiers replace a mesh with its box or hull (#615).
diff --git a/changes/615-field-math.size.md b/changes/615-field-math.size.md
new file mode 100644
index 00000000..b67e749b
--- /dev/null
+++ b/changes/615-field-math.size.md
@@ -0,0 +1,8 @@
+- entry:mesh: rotation operators for fields, curve resample and fillet for instances, and the bounding box and convex hull modifiers are about 1.8 KB gzip of mesh code that agents cannot get any other way.
+- entry:light-bake: it bundles the mesh code, so it carries the same 1.8 KB of new mesh operators.
+- entry:light-bake-gpu: it bundles the mesh code, so it carries the same new mesh operators.
+- entry:ground-bounce: it bundles the mesh code, so it carries the same new mesh operators.
+- entry:floor-sky-visibility: it bundles the mesh code, so it carries the same new mesh operators.
+- entry:water-reflection: it bundles the mesh code, so it carries the same new mesh operators.
+- scene:agent-scene+lazy: the new mesh operators live in the lazy part, which holds the whole mesh engine.
+- goal:agent-scene: the core grows 32 bytes for the operator names; the notes were shortened elsewhere to pay for the rest.
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index f1f643e4..38de2245 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -258,7 +258,7 @@ Give exactly one point source. `grid` is `{ counts: [nx, ny, nz], spacing: [dx,
on the triangles of a recipe geometry in proportion to their area; they are in that geometry's own space, so parent
the group to the node that carries it. `seed` (default 0) fixes the placement. `where` is a number
[field expression](mesh.md#field-expressions) over the points (position, normal, index): points where it is 0 are
-dropped. `yaw` turns each instance randomly about up, `alignToNormal` (surface only) tilts up to the surface normal, and `scale`
+dropped. `curve` is `{ points, count, closed, fillet }`: `count` points at equal arc length along the polyline through `points` (2 to 256, the first and last on its ends unless `closed`), with `fillet` rounding every corner by that radius (reduced where it does not fit). `yaw` turns each instance randomly about up, `alignToNormal` (surface or curve) turns up to the surface normal or the direction of the curve, and `scale`
is a random uniform `[min, max]`. At most 2048 candidate points per node, and the scene's node limit still applies.
The group's own scale applies to the spacing and the points, because they are in its space.
diff --git a/docs/mesh.md b/docs/mesh.md
index 45dc87ec..d3f9bffb 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -218,7 +218,7 @@ Normals stay those of the base mesh. Test: `tests/mesh-shape-keys.test.js`.
### Whole-mesh modifiers
-`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `weighted_normal` and `smooth_by_angle` take no selection and no name, and work as edits or stack nodes. Their fields and defaults are plain data in `MESH_MODIFIER_NOTES` (`src/agent-scene-capabilities.js`), which `scene_capabilities` returns as `meshModifiers`; the code is in `src/mesh-modifiers.js` and `src/mesh-restructure.js`.
+`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `bounding_box`, `convex_hull`, `weighted_normal` and `smooth_by_angle` take no selection and no name, and work as edits or stack nodes. Their fields and defaults are plain data in `MESH_MODIFIER_NOTES` (`src/agent-scene-capabilities.js`), which `scene_capabilities` returns as `meshModifiers`; the code is in `src/mesh-modifiers.js` and `src/mesh-restructure.js`.
| op | fields | does |
| --- | --- | --- |
@@ -237,6 +237,8 @@ Normals stay those of the base mesh. Test: `tests/mesh-shape-keys.test.js`.
| `wave` | `height` (0.5), `width` (1.5), `narrowness` (1.5), `speed` (0.25), `time` (0), `timeOffset`, `start`, `cyclic` (true), `axes` (xy), `normal` | A travelling gaussian ripple along z, equal to Blender Wave at the same frame. |
| `weighted_normal` | `angle` (30), `weight` (50, 1 to 100) | Stores one shading normal per corner: faces around a vertex share it unless the edge is sharp or bends more than the angle, each face counting by its area to the power weight / 50. Put it last in the stack. |
| `smooth_by_angle` | `angle` (30), `ignoreSharp` (false) | Marks edges bending more than the angle sharp and the others smooth, over the geometry `smoothAngle`; sharp edges made by hand, and the 12 of a box, stay sharp unless `ignoreSharp` is set. |
+| `bounding_box` | none | Replaces the mesh with the axis-aligned box around all its vertices: 8 vertices and 6 quads. Tags and attributes are dropped. |
+| `convex_hull` | none | Replaces the mesh with its convex hull, outward triangles on the extreme vertices only, from at most 8192 vertices. A mesh whose vertices lie on one line or in one plane has no hull and is refused. Tags and attributes are dropped. |
`triangulate` and `edge_split` check their output size before building it, against the same vertex and face limits as the other edits. Each op has cases in `tests/fixtures/blender/cases.json` and matches Blender 5.2 with no listed difference. `screw` and `wireframe` have cases in the same fixtures (the volume of the open screw strips differs by winding, listed in `differences.json`); `wave` matches Blender on two cases; `skin`, `lattice`, `curve` and `hook` are not compared with Blender, because each needs a second object there. The two normal modifiers are tested by their own properties, because the Blender comparison does not measure normals. Not yet: `shrinkwrap` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.
@@ -266,6 +268,7 @@ Operators that take numbers also take vectors and work on each component; a numb
| Comparison and logic | `lt` `lte` `gt` `gte` `eq` give 1 or 0; `and` `or` `not`; `if: [condition, a, b]` |
| Motion only | `"time"` and `{ "node", "property", "component", "space" }` read time and node values in a driver; a field rejects them, and a driver rejects the field inputs below. |
| Vectors | `vec: [x, y, z]`, `dot` `cross` `distance`, `length` `normalize`, `x` `y` `z` read a component |
+| Rotation | `rotate: [vector, axis, angle]` turns a vector about an axis (radians; a zero axis does nothing); `align: [direction]` gives the Euler angles (X then Y then Z, radians) that turn +Y onto the direction; `transform: [point, move, euler, size]` scales, rotates, then moves a point (only the point is required) |
| Attributes | `{ "attr": "position" \| "normal" }` with optional `component`, `{ "attr": "index" }`, `{ "attr": "tag", "name": "top" }` |
| Random | `{ "noise": { "scale", "seed", "octaves", "at" } }` smooth value noise in 0 to 1 at a position (default the element's), `{ "random": { "seed" } }` a number in 0 to 1 per element |
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 1bf4d67a..e181d5c2 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -59,12 +59,13 @@ const instanceSpec = z.strictObject({
grid: z.strictObject({ counts: z.tuple([instanceCount, instanceCount, instanceCount]), spacing: vector3 }).optional().describe('Grid of counts[0] x counts[1] x counts[2] points centred on the group.'),
scatter: z.strictObject({ count: instanceCount, min: vector3, max: vector3 }).optional().describe('Seeded random points in a box.'),
surface: z.strictObject({ geometry: identifier, count: instanceCount }).optional().describe("Seeded random points on the surface of a recipe geometry, in that geometry's own space; parent the instanced node to the node that carries it."),
+ curve: z.strictObject({ points: z.array(vector3).min(2).max(256), count: instanceCount, closed: z.boolean().optional(), fillet: z.number().positive().optional() }).optional().describe('Equal steps along a polyline; fillet is a corner radius.'),
seed: z.number().int().min(0).max(2147483647).optional(),
where: fieldExpression.optional().describe('Number expression over the points (position, normal, index); points where it is 0 are dropped.'),
yaw: z.boolean().optional().describe('Random turn about up.'),
- alignToNormal: z.boolean().optional().describe('Surface only: tilt up to the surface normal.'),
+ alignToNormal: z.boolean().optional().describe('Surface or curve: turn up to the normal or direction.'),
scale: z.tuple([z.number().min(0.001).max(1000), z.number().min(0.001).max(1000)]).optional().describe('Random uniform scale range [min, max].'),
-}).describe('Exactly one of grid, scatter or surface. Expands at scene_create into a group node plus one child node per point (<id>.0, <id>.1, ...) that share geometry and material and draw as one instanced batch. At most 2048 candidate points.');
+}).describe('One of grid, scatter, surface or curve. Expands at scene_create into a group node plus one child node per point (<id>.0, <id>.1, ...) that share geometry and material and draw as one instanced batch. At most 2048 candidate points.');
const nodeRecord = z.strictObject({ armature: identifier.optional().describe('Set on nodes an armature generates, and ignored on input. Edit bones through armatures.'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), instances: instanceSpec.optional().describe('Repeat geometry and material at points; needs both ids. Only in the recipe given to scene_create, not in add-node.'), ...nodeFields });
const materialGraph = z.record(z.string(), z.unknown()).describe('Node graph as plain JSON, never code. Outputs, nodes, inputs and limits are in scene_capabilities materialGraph.');
const materialPattern = z.strictObject({
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4f619f87..7b009472 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -155,6 +155,8 @@ export const MESH_MODIFIER_NOTES = Object.freeze({
wave: 'a gaussian ripple of height 0.5 along z (normal true: along the vertex normal) that travels from start [0,0] over axes xy (default), x or y; width 1.5, narrowness 0 to 50 (1.5), speed 0.25 per frame, time 0 (a frame number), timeOffset 0, cyclic true repeats it. Matches Blender Wave at the same frame.',
weighted_normal: 'corner normals weighted by face area ^ (weight/50), weight 1-100 (50), smoothed across edges under angle 30 that are not sharp. Put it last in the stack.',
smooth_by_angle: 'edges bending over angle 30 (0-180) become sharp, others smooth, over smoothAngle; ignoreSharp true also clears hand-made sharp edges.',
+ bounding_box: 'becomes its axis-aligned box.',
+ convex_hull: 'becomes its convex hull, up to 8192 vertices.',
});
// Vertex colors and groups. Details stay here so the tool schemas stay small.
@@ -165,7 +167,7 @@ export const MESH_ATTRIBUTE_NOTES = Object.freeze({
// Shape keys on a recipe mesh. Details stay here so the tool schemas stay small.
export const MESH_SHAPE_KEY_NOTES = Object.freeze({
- shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are mesh edits that only move vertices (set_position, displace, sculpt, simple_deform, lattice, hook and so on) run on the finished mesh, after the stack. A key that adds or removes vertices is refused. value (0, from 0 to 1) is the weight without motion. Each key becomes a glTF morph target of the mesh. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes } (weight 0 to 1; keys add up); a GLB export writes the targets, their names (mesh.extras.targetNames) and the weights. Normals stay those of the base mesh.',
+ shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are vertex-moving mesh edits (set_position, displace, sculpt, simple_deform, lattice, hook...) run after the stack. value (0, 0 to 1) is the weight without motion. Each key is a glTF morph target. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes }; a GLB export writes targets, names (mesh.extras.targetNames) and weights.',
});
// Organic shaping edits. Details stay here so the tool schemas stay small.
@@ -180,7 +182,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, default 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its width and height. fStop (0.7 to 64) turns on depth of field focused on target; 1.4 or lower is full blur, and effects.depthOfField.blur must stay 0. Orthographic and shifted cameras render with the rasterizer, not the path tracer.',
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} with 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; scene_create_asset is one asset alone). 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, on a decoded copy of its own; scene_apply set-motion tracks move the node as usual and scene time seeks the clip. Copies of one asset share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy of its own (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds its wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',
- navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a node translation track with interpolation LINEAR. radius 0.3 m is how far the walker position stays from holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y, such as half the walker height. Ground and avoided nodes are read at their authored pose. Errors name an unwalkable start or goal, or one that cannot be reached.',
+ navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a node translation track with interpolation LINEAR. radius 0.3 m is how far the walker position stays from holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y, such as half the walker height. Ground and avoided nodes are read at their authored pose.',
meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),
meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),
meshModifiers: MESH_MODIFIER_NOTES,
@@ -190,6 +192,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
fieldExpressions: Object.freeze({
operators: FIELD_OPERATOR_NAMES, attributes: FIELD_ATTRIBUTES,
maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxElements: MAX_FIELD_ELEMENTS,
+ rotation: 'rotate [v, axis, rad]; align [dir]: Euler of +Y to dir; transform [p, move, euler, size].',
}),
instancing: Object.freeze({ sources: INSTANCE_SOURCES, maxCandidatePoints: MAX_INSTANCE_CANDIDATES }),
operations: Object.freeze([
diff --git a/src/curve-operations.js b/src/curve-operations.js
new file mode 100644
index 00000000..ce80a379
--- /dev/null
+++ b/src/curve-operations.js
@@ -0,0 +1,122 @@
+// Polyline curves as plain arrays of [x, y, z]: fillet rounds the corners with circular arcs and resample places points
+// at equal arc length with the direction of travel at each one. Both are deterministic and bounded.
+
+export const MAX_CURVE_POINTS = 256;
+export const MAX_FILLET_ARC_SEGMENTS = 16;
+export const MAX_FILLETED_POINTS = 4096;
+const MINIMUM_LENGTH = 1e-9;
+const STRAIGHT_LIMIT = 1 - 1e-9;
+
+function subtract(first, second) {
+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];
+}
+
+function addScaled(base, direction, factor) {
+ return [base[0] + direction[0] * factor, base[1] + direction[1] * factor, base[2] + direction[2] * factor];
+}
+
+function dot(first, second) {
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
+}
+
+function lengthOf(vector) {
+ return Math.hypot(vector[0], vector[1], vector[2]);
+}
+
+function unit(vector) {
+ const length = lengthOf(vector);
+ return length < MINIMUM_LENGTH ? [0, 0, 0] : [vector[0] / length, vector[1] / length, vector[2] / length];
+}
+
+/** The segments of a polyline as { from, to, length }; a closed curve ends with the segment back to the first point. */
+function segmentsOf(points, closed) {
+ const segments = [];
+ const last = closed ? points.length : points.length - 1;
+ for (let index = 0; index < last; index++) {
+ const from = points[index];
+ const to = points[(index + 1) % points.length];
+ segments.push({ from, to, length: lengthOf(subtract(to, from)) });
+ }
+ return segments;
+}
+
+/** Total length of a polyline. */
+export function curveLength(points, closed = false) {
+ return segmentsOf(points, closed).reduce((total, segment) => total + segment.length, 0);
+}
+
+/**
+ * `count` points at equal arc length along the polyline, each with the unit direction of the segment it lies on.
+ * An open curve puts the first and last sample on its ends (count at least 2); a closed one spreads them around the loop.
+ */
+export function resampleCurve(points, count, closed = false) {
+ const segments = segmentsOf(points, closed);
+ const total = segments.reduce((sum, segment) => sum + segment.length, 0);
+ if (!(total > MINIMUM_LENGTH)) throw new RangeError('The curve has no length.');
+ const step = closed ? total / count : total / (count - 1);
+ const samples = [];
+ let segmentIndex = 0;
+ let segmentStart = 0;
+ for (let sample = 0; sample < count; sample++) {
+ const distance = sample * step;
+ while (segmentIndex < segments.length - 1 && distance > segmentStart + segments[segmentIndex].length) {
+ segmentStart += segments[segmentIndex].length;
+ segmentIndex++;
+ }
+ const segment = segments[segmentIndex];
+ const along = segment.length < MINIMUM_LENGTH ? 0 : Math.min(1, Math.max(0, (distance - segmentStart) / segment.length));
+ samples.push({
+ point: addScaled(segment.from, subtract(segment.to, segment.from), along),
+ direction: unit(subtract(segment.to, segment.from)),
+ });
+ }
+ return samples;
+}
+
+function filletCorner(previous, corner, next, radius, arcSegments) {
+ const toPrevious = unit(subtract(previous, corner));
+ const toNext = unit(subtract(next, corner));
+ const cosine = dot(toPrevious, toNext);
+ if (cosine <= -STRAIGHT_LIMIT || cosine >= STRAIGHT_LIMIT) return [corner];
+ const halfAngle = Math.acos(cosine) / 2;
+ // The arc may use at most half of each neighbouring segment, so two corners never fight over one segment.
+ const room = Math.min(lengthOf(subtract(previous, corner)), lengthOf(subtract(next, corner))) / 2;
+ const reach = Math.min(radius / Math.tan(halfAngle), room);
+ const usedRadius = reach * Math.tan(halfAngle);
+ const start = addScaled(corner, toPrevious, reach);
+ const end = addScaled(corner, toNext, reach);
+ const bisector = unit([toPrevious[0] + toNext[0], toPrevious[1] + toNext[1], toPrevious[2] + toNext[2]]);
+ const center = addScaled(corner, bisector, usedRadius / Math.sin(halfAngle));
+ const startArm = subtract(start, center);
+ const endArm = subtract(end, center);
+ const sweep = Math.acos(Math.min(1, Math.max(-1, dot(unit(startArm), unit(endArm)))));
+ const arc = [];
+ for (let step = 0; step <= arcSegments; step++) {
+ const fraction = step / arcSegments;
+ const weightStart = Math.sin((1 - fraction) * sweep) / Math.sin(sweep);
+ const weightEnd = Math.sin(fraction * sweep) / Math.sin(sweep);
+ arc.push([0, 1, 2].map(axis => center[axis] + startArm[axis] * weightStart + endArm[axis] * weightEnd));
+ }
+ return arc;
+}
+
+/**
+ * Round every interior corner (every corner of a closed curve) with a circular arc of the given radius, drawn in
+ * `arcSegments` straight pieces. A radius that does not fit between neighbouring corners is reduced to fit.
+ */
+export function filletCurve(points, radius, arcSegments, closed = false) {
+ const result = [];
+ const count = points.length;
+ for (let index = 0; index < count; index++) {
+ const isEnd = !closed && (index === 0 || index === count - 1);
+ if (isEnd) {
+ result.push(points[index]);
+ continue;
+ }
+ const previous = points[(index + count - 1) % count];
+ const next = points[(index + 1) % count];
+ result.push(...filletCorner(previous, points[index], next, radius, arcSegments));
+ if (result.length > MAX_FILLETED_POINTS) throw new RangeError(`Fillet makes more than ${MAX_FILLETED_POINTS} points; use fewer corners or arc segments.`);
+ }
+ return result;
+}
diff --git a/src/field-rotation.js b/src/field-rotation.js
new file mode 100644
index 00000000..9589133e
--- /dev/null
+++ b/src/field-rotation.js
@@ -0,0 +1,116 @@
+import { partsOf, requireScalar, vectorValue } from './expression.js';
+
+// Rotation and matrix operators of the field language, kept apart from the vector basics in mesh-fields.js.
+// Angles are radians and an Euler triple is X then Y then Z (the rotation of a node), like sin and cos.
+//
+// { "rotate": [vector, axis, angle] } turn a vector about an axis
+// { "align": [direction] } Euler angles that turn +Y onto the direction
+// { "transform": [point, move, euler, size] } scale, rotate, then move a point (move, euler and size are optional)
+
+const UP = Object.freeze([0, 1, 0]);
+const PARALLEL_LIMIT = 1 - 1e-12;
+const GIMBAL_LIMIT = 1 - 1e-9;
+
+function normalizedOrZero(vector) {
+ const length = Math.hypot(vector[0], vector[1], vector[2]);
+ return length === 0 ? [0, 0, 0] : [vector[0] / length, vector[1] / length, vector[2] / length];
+}
+
+/** Rodrigues rotation of a vector about an axis; a zero axis leaves the vector as it is. */
+export function rotateAboutAxis(vector, axis, angle) {
+ const unit = normalizedOrZero(axis);
+ if (unit[0] === 0 && unit[1] === 0 && unit[2] === 0) return [...vector];
+ const cosine = Math.cos(angle);
+ const sine = Math.sin(angle);
+ const along = unit[0] * vector[0] + unit[1] * vector[1] + unit[2] * vector[2];
+ const crossed = [
+ unit[1] * vector[2] - unit[2] * vector[1],
+ unit[2] * vector[0] - unit[0] * vector[2],
+ unit[0] * vector[1] - unit[1] * vector[0],
+ ];
+ return vector.map((component, axisIndex) => component * cosine + crossed[axisIndex] * sine + unit[axisIndex] * along * (1 - cosine));
+}
+
+/** Rotation matrix (row major, 9 numbers) for XYZ Euler angles: Rz * Ry * Rx. */
+export function eulerMatrix([angleX, angleY, angleZ]) {
+ const [sinX, cosX, sinY, cosY, sinZ, cosZ] = [Math.sin(angleX), Math.cos(angleX), Math.sin(angleY), Math.cos(angleY), Math.sin(angleZ), Math.cos(angleZ)];
+ 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,
+ ];
+}
+
+/** XYZ Euler angles of the shortest turn that takes +Y onto the direction; a zero direction gives no turn. */
+export function alignEuler(direction) {
+ const target = normalizedOrZero(direction);
+ const cosine = target[1];
+ if (target[0] === 0 && target[1] === 0 && target[2] === 0) return [0, 0, 0];
+ let axis = [UP[1] * target[2] - UP[2] * target[1], UP[2] * target[0] - UP[0] * target[2], UP[0] * target[1] - UP[1] * target[0]];
+ if (cosine <= -PARALLEL_LIMIT) axis = [1, 0, 0];
+ const angle = Math.acos(Math.min(1, Math.max(-1, cosine)));
+ const columns = [[1, 0, 0], [0, 1, 0], [0, 0, 1]].map(basis => rotateAboutAxis(basis, axis, angle));
+ const entry = (row, column) => columns[column][row];
+ if (Math.abs(entry(2, 0)) >= GIMBAL_LIMIT) {
+ return [Math.atan2(-entry(1, 2), entry(1, 1)), Math.asin(Math.max(-1, Math.min(1, -entry(2, 0)))), 0];
+ }
+ return [Math.atan2(entry(2, 1), entry(2, 2)), Math.asin(-entry(2, 0)), Math.atan2(entry(1, 0), entry(0, 0))];
+}
+
+function vectorOperand(value, label) {
+ if (value.kind !== 'vector') throw new TypeError(`${label} needs a vector.`);
+ return value.parts;
+}
+
+// One result per element is shared by the three parts, so a vector result is computed once per element.
+function sharedVector(compute) {
+ let cachedIndex = -1;
+ let cachedResult = null;
+ return axis => index => {
+ if (index !== cachedIndex) {
+ cachedResult = compute(index);
+ cachedIndex = index;
+ }
+ return cachedResult[axis];
+ };
+}
+
+function readVector(parts, index) {
+ return [parts[0](index), parts[1](index), parts[2](index)];
+}
+
+function buildRotate([vector, axis, angle]) {
+ const vectorParts = vectorOperand(vector, 'rotate');
+ const axisParts = vectorOperand(axis, 'rotate');
+ const angleAt = requireScalar(angle, 'rotate');
+ const part = sharedVector(index => rotateAboutAxis(readVector(vectorParts, index), readVector(axisParts, index), angleAt(index)));
+ return vectorValue(part(0), part(1), part(2));
+}
+
+function buildAlign([direction]) {
+ const directionParts = vectorOperand(direction, 'align');
+ const part = sharedVector(index => alignEuler(readVector(directionParts, index)));
+ return vectorValue(part(0), part(1), part(2));
+}
+
+function buildTransform([point, move, euler, size]) {
+ const pointParts = vectorOperand(point, 'transform');
+ const moveParts = move === undefined ? null : partsOf(move);
+ const eulerParts = euler === undefined ? null : vectorOperand(euler, 'transform');
+ const sizeParts = size === undefined ? null : partsOf(size);
+ const part = sharedVector(index => {
+ const scaled = readVector(pointParts, index).map((component, axis) => (sizeParts ? component * sizeParts[axis](index) : component));
+ const matrix = eulerParts ? eulerMatrix(readVector(eulerParts, index)) : null;
+ const turned = matrix
+ ? [0, 1, 2].map(row => matrix[row * 3] * scaled[0] + matrix[row * 3 + 1] * scaled[1] + matrix[row * 3 + 2] * scaled[2])
+ : scaled;
+ return turned.map((component, axis) => (moveParts ? component + moveParts[axis](index) : component));
+ });
+ return vectorValue(part(0), part(1), part(2));
+}
+
+export const ROTATION_OPERATORS = Object.freeze({
+ rotate: { min: 3, max: 3, build: buildRotate },
+ align: { min: 1, max: 1, build: buildAlign },
+ transform: { min: 1, max: 4, build: buildTransform },
+});
diff --git a/src/mesh-fields.js b/src/mesh-fields.js
index b421e9fa..7426a987 100644
--- a/src/mesh-fields.js
+++ b/src/mesh-fields.js
@@ -1,6 +1,7 @@
import { TAG_PREFIX, meshTags } from './mesh-data.js';
import { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK, FIELD_ATTRIBUTES } from './mesh-operations.js';
import { faceCentroids, faceNormals, vertexNormals } from './mesh-normals.js';
+import { ROTATION_OPERATORS } from './field-rotation.js';
import {
COMPONENTS, compileNode, createOperators, describeKey, isBoundedNumber, isPlainObject, requireScalar, scalarValue, vectorValue,
} from './expression.js';
@@ -157,6 +158,7 @@ OPERATORS.set('normalize', vectorOperator(1, 1, normalizeValue));
OPERATORS.set('x', vectorOperator(1, 1, selectComponent(0)));
OPERATORS.set('y', vectorOperator(1, 1, selectComponent(1)));
OPERATORS.set('z', vectorOperator(1, 1, selectComponent(2)));
+for (const [name, operator] of Object.entries(ROTATION_OPERATORS)) OPERATORS.set(name, operator);
export { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK };
const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random']);
diff --git a/src/mesh-hull-modifiers.js b/src/mesh-hull-modifiers.js
new file mode 100644
index 00000000..c702f4cb
--- /dev/null
+++ b/src/mesh-hull-modifiers.js
@@ -0,0 +1,158 @@
+import { createMeshData } from './mesh-data.js';
+
+// Two whole-mesh modifiers that replace the mesh with a simple solid around it: bounding_box is the axis-aligned box
+// (6 quads) and convex_hull is the smallest convex solid (triangles). Tags and attributes are dropped.
+
+export const MAX_HULL_VERTICES = 8192;
+const HULL_EPSILON_SCALE = 1e-9;
+
+// Corner k of the box is (k & 1, k >> 1 & 1, k >> 2 & 1), 0 for the minimum and 1 for the maximum of that axis.
+// Every face lists its corners counter-clockwise seen from outside.
+const BOX_FACES = Object.freeze([[0, 4, 6, 2], [1, 3, 7, 5], [0, 1, 5, 4], [2, 6, 7, 3], [0, 2, 3, 1], [4, 5, 7, 6]]);
+
+/** The axis-aligned box around all vertices: 8 vertices, 6 quads. */
+export function boundingBoxMesh(mesh) {
+ const low = [Infinity, Infinity, Infinity];
+ const high = [-Infinity, -Infinity, -Infinity];
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ for (let axis = 0; axis < 3; axis++) {
+ const value = mesh.positions[vertex * 3 + axis];
+ if (value < low[axis]) low[axis] = value;
+ if (value > high[axis]) high[axis] = value;
+ }
+ }
+ const positions = new Float32Array(24);
+ for (let corner = 0; corner < 8; corner++) {
+ for (let axis = 0; axis < 3; axis++) positions[corner * 3 + axis] = (corner >> axis) & 1 ? high[axis] : low[axis];
+ }
+ const faceOffsets = Uint32Array.from({ length: 7 }, (unused, face) => face * 4);
+ return createMeshData({ positions, faceOffsets, cornerVertices: Uint32Array.from(BOX_FACES.flat()) });
+}
+
+function pointAt(positions, vertex) {
+ return [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]];
+}
+
+function subtract(first, second) {
+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];
+}
+
+function cross(first, second) {
+ return [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];
+}
+
+function dot(first, second) {
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
+}
+
+// A hull face keeps its outward plane, so "which side of it is this point" is one dot product.
+function createFace(positions, first, second, third) {
+ const origin = pointAt(positions, first);
+ const raw = cross(subtract(pointAt(positions, second), origin), subtract(pointAt(positions, third), origin));
+ const length = Math.hypot(raw[0], raw[1], raw[2]) || 1;
+ const normal = [raw[0] / length, raw[1] / length, raw[2] / length];
+ return { corners: [first, second, third], normal, offset: dot(normal, origin), alive: true };
+}
+
+function distanceAbove(face, point) {
+ return dot(face.normal, point) - face.offset;
+}
+
+function findStartingTetrahedron(positions, count, epsilon) {
+ const extreme = [0, 0];
+ for (let vertex = 1; vertex < count; vertex++) {
+ if (positions[vertex * 3] < positions[extreme[0] * 3]) extreme[0] = vertex;
+ if (positions[vertex * 3] > positions[extreme[1] * 3]) extreme[1] = vertex;
+ }
+ const first = extreme[0];
+ let second = extreme[1];
+ if (first === second || Math.hypot(...subtract(pointAt(positions, first), pointAt(positions, second))) <= epsilon) {
+ second = Array.from({ length: count }, (unused, vertex) => vertex)
+ .reduce((best, vertex) => (Math.hypot(...subtract(pointAt(positions, vertex), pointAt(positions, first))) > Math.hypot(...subtract(pointAt(positions, best), pointAt(positions, first))) ? vertex : best), first);
+ }
+ const line = subtract(pointAt(positions, second), pointAt(positions, first));
+ let third = -1;
+ let bestArea = epsilon;
+ for (let vertex = 0; vertex < count; vertex++) {
+ const area = Math.hypot(...cross(line, subtract(pointAt(positions, vertex), pointAt(positions, first))));
+ if (area > bestArea) {
+ bestArea = area;
+ third = vertex;
+ }
+ }
+ if (third < 0) throw new RangeError('convex_hull needs vertices that do not all lie on one line.');
+ const normal = cross(line, subtract(pointAt(positions, third), pointAt(positions, first)));
+ let fourth = -1;
+ let bestHeight = epsilon * Math.hypot(...normal);
+ for (let vertex = 0; vertex < count; vertex++) {
+ const height = Math.abs(dot(normal, subtract(pointAt(positions, vertex), pointAt(positions, first))));
+ if (height > bestHeight) {
+ bestHeight = height;
+ fourth = vertex;
+ }
+ }
+ if (fourth < 0) throw new RangeError('convex_hull needs vertices that do not all lie in one plane.');
+ return [first, second, third, fourth];
+}
+
+/** Incremental convex hull of all vertices as a triangle mesh with outward faces; unused vertices are dropped. */
+export function convexHullMesh(mesh) {
+ if (mesh.vertexCount > MAX_HULL_VERTICES) {
+ throw new RangeError(`convex_hull takes at most ${MAX_HULL_VERTICES} vertices and the mesh has ${mesh.vertexCount}. Decimate or weld first.`);
+ }
+ const { positions } = mesh;
+ const count = mesh.vertexCount;
+ const bounds = boundingBoxMesh(mesh).positions;
+ const epsilon = Math.hypot(bounds[21] - bounds[0], bounds[22] - bounds[1], bounds[23] - bounds[2]) * HULL_EPSILON_SCALE;
+ const [first, second, third, fourth] = findStartingTetrahedron(positions, count, epsilon);
+ const inside = [0, 1, 2].map(axis => (positions[first * 3 + axis] + positions[second * 3 + axis] + positions[third * 3 + axis] + positions[fourth * 3 + axis]) / 4);
+ const faces = [];
+ for (const [a, b, c] of [[first, second, third], [first, second, fourth], [first, third, fourth], [second, third, fourth]]) {
+ const face = createFace(positions, a, b, c);
+ if (distanceAbove(face, inside) > 0) {
+ face.corners = [a, c, b];
+ face.normal = face.normal.map(component => -component);
+ face.offset = -face.offset;
+ }
+ faces.push(face);
+ }
+ const used = new Set([first, second, third, fourth]);
+ for (let vertex = 0; vertex < count; vertex++) {
+ if (used.has(vertex)) continue;
+ const point = pointAt(positions, vertex);
+ const visible = faces.filter(face => face.alive && distanceAbove(face, point) > epsilon);
+ if (visible.length === 0) continue;
+ const horizon = new Map();
+ for (const face of visible) {
+ face.alive = false;
+ for (let side = 0; side < 3; side++) horizon.set(`${face.corners[side]}:${face.corners[(side + 1) % 3]}`, [face.corners[side], face.corners[(side + 1) % 3]]);
+ }
+ for (const [start, end] of horizon.values()) {
+ if (horizon.has(`${end}:${start}`)) continue;
+ faces.push(createFace(positions, start, end, vertex));
+ }
+ }
+ const alive = faces.filter(face => face.alive);
+ const remap = new Map();
+ const hullPositions = [];
+ const cornerVertices = [];
+ for (const face of alive) {
+ for (const vertex of face.corners) {
+ if (!remap.has(vertex)) {
+ remap.set(vertex, remap.size);
+ hullPositions.push(...pointAt(positions, vertex));
+ }
+ cornerVertices.push(remap.get(vertex));
+ }
+ }
+ const faceOffsets = Uint32Array.from({ length: alive.length + 1 }, (unused, face) => face * 3);
+ return createMeshData({ positions: Float32Array.from(hullPositions), faceOffsets, cornerVertices: Uint32Array.from(cornerVertices) });
+}
+
+export const HULL_RUNNERS = Object.freeze({
+ bounding_box: mesh => ({ mesh: boundingBoxMesh(mesh), result: {} }),
+ convex_hull: mesh => {
+ const hull = convexHullMesh(mesh);
+ return { mesh: hull, result: { hullVertices: hull.vertexCount } };
+ },
+});
diff --git a/src/mesh-instances.js b/src/mesh-instances.js
index 94d4de69..6e922182 100644
--- a/src/mesh-instances.js
+++ b/src/mesh-instances.js
@@ -1,6 +1,7 @@
import { quat } from 'gl-matrix';
import { INSTANCE_SOURCES, MAX_INSTANCE_CANDIDATES } from './mesh-operations.js';
import { evaluateField, pointSetContext, seededRandom } from './mesh-fields.js';
+import { MAX_CURVE_POINTS, filletCurve, resampleCurve } from './curve-operations.js';
// Instance on points: a node with an `instances` record becomes a group node plus one child node per point, all
// sharing the node's geometry and material, so the renderer draws them in one instanced call. Points come from a
@@ -20,6 +21,7 @@ const MAX_COORDINATE = 1e6;
const SOURCES = INSTANCE_SOURCES;
const INSTANCE_FIELDS = Object.freeze([...SOURCES, 'seed', 'where', 'yaw', 'alignToNormal', 'scale']);
const MAX_SEED = 0x7fffffff;
+const CURVE_FILLET_SEGMENTS = 8;
const UP = Object.freeze([0, 1, 0]);
const CHANNEL_SCATTER = 20;
@@ -141,11 +143,37 @@ export function surfacePoints(geometry, count, seed) {
return { positions, normals };
}
+// Points at equal arc length along a polyline, optionally with rounded corners; the "normal" of each point is the
+// direction of travel, so alignToNormal turns up along the curve.
+function curvePoints(source) {
+ plainRecord(source, 'curve', ['points', 'count', 'closed', 'fillet']);
+ if (!Array.isArray(source.points) || source.points.length < 2 || source.points.length > MAX_CURVE_POINTS) {
+ throw instanceError(`curve points are 2 to ${MAX_CURVE_POINTS} positions.`);
+ }
+ const corners = source.points.map(point => coordinates(point, 'curve point'));
+ const closed = source.closed === true;
+ if (source.closed !== undefined && typeof source.closed !== 'boolean') throw instanceError('curve closed must be boolean.');
+ const count = wholeNumber(source.count, closed ? 3 : 2, MAX_INSTANCE_CANDIDATES, 'curve count');
+ if (source.fillet !== undefined && !(typeof source.fillet === 'number' && source.fillet > 0 && source.fillet <= MAX_COORDINATE)) {
+ throw instanceError('curve fillet is a radius above 0.');
+ }
+ const path = source.fillet === undefined ? corners : filletCurve(corners, source.fillet, CURVE_FILLET_SEGMENTS, closed);
+ const samples = resampleCurve(path, count, closed);
+ const positions = new Float64Array(count * 3);
+ const normals = new Float64Array(count * 3);
+ samples.forEach(({ point, direction }, index) => {
+ positions.set(point, index * 3);
+ normals.set(direction, index * 3);
+ });
+ return { positions, normals };
+}
+
function candidatePoints(spec, seed, resolveSurface) {
const sourceName = SOURCES.filter(name => Object.hasOwn(spec, name));
if (sourceName.length !== 1) throw instanceError(`give exactly one point source: ${SOURCES.join(', ')}.`);
if (sourceName[0] === 'grid') return gridPoints(spec.grid);
if (sourceName[0] === 'scatter') return scatterPoints(spec.scatter, seed);
+ if (sourceName[0] === 'curve') return curvePoints(spec.curve);
const source = plainRecord(spec.surface, 'surface', ['geometry', 'count']);
const count = wholeNumber(source.count, 1, MAX_INSTANCE_CANDIDATES, 'surface count');
if (typeof source.geometry !== 'string') throw instanceError('surface needs a geometry id.');
@@ -191,7 +219,7 @@ function checkedSpec(spec) {
for (const flag of ['yaw', 'alignToNormal']) {
if (spec[flag] !== undefined && typeof spec[flag] !== 'boolean') throw instanceError(`${flag} must be boolean.`);
}
- if (spec.alignToNormal && !Object.hasOwn(spec, 'surface')) throw instanceError('alignToNormal needs a surface source, because only a surface has normals.');
+ if (spec.alignToNormal && !Object.hasOwn(spec, 'surface') && !Object.hasOwn(spec, 'curve')) throw instanceError('alignToNormal needs a surface or curve source, because only those have normals.');
if (spec.scale !== undefined) {
const range = spec.scale;
if (!Array.isArray(range) || range.length !== 2 || !range.every(entry => typeof entry === 'number' && Number.isFinite(entry) && entry > 0 && entry <= 1000) || range[0] > range[1]) {
diff --git a/src/mesh-modifiers.js b/src/mesh-modifiers.js
index 78e348d8..c1dfabe1 100644
--- a/src/mesh-modifiers.js
+++ b/src/mesh-modifiers.js
@@ -5,6 +5,7 @@ import { MODIFIER_OPERATIONS } from './mesh-operations.js';
import { normalizeGeneratorEdit, GENERATOR_RUNNERS } from './mesh-generator-modifiers.js';
import { normalizeNormalEdit, NORMAL_RUNNERS } from './mesh-normal-modifiers.js';
import { isDeformModifier, normalizeDeformEdit, runDeformEdit } from './mesh-deform-modifiers.js';
+import { HULL_RUNNERS } from './mesh-hull-modifiers.js';
// The whole-mesh modifiers as recipe operations: validation of their fields and running them on MeshData. Smooth, cast and
// simple_deform only move vertices; weld, triangulate and edge_split change the faces (see mesh-restructure.js).
@@ -187,6 +188,7 @@ function simpleDeformPositions(mesh, { mode, axis, angle, factor }) {
export function runModifierEdit(mesh, edit, { maxVertices, maxFaces }) {
if (Object.hasOwn(GENERATOR_RUNNERS, edit.op)) return GENERATOR_RUNNERS[edit.op](mesh, edit, { maxVertices, maxFaces });
if (Object.hasOwn(NORMAL_RUNNERS, edit.op)) return { mesh: NORMAL_RUNNERS[edit.op](mesh, edit), result: {} };
+ if (Object.hasOwn(HULL_RUNNERS, edit.op)) return HULL_RUNNERS[edit.op](mesh);
if (isDeformModifier(edit.op)) return runDeformEdit(mesh, edit);
switch (edit.op) {
case 'weld': {
diff --git a/src/mesh-operations.js b/src/mesh-operations.js
index f1cf9d9b..0652f422 100644
--- a/src/mesh-operations.js
+++ b/src/mesh-operations.js
@@ -21,6 +21,8 @@ export const MODIFIER_OPERATIONS = Object.freeze({
wave: { fields: ['height', 'width', 'narrowness', 'speed', 'time', 'timeOffset', 'start', 'cyclic', 'axes', 'normal'], tags: [] },
weighted_normal: { fields: ['angle', 'weight'], tags: [] },
smooth_by_angle: { fields: ['angle', 'ignoreSharp'], tags: [] },
+ bounding_box: { fields: [], tags: [] },
+ convex_hull: { fields: [], tags: [] },
});
export const MESH_EDIT_OPERATIONS = Object.freeze({
@@ -84,9 +86,10 @@ export const FIELD_OPERATOR_NAMES = Object.freeze([
'neg', 'abs', 'sqrt', 'sin', 'cos', 'floor', 'ceil', 'round', 'fract', 'sign', 'saturate',
'lt', 'lte', 'gt', 'gte', 'eq', 'and', 'or', 'not', 'if',
'vec', 'dot', 'cross', 'distance', 'length', 'normalize', 'x', 'y', 'z',
+ 'rotate', 'align', 'transform',
'attr', 'noise', 'random',
]);
-export const INSTANCE_SOURCES = Object.freeze(['grid', 'scatter', 'surface']);
+export const INSTANCE_SOURCES = Object.freeze(['grid', 'scatter', 'surface', 'curve']);
export const MAX_INSTANCE_CANDIDATES = 2048;
// Imported GLB parts take the same edits. Skin weights, morph deltas and vertex colours of new geometry come from the
diff --git a/tests/field-math.test.js b/tests/field-math.test.js
new file mode 100644
index 00000000..e1181695
--- /dev/null
+++ b/tests/field-math.test.js
@@ -0,0 +1,112 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { quat, vec3 } from 'gl-matrix';
+import { createMeshData, applyMeshEdits } from '../src/mesh.js';
+import { FIELD_OPERATORS, evaluateField, pointSetContext } from '../src/mesh-fields.js';
+import { expandInstancedNodes } from '../src/mesh-instances.js';
+import { filletCurve, resampleCurve, curveLength } from '../src/curve-operations.js';
+import { boundingBoxMesh, convexHullMesh } from '../src/mesh-hull-modifiers.js';
+import { signedVolume } from '../src/mesh-surface-distance.js';
+import { alignEuler } from '../src/field-rotation.js';
+import { FIELD_OPERATOR_NAMES } from '../src/mesh-operations.js';
+
+function evaluateVector(expression) {
+ const positions = new Float64Array(3);
+ const normals = new Float64Array(3);
+ return Array.from(evaluateField(expression, pointSetContext(positions, normals), { kind: 'vector' }).values);
+}
+
+function assertClose(actual, expected, message) {
+ assert.equal(actual.length, expected.length, message);
+ actual.forEach((value, index) => assert.ok(Math.abs(value - expected[index]) < 1e-6, `${message}: ${actual} vs ${expected}`));
+}
+
+function cubePoints() {
+ const points = [];
+ for (let corner = 0; corner < 8; corner++) points.push([corner & 1, (corner >> 1) & 1, (corner >> 2) & 1]);
+ points.push([0.5, 0.5, 0.5], [0.2, 0.3, 0.4]);
+ return points;
+}
+
+function pointCloudMesh(points) {
+ return createMeshData({ positions: Float32Array.from(points.flat()), faceOffsets: Uint32Array.from([0, 3]), cornerVertices: Uint32Array.from([0, 1, 2]) });
+}
+
+function instancesFor(spec, maxNodes = 100) {
+ return expandInstancedNodes([{ id: 'post', geometry: 'g', material: 'm', instances: spec }], { resolveSurface: () => null, maxNodes });
+}
+
+test('rotate turns a vector about an axis by an angle', () => {
+ assertClose(evaluateVector({ rotate: [[1, 0, 0], [0, 0, 1], Math.PI / 2] }), [0, 1, 0], 'x about z by a quarter turn');
+ assertClose(evaluateVector({ rotate: [[1, 2, 3], [0, 0, 0], 1] }), [1, 2, 3], 'a zero axis leaves it');
+});
+
+test('align gives Euler angles that turn +Y onto the direction, and transform applies them', () => {
+ for (const direction of [[1, 0, 0], [0, 0, 1], [0, -1, 0], [0, 1, 0], [1, 2, -3], [-2, -0.5, 1]]) {
+ const unit = vec3.normalize(vec3.create(), direction);
+ assertClose(evaluateVector({ transform: [[0, 1, 0], [0, 0, 0], { align: [direction] }, 1] }), Array.from(unit), `align ${direction}`);
+ }
+ assertClose(evaluateVector({ transform: [[1, 1, 1], [1, 2, 3], [0, 0, 0], [2, 3, 4]] }), [3, 5, 7], 'scale then move');
+ assertClose(evaluateVector({ transform: [[1, 0, 0], [0, 0, 0], [0, 0, Math.PI / 2]] }), [0, 1, 0], 'euler z');
+ assert.deepEqual(alignEuler([0, 0, 0]), [0, 0, 0]);
+});
+
+test('the field operator names stay in step with the language', () => {
+ assert.deepEqual([...FIELD_OPERATORS].sort(), [...FIELD_OPERATOR_NAMES].sort());
+});
+
+test('resample places points at equal arc length with the direction of travel', () => {
+ const samples = resampleCurve([[0, 0, 0], [4, 0, 0], [4, 4, 0]], 5, false);
+ assertClose(samples[2].point, [4, 0, 0], 'middle of an L is its corner');
+ assertClose(samples[0].direction, [1, 0, 0], 'first direction');
+ assertClose(samples[4].point, [4, 4, 0], 'last sample on the end');
+ assertClose(samples[3].direction, [0, 1, 0], 'second leg direction');
+ const loop = resampleCurve([[0, 0, 0], [2, 0, 0], [2, 2, 0], [0, 2, 0]], 8, true);
+ assertClose(loop[1].point, [1, 0, 0], 'closed loop step is perimeter / count');
+});
+
+test('fillet rounds a corner with an arc of the given radius and keeps the ends', () => {
+ const path = filletCurve([[0, 0, 0], [4, 0, 0], [4, 4, 0]], 1, 8, false);
+ assertClose(path[0], [0, 0, 0], 'start kept');
+ assertClose(path.at(-1), [4, 4, 0], 'end kept');
+ const arc = path.slice(1, -1);
+ assert.equal(arc.length, 9);
+ assertClose(arc[0], [3, 0, 0], 'arc starts one radius before the corner');
+ assertClose(arc.at(-1), [4, 1, 0], 'arc ends one radius after the corner');
+ for (const point of arc) assert.ok(Math.abs(Math.hypot(point[0] - 3, point[1] - 1) - 1) < 1e-9, 'every arc point is one radius from the center');
+ assert.ok(curveLength(path) < 8, 'rounding shortens the path');
+ const tight = filletCurve([[0, 0, 0], [1, 0, 0], [1, 1, 0]], 5, 4, false);
+ assertClose(tight[1], [0.5, 0, 0], 'a radius that does not fit is reduced to half the segment');
+});
+
+test('instances align along a curve', () => {
+ const children = instancesFor({ curve: { points: [[0, 0, 0], [4, 0, 0], [4, 4, 0]], count: 5 }, alignToNormal: true }).slice(1);
+ assert.equal(children.length, 5);
+ assertClose(children[2].translation, [4, 0, 0], 'placed on the curve');
+ assertClose(Array.from(vec3.transformQuat(vec3.create(), [0, 1, 0], children[0].rotation)), [1, 0, 0], 'up follows the first leg');
+ assertClose(Array.from(vec3.transformQuat(vec3.create(), [0, 1, 0], children[4].rotation)), [0, 1, 0], 'up follows the second leg');
+ assert.ok(quat.length(children[0].rotation) > 0.99);
+ const rounded = instancesFor({ curve: { points: [[0, 0, 0], [4, 0, 0], [4, 4, 0]], count: 9, fillet: 1 }, alignToNormal: true });
+ assert.equal(rounded.length, 10);
+ assert.throws(() => instancesFor({ grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, alignToNormal: true }), /surface or curve/);
+});
+
+test('bounding_box is the axis-aligned box around the mesh', () => {
+ const box = boundingBoxMesh(pointCloudMesh([[1, 2, 3], [-1, 5, 0], [0, 0, 4]]));
+ assert.equal(box.vertexCount, 8);
+ assert.equal(box.faceCount, 6);
+ assert.ok(Math.abs(signedVolume(box) - 2 * 5 * 4) < 1e-6, 'outward faces and the right size');
+});
+
+test('convex_hull wraps the points in outward triangles and drops inner points', () => {
+ const hull = convexHullMesh(pointCloudMesh(cubePoints()));
+ assert.equal(hull.vertexCount, 8);
+ assert.ok(Math.abs(signedVolume(hull) - 1) < 1e-6, `unit cube volume, got ${signedVolume(hull)}`);
+ assert.throws(() => convexHullMesh(pointCloudMesh([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]])), /one plane/);
+ assert.throws(() => convexHullMesh(pointCloudMesh([[0, 0, 0], [1, 1, 1], [2, 2, 2]])), /one line/);
+});
+
+test('bounding_box and convex_hull run as recipe edits', () => {
+ const { mesh } = applyMeshEdits(pointCloudMesh(cubePoints()), [{ op: 'convex_hull' }, { op: 'bounding_box' }]);
+ assert.equal(mesh.faceCount, 6);
+});