3D engine that AI agents drive
Add arc, spiral and star curve shapes, poly and NURBS splines, trim and several splines per curve
Nguyen Xuan An612be5feb929
diff --git a/changes/701.md b/changes/701.mdnew file mode 100644index 00000000..09c1a40d--- /dev/null+++ b/changes/701.md@@ -0,0 +1 @@+- `curve` geometry takes `kind` poly or nurbs, several `splines`, arc, spiral and star `shape`s and a `trim`, so rails, ropes and a growing vine need no hand-placed points (#701)diff --git a/changes/701.size.md b/changes/701.size.mdnew file mode 100644index 00000000..d0abd7cb--- /dev/null+++ b/changes/701.size.md@@ -0,0 +1,4 @@+- entry:modeling: arc, spiral and star primitives, poly and NURBS splines, trim and several splines per curve are a modeling capability agents lacked (3094 bytes gzip)+- scene:agent-scene: the curve geometry accepts shape, splines, kind, weights and trim (244 bytes gzip)+- scene:agent-scene+lazy: the same code ships in the lazy bundle (3366 bytes gzip)+- goal:agent-scene: the capability is worth 244 bytes gzip over the goal; lead approved growth for modeling featuresdiff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 80c0002a..a8acebdb 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -90,7 +90,7 @@ The generators also enforce their existing numeric and modeling constraints.| `lathe` | `profile`, `segments`, `startAngle`, `sweep` | Required XY profile, `64`, `0`, `2π` || `extrude` | `contour`, `holes`, `depth`, `steps`, `bevel`, `bevelThickness`, `bevelSegments` | Required XY contour, `[]`, `1`, `1`, `0`, bevel, `3` || `tube` | `path`, `radius`, `segments`, `radialSegments`, `closed` | Required XYZ path, `0.1`, `64`, `12`, `false` |-| `curve` | `points`, `closed`, `radius`, `taper`, `profile`, `resolution`, `radialSegments` | Required points, `false`, `0.05`, none, round, `12`, `8` |+| `curve` | `points` or `shape` or `splines`, `closed`, `kind`, `weights`, `trim`, `radius`, `taper`, `profile`, `resolution`, `radialSegments` | One of points, shape or splines, `false`, `bezier`, 1, none, `0.05`, none, round, `12`, `8` || `text` | `text`, `size`, `depth`, `font`, `align`, `curveSegments` | Required string, `1`, `0.2`, `default`, `left`, `4` || `terrain` | `size`, `resolution`, `seed`, `amplitude`, `holes` | `40` m, `64` cells, `1`, `1` m, none |diff --git a/docs/modeling.md b/docs/modeling.mdindex d088c1f2..28003451 100644--- a/docs/modeling.md+++ b/docs/modeling.md@@ -66,6 +66,31 @@ sweeps a cross-section along a chain of cubic Bezier spans, the way a Blender cuVolume, area and bounds match Blender 5.2 for an open and a closed Bezier curve with a round bevel to 2e-5(`tests/blender-curve-text.test.js`). A Blender bevel resolution of `n` is `radialSegments: 4 + 2n`.+### Splines, shapes and trim++`curveSet(splines, options)` sweeps up to 64 splines (4096 points in all) into one mesh that shares `radius`, `taper`,+`profile`, `resolution` and `radialSegments`. The scene geometry `curve` takes one spline in its own fields or several+in `splines`, never both. A spline is `{ points | shape, closed, kind, weights, trim }`, and `curve(points, { kind, weights, trim })` is the one-spline form.++- `kind` is `bezier` (default), `poly` or `nurbs`. A poly spline is straight segments with sharp corners; each ring takes the+ direction of the segment that leaves it, so corners are not mitred. A NURBS spline is a uniform cubic B-spline: open ones are+ clamped (they start and end on the first and last point), closed ones are periodic. `weights` holds one number above 0 per+ point (default 1); a higher weight pulls the curve toward its point.+- `shape` replaces `points` with a primitive in the XY plane, and sets `closed` and `kind` itself:+ - `{ type: 'arc', radius = 1, startAngle = 0, sweep = 3.14159, segments = 8 }`: a Bezier arc, exact to about 1e-7 of the radius;+ a sweep of 2 pi closes it. Angles are radians; circle segments are arcs.+ - `{ type: 'spiral', rotations = 2, startRadius = 1, endRadius = 1, height = 2, pointsPerRotation = 12, reverse }`: a helix+ along +Z, smooth through its points (a spiral staircase rail is `height` over `rotations`).+ - `{ type: 'star', points = 5, innerRadius = 0.5, outerRadius = 1, innerTwist = 0 }`: a closed poly spline of `2 * points` vertices.+- `trim: { start = 0, end = 1, length = false }` keeps the arc-length range from `start` to `end` as factors of the length, or+ as lengths when `length` is true (lengths past the end are clamped to it). `end` must be greater than `start`. A trimmed+ curve is open and gets caps, also when it was closed. Trimming a range that covers an open curve changes nothing. Trim is+ computed from the same samples every time, so raising `end` frame by frame grows the curve along the same path: that is how a+ vine grows. Building a mesh per frame is the caller's job.++Not covered: trim ranges that wrap around the start of a closed curve, NURBS of other orders or with custom knots, a spline+fill, and mesh edges to curve.+## Text`text(content, { size = 1, depth = 0.2, font = 'default', align = 'left', curveSegments = 4, maxVertices })`diff --git a/docs/parity.md b/docs/parity.mdindex a199dcb1..442979ec 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -52,7 +52,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Meshes > UVs | partial | `uv_unwrap` with LSCM, axis charts and shelf packing. Patterns can not use the result yet. | | #50 || Modeling > Meshes > Mesh Analysis | partial | `lintMesh` reports topology problems. With `{ geometry: true }` (always on in `mesh_inspect`) it also warns of crossing parts, a solid cutting itself, thin walls, floating parts and near-symmetry, using the BVH within face budgets. Checks are heuristics on parts, not Blender's exact Select Non-Manifold or Intersect checks. | [tests/mesh-lint-geometry.test.js](../tests/mesh-lint-geometry.test.js), [src/mesh-lint-geometry.js](../src/mesh-lint-geometry.js) | #66 || Modeling > Meshes > Remeshing | partial | `remesh` rebuilds a closed mesh as an even quad surface on a voxel grid (surface nets over a BVH signed distance). Quad remesh and Instant Meshes style retopology are not here. | [blender golden](../tests/blender-golden.test.js) | #40 |-| 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. There is no NURBS or poly spline, 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), [Blender comparison](../tests/blender-curve-text.test.js) | #45 |+| 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. | | |diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 18e5e087..6a71ff59 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -65,6 +65,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.',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']);diff --git a/src/agent-scene.js b/src/agent-scene.jsindex b8f2e843..dc17eb25 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -452,7 +452,7 @@ const GEOMETRY_FIELDS = {lathe: ['profile', 'segments', 'startAngle', 'sweep'],extrude: ['contour', 'holes', 'depth', 'steps', 'bevel', 'bevelThickness', 'bevelSegments'],tube: ['path', 'radius', 'segments', 'radialSegments', 'closed'],- curve: ['points', 'closed', 'radius', 'taper', 'profile', 'resolution', 'radialSegments'],+ 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'],terrain: ['size', 'resolution', 'seed', 'amplitude', 'holes'],@@ -486,7 +486,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'].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'].includes(field)) {finite(value[field], field);}}@@ -522,6 +522,9 @@ function geometryEstimate(value) {}return (detail('segments', 64, 3, 2048) + 1) * (detail('radialSegments', 12, 3, 128) + 1);case 'curve': {+ if (['shape', 'splines', 'kind', 'weights', 'trim'].some(field => value[field] !== undefined)) {+ return agentSceneModule('modeling').curveGeometryVertexCount(value);+ }const knots = value.points;if (!Array.isArray(knots) || knots.length < 2 || knots.length > CURVE_TEXT_LIMITS.maxCurvePoints) {throw invalidField('points', Array.isArray(knots) ? `${knots.length} points` : knots, `a list of 2 to ${CURVE_TEXT_LIMITS.maxCurvePoints} points, such as [[0, 0, 0], [0, 1, 0]]`);@@ -617,7 +620,7 @@ function generateGeometry(value, maxVertices) {case 'tube':return agentSceneModule('modeling').tube(value.path, { ...value, maxVertices });case 'curve':- return agentSceneModule('modeling').curve(value.points, { ...value, maxVertices });+ return agentSceneModule('modeling').curveGeometry(value, maxVertices);case 'text':return agentSceneModule('text').text(value.text, { ...value, maxVertices });case 'terrain':diff --git a/src/modeling-bezier.js b/src/modeling-bezier.jsindex f5f2849d..3b3e800f 100644--- a/src/modeling-bezier.js+++ b/src/modeling-bezier.js@@ -80,7 +80,7 @@ export function sampleBezierSpans(handles, closed, resolution) {}// A handle that sits on its knot makes the derivative zero there; the chord to a neighbour stands in.-function fillZeroTangents(points, tangents, closed) {+export function fillZeroTangents(points, tangents, closed) {const count = points.length;const unit = tangents.map(tangent => {const length = lengthOf(tangent);@@ -161,6 +161,11 @@ function taperAt(taper, fraction) {*/export function buildBezierSweep({ handles, closed, radius, taper, profile, resolution, radialSegments }) {const { points, tangents } = sampleBezierSpans(handles, closed, resolution);+ return sweepSamples({ points, tangents, closed, radius, taper, profile, radialSegments });+}++/** The sweep of buildBezierSweep along any samples: points with unit tangents, a closed curve not repeating its first point. */+export function sweepSamples({ points, tangents, closed, radius, taper, profile, radialSegments }) {const count = points.length;const frames = transportFrames(closed ? [...tangents, tangents[0]] : tangents, closed);const distances = [0];diff --git a/src/modeling-splines.js b/src/modeling-splines.jsnew file mode 100644index 00000000..dbf0a5da--- /dev/null+++ b/src/modeling-splines.js@@ -0,0 +1,262 @@+// Spline sources for the curve geometry: arc, spiral and star primitives, poly and NURBS splines, and trimming.+// Every function is deterministic and returns plain arrays; modeling.js validates the public input first.+import { fillZeroTangents, resolveHandles, sampleBezierSpans } from './modeling-bezier.js';++const TWO_PI = Math.PI * 2;+const NURBS_ORDER = 4;+const DERIVATIVE_STEP = 1e-5;+const MINIMUM_SEGMENT = 1e-9;++export const SHAPE_TYPES = ['arc', 'spiral', 'star'];++function number(value, fallback, name, minimum, maximum) {+ const result = value === undefined ? fallback : value;+ if (!Number.isFinite(result) || result < minimum || result > maximum) {+ throw new RangeError(`${name} must be a number from ${minimum} to ${maximum}, such as ${fallback}.`);+ }+ return result;+}++function whole(value, fallback, name, minimum, maximum) {+ const result = value === undefined ? fallback : value;+ if (!Number.isInteger(result) || result < minimum || result > maximum) {+ throw new RangeError(`${name} must be an integer from ${minimum} to ${maximum}, such as ${fallback}.`);+ }+ return result;+}++function knownFields(shape, allowed) {+ for (const key of Object.keys(shape)) {+ if (!allowed.includes(key)) throw new TypeError(`Unknown shape field: ${key}. Use ${allowed.join(', ')}.`);+ }+}++// Exact quarter-turn style Bezier arc: the handle length is 4/3 tan(sweep / 4) times the radius.+function arcSpline(shape) {+ knownFields(shape, ['type', 'radius', 'startAngle', 'sweep', 'segments']);+ const radius = number(shape.radius, 1, 'shape.radius', 1e-6, 1e6);+ const startAngle = number(shape.startAngle, 0, 'shape.startAngle', -1e4, 1e4);+ const sweep = number(shape.sweep, Math.PI, 'shape.sweep', -TWO_PI, TWO_PI);+ const segments = whole(shape.segments, 8, 'shape.segments', 1, 256);+ if (Math.abs(sweep) < 1e-6) throw new RangeError('shape.sweep must not be 0. Pass an angle in radians such as 3.14.');+ const closed = Math.abs(Math.abs(sweep) - TWO_PI) < 1e-9;+ const step = sweep / segments;+ const handleLength = 4 / 3 * Math.tan(step / 4) * radius;+ const knotCount = closed ? segments : segments + 1;+ const points = Array.from({ length: knotCount }, (_, index) => {+ const angle = startAngle + step * index;+ const cosine = Math.cos(angle);+ const sine = Math.sin(angle);+ const position = [radius * cosine, radius * sine, 0];+ const tangent = [-sine * handleLength, cosine * handleLength, 0];+ return {+ position,+ handleIn: [position[0] - tangent[0], position[1] - tangent[1], 0],+ handleOut: [position[0] + tangent[0], position[1] + tangent[1], 0],+ };+ });+ return { type: 'bezier', closed, points };+}++// A rising helix of radius from startRadius to endRadius, smooth through its points.+function spiralSpline(shape) {+ knownFields(shape, ['type', 'rotations', 'startRadius', 'endRadius', 'height', 'pointsPerRotation', 'reverse']);+ const rotations = number(shape.rotations, 2, 'shape.rotations', 0.05, 64);+ const startRadius = number(shape.startRadius, 1, 'shape.startRadius', 0, 1e6);+ const endRadius = number(shape.endRadius, 1, 'shape.endRadius', 0, 1e6);+ const height = number(shape.height, 2, 'shape.height', -1e6, 1e6);+ const pointsPerRotation = whole(shape.pointsPerRotation, 12, 'shape.pointsPerRotation', 3, 128);+ if (shape.reverse !== undefined && typeof shape.reverse !== 'boolean') throw new TypeError('shape.reverse must be true or false.');+ const segments = Math.max(1, Math.ceil(rotations * pointsPerRotation));+ if (segments + 1 > 1024) throw new RangeError('The spiral needs at most 1024 points. Lower shape.rotations or shape.pointsPerRotation.');+ const direction = shape.reverse ? -1 : 1;+ const points = Array.from({ length: segments + 1 }, (_, index) => {+ const fraction = index / segments;+ const angle = direction * TWO_PI * rotations * fraction;+ const radius = startRadius + (endRadius - startRadius) * fraction;+ return [radius * Math.cos(angle), radius * Math.sin(angle), height * fraction];+ });+ return { type: 'bezier', closed: false, points };+}++// A closed poly star; innerTwist (radians) turns the inner vertices against the outer ones.+function starSpline(shape) {+ knownFields(shape, ['type', 'points', 'innerRadius', 'outerRadius', 'innerTwist']);+ const count = whole(shape.points, 5, 'shape.points', 3, 256);+ const innerRadius = number(shape.innerRadius, 0.5, 'shape.innerRadius', 1e-6, 1e6);+ const outerRadius = number(shape.outerRadius, 1, 'shape.outerRadius', 1e-6, 1e6);+ const twist = number(shape.innerTwist, 0, 'shape.innerTwist', -TWO_PI, TWO_PI);+ const points = [];+ for (let index = 0; index < count; index++) {+ const outerAngle = TWO_PI * index / count;+ const innerAngle = outerAngle + Math.PI / count + twist;+ points.push([outerRadius * Math.cos(outerAngle), outerRadius * Math.sin(outerAngle), 0]);+ points.push([innerRadius * Math.cos(innerAngle), innerRadius * Math.sin(innerAngle), 0]);+ }+ return { type: 'poly', closed: true, points };+}++/** A primitive shape as a spline: `{ type: 'bezier' | 'poly', closed, points }`, in the XY plane. */+export function shapeToSpline(shape) {+ if (!shape || typeof shape !== 'object' || Array.isArray(shape)) throw new TypeError(`shape must be an object with type ${SHAPE_TYPES.join(', ')}.`);+ if (shape.type === 'arc') return arcSpline(shape);+ if (shape.type === 'spiral') return spiralSpline(shape);+ if (shape.type === 'star') return starSpline(shape);+ throw new RangeError(`shape.type must be one of ${SHAPE_TYPES.join(', ')}, not ${JSON.stringify(shape.type)}.`);+}++function subtract(first, second) {+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];+}++function unitOrNull(vector) {+ const length = Math.hypot(vector[0], vector[1], vector[2]);+ return length > MINIMUM_SEGMENT ? [vector[0] / length, vector[1] / length, vector[2] / length] : null;+}++/** Straight segments between the points; a corner takes the direction of the segment that leaves it. */+function samplePoly(points, closed) {+ const count = points.length;+ const tangents = points.map((point, index) => {+ const isLastOfOpen = index === count - 1 && !closed;+ const direction = isLastOfOpen ? subtract(point, points[index - 1]) : subtract(points[(index + 1) % count], point);+ return unitOrNull(direction);+ });+ return { points, tangents: fillZeroTangents(points, tangents, closed) };+}++// Clamped (open) or periodic (closed) uniform knot vector for a cubic B-spline over `count` control points.+function knotVector(count, order, closed) {+ const total = count + order;+ if (closed) return Array.from({ length: total }, (_, index) => index);+ return Array.from({ length: total }, (_, index) => Math.min(Math.max(index - order + 1, 0), count - order + 1));+}++function findSpan(count, order, parameter, knots) {+ const degree = order - 1;+ if (parameter >= knots[count]) return count - 1;+ let span = degree;+ while (span < count - 1 && parameter >= knots[span + 1]) span++;+ return span;+}++// Cox-de Boor: the `order` basis values that are not zero at the parameter, starting at index span - degree.+function basisValues(span, parameter, knots, order) {+ const degree = order - 1;+ const values = [1];+ const left = [];+ const right = [];+ for (let level = 1; level <= degree; level++) {+ left[level] = parameter - knots[span + 1 - level];+ right[level] = knots[span + level] - parameter;+ let saved = 0;+ for (let index = 0; index < level; index++) {+ const denominator = right[index + 1] + left[level - index];+ const term = denominator === 0 ? 0 : values[index] / denominator;+ values[index] = saved + right[index + 1] * term;+ saved = left[level - index] * term;+ }+ values[level] = saved;+ }+ return values;+}++function nurbsPoint(controls, weights, knots, order, parameter) {+ const count = controls.length;+ const span = findSpan(count, order, parameter, knots);+ const values = basisValues(span, parameter, knots, order);+ const sum = [0, 0, 0];+ let weightSum = 0;+ values.forEach((value, offset) => {+ const index = span - (order - 1) + offset;+ const weighted = value * weights[index];+ weightSum += weighted;+ for (let axis = 0; axis < 3; axis++) sum[axis] += weighted * controls[index][axis];+ });+ return sum.map(component => component / weightSum);+}++/**+ * Uniform cubic NURBS (order 4, or the point count when lower): an open spline is clamped so it starts and ends on its+ * first and last control point, a closed one is periodic. `resolution` samples per control point span.+ */+export function sampleNurbs(controlPoints, weights, closed, resolution) {+ const order = Math.min(NURBS_ORDER, controlPoints.length);+ const wrap = closed ? order - 1 : 0;+ const controls = [...controlPoints, ...controlPoints.slice(0, wrap)];+ const controlWeights = [...weights, ...weights.slice(0, wrap)];+ const knots = knotVector(controls.length, order, closed);+ const start = knots[order - 1];+ const end = knots[controls.length];+ const spans = closed ? controlPoints.length : controlPoints.length - 1;+ const sampleCount = closed ? spans * resolution : spans * resolution + 1;+ const parameterAt = index => start + (end - start) * index / (spans * resolution);+ const evaluate = parameter => nurbsPoint(controls, controlWeights, knots, order, Math.min(Math.max(parameter, start), end));+ const points = Array.from({ length: sampleCount }, (_, index) => evaluate(parameterAt(index)));+ const step = DERIVATIVE_STEP * (end - start);+ const tangents = Array.from({ length: sampleCount }, (_, index) => {+ const parameter = parameterAt(index);+ const before = closed ? evaluate(start + ((parameter - step - start + (end - start)) % (end - start))) : evaluate(parameter - step);+ const after = closed ? evaluate(start + ((parameter + step - start) % (end - start))) : evaluate(parameter + step);+ return unitOrNull(subtract(after, before));+ });+ return { points, tangents: fillZeroTangents(points, tangents, closed) };+}++/** Points and unit tangents of a resolved spline `{ type, closed, points, weights }`. */+export function sampleSpline(spline, resolution) {+ if (spline.type === 'poly') return samplePoly(spline.points, spline.closed);+ if (spline.type === 'nurbs') return sampleNurbs(spline.points, spline.weights, spline.closed, resolution);+ return sampleBezierSpans(resolveHandles(spline.points, spline.closed), spline.closed, resolution);+}++function lerp(first, second, weight) {+ return first.map((value, axis) => value + (second[axis] - value) * weight);+}++/** The vertex count a spline of this kind and size samples to, trimmed or not, before any budget check. */+export function sampleCountOf(spline, resolution) {+ const count = spline.points.length;+ if (spline.type === 'poly') return count;+ const spans = spline.closed ? count : count - 1;+ return spans * resolution + (spline.closed ? 0 : 1);+}++/**+ * Cuts samples to the arc-length range [start, end] (factors of the length, or lengths when `byLength`). The result is+ * open. A range that covers a whole open curve returns it unchanged. Lengths past the curve are clamped to it.+ */+export function trimSamples(samples, closed, { start = 0, end = 1, length: byLength = false }) {+ const loop = closed ? [...samples.points, samples.points[0]] : samples.points;+ const loopTangents = closed ? [...samples.tangents, samples.tangents[0]] : samples.tangents;+ const distances = [0];+ for (let index = 1; index < loop.length; index++) {+ const segment = subtract(loop[index], loop[index - 1]);+ distances.push(distances[index - 1] + Math.hypot(segment[0], segment[1], segment[2]));+ }+ const total = distances.at(-1);+ const from = Math.min(byLength ? start : start * total, total);+ const to = Math.min(byLength ? end : end * total, total);+ if (to - from <= MINIMUM_SEGMENT * Math.max(total, 1)) {+ throw new RangeError('trim leaves no curve. Pass trim.end greater than trim.start, within the curve length.');+ }+ if (!closed && from <= 0 && to >= total) return samples;+ const points = [];+ const tangents = [];+ const place = distance => {+ let upper = distances.findIndex(value => value >= distance);+ if (upper <= 0) upper = 1;+ const weight = (distance - distances[upper - 1]) / ((distances[upper] - distances[upper - 1]) || 1);+ points.push(lerp(loop[upper - 1], loop[upper], weight));+ tangents.push(unitOrNull(lerp(loopTangents[upper - 1], loopTangents[upper], weight)) ?? loopTangents[upper]);+ };+ place(from);+ for (let index = 0; index < loop.length; index++) {+ if (distances[index] > from + MINIMUM_SEGMENT && distances[index] < to - MINIMUM_SEGMENT) {+ points.push(loop[index]);+ tangents.push(loopTangents[index]);+ }+ }+ place(to);+ return { points, tangents };+}diff --git a/src/modeling.js b/src/modeling.jsindex 735ef578..7671b0a3 100644--- a/src/modeling.js+++ b/src/modeling.js@@ -1,5 +1,6 @@import { buildLathe, buildExtrusion, buildTube } from './modeling-shapes.js';-import { buildBezierSweep, resolveHandles } from './modeling-bezier.js';+import { sweepSamples } from './modeling-bezier.js';+import { sampleCountOf, sampleSpline, shapeToSpline, trimSamples } from './modeling-splines.js';const MAX_INPUT_POINTS = 4096;const DEFAULT_VERTEX_LIMIT = 250_000;@@ -270,29 +271,173 @@ export function extrude(contour, {return closeTJunctions(meshFrom(buildExtrusion(outer, inner, { depth, steps, bevel, bevelThickness, bevelSegments }), maxVertices));}+const SPLINE_TYPES = ['bezier', 'poly', 'nurbs'];+const MAX_SPLINES = 64;+const MAX_CURVE_POINTS = 1024;+const MAX_TOTAL_CURVE_POINTS = 4096;+const SPLINE_FIELDS = ['points', 'shape', 'closed', 'kind', 'weights', 'trim'];++function trimFrom(input, label) {+ if (input === undefined) return null;+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError(`${label} must be an object such as { "start": 0, "end": 0.5 }.`);+ for (const key of Object.keys(input)) {+ if (!['start', 'end', 'length'].includes(key)) throw new TypeError(`Unknown ${label} field: ${key}. Use start, end, length.`);+ }+ if (input.length !== undefined && typeof input.length !== 'boolean') throw new TypeError(`${label}.length must be true (start and end are lengths) or false (factors 0 to 1).`);+ const byLength = input.length === true;+ const maximum = byLength ? 1e9 : 1;+ const start = finite(input.start ?? 0, `${label}.start`);+ const end = finite(input.end ?? maximum, `${label}.end`);+ if (start < 0 || start > maximum || end < 0 || end > maximum) {+ throw new RangeError(`${label}.start and ${label}.end must be from 0 to ${byLength ? 'the curve length' : '1'}.`);+ }+ if (end <= start) throw new RangeError(`${label}.end must be greater than ${label}.start. Pass a range such as { "start": 0, "end": 0.5 }.`);+ return { start, end, length: byLength };+}++function weightsFrom(input, count, label) {+ if (input === undefined) return Array(count).fill(1);+ if (!Array.isArray(input) || input.length !== count) throw new RangeError(`${label} needs one weight per point (${count}).`);+ return input.map(weight => {+ finite(weight, label);+ if (weight <= 0 || weight > 1e6) throw new RangeError(`${label} must be greater than 0 and at most 1000000.`);+ return weight;+ });+}++// One spline: points or a primitive shape, a type (bezier, poly, nurbs), closed, NURBS weights and a trim.+function splineFrom(input, label) {+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError(`${label} must be an object with points or shape.`);+ for (const key of Object.keys(input)) {+ if (!SPLINE_FIELDS.includes(key)) throw new TypeError(`Unknown ${label} field: ${key}. Use ${SPLINE_FIELDS.join(', ')}.`);+ }+ if ((input.points === undefined) === (input.shape === undefined)) throw new TypeError(`${label} needs exactly one of points or shape.`);+ let { points, closed = false, kind = 'bezier' } = input;+ if (input.shape !== undefined) {+ if (input.closed !== undefined || input.kind !== undefined) throw new TypeError(`${label}.closed and ${label}.kind come from shape. Remove them.`);+ ({ points, closed, type: kind } = shapeToSpline(input.shape));+ }+ if (typeof closed !== 'boolean') throw new RangeError('radius must be positive and closed must be boolean.');+ if (!SPLINE_TYPES.includes(kind)) throw new RangeError(`${label}.kind must be one of ${SPLINE_TYPES.join(', ')}.`);+ if (!Array.isArray(points) || points.length < (closed ? 3 : 2) || points.length > MAX_CURVE_POINTS) {+ throw new RangeError(`${label === 'points' ? 'points' : `${label}.points`} needs ${closed ? 3 : 2} to ${MAX_CURVE_POINTS} entries.`);+ }+ if (kind !== 'nurbs' && input.weights !== undefined) throw new TypeError(`${label}.weights apply to kind nurbs only.`);+ const resolved = kind === 'bezier' ? points.map(knotFrom) : points.map(point => vectorFrom(point, 'point'));+ const weights = kind === 'nurbs' ? weightsFrom(input.weights, points.length, `${label}.weights`) : undefined;+ return { type: kind, closed, points: resolved, weights, trim: trimFrom(input.trim, `${label}.trim`) };+}++function joinSweeps(parts) {+ if (parts.length === 1) return parts[0];+ const vertexTotal = parts.reduce((sum, part) => sum + part.positions.length / 3, 0);+ const indexTotal = parts.reduce((sum, part) => sum + part.indices.length, 0);+ const joined = {+ positions: new Float32Array(vertexTotal * 3),+ normals: new Float32Array(vertexTotal * 3),+ uvs: new Float32Array(vertexTotal * 2),+ indices: new Uint32Array(indexTotal),+ };+ let vertexOffset = 0;+ let indexOffset = 0;+ for (const part of parts) {+ joined.positions.set(part.positions, vertexOffset * 3);+ joined.normals.set(part.normals, vertexOffset * 3);+ joined.uvs.set(part.uvs, vertexOffset * 2);+ part.indices.forEach((vertex, index) => {+ joined.indices[indexOffset + index] = vertex + vertexOffset;+ });+ vertexOffset += part.positions.length / 3;+ indexOffset += part.indices.length;+ }+ return joined;+}+/**- * Sweep a round or custom profile along a cubic Bezier curve. Points are [x, y, z] (smooth automatic handles) or- * { position, handleIn, handleOut } with absolute handle positions; `taper` lists radius factors spread along the length.+ * Sweep a round or custom profile along one or more splines. A spline is { points | shape, closed, kind, weights,+ * trim }: kind is bezier (default), poly or nurbs; shape is an arc, spiral or star; trim cuts an arc-length range.+ * The splines share radius, taper, profile and resolution and become one mesh.*/-export function curve(points, {- closed = false, radius = 0.05, taper, profile, resolution = 12, radialSegments = 8,- maxVertices = DEFAULT_VERTEX_LIMIT,-} = {}) {+export function curveSet(splines, options = {}, labelFirst = 'splines[0]') {+ const { maxVertices = DEFAULT_VERTEX_LIMIT } = options;+ const plan = planCurveSet(splines, options, labelFirst);+ checkBudget(plan.vertexCount, maxVertices);+ const { resolved, radius, profilePoints, taperFactors, radialSegments, resolution } = plan;+ const parts = resolved.map(spline => {+ let samples = sampleSpline(spline, resolution);+ let closed = spline.closed;+ if (spline.trim) {+ samples = trimSamples(samples, closed, spline.trim);+ closed = false;+ }+ return sweepSamples({ ...samples, closed, radius, taper: taperFactors, profile: profilePoints, radialSegments });+ });+ return meshFrom(joinSweeps(parts), maxVertices);+}++/** Validates curveSet input and returns the vertex count it would build, without building it. */+export function curveSetVertexCount(splines, options = {}) {+ return planCurveSet(splines, options, 'splines[0]').vertexCount;+}++function planCurveSet(splines, {+ radius = 0.05, taper, profile, resolution = 12, radialSegments = 8,+} , labelFirst) {radius = finite(radius, 'radius');- if (radius <= 0 || typeof closed !== 'boolean') throw new RangeError('radius must be positive and closed must be boolean.');+ if (radius <= 0) throw new RangeError('radius must be positive and closed must be boolean.');integer(resolution, 1, 64, 'resolution');integer(radialSegments, 3, 128, 'radialSegments');- if (!Array.isArray(points) || points.length < (closed ? 3 : 2) || points.length > 1024) {- throw new RangeError(`points needs ${closed ? 3 : 2} to 1024 entries.`);- }- const knots = points.map(knotFrom);+ if (!Array.isArray(splines) || splines.length < 1 || splines.length > MAX_SPLINES) throw new RangeError(`splines needs 1 to ${MAX_SPLINES} entries.`);+ const resolved = splines.map((spline, index) => splineFrom(spline, index === 0 ? labelFirst : `splines[${index}]`));+ const totalPoints = resolved.reduce((sum, spline) => sum + spline.points.length, 0);+ if (totalPoints > MAX_TOTAL_CURVE_POINTS) throw new RangeError(`splines hold ${totalPoints} points in all; at most ${MAX_TOTAL_CURVE_POINTS}. Remove points or splines.`);const profilePoints = profile === undefined ? null : pointsFrom(profile, 2, 3, 'profile');if (profilePoints && profilePoints.length > 256) throw new RangeError('profile needs 3 to 256 points.');const sides = profilePoints ? profilePoints.length : radialSegments;- const rings = (closed ? knots.length : knots.length - 1) * resolution + 1;- checkBudget(rings * sides * 2 + (closed ? 0 : 2 * (sides + 1)), maxVertices);- const handles = resolveHandles(knots, closed);- return meshFrom(buildBezierSweep({ handles, closed, radius, taper: taperFrom(taper), profile: profilePoints, resolution, radialSegments }), maxVertices);+ const taperFactors = taperFrom(taper);+ const vertexCount = resolved.reduce((sum, spline) => {+ const samples = sampleCountOf(spline, resolution);+ const rings = spline.trim ? samples + 3 : samples + (spline.closed ? 1 : 0);+ return sum + rings * sides * 2 + (spline.closed && !spline.trim ? 0 : 2 * (sides + 1));+ }, 0);+ return { resolved, vertexCount, radius, profilePoints, taperFactors, radialSegments, resolution };+}++const SINGLE_SPLINE_FIELDS = ['points', 'shape', 'closed', 'kind', 'weights', 'trim'];++// The scene geometry `curve` holds one spline in its own fields, or several in `splines`.+function splinesOfGeometry(value) {+ if (value.splines === undefined) {+ const spline = Object.fromEntries(SINGLE_SPLINE_FIELDS.map(key => [key, value[key]]));+ return { splines: [spline], label: 'points' };+ }+ for (const key of SINGLE_SPLINE_FIELDS) {+ if (value[key] !== undefined) throw new TypeError(`${key} cannot be used with splines. Put ${key} inside a splines entry.`);+ }+ return { splines: value.splines, label: 'splines[0]' };+}++/** The curve scene geometry: points, a shape or splines, with the shared sweep options. */+export function curveGeometry(value, maxVertices) {+ const { splines, label } = splinesOfGeometry(value);+ return curveSet(splines, { ...value, maxVertices }, label);+}++/** The vertex count of a curve scene geometry, validated like curveGeometry. */+export function curveGeometryVertexCount(value) {+ const { splines, label } = splinesOfGeometry(value);+ return planCurveSet(splines, value, label).vertexCount;+}++/**+ * Sweep a round or custom profile along a curve: cubic Bezier by default (points are [x, y, z] with smooth automatic+ * handles, or { position, handleIn, handleOut } with absolute handle positions), or kind poly or nurbs. `taper` lists+ * radius factors spread along the length. For several splines or a primitive shape see curveSet.+ */+export function curve(points, {+ closed = false, kind, weights, trim, radius, taper, profile, resolution, radialSegments, maxVertices,+} = {}) {+ return curveSet([{ points, closed, kind, weights, trim }], { radius, taper, profile, resolution, radialSegments, maxVertices }, 'points');}/** Sweep a circular tube along a centripetal Catmull-Rom curve. */diff --git a/tests/curve-splines.test.js b/tests/curve-splines.test.jsnew file mode 100644index 00000000..e5533c62--- /dev/null+++ b/tests/curve-splines.test.js@@ -0,0 +1,192 @@+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 { curve, curveSet } from '../src/modeling.js';+import { sampleNurbs, sampleSpline, shapeToSpline, trimSamples } from '../src/modeling-splines.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 bounds({ 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 };+}++function openEdges({ positions, indices }) {+ const keyOf = vertex => Array.from(positions.subarray(vertex * 3, vertex * 3 + 3), value => value.toFixed(5)).join(',');+ const uses = new Map();+ for (let offset = 0; offset < indices.length; offset += 3) {+ for (let side = 0; side < 3; side++) {+ const from = keyOf(indices[offset + side]);+ const to = keyOf(indices[offset + (side + 1) % 3]);+ if (from === to) continue;+ const edge = from < to ? `${from}|${to}` : `${to}|${from}`;+ uses.set(edge, (uses.get(edge) ?? 0) + 1);+ }+ }+ return [...uses.values()].filter(count => count !== 2).length;+}++const wire = { radius: 0.01, radialSegments: 4 };++test('an arc primitive lies on its circle and ends where the sweep ends', () => {+ const spline = shapeToSpline({ type: 'arc', radius: 2, startAngle: 0, sweep: Math.PI, segments: 4 });+ const { points } = sampleSpline({ ...spline, points: spline.points }, 16);+ for (const point of points) assert.ok(Math.abs(Math.hypot(point[0], point[1]) - 2) < 1e-5, `off the circle: ${point}`);+ assert.deepEqual(points[0].map(Math.abs).map(value => Math.round(value * 1e6)), [2e6, 0, 0]);+ assert.ok(Math.abs(points.at(-1)[0] + 2) < 1e-9 && Math.abs(points.at(-1)[1]) < 1e-9);+ assert.equal(spline.closed, false);+ assert.equal(shapeToSpline({ type: 'arc', sweep: Math.PI * 2 }).closed, true, 'a full turn closes');+});++test('a spiral rises and widens, and a spiral staircase rail is a watertight swept tube', () => {+ const rail = curveSet([{ shape: { type: 'spiral', rotations: 1.5, startRadius: 1, endRadius: 1, height: 3, pointsPerRotation: 24 } }], { radius: 0.03, radialSegments: 6 });+ const { minimum, maximum } = bounds(rail);+ assert.ok(Math.abs(minimum[1]) < 0.06 || Math.abs(minimum[2]) < 0.06);+ assert.ok(Math.abs(maximum[2] - 3) < 0.04, `rail top at ${maximum[2]}`);+ assert.ok(maximum[0] <= 1.04 && minimum[0] >= -1.04);+ assert.equal(openEdges(rail), 0);+ const cone = shapeToSpline({ type: 'spiral', rotations: 2, startRadius: 0.5, endRadius: 2, height: 0, pointsPerRotation: 8 });+ assert.equal(cone.points.length, 17);+ assert.ok(Math.abs(Math.hypot(...cone.points.at(-1).slice(0, 2)) - 2) < 1e-9);+ const reversed = shapeToSpline({ type: 'spiral', rotations: 0.25, reverse: true, height: 0, pointsPerRotation: 4 });+ assert.ok(reversed.points[1][1] < 0, 'reverse turns clockwise');+});++test('a star alternates outer and inner radius and is a closed poly spline', () => {+ const star = shapeToSpline({ type: 'star', points: 5, innerRadius: 0.4, outerRadius: 1, innerTwist: 0 });+ assert.equal(star.type, 'poly');+ assert.equal(star.closed, true);+ assert.equal(star.points.length, 10);+ star.points.forEach((point, index) => assert.ok(Math.abs(Math.hypot(point[0], point[1]) - (index % 2 ? 0.4 : 1)) < 1e-9));+ assert.equal(openEdges(curveSet([{ shape: { type: 'star' } }], wire)), 0);+});++test('trim by factor keeps a prefix of the curve, and by length matches', () => {+ const full = [[0, 0, 0], [4, 0, 0]];+ const half = curve(full, { ...wire, trim: { end: 0.5 } });+ assert.ok(Math.abs(bounds(half).maximum[0] - 2) < 1e-6);+ assert.equal(openEdges(half), 0, 'a trimmed curve is capped');+ const byLength = curve(full, { ...wire, trim: { start: 1, end: 3, length: true } });+ const { minimum, maximum } = bounds(byLength);+ assert.ok(Math.abs(minimum[0] - 1) < 1e-6 && Math.abs(maximum[0] - 3) < 1e-6);+ const clamped = curve(full, { ...wire, trim: { start: 1, end: 99, length: true } });+ assert.ok(Math.abs(bounds(clamped).maximum[0] - 4) < 1e-6, 'a length past the end stops at the end');+ const whole = curve(full, { ...wire, trim: { start: 0, end: 1 } });+ assert.equal(hashOf(whole), hashOf(curve(full, wire)), 'the full range changes nothing on an open curve');+});++test('trimming a closed curve opens it', () => {+ const ring = { shape: { type: 'arc', sweep: Math.PI * 2, segments: 8 } };+ const closed = curveSet([ring], wire);+ const quarter = curveSet([{ ...ring, trim: { end: 0.25 } }], wire);+ assert.equal(openEdges(closed), 0);+ assert.equal(openEdges(quarter), 0);+ const { minimum, maximum } = bounds(quarter);+ assert.ok(minimum[0] > -0.02 && minimum[1] > -0.02, 'a quarter turn stays in the first quadrant');+ assert.ok(Math.abs(maximum[0] - 1) < 0.02 && Math.abs(maximum[1] - 1) < 0.02);+});++test('a growing vine: each growth step extends the previous trim with the same start', () => {+ const vine = [[0, 0, 0], [1, 1, 0], [2, 0, 1], [3, 1, 1], [4, 0, 0]];+ const reach = growth => bounds(curve(vine, { ...wire, resolution: 8, trim: { end: growth } })).maximum[0];+ const fractions = [0.1, 0.25, 0.5, 0.75, 1];+ const reaches = fractions.map(reach);+ for (let index = 1; index < reaches.length; index++) assert.ok(reaches[index] > reaches[index - 1], `step ${index} grows`);+ const sampled = sampleSpline({ type: 'bezier', closed: false, points: vine.map(position => ({ position })) }, 8);+ const prefix = trimSamples(sampled, false, { end: 0.5 });+ assert.deepEqual(prefix.points[0], sampled.points[0]);+ const lastKept = prefix.points.at(-2);+ assert.ok(sampled.points.some(point => point.every((value, axis) => value === lastKept[axis])), 'interior samples are untouched');+});++test('a spline set merges its splines into one mesh with indices offset', () => {+ const first = curve([[0, 0, 0], [1, 0, 0]], wire);+ const second = curveSet([{ shape: { type: 'star' } }], wire);+ const both = curveSet([{ points: [[0, 0, 0], [1, 0, 0]] }, { shape: { type: 'star' } }], wire);+ assert.equal(both.positions.length, first.positions.length + second.positions.length);+ assert.equal(both.indices.length, first.indices.length + second.indices.length);+ assert.deepEqual(Array.from(both.positions.subarray(0, first.positions.length)), Array.from(first.positions));+ assert.equal(Math.max(...both.indices), both.positions.length / 3 - 1);+ assert.equal(openEdges(both), 0);+});++test('a poly spline keeps its corners and a NURBS spline passes through its ends', () => {+ const corner = [[0, 0, 0], [1, 0, 0], [1, 1, 0]];+ const poly = curve(corner, { ...wire, kind: 'poly' });+ assert.ok(Math.abs(bounds(poly).maximum[0] - 1.01) < 1e-6, 'the corner is not rounded off');+ const nurbs = sampleNurbs(corner, [1, 1, 1], false, 8);+ assert.deepEqual(nurbs.points[0], corner[0]);+ assert.ok(nurbs.points.at(-1).every((value, axis) => Math.abs(value - corner[2][axis]) < 1e-12));+ const pulled = sampleNurbs(corner, [1, 8, 1], false, 8);+ const middle = point => Math.hypot(point[0] - 1, point[1] - 0);+ assert.ok(Math.min(...pulled.points.map(middle)) < Math.min(...nurbs.points.map(middle)), 'a higher weight pulls the curve to its point');+ const ring = sampleNurbs([[1, 0, 0], [0, 1, 0], [-1, 0, 0], [0, -1, 0]], [1, 1, 1, 1], true, 6);+ assert.equal(ring.points.length, 24);+ assert.equal(openEdges(curve([[1, 0, 0], [0, 1, 0], [-1, 0, 0], [0, -1, 0]], { ...wire, kind: 'nurbs', closed: true })), 0);+});++test('curve output is deterministic and matches the recorded geometry', () => {+ const build = () => curveSet([+ { shape: { type: 'spiral', rotations: 1, height: 1 }, trim: { start: 0.1, end: 0.9 } },+ { points: [[0, 0, 0], [1, 1, 0], [2, 0, 1], [3, 1, 1]], kind: 'nurbs', weights: [1, 2, 1, 1] },+ { shape: { type: 'star', points: 6 } },+ ], { radius: 0.02, radialSegments: 5, taper: [1, 0.5] });+ assert.equal(hashOf(build()), hashOf(build()));+ assert.equal(hashOf(build()), '066f5ace79bc38d147707b116d1488465cc729d4effa8a17ce10ae9a1f31289b');+});++test('curve rejects bad splines with the field and what to pass', () => {+ const line = [[0, 0, 0], [1, 0, 0]];+ const cases = [+ [() => curve(line, { trim: { start: 0.6, end: 0.4 } }), /trim\.end must be greater than points\.trim\.start|trim\.end must be greater/],+ [() => curve(line, { trim: { end: 2 } }), /trim\.start and .*trim\.end must be from 0 to 1/],+ [() => curve(line, { trim: { bogus: 1 } }), /Unknown .*trim field: bogus/],+ [() => curve(line, { kind: 'spiral' }), /kind must be one of bezier, poly, nurbs/],+ [() => curve(line, { weights: [1, 1] }), /weights apply to kind nurbs only/],+ [() => curve(line, { kind: 'nurbs', weights: [1] }), /needs one weight per point \(2\)/],+ [() => curve(line, { kind: 'nurbs', weights: [1, 0] }), /greater than 0/],+ [() => curveSet([], {}), /splines needs 1 to 64 entries/],+ [() => curveSet(Array.from({ length: 65 }, () => ({ points: line })), {}), /splines needs 1 to 64 entries/],+ [() => curveSet([{ points: line, shape: { type: 'star' } }], {}), /exactly one of points or shape/],+ [() => curveSet([{ shape: { type: 'star' }, closed: true }], {}), /closed and .*kind come from shape/],+ [() => curveSet([{ shape: { type: 'wave' } }], {}), /shape\.type must be one of arc, spiral, star/],+ [() => curveSet([{ shape: { type: 'star', points: 2 } }], {}), /shape\.points must be an integer from 3 to 256/],+ [() => curveSet([{ shape: { type: 'arc', sweep: 0 } }], {}), /shape\.sweep must not be 0/],+ [() => curveSet([{ shape: { type: 'spiral', rotations: 64, pointsPerRotation: 128 } }], {}), /at most 1024 points/],+ [() => curveSet([{ shape: { type: 'star', spikes: 3 } }], {}), /Unknown shape field: spikes/],+ [() => curveSet([{ points: line }, { points: [line[0]] }], {}), /splines\[1\]\.points needs 2 to 1024 entries/],+ [() => curveSet(Array.from({ length: 5 }, () => ({ points: Array.from({ length: 1000 }, (_, index) => [index, 0, 0]) })), {}), /at most 4096/],+ [() => curveSet([{ shape: { type: 'star', points: 256 } }], { maxVertices: 100 }), /exceeding maxVertices 100/],+ ];+ for (const [attempt, pattern] of cases) assert.throws(attempt, pattern);+});++test('a recipe curve geometry takes a shape, splines, kind and trim, and rejects mixing them', () => {+ const recipe = geometry => ({+ format: '67js.scene',+ schemaVersion: 1,+ materials: [{ id: 'metal', color: [0.6, 0.6, 0.65], metallic: 1, roughness: 0.3 }],+ geometries: [{ id: 'g', type: 'curve', ...geometry }],+ nodes: [{ id: 'n', geometry: 'g', material: 'metal' }],+ });+ const star = createAgentScene(recipe({ shape: { type: 'star' }, radius: 0.02 }));+ assert.ok(star.parts[0].geometry.indices.length > 0);+ const several = createAgentScene(recipe({ splines: [{ points: [[0, 0, 0], [1, 0, 0]], trim: { end: 0.5 } }, { shape: { type: 'arc' } }], radius: 0.02 }));+ assert.ok(several.parts[0].geometry.indices.length > 0);+ assert.throws(() => createAgentScene(recipe({ points: [[0, 0, 0], [1, 0, 0]], splines: [{ shape: { type: 'star' } }] })), /cannot be used with splines/);+ assert.throws(() => createAgentScene(recipe({ shape: { type: 'star', points: 1 } })), /shape\.points/);+ assert.throws(() => createAgentScene(recipe({ shape: { type: 'star' }, trim: { end: 3 } })), /trim/);+});