3D engine that AI agents drive
Add NURBS order and knots and mesh edges to curve splines (part of #841)
Nguyen Xuan An4d9a7881db7e
diff --git a/changes/841-mesh-to-curve.md b/changes/841-mesh-to-curve.mdnew file mode 100644index 00000000..c251bc91--- /dev/null+++ b/changes/841-mesh-to-curve.md@@ -0,0 +1 @@+- NURBS splines take `order`, `knots` and `knotMode`, and `meshEdgesToSplines` turns mesh edge loops and chains into curve splines (#841)diff --git a/changes/841-mesh-to-curve.size.md b/changes/841-mesh-to-curve.size.mdnew file mode 100644index 00000000..b64d684b--- /dev/null+++ b/changes/841-mesh-to-curve.size.md@@ -0,0 +1,5 @@+- entry:modeling: 492 bytes gzip for NURBS order, knot vector and knot mode validation and sampling, the missing half of #701 (agent-facing curve control)+- scene:agent-scene: 72 bytes gzip for the order, knots and knotMode curve fields+- scene:agent-scene+lazy: 563 bytes gzip for the same fields and the mesh edge walk that turns loops and chains into splines+- goal:agent-scene: 72 bytes gzip for NURBS order and knots, an agent-facing capability; needs An to accept+- tool:scene_create: the curve topic text names order, knots and knotModediff --git a/docs/modeling.md b/docs/modeling.mdindex c99aed2e..0de3707a 100644--- a/docs/modeling.md+++ b/docs/modeling.md@@ -70,12 +70,19 @@ Volume, area and bounds match Blender 5.2 for an open and a closed Bezier curve`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.+in `splines`, never both. A spline is `{ points | shape, closed, kind, weights, order, knots, knotMode, trim }`, and `curve(points, { kind, weights, order, knots, knotMode, 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+ direction of the segment that leaves it, so corners are not mitred. A NURBS spline is a cubic B-spline by default: open ones areclamped (they start and end on the first and last point), closed ones are periodic. `weights` holds one number above 0 perpoint (default 1); a higher weight pulls the curve toward its point.+- NURBS `order` is an integer from 2 to 8 and at most the point count (default 4, cubic; 2 follows the control polygon, 3 with+ weights draws exact conic arcs). An open NURBS takes `knotMode` `clamped` (default) or `uniform` (evenly spaced knots, the+ curve does not reach its end points), or explicit `knots`: point count plus order numbers that never decrease and rise+ between `knots[order - 1]` and `knots[count]`, where the curve is defined; repeated knots lower the smoothness there. `knots`+ and `knotMode` exclude each other and do not apply to a closed spline, which is periodic. Samples spread evenly over that+ parameter range, so unevenly spaced knots do not change the sample count. Tests compare the points with the Cox-de Boor+ recursion written out from its definition.- `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.@@ -93,8 +100,22 @@ in `splines`, never both. A spline is `{ points | shape, closed, kind, weights,The growth runs over the spline's own trim range (a trim in factors). `value` is the growth with no track. More steps followa curved path more closely; between steps the tube blends the two neighbours.-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.+### Mesh edges to curve++`meshEdgesToSplines(mesh, selection)` from `src/mesh.js` turns selected edges of a `MeshData` into poly splines that+`curveSet` sweeps: `[{ kind: 'poly', closed, points }]`. The selection is one of+- an edge rule of `selectEdges`, such as `{ open: true }` (boundary edges of a hole or rim), `{ angle: 45 }` or `{ along: [0, 1, 0] }`;+- `{ group, minWeight = 0.5 }`: edges whose two vertices both weigh at least `minWeight` in the vertex group;+- `{ edges: [edge indices] }`.++A loop where every vertex has two selected edges becomes a closed spline, starting at its lowest vertex and leaving toward its+lower neighbour. A chain becomes an open spline from its end or from a junction vertex (three or more edges), so a branching+selection is several splines that meet there. The order is by first vertex and does not depend on the selection order. At most+64 splines, 1024 points in one and 4096 in all; a selection past that fails and says to pick fewer edges. It is a library+call; a recipe curve takes the resulting splines in `splines`.++Not covered: trim ranges that wrap around the start of a closed curve, a spline fill, and reading the edges of a scene part+through MCP.## Textdiff --git a/docs/parity.md b/docs/parity.mdindex d58d4493..a2c41df2 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. 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. A `grow` field turns the trim into a morph track, so a vine grows over a motion. 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 | 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. A `grow` field turns the trim into a morph track, so a vine grows over a motion. NURBS take an `order` (2 to 8) and clamped, uniform or explicit knots, checked against a Cox-de Boor reference. `meshEdgesToSplines` turns the edge loops and chains of a mesh (an edge rule, vertex group or edge list) into poly splines, in order, closed where the loop is, but only as a library call, not through MCP. There are 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), [mesh-to-curve](../tests/mesh-to-curve.test.js), [Blender comparison](../tests/blender-curve-text.test.js) | #45, #701, #841 || 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 | partial | The `sdf` geometry blends spheres and other primitives with a smooth union, which gives the metaball look as a mesh meshed by surface nets. There is no metaball object, no per-element stiffness and no threshold setting. | [modeling-sdf](../tests/modeling-sdf.test.js) | #700 |diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex dda033ba..9c642634 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -65,7 +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. grow {name, steps 2-16, value}: morph targets of the curve grown step by step; animate with a motion track { kind: "morph", id: <name>, property: "weight", keyframes 0-1 } so a vine grows. See docs/modeling.md.',+ splines: 'Geometry curve takes points (kind bezier|poly|nurbs, closed; nurbs also weights, order 2-8 default 4, and for open splines knotMode clamped|uniform or knots: point count plus order values that never decrease), 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. grow {name, steps 2-16, value}: morph targets of the curve grown step by step; animate with a motion track { kind: "morph", id: <name>, property: "weight", keyframes 0-1 } so a vine grows. See docs/modeling.md.',sdf: 'Geometry sdf: root is a tree meshed by surface nets, resolution 4-128 cells along the longest side (default 32). Primitive {shape sphere|box|roundBox|capsule|cylinder|torus, radius, size, height, tubeRadius, position, rotation (Euler radians), scale (uniform)}. Operation {op union|subtract|intersect, smooth (blend radius), children: 2-16} (subtract removes the rest from the first) or {op offset, distance, child}. At most 64 nodes, 8 levels. See docs/modeling.md.',text: 'Extruded text, baseline y=0 along +X, facing +Z. text (\n for lines), size (1), depth (0.2), align left|center|right, curveSegments, font. See docs/modeling.md.',});diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 6438dffa..4410bde5 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -461,7 +461,7 @@ const GEOMETRY_FIELDS = {extrude: ['contour', 'holes', 'depth', 'steps', 'bevel', 'bevelThickness', 'bevelSegments'],tube: ['path', 'radius', 'segments', 'radialSegments', 'closed'],sdf: ['root', 'resolution'],- curve: ['points', 'shape', 'splines', 'closed', 'kind', 'weights', 'trim', 'grow', 'radius', 'taper', 'profile', 'resolution', 'radialSegments'],+ curve: ['points', 'shape', 'splines', 'closed', 'kind', 'weights', 'order', 'knots', 'knotMode', 'trim', 'grow', 'radius', 'taper', 'profile', 'resolution', 'radialSegments'],text: ['text', 'size', 'depth', 'font', 'align', 'curveSegments'],mesh: ['base', 'edits', 'stack', 'smoothAngle', 'shapeKeys'],terrain: ['size', 'resolution', 'seed', 'amplitude', 'holes'],@@ -495,7 +495,7 @@ function geometryEstimate(value, scope = PENDING_CUTTER_SCOPE) {return input.length;}for (const field of GEOMETRY_FIELDS[value.type]) {- if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed', 'base', 'edits', 'stack', 'shapeKeys', 'points', 'taper', 'text', 'font', 'align', 'from', 'to', 'shape', 'splines', 'kind', 'weights', 'trim', 'grow', 'root'].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', 'order', 'knots', 'knotMode', 'trim', 'grow', 'root'].includes(field)) {finite(value[field], field);}}@@ -531,7 +531,7 @@ function geometryEstimate(value, scope = PENDING_CUTTER_SCOPE) {}return (detail('segments', 64, 3, 2048) + 1) * (detail('radialSegments', 12, 3, 128) + 1);case 'curve': {- if (['shape', 'splines', 'kind', 'weights', 'trim', 'grow'].some(field => value[field] !== undefined)) {+ if (['shape', 'splines', 'kind', 'weights', 'order', 'knots', 'knotMode', 'trim', 'grow'].some(field => value[field] !== undefined)) {return agentSceneModule('modeling').curveGeometryVertexCount(value);}const knots = value.points;diff --git a/src/mesh-to-curve.js b/src/mesh-to-curve.jsnew file mode 100644index 00000000..fe6e8c06--- /dev/null+++ b/src/mesh-to-curve.js@@ -0,0 +1,139 @@+// Mesh edges to curve splines: a loop or chain of selected edges becomes one poly spline, in walking order.+import { edgeFaces, selectEdges } from './mesh-bevel.js';+import { vertexGroupWeights } from './mesh-data.js';++export const MAX_CURVE_SPLINES = 64;+export const MAX_POINTS_PER_SPLINE = 1024;+export const MAX_TOTAL_CURVE_POINTS = 4096;++// The selection is one of: an edge rule of selectEdges ({ open: true }, { angle: 30 }, ...),+// { group, minWeight } (edges whose two vertices both weigh at least minWeight), or { edges: [edge indices] }.+function selectedEdgeMask(mesh, selection) {+ if (!selection || typeof selection !== 'object' || Array.isArray(selection)) {+ throw new TypeError('selection must be an object such as { "open": true }, { "group": "rim" } or { "edges": [0, 1, 2] }.');+ }+ if (selection.edges !== undefined) return maskFromEdgeList(mesh, selection);+ if (selection.group !== undefined) return maskFromGroup(mesh, selection);+ return selectEdges(mesh, selection, edgeFaces(mesh));+}++function maskFromEdgeList(mesh, selection) {+ const extra = Object.keys(selection).filter(key => key !== 'edges');+ if (extra.length) throw new TypeError(`selection.edges does not take ${extra.join(', ')}.`);+ const list = selection.edges;+ if (!Array.isArray(list) || list.length < 1 || list.length > mesh.edgeCount) {+ throw new RangeError(`selection.edges needs 1 to ${mesh.edgeCount} edge indices, such as [0, 1, 2].`);+ }+ const mask = new Uint8Array(mesh.edgeCount);+ for (const edge of list) {+ if (!Number.isInteger(edge) || edge < 0 || edge >= mesh.edgeCount) {+ throw new RangeError(`selection.edges holds ${JSON.stringify(edge)}; every index must be an integer from 0 to ${mesh.edgeCount - 1}.`);+ }+ mask[edge] = 1;+ }+ return mask;+}++function maskFromGroup(mesh, selection) {+ const extra = Object.keys(selection).filter(key => key !== 'group' && key !== 'minWeight');+ if (extra.length) throw new TypeError(`selection.group does not take ${extra.join(', ')}. Use group and minWeight.`);+ if (typeof selection.group !== 'string') throw new TypeError('selection.group must be a vertex group name such as "rim".');+ const minWeight = selection.minWeight ?? 0.5;+ if (!Number.isFinite(minWeight) || minWeight <= 0 || minWeight > 1) {+ throw new RangeError('selection.minWeight must be a number above 0 and at most 1, such as 0.5.');+ }+ const weights = vertexGroupWeights(mesh, selection.group);+ const mask = new Uint8Array(mesh.edgeCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const inGroup = weights[mesh.edgeVertices[edge * 2]] >= minWeight && weights[mesh.edgeVertices[edge * 2 + 1]] >= minWeight;+ mask[edge] = inGroup ? 1 : 0;+ }+ return mask;+}++// Neighbours of each selected vertex as [vertex, edge] pairs, sorted so the walk is the same every run.+function adjacencyOf(mesh, mask) {+ const adjacency = new Map();+ const link = (from, to, edge) => {+ if (!adjacency.has(from)) adjacency.set(from, []);+ adjacency.get(from).push([to, edge]);+ };+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ if (!mask[edge]) continue;+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ link(first, second, edge);+ link(second, first, edge);+ }+ for (const neighbours of adjacency.values()) neighbours.sort((left, right) => left[0] - right[0] || left[1] - right[1]);+ return adjacency;+}++// Follows edges from the start until the path ends, meets a junction (not two edges) or comes back to the start.+function walk(startVertex, firstStep, adjacency, usedEdges) {+ const vertices = [startVertex];+ let [vertex, edge] = firstStep;+ usedEdges.add(edge);+ vertices.push(vertex);+ while (vertex !== startVertex && adjacency.get(vertex).length === 2) {+ const next = adjacency.get(vertex).find(([, candidate]) => !usedEdges.has(candidate));+ if (!next) break;+ [vertex, edge] = next;+ usedEdges.add(edge);+ vertices.push(vertex);+ }+ return vertices;+}++function chainsOf(adjacency) {+ const usedEdges = new Set();+ const chains = [];+ const vertices = [...adjacency.keys()].sort((left, right) => left - right);+ // Open chains first: they start at an end or a junction, any vertex without exactly two edges.+ for (const start of vertices) {+ if (adjacency.get(start).length === 2) continue;+ for (const step of adjacency.get(start)) {+ if (usedEdges.has(step[1])) continue;+ chains.push({ vertices: walk(start, step, adjacency, usedEdges), closed: false });+ }+ }+ // What is left is closed loops; each starts at its lowest vertex.+ for (const start of vertices) {+ const step = adjacency.get(start).find(([, edge]) => !usedEdges.has(edge));+ if (!step) continue;+ chains.push({ vertices: walk(start, step, adjacency, usedEdges).slice(0, -1), closed: true });+ }+ return chains;+}++/**+ * Turns the selected edges of a mesh into poly splines for the `curve` geometry: `[{ kind: 'poly', closed, points }]`.+ * A loop (every vertex has two selected edges) is a closed spline that starts at its lowest vertex and leaves toward+ * its lower neighbour; a chain is an open spline from its end or junction vertex. Splines come in order of their+ * first vertex, so the result is the same on every call. Counts are bounded: at most 64 splines, 1024 points in one+ * and 4096 in all.+ */+export function meshEdgesToSplines(mesh, selection) {+ const mask = selectedEdgeMask(mesh, selection);+ const adjacency = adjacencyOf(mesh, mask);+ if (adjacency.size === 0) {+ throw new RangeError('selection matches no edge of the mesh. Pick edges that exist, for example { "open": true } on a mesh with a hole.');+ }+ const chains = chainsOf(adjacency);+ if (chains.length > MAX_CURVE_SPLINES) {+ throw new RangeError(`The selection makes ${chains.length} splines; at most ${MAX_CURVE_SPLINES}. Select fewer edge loops or chains.`);+ }+ let total = 0;+ const splines = chains.map(chain => {+ if (chain.vertices.length > MAX_POINTS_PER_SPLINE) {+ throw new RangeError(`A selected chain has ${chain.vertices.length} points; at most ${MAX_POINTS_PER_SPLINE} for one spline. Select a shorter chain.`);+ }+ total += chain.vertices.length;+ const points = chain.vertices.map(vertex => Array.from(mesh.positions.subarray(vertex * 3, vertex * 3 + 3)));+ return { kind: 'poly', closed: chain.closed, points };+ });+ if (total > MAX_TOTAL_CURVE_POINTS) {+ throw new RangeError(`The selection makes ${total} points in all; at most ${MAX_TOTAL_CURVE_POINTS}. Select fewer edges.`);+ }+ return splines;+}diff --git a/src/mesh.js b/src/mesh.jsindex 8abc7582..340fdf9d 100644--- a/src/mesh.js+++ b/src/mesh.js@@ -15,6 +15,7 @@ export { applyMeshEdits, normalizeMeshEdits, transformMesh, MESH_EDIT_OPERATIONSexport { evaluateMeshStack, normalizeMeshStack, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-recipe.js';export { mirrorMesh, arrayMesh, solidifyMesh, removeCoincidentFaces } from './mesh-stack.js';export { bevelEdges, selectEdges } from './mesh-bevel.js';+export { meshEdgesToSplines } from './mesh-to-curve.js';export { loopCut } from './mesh-loopcut.js';export { unwrapUv } from './mesh-uv.js';export { projectUv, packUvIslands } from './mesh-uv-project.js';diff --git a/src/modeling-splines.js b/src/modeling-splines.jsindex 9523e026..eb5ecc88 100644--- a/src/modeling-splines.js+++ b/src/modeling-splines.js@@ -3,7 +3,9 @@import { fillZeroTangents, resolveHandles, sampleBezierSpans } from './modeling-bezier.js';const TWO_PI = Math.PI * 2;-const NURBS_ORDER = 4;+export const NURBS_DEFAULT_ORDER = 4;+export const NURBS_MAX_ORDER = 8;+export const KNOT_MODES = ['clamped', 'uniform'];const DERIVATIVE_STEP = 1e-5;const MINIMUM_SEGMENT = 1e-9;@@ -125,10 +127,11 @@ function samplePoly(points, closed) {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) {+// Clamped (open, the default), uniform (open, not touching the end points) or periodic (closed) knot vector for a+// B-spline of the given order over `count` control points.+function knotVector(count, order, closed, knotMode = 'clamped') {const total = count + order;- if (closed) return Array.from({ length: total }, (_, index) => index);+ if (closed || knotMode === 'uniform') return Array.from({ length: total }, (_, index) => index);return Array.from({ length: total }, (_, index) => Math.min(Math.max(index - order + 1, 0), count - order + 1));}@@ -177,15 +180,16 @@ function nurbsPoint(controls, weights, knots, order, parameter) {}/**- * 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.+ * NURBS of `options.order` (default 4, or the point count when lower). An open spline uses `options.knots` (one+ * non-decreasing value per control point plus the order) or a `knotMode`: `clamped` starts and ends on the first and+ * last control point, `uniform` does not. 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);+export function sampleNurbs(controlPoints, weights, closed, resolution, options = {}) {+ const order = Math.min(options.order ?? NURBS_DEFAULT_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 knots = options.knots ?? knotVector(controls.length, order, closed, options.knotMode);const start = knots[order - 1];const end = knots[controls.length];const spans = closed ? controlPoints.length : controlPoints.length - 1;@@ -206,7 +210,7 @@ export function sampleNurbs(controlPoints, weights, closed, resolution) {/** 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);+ if (spline.type === 'nurbs') return sampleNurbs(spline.points, spline.weights, spline.closed, resolution, spline.basis);return sampleBezierSpans(resolveHandles(spline.points, spline.closed), spline.closed, resolution);}diff --git a/src/modeling.js b/src/modeling.jsindex 1cced501..8b0cc570 100644--- a/src/modeling.js+++ b/src/modeling.js@@ -1,6 +1,6 @@import { buildLathe, buildExtrusion, buildTube } from './modeling-shapes.js';import { sweepSamples } from './modeling-bezier.js';-import { resampleSamples, sampleCountOf, sampleSpline, shapeToSpline, trimSamples } from './modeling-splines.js';+import { KNOT_MODES, NURBS_DEFAULT_ORDER, NURBS_MAX_ORDER, resampleSamples, sampleCountOf, sampleSpline, shapeToSpline, trimSamples } from './modeling-splines.js';import { planSdf, sdfGeometry as buildSdf } from './modeling-sdf.js';const MAX_INPUT_POINTS = 4096;@@ -276,7 +276,7 @@ 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'];+const SPLINE_FIELDS = ['points', 'shape', 'closed', 'kind', 'weights', 'order', 'knots', 'knotMode', 'trim'];function trimFrom(input, label) {if (input === undefined) return null;@@ -306,6 +306,27 @@ function weightsFrom(input, count, label) {});}+// NURBS order, knot vector and knot mode. The order is at most the point count; an open spline takes explicit knots+// (point count plus order values that never decrease and span a range) or a knotMode; a closed one is periodic.+function nurbsBasisFrom(input, count, closed, label) {+ const { order = Math.min(NURBS_DEFAULT_ORDER, count), knots, knotMode } = input;+ if (!Number.isInteger(order) || order < 2 || order > Math.min(NURBS_MAX_ORDER, count)) {+ throw new RangeError(`${label}.order must be an integer from 2 to ${Math.min(NURBS_MAX_ORDER, count)} (at most ${NURBS_MAX_ORDER} and the point count ${count}), such as ${Math.min(NURBS_DEFAULT_ORDER, count)}.`);+ }+ if (knots !== undefined && knotMode !== undefined) throw new TypeError(`${label}.knots and ${label}.knotMode exclude each other. Pass one.`);+ if ((knots !== undefined || knotMode !== undefined) && closed) throw new TypeError(`${label}.knots and ${label}.knotMode apply to open splines; a closed spline is periodic. Set closed to false.`);+ if (knotMode !== undefined && !KNOT_MODES.includes(knotMode)) throw new RangeError(`${label}.knotMode must be one of ${KNOT_MODES.join(', ')}.`);+ if (knots !== undefined) {+ if (!Array.isArray(knots) || knots.length !== count + order) throw new RangeError(`${label}.knots needs ${count + order} values (points ${count} plus order ${order}).`);+ knots.forEach((knot, index) => {+ finite(knot, `${label}.knots`);+ if (index > 0 && knot < knots[index - 1]) throw new RangeError(`${label}.knots must not decrease; knots[${index}] ${knot} is below knots[${index - 1}] ${knots[index - 1]}.`);+ });+ if (!(knots[count] > knots[order - 1])) throw new RangeError(`${label}.knots must rise between knots[${order - 1}] and knots[${count}]; the curve is defined only there.`);+ }+ return { order, knots: knots && [...knots], knotMode };+}+// 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.`);@@ -323,10 +344,13 @@ function splineFrom(input, label) {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.`);+ for (const key of ['weights', 'order', 'knots', 'knotMode']) {+ if (kind !== 'nurbs' && input[key] !== undefined) throw new TypeError(`${label}.${key} is not allowed here: weights apply to kind nurbs only, as do order, knots and knotMode.`);+ }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`) };+ const basis = kind === 'nurbs' ? nurbsBasisFrom(input, points.length, closed, label) : undefined;+ return { type: kind, closed, points: resolved, weights, basis, trim: trimFrom(input.trim, `${label}.trim`) };}function joinSweeps(parts) {@@ -407,7 +431,7 @@ function planCurveSet(splines, {return { resolved, vertexCount, radius, profilePoints, taperFactors, radialSegments, resolution };}-const SINGLE_SPLINE_FIELDS = ['points', 'shape', 'closed', 'kind', 'weights', 'trim'];+const SINGLE_SPLINE_FIELDS = SPLINE_FIELDS;// The scene geometry `curve` holds one spline in its own fields, or several in `splines`.function splinesOfGeometry(value) {@@ -505,9 +529,9 @@ export function curveGeometryVertexCount(value) {* 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,+ closed = false, kind, weights, order, knots, knotMode, trim, radius, taper, profile, resolution, radialSegments, maxVertices,} = {}) {- return curveSet([{ points, closed, kind, weights, trim }], { radius, taper, profile, resolution, radialSegments, maxVertices }, 'points');+ return curveSet([{ points, closed, kind, weights, order, knots, knotMode, 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.jsindex 0eb1cfba..f4e8ac01 100644--- a/tests/curve-splines.test.js+++ b/tests/curve-splines.test.js@@ -276,3 +276,108 @@ test('a closed curve grows to full length with no trim, and its first and last sassert.equal(geometry.morphTargets[3].positions.length, vertexCount, `${name} last state`);}});++// Cox-de Boor recursion straight from the definition of the basis functions, to check the implementation against.+function referenceBasis(index, degree, parameter, knots, lastDomainKnot) {+ if (degree === 0) {+ const inSpan = parameter >= knots[index] && parameter < knots[index + 1];+ const atEnd = parameter === lastDomainKnot && knots[index] < knots[index + 1] && knots[index + 1] === lastDomainKnot;+ return inSpan || atEnd ? 1 : 0;+ }+ const leftSpan = knots[index + degree] - knots[index];+ const rightSpan = knots[index + degree + 1] - knots[index + 1];+ const left = leftSpan === 0 ? 0 : (parameter - knots[index]) / leftSpan * referenceBasis(index, degree - 1, parameter, knots, lastDomainKnot);+ const right = rightSpan === 0 ? 0 : (knots[index + degree + 1] - parameter) / rightSpan * referenceBasis(index + 1, degree - 1, parameter, knots, lastDomainKnot);+ return left + right;+}++function referenceNurbs(controls, weights, order, knots, parameter) {+ const sum = [0, 0, 0];+ let weightSum = 0;+ controls.forEach((control, index) => {+ const weighted = referenceBasis(index, order - 1, parameter, knots, knots[controls.length]) * weights[index];+ weightSum += weighted;+ for (let axis = 0; axis < 3; axis++) sum[axis] += weighted * control[axis];+ });+ return sum.map(value => value / weightSum);+}++function assertMatchesReference(controls, weights, options, resolution) {+ const { order, knots } = options;+ const samples = sampleNurbs(controls, weights, false, resolution, options);+ const start = knots[order - 1];+ const end = knots[controls.length];+ const spans = controls.length - 1;+ samples.points.forEach((point, index) => {+ const expected = referenceNurbs(controls, weights, order, knots, start + (end - start) * index / (spans * resolution));+ point.forEach((value, axis) => assert.ok(Math.abs(value - expected[axis]) < 1e-9, `sample ${index} axis ${axis}: ${value} against ${expected[axis]}`));+ });+}++test('NURBS order and knots match a reference evaluation', () => {+ const controls = [[0, 0, 0], [1, 2, 0], [2, -1, 1], [3, 2, 0], [4, 0, 2]];+ const weights = [1, 2, 0.5, 1.5, 1];+ assertMatchesReference(controls, weights, { order: 3, knots: [0, 0, 0, 1, 2, 3, 3, 3] }, 7);+ assertMatchesReference(controls, weights, { order: 5, knots: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] }, 7);+ assertMatchesReference(controls, weights, { order: 4, knots: [0, 1, 2, 3, 4, 5, 6, 7, 8] }, 7);+ assertMatchesReference(controls, weights, { order: 3, knots: [0, 0, 0, 0.5, 0.5, 2, 2, 2] }, 7);+});++test('a quadratic rational NURBS draws an exact quarter circle', () => {+ const controls = [[1, 0, 0], [1, 1, 0], [0, 1, 0]];+ const samples = sampleNurbs(controls, [1, Math.SQRT1_2, 1], false, 16, { order: 3 });+ for (const [x, y] of samples.points) assert.ok(Math.abs(Math.hypot(x, y) - 1) < 1e-12);+});++test('knotMode uniform leaves the end points, clamped keeps them, order 2 is the control polygon', () => {+ const controls = [[0, 0, 0], [1, 1, 0], [2, 0, 0], [3, 1, 0], [4, 0, 0]];+ const weights = Array(5).fill(1);+ const clamped = sampleNurbs(controls, weights, false, 4, { order: 4, knotMode: 'clamped' });+ const uniform = sampleNurbs(controls, weights, false, 4, { order: 4, knotMode: 'uniform' });+ assert.deepEqual(clamped.points[0], controls[0]);+ assert.notDeepEqual(uniform.points[0], controls[0]);+ assert.deepEqual(sampleNurbs(controls, weights, false, 4), clamped);+ const linear = sampleNurbs(controls, weights, false, 4, { order: 2 });+ assert.deepEqual(linear.points[4], controls[1]);+});++test('curve takes order, knots and knotMode and rejects bad ones with what to pass', () => {+ const points = [[0, 0, 0], [1, 1, 0], [2, 0, 0], [3, 1, 0]];+ const wire = { radius: 0.05, resolution: 4 };+ const base = curve(points, { ...wire, kind: 'nurbs' });+ assert.equal(hashOf(curve(points, { ...wire, kind: 'nurbs', order: 4 })), hashOf(base));+ assert.equal(hashOf(curve(points, { ...wire, kind: 'nurbs', knots: [0, 0, 0, 0, 1, 1, 1, 1] })), hashOf(base));+ assert.notEqual(hashOf(curve(points, { ...wire, kind: 'nurbs', order: 3 })), hashOf(base));+ assert.equal(hashOf(curve(points, { ...wire, kind: 'nurbs', order: 3 })), hashOf(curve(points, { ...wire, kind: 'nurbs', order: 3 })));+ const nurbs = { ...wire, kind: 'nurbs' };+ const cases = [+ [{ ...nurbs, order: 1 }, /order must be an integer from 2 to 4/],+ [{ ...nurbs, order: 5 }, /order must be an integer from 2 to 4/],+ [{ ...nurbs, order: 2.5 }, /order must be an integer/],+ [{ ...nurbs, knots: [0, 0, 0, 1, 1, 1] }, /needs 8 values \(points 4 plus order 4\)/],+ [{ ...nurbs, knots: [0, 0, 0, 0, 1, 0.5, 1, 1] }, /must not decrease; knots\[5\]/],+ [{ ...nurbs, knots: [0, 0, 0, 0, 0, 0, 0, 0] }, /must rise between knots\[3\] and knots\[4\]/],+ [{ ...nurbs, knots: [0, 0, 0, 0, 1, 1, 1, NaN] }, /knots must be a finite float/],+ [{ ...nurbs, knots: [0, 0, 0, 0, 1, 1, 1, 1], knotMode: 'uniform' }, /exclude each other/],+ [{ ...nurbs, knotMode: 'periodic' }, /knotMode must be one of clamped, uniform/],+ [{ ...nurbs, closed: true, knotMode: 'uniform' }, /apply to open splines/],+ [{ ...wire, order: 3 }, /order is not allowed here/],+ [{ ...wire, knotMode: 'uniform' }, /knotMode is not allowed here/],+ ];+ for (const [options, pattern] of cases) assert.throws(() => curve(points, options), pattern);+});++test('a recipe curve geometry takes order and knots', () => {+ const recipe = geometry => ({+ format: '67js.scene',+ schemaVersion: 1,+ materials: [{ id: 'metal', color: [0.6, 0.6, 0.65] }],+ geometries: [{ id: 'g', type: 'curve', kind: 'nurbs', points: [[0, 0, 0], [1, 1, 0], [2, 0, 0], [3, 1, 0]], radius: 0.05, ...geometry }],+ nodes: [{ id: 'n', geometry: 'g', material: 'metal' }],+ });+ const cubic = createAgentScene(recipe({}));+ const quadratic = createAgentScene(recipe({ order: 3, knots: [0, 0, 0, 1, 2, 2, 2] }));+ assert.ok(quadratic.parts[0].geometry.indices.length > 0);+ assert.notEqual(hashOf(quadratic.parts[0].geometry), hashOf(cubic.parts[0].geometry));+ assert.throws(() => createAgentScene(recipe({ order: 9 })), /order must be an integer from 2 to 4/);+});diff --git a/tests/mesh-to-curve.test.js b/tests/mesh-to-curve.test.jsnew file mode 100644index 00000000..1e5a06d7--- /dev/null+++ b/tests/mesh-to-curve.test.js@@ -0,0 +1,123 @@+import './support/load-agent-scene-modules.mjs';+import assert from 'node:assert/strict';+import test from 'node:test';+import { box, cylinder, grid } from '../src/geometry.js';+import { curveSet } from '../src/modeling.js';+import { meshFromGeometry, meshEdgesToSplines } from '../src/mesh.js';+import { createMeshData } from '../src/mesh-data.js';++const SWEEP_RADIUS = 0.02;++// A square pillar with its top face removed: the open rim is one closed loop of four edges.+function openPillar() {+ const full = meshFromGeometry(box(0, 1));+ const { faceOffsets, cornerVertices } = full;+ const keptFaces = [];+ for (let face = 0; face < full.faceCount; face++) {+ const corners = Array.from(cornerVertices.subarray(faceOffsets[face], faceOffsets[face + 1]));+ const averageHeight = corners.reduce((sum, vertex) => sum + full.positions[vertex * 3 + 1], 0) / corners.length;+ if (!(averageHeight > 0.49 && corners.every(vertex => full.positions[vertex * 3 + 1] > 0.49))) keptFaces.push(corners);+ }+ const offsets = [0];+ const corners = [];+ for (const face of keptFaces) {+ corners.push(...face);+ offsets.push(corners.length);+ }+ return createMeshData({ positions: full.positions, faceOffsets: Uint32Array.from(offsets), cornerVertices: Uint32Array.from(corners) });+}++function distanceToSegment(point, from, to) {+ const direction = to.map((value, axis) => value - from[axis]);+ const offset = point.map((value, axis) => value - from[axis]);+ const lengthSquared = direction.reduce((sum, value) => sum + value * value, 0);+ const along = Math.min(Math.max(offset.reduce((sum, value, axis) => sum + value * direction[axis], 0) / lengthSquared, 0), 1);+ return Math.hypot(...offset.map((value, axis) => value - direction[axis] * along));+}++function distanceToLoop(point, loop) {+ return Math.min(...loop.map((from, index) => distanceToSegment(point, from, loop[(index + 1) % loop.length])));+}++test('an open mesh rim becomes a closed curve and sweeping it gives back the outline', () => {+ const pillar = openPillar();+ const [spline, ...others] = meshEdgesToSplines(pillar, { open: true });+ assert.equal(others.length, 0);+ assert.equal(spline.kind, 'poly');+ assert.equal(spline.closed, true);+ assert.equal(spline.points.length, 4);+ for (const point of spline.points) {+ assert.ok(Math.abs(point[1] - 0.5) < 1e-6, 'the rim sits at the top');+ assert.ok(Math.abs(Math.abs(point[0]) - 0.5) < 1e-6 && Math.abs(Math.abs(point[2]) - 0.5) < 1e-6);+ }+ // consecutive points share an edge: one coordinate changes by the full side+ spline.points.forEach((point, index) => {+ const next = spline.points[(index + 1) % 4];+ const changed = point.filter((value, axis) => Math.abs(value - next[axis]) > 0.5).length;+ assert.equal(changed, 1);+ });+ const sweep = curveSet([spline], { radius: SWEEP_RADIUS, radialSegments: 6, maxVertices: 100000 });+ assert.ok(sweep.indices.length > 0);+ let worst = 0;+ for (let offset = 0; offset < sweep.positions.length; offset += 3) {+ const point = Array.from(sweep.positions.subarray(offset, offset + 3));+ worst = Math.max(worst, distanceToLoop(point, spline.points));+ }+ assert.ok(worst <= SWEEP_RADIUS * 1.0001, `swept vertices stay within the tube radius of the outline (worst distance ${worst})`);+});++test('an explicit edge list gives an open chain in walking order, the same every call', () => {+ const pillar = openPillar();+ const rim = meshEdgesToSplines(pillar, { open: true })[0];+ const rimEdges = [];+ for (let edge = 0; edge < pillar.edgeCount; edge++) {+ const vertices = [pillar.edgeVertices[edge * 2], pillar.edgeVertices[edge * 2 + 1]];+ if (vertices.every(vertex => pillar.positions[vertex * 3 + 1] > 0.49)) rimEdges.push(edge);+ }+ assert.equal(rimEdges.length, 4);+ const chain = meshEdgesToSplines(pillar, { edges: rimEdges.slice(0, 3) });+ assert.equal(chain.length, 1);+ assert.equal(chain[0].closed, false);+ assert.equal(chain[0].points.length, 4);+ assert.deepEqual(meshEdgesToSplines(pillar, { edges: rimEdges.slice(0, 3) }), chain);+ assert.deepEqual(meshEdgesToSplines(pillar, { edges: [...rimEdges].reverse() }), [rim]);+});++test('a vertex group selects the loop and a junction splits chains', () => {+ const pillar = openPillar();+ const weights = new Float32Array(pillar.vertexCount);+ for (let vertex = 0; vertex < pillar.vertexCount; vertex++) weights[vertex] = pillar.positions[vertex * 3 + 1] > 0.49 ? 1 : 0;+ const withGroup = createMeshData({+ positions: pillar.positions,+ faceOffsets: pillar.faceOffsets,+ cornerVertices: pillar.cornerVertices,+ attributes: { point: { 'group:rim': { data: weights, size: 1 } } },+ });+ assert.deepEqual(meshEdgesToSplines(withGroup, { group: 'rim' }), meshEdgesToSplines(pillar, { open: true }));+ // all four vertical edges meet the rim: they form a star of 3-edge junction vertices+ const vertical = meshEdgesToSplines(pillar, { along: [0, 1, 0] });+ assert.equal(vertical.length, 4);+ assert.ok(vertical.every(spline => spline.closed === false && spline.points.length === 2));+});++test('mesh edges to curve rejects bad selections with what to pass', () => {+ const pillar = openPillar();+ const cases = [+ [undefined, /selection must be an object/],+ [{ edges: [] }, /selection\.edges needs 1 to/],+ [{ edges: [999] }, /every index must be an integer from 0 to/],+ [{ edges: [0], extra: 1 }, /selection\.edges does not take extra/],+ [{ group: 'nope' }, /Unknown vertex group nope/],+ [{ group: 7 }, /selection\.group must be a vertex group name/],+ [{ group: 'rim', minWeight: 0 }, /selection\.minWeight must be a number above 0/],+ [{ open: { inside: { min: [5, 5, 5], max: [6, 6, 6] } } }, /matches no edge/],+ ];+ for (const [selection, pattern] of cases) assert.throws(() => meshEdgesToSplines(pillar, selection), pattern);+});++test('mesh edges to curve is bounded', () => {+ const drum = meshFromGeometry(cylinder(2000, 0, 1));+ assert.throws(() => meshEdgesToSplines(drum, { angle: 45 }), /A selected chain has 2000 points; at most 1024/);+ const rows = meshFromGeometry(grid(64));+ assert.throws(() => meshEdgesToSplines(rows, { along: [1, 0, 0] }), /makes 65 splines; at most 64/);+});