Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add lattice, curve, hook and wave modifiers (Part of #42)

Nguyen Xuan Ane15a9cbeb512
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1b423b49..84b6de65 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Add the `lattice`, `curve`, `hook` and `wave` modifiers as edits and stack nodes (part of issue #42). `lattice` moves up to 64 control points of a grid over the mesh bounds, `curve` bends a mesh along a Catmull-Rom path, `hook` pulls the vertices near a point and `wave` is a travelling ripple that matches Blender 5.2 at the same frame on two cases. Lists are bounded and the errors name the limit.
- Add the `screw`, `wireframe` and `skin` modifiers as edits and stack nodes (part of issue #42). `screw` revolves the edges of a mesh about an axis with steps, iterations and lift, and `wireframe` leaves a rim on every face with thickness, offset and even offset; both match Blender 5.2 on counts, area and positions (`wireframe` on three cases, `screw` on two). `skin` is a simple version, a closed square tube per edge with a radius per vertex and no branch solver. Sizes are bounded and the errors say what to lower. Details are in `scene_capabilities` `meshModifiers`, and the modifier entry of the tool schemas is now an open object so it no longer grows with each modifier.
- Import `SheenChair` and score it (part of issue #51). A glTF normal map may now carry its own `KHR_texture_transform` offset and positive scale (same rotation) on top of the transform the other maps share: the importer bakes the shared one into the UVs and stores the remainder as `uvTransform` on the normal map descriptor, and the `normalMapTransform` shader feature in `addons/material-layer-shaders` applies it (a scene without such a normal map compiles the same shader as before). Any other difference between the maps of one material still fails the import, and an extension `texCoord` equal to the texture's own is no longer refused. Core grew by 25 bytes gzip (`lit-box` 60,179 to 60,204): a hook in the normal map lookup, one feature line and the `bind` argument; the glTF importer grew by about 370.
- Fix the automatic floor skipping a lone flat object (part of issue #53). A lone part never counts as the recipe's own floor, so a gear lying flat, which spans its whole scene and is the lowest geometry, now gets a floor and a contact shadow (before, `agentGroundPlacement` returned null for it). The surface judge on the six cold recipes goes from 0 before the floor, to 6 with the first rule, to 7 with this fix (gear 0 to 1; one call per task, so direction only). A flat object with a hub on it is still read as a plate. Core did not change.
diff --git a/docs/mesh.md b/docs/mesh.md
index 22d24181..e5400661 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -197,7 +197,7 @@ These three (and `bevel`, below) work as edits and as stack nodes:
### Modifier stack
-A recipe mesh may carry `stack`, a list of `mirror`, `array`, `solidify`, `bevel`, `subdivide`, `uv_unwrap`, `set_position`, `displace`, `decimate`, `remesh`, `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe` and `skin` nodes (up to 16) evaluated after the
+A recipe mesh may carry `stack`, a list of `mirror`, `array`, `solidify`, `bevel`, `subdivide`, `uv_unwrap`, `set_position`, `displace`, `decimate`, `remesh`, `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook` and `wave` nodes (up to 16) evaluated after the
edits without changing them, as Blender's modifier stack. Every prefix (the edit result, then each node) is cached
by its recipe text in a least-recently-used cache bounded at 64 entries and 64 MiB, so changing a late node reuses
the earlier work. Results list one entry per node with `cached: true` when reused. `meshCacheStats()` reports hits
@@ -208,7 +208,7 @@ as Blender's Apply modifier, which leaves the result unchanged.
### Whole-mesh modifiers
-`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe` and `skin` 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` and `wave` 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 |
| --- | --- | --- |
@@ -221,8 +221,12 @@ as Blender's Apply modifier, which leaves the result unchanged.
| `screw` | `axis` (z), `angle` (360), `steps` (16, up to 256), `iterations` (1, up to 64), `lift` (0) | Revolves every edge of the mesh about the axis through the origin, as Blender Screw; the faces of the input are dropped. A whole number of turns with no lift closes the ring. |
| `wireframe` | `thickness` (0.02), `offset` (0), `evenOffset` (true), `replace` (true) | Leaves a rim of that width on every face, as Blender Wireframe; `offset` -1 to 1 moves the strut from inside to outside the surface. |
| `skin` | `radius` (0.1, a number or a scalar field per vertex) | A closed square tube on every edge. A simple version: tubes that meet overlap, and there is no branch solver. |
+| `lattice` | `divisions` ([2,2,2], 2 to 8), `moves` (up to 64 of `{ point, offset }`) | A grid of control points over the mesh bounds; each move shifts one point and vertices follow the trilinear blend. |
+| `curve` | `path` (2 to 64 points), `axis` (x) | Bends the mesh along a Catmull-Rom path; the coordinate along the axis is the distance from the path start. |
+| `hook` | `center`, `radius` (1), `translation`, `strength` (1), `falloff` (smooth) | Pulls the vertices within the radius by the translation, weighted by the falloff. |
+| `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. |
-`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`); `skin` is not compared with Blender. Not yet: `lattice`, `curve`, `hook`, `wave`, `shrinkwrap`, `weighted_normal`, `smooth_by_angle` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.
+`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. Not yet: `shrinkwrap`, `weighted_normal`, `smooth_by_angle` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.
### Field expressions
diff --git a/docs/parity.md b/docs/parity.md
index 8bc0fc07..2d73357a 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -3,7 +3,7 @@
This ledger compares 67js with each feature in the [Blender 5.2 manual](https://docs.blender.org/manual/en/latest/).
It is the record for the goal in issue #23. Use `npm run parity` to print the coverage of each section.
-Modifier coverage (rows under `Modeling > Modifiers`, from `npm run parity`): 11 done, 21 partial, 28 missing and 1 out of scope, 8 of the done rows compared with Blender, 18% of the in-scope rows done.
+Modifier coverage (rows under `Modeling > Modifiers`, from `npm run parity`): 11 done, 25 partial, 24 missing and 1 out of scope, 8 of the done rows compared with Blender, 18% of the in-scope rows done.
## How to read it
@@ -92,11 +92,11 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Generate > Wireframe Modifier | partial | `wireframe` edit and stack node: `thickness`, `offset`, `evenOffset` and `replace`. Counts, area and positions match Blender on 3 cases (closed cube, keep original, open quad). No boundary struts, no crease weight and no vertex groups. | [mesh-generator-modifiers](../tests/mesh-generator-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 |
| Modeling > Modifiers > Deform > Armature Modifier | partial | A node `skin` binds a recipe mesh to an armature with automatic weights, and imported rigs keep GPU skinning. No envelope mode and no hand-edited weights. | [rigging](../tests/rigging.test.js), [skinning](../tests/skinning.test.js) | #46 |
| Modeling > Modifiers > Deform > Cast Modifier | partial | `cast` edit and stack node, sphere shape about the origin with `factor` and `size`. No cylinder or cuboid shape, no radius limit, no control object. | [mesh-modifiers](../tests/mesh-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 |
-| Modeling > Modifiers > Deform > Curve Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |
+| Modeling > Modifiers > Deform > Curve Modifier | partial | `curve` edit and stack node bends the mesh along a Catmull-Rom path of 2 to 64 points: the coordinate along the axis is the distance from the path start, the others are offsets in a twist-free frame. No curve object, no radius or tilt from the curve, and no Blender comparison. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js) | #42 |
| Modeling > Modifiers > Deform > Displace Modifier | done | `displace` edit and stack node with a field as the texture, along the normal or an axis, with strength, midlevel and a face selection. Positions match Blender with a constant and with a Blend texture. | [src/mesh-field-edits.js](../src/mesh-field-edits.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js) | #43 |
-| Modeling > Modifiers > Deform > Hook Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |
+| Modeling > Modifiers > Deform > Hook Modifier | partial | `hook` edit and stack node: vertices within `radius` of a `center` move by a `translation` with `strength` and a smooth, linear or constant falloff. No hook object that is animated later, no vertex groups and no Blender comparison. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js) | #42 |
| Modeling > Modifiers > Deform > Laplacian Deform Modifier | missing | No equivalent. | | |
-| Modeling > Modifiers > Deform > Lattice Modifier | missing | No lattice. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |
+| Modeling > Modifiers > Deform > Lattice Modifier | partial | `lattice` edit and stack node: a grid of 2 to 8 control points per axis over the mesh bounds, with up to 64 moved points and a trilinear blend (Blender's default is a B-spline blend). No lattice object and no Blender comparison. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js) | #42 |
| Modeling > Modifiers > Deform > Mesh Deform Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Deform > Shrinkwrap Modifier | partial | The `shrinkwrap` mesh edit moves the vertices of the selected faces onto a primitive, to the nearest point or projected along a direction, with an offset, a distance limit and keep-on-miss. Blender's modes beyond nearest surface point and projection along one axis, its vertex group and wrap-on-inside and outside modes are not here, and the target is a primitive, not another node. Compared with the Shrinkwrap modifier on a cylinder, nearest and projected with an offset. `addons/shrinkwrap` still serves code. | [mesh-sculpt-shrinkwrap](../tests/mesh-sculpt-shrinkwrap.test.js), [blender golden](../tests/blender-golden.test.js) | #42, #47 |
| Modeling > Modifiers > Deform > Simple Deform Modifier | partial | `simple_deform` edit and stack node: twist, bend, taper and stretch about x, y or z over the whole mesh extent. No limits, lock axes, origin object or vertex groups. | [mesh-modifiers](../tests/mesh-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 |
@@ -106,7 +106,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Deform > Surface Deform Modifier | missing | `addons/surface-attachment` binds points, not whole meshes. | | |
| Modeling > Modifiers > Deform > Volume Displace Modifier | missing | No volume objects. | | |
| Modeling > Modifiers > Deform > Warp Modifier | missing | No equivalent. | | |
-| Modeling > Modifiers > Deform > Wave Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |
+| Modeling > Modifiers > Deform > Wave Modifier | partial | `wave` edit and stack node: height, width, narrowness, speed, frame `time`, offset, start, cyclic, x and y axes and along the normal. Positions match Blender at the same frame on 2 cases. No falloff, lifetime or damping, no texture and no vertex groups. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 |
| Modeling > Modifiers > Normals > Normal Edit Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Normals > Weighted Normal Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |
| Modeling > Modifiers > Normals > Smooth By Angle Modifier | partial | `smoothAngle` is a geometry setting. It is not a stack node. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |
diff --git a/scripts/blender-golden.py b/scripts/blender-golden.py
index 3c69433d..430d6467 100644
--- a/scripts/blender-golden.py
+++ b/scripts/blender-golden.py
@@ -541,7 +541,26 @@ def add_wireframe(mesh_object, edit, _inputs):
modifier.use_boundary = False
+# Blender reads the frame number as the time of the wave.
+def add_wave(mesh_object, edit, _inputs):
+ modifier = mesh_object.modifiers.new("Wave", "WAVE")
+ modifier.height = edit.get("height", 0.5)
+ modifier.width = edit.get("width", 1.5)
+ modifier.narrowness = edit.get("narrowness", 1.5)
+ modifier.speed = edit.get("speed", 0.25)
+ modifier.time_offset = edit.get("timeOffset", 0)
+ start = edit.get("start", [0, 0])
+ modifier.start_position_x = start[0]
+ modifier.start_position_y = start[1]
+ modifier.use_cyclic = edit.get("cyclic", True)
+ modifier.use_normal = edit.get("normal", False)
+ modifier.use_x = edit.get("axes", "xy") in ("xy", "x")
+ modifier.use_y = edit.get("axes", "xy") in ("xy", "y")
+ bpy.context.scene.frame_set(int(edit.get("time", 0)))
+
+
MODIFIERS = {
+ "wave": add_wave,
"screw": add_screw,
"wireframe": add_wireframe,
"weld": add_weld,
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 249c3bc5..b39746c8 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -133,6 +133,10 @@ export const MESH_MODIFIER_NOTES = Object.freeze({
screw: 'revolves every edge of the mesh (the profile; its faces are dropped) about the x, y or z axis (z) through the origin: angle 360 degrees per iteration, steps 16 (1 to 256) per iteration, iterations 1 to 64, lift 0 rise per iteration along the axis. A whole number of turns with no lift closes the ring. Vertices stay in step-major order.',
wireframe: 'keeps a rim of width thickness (0.02) on every face, as Blender Wireframe: offset -1 to 1 (0) moves the strut from inside to outside the surface, evenOffset true makes struts as wide as the thickness, replace true drops the original faces. Open edges get no extra strut.',
skin: 'a square tube along every edge, radius 0.1 or a scalar field per vertex (above zero), closed by end caps. Simple version: tubes that meet overlap and there is no branch solver, so it is partial against Blender.',
+ lattice: 'a grid of divisions [2,2,2] control points (2 to 8 each) spanning the mesh bounds; moves is up to 64 of {point:[i,j,k], offset:[x,y,z]} that shift one control point, and vertices follow the trilinear blend. Blender blends with a B-spline.',
+ curve: 'bends the mesh along path, 2 to 64 points [x,y,z] through a Catmull-Rom spline. The coordinate along axis (x) is the distance from the path start, the other two become offsets in a twist-free frame; past the ends the mesh continues straight. Model the mesh along the axis starting at 0.',
+ hook: 'pulls the vertices within radius (1) of center [0,0,0] by translation [0,0,0] times strength 0 to 1 (1); falloff smooth (default), linear or constant.',
+ 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.',
});
// Organic shaping edits. Details stay here so the tool schemas stay small.
diff --git a/src/mesh-deform-modifiers.js b/src/mesh-deform-modifiers.js
new file mode 100644
index 00000000..ad586234
--- /dev/null
+++ b/src/mesh-deform-modifiers.js
@@ -0,0 +1,283 @@
+import { withPositions } from './mesh-field-edits.js';
+import { vertexNormals } from './mesh-normals.js';
+
+// Modifiers that only move vertices, each from a few numbers: lattice (a coarse grid of moved control points), curve (bend
+// along a path), hook (pull the vertices near a point) and wave (a travelling ripple). Every list is bounded, and the
+// errors name the field and the limit.
+
+export const MAX_LATTICE_DIVISIONS = 8;
+export const MAX_LATTICE_MOVES = 64;
+export const MAX_CURVE_POINTS = 64;
+export const HOOK_FALLOFFS = Object.freeze(['smooth', 'linear', 'constant']);
+export const WAVE_AXES = Object.freeze(['xy', 'x', 'y']);
+const AXIS_NAMES = Object.freeze({ x: 0, y: 1, z: 2 });
+const CURVE_SAMPLES_PER_SEGMENT = 16;
+const MINIMUM_SPAN = 1e-9;
+
+function meshBounds(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++) {
+ low[axis] = Math.min(low[axis], mesh.positions[vertex * 3 + axis]);
+ high[axis] = Math.max(high[axis], mesh.positions[vertex * 3 + axis]);
+ }
+ }
+ return { low, high };
+}
+
+/**
+ * A lattice of `divisions` control points per axis spanning the mesh bounds. Each move shifts one control point by an
+ * offset, and every vertex follows the trilinear blend of the shifts around it. Blender's default is a B-spline blend,
+ * which is smoother between points.
+ */
+export function latticeDeform(mesh, { divisions, moves }) {
+ const [countX, countY, countZ] = divisions;
+ const shifts = new Float64Array(countX * countY * countZ * 3);
+ const indexOfPoint = (x, y, z) => ((z * countY + y) * countX + x) * 3;
+ for (const { point, offset } of moves) {
+ for (let axis = 0; axis < 3; axis++) shifts[indexOfPoint(...point) + axis] += offset[axis];
+ }
+ const { low, high } = meshBounds(mesh);
+ const counts = [countX, countY, countZ];
+ const positions = new Float32Array(mesh.positions);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const cells = [0, 0, 0];
+ const fractions = [0, 0, 0];
+ for (let axis = 0; axis < 3; axis++) {
+ const span = high[axis] - low[axis];
+ const position = span > MINIMUM_SPAN ? (mesh.positions[vertex * 3 + axis] - low[axis]) / span * (counts[axis] - 1) : 0;
+ cells[axis] = Math.min(Math.floor(position), counts[axis] - 2);
+ fractions[axis] = position - cells[axis];
+ }
+ for (let corner = 0; corner < 8; corner++) {
+ const stepX = corner & 1;
+ const stepY = (corner >> 1) & 1;
+ const stepZ = (corner >> 2) & 1;
+ const weight = (stepX ? fractions[0] : 1 - fractions[0]) * (stepY ? fractions[1] : 1 - fractions[1]) * (stepZ ? fractions[2] : 1 - fractions[2]);
+ if (weight === 0) continue;
+ const base = indexOfPoint(cells[0] + stepX, cells[1] + stepY, cells[2] + stepZ);
+ for (let axis = 0; axis < 3; axis++) positions[vertex * 3 + axis] += shifts[base + axis] * weight;
+ }
+ }
+ return positions;
+}
+
+function hookWeight(falloff, distance, radius) {
+ if (distance >= radius) return 0;
+ const closeness = 1 - distance / radius;
+ if (falloff === 'constant') return 1;
+ if (falloff === 'linear') return closeness;
+ return closeness * closeness * (3 - 2 * closeness);
+}
+
+/** Blender's Hook: vertices within `radius` of `center` move by `translation` times `strength` and the falloff weight. */
+export function hookDeform(mesh, { center, radius, translation, strength, falloff }) {
+ const positions = new Float32Array(mesh.positions);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const distance = Math.hypot(
+ mesh.positions[vertex * 3] - center[0],
+ mesh.positions[vertex * 3 + 1] - center[1],
+ mesh.positions[vertex * 3 + 2] - center[2],
+ );
+ const weight = hookWeight(falloff, distance, radius) * strength;
+ if (weight === 0) continue;
+ for (let axis = 0; axis < 3; axis++) positions[vertex * 3 + axis] += translation[axis] * weight;
+ }
+ return positions;
+}
+
+/**
+ * Blender's Wave: a gaussian ripple along z (or the vertex normal) that travels away from `start` in x, y or both. `time` is a
+ * frame number, as the scene frame is in Blender; the ripple moves `speed` units per frame after `timeOffset`.
+ */
+export function waveDeform(mesh, { height, width, narrowness, speed, time, timeOffset, start, cyclic, axes, normal }) {
+ const positions = new Float32Array(mesh.positions);
+ const normals = normal ? vertexNormals(mesh) : null;
+ const floor = 1 / Math.exp(width * narrowness * width * narrowness);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const x = mesh.positions[vertex * 3] - start[0];
+ const y = mesh.positions[vertex * 3 + 1] - start[1];
+ let phase = axes === 'xy' ? Math.hypot(x, y) : axes === 'x' ? x : y;
+ phase -= (time - timeOffset) * speed;
+ if (cyclic) phase = (phase - width) % (width * 2) + width;
+ if (!(phase > -width && phase < width)) continue;
+ const scaled = phase * narrowness;
+ const displacement = height * (1 / Math.exp(scaled * scaled) - floor);
+ if (normals) {
+ for (let axis = 0; axis < 3; axis++) positions[vertex * 3 + axis] += normals[vertex * 3 + axis] * displacement;
+ } else {
+ positions[vertex * 3 + 2] += displacement;
+ }
+ }
+ return positions;
+}
+
+function catmullRom(before, from, to, after, fraction) {
+ const squared = fraction * fraction;
+ const cubed = squared * fraction;
+ return from.map((value, axis) => 0.5 * (
+ 2 * value + (to[axis] - before[axis]) * fraction
+ + (2 * before[axis] - 5 * value + 4 * to[axis] - after[axis]) * squared
+ + (3 * value - before[axis] - 3 * to[axis] + after[axis]) * cubed));
+}
+
+function normalizedVector(vector) {
+ const length = Math.hypot(...vector);
+ return vector.map(component => component / length);
+}
+
+function dotProduct(first, second) {
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
+}
+
+function crossProduct(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]];
+}
+
+/** The path as a dense polyline with its distance from the start and a twist-free frame (tangent, normal, binormal) at each sample. */
+function sampleCurve(path, upAxis) {
+ const points = [];
+ for (let segment = 0; segment + 1 < path.length; segment++) {
+ const before = path[Math.max(segment - 1, 0)];
+ const after = path[Math.min(segment + 2, path.length - 1)];
+ for (let sample = 0; sample < CURVE_SAMPLES_PER_SEGMENT; sample++) {
+ points.push(catmullRom(before, path[segment], path[segment + 1], after, sample / CURVE_SAMPLES_PER_SEGMENT));
+ }
+ }
+ points.push(path.at(-1));
+ const distances = [0];
+ for (let index = 1; index < points.length; index++) {
+ distances.push(distances[index - 1] + Math.hypot(...points[index].map((value, axis) => value - points[index - 1][axis])));
+ }
+ if (!(distances.at(-1) > MINIMUM_SPAN)) throw new RangeError('curve path has no length. Give points that are apart.');
+ const tangents = points.map((point, index) => {
+ const ahead = points[Math.min(index + 1, points.length - 1)];
+ const behind = points[Math.max(index - 1, 0)];
+ const direction = ahead.map((value, axis) => value - behind[axis]);
+ return Math.hypot(...direction) > 0 ? normalizedVector(direction) : [1, 0, 0];
+ });
+ const up = [0, 0, 0];
+ up[upAxis] = 1;
+ const frames = [];
+ let normal = up;
+ tangents.forEach((tangent, index) => {
+ let candidate = normal.map((value, axis) => value - dotProduct(normal, tangent) * tangent[axis]);
+ if (Math.hypot(...candidate) < 1e-6) {
+ const other = [0, 0, 0];
+ other[(upAxis + 1) % 3] = 1;
+ candidate = other.map((value, axis) => value - dotProduct(other, tangent) * tangent[axis]);
+ }
+ normal = normalizedVector(candidate);
+ frames.push({ tangent, normal, binormal: crossProduct(tangent, normal), point: points[index], distance: distances[index] });
+ });
+ return frames;
+}
+
+function frameAtDistance(frames, distance) {
+ const last = frames.length - 1;
+ if (distance <= 0) return { ...frames[0], along: distance };
+ if (distance >= frames[last].distance) return { ...frames[last], along: distance - frames[last].distance };
+ let low = 0;
+ let high = last;
+ while (high - low > 1) {
+ const middle = (low + high) >> 1;
+ if (frames[middle].distance <= distance) low = middle;
+ else high = middle;
+ }
+ const span = frames[high].distance - frames[low].distance;
+ const fraction = span > 0 ? (distance - frames[low].distance) / span : 0;
+ const mix = (first, second) => first.map((value, axis) => value + (second[axis] - value) * fraction);
+ const tangent = normalizedVector(mix(frames[low].tangent, frames[high].tangent));
+ const normal = normalizedVector(mix(frames[low].normal, frames[high].normal));
+ return { tangent, normal, binormal: crossProduct(tangent, normal), point: mix(frames[low].point, frames[high].point), along: 0 };
+}
+
+/**
+ * Blender's Curve: the coordinate of each vertex along `axis` is a distance from the start of the path, and the other two
+ * coordinates become offsets from the path in a twist-free frame. The path is a Catmull-Rom spline through `path`; past
+ * either end the mesh continues along the end tangent.
+ */
+export function curveDeform(mesh, { path, axis }) {
+ const axisIndex = AXIS_NAMES[axis];
+ const frames = sampleCurve(path, (axisIndex + 1) % 3);
+ const positions = new Float32Array(mesh.positions);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const distance = mesh.positions[vertex * 3 + axisIndex];
+ const acrossFirst = mesh.positions[vertex * 3 + (axisIndex + 1) % 3];
+ const acrossSecond = mesh.positions[vertex * 3 + (axisIndex + 2) % 3];
+ const frame = frameAtDistance(frames, distance);
+ for (let component = 0; component < 3; component++) {
+ positions[vertex * 3 + component] = frame.point[component] + frame.tangent[component] * frame.along
+ + frame.normal[component] * acrossFirst + frame.binormal[component] * acrossSecond;
+ }
+ }
+ return positions;
+}
+
+function checkedVector(value, index, label, finiteNumber) {
+ if (!Array.isArray(value) || value.length !== 3) throw new TypeError(`Mesh edit ${index} (${label} needs three numbers)`);
+ return value.map(component => finiteNumber(component, index, label));
+}
+
+function normalizeLattice(edit, normalized, index, { finiteNumber, integerInRange }) {
+ const divisions = edit.divisions ?? [2, 2, 2];
+ if (!Array.isArray(divisions) || divisions.length !== 3) throw new TypeError(`Mesh edit ${index} (divisions needs three integers from 2 to ${MAX_LATTICE_DIVISIONS})`);
+ normalized.divisions = divisions.map(count => integerInRange(count, index, 'divisions', 2, MAX_LATTICE_DIVISIONS));
+ const moves = edit.moves ?? [];
+ if (!Array.isArray(moves) || moves.length > MAX_LATTICE_MOVES) throw new RangeError(`Mesh edit ${index} (moves is a list of at most ${MAX_LATTICE_MOVES} of { point, offset })`);
+ normalized.moves = moves.map((move, moveIndex) => {
+ if (!move || typeof move !== 'object' || Array.isArray(move)) throw new TypeError(`Mesh edit ${index} (moves[${moveIndex}] must be { point, offset })`);
+ if (!Array.isArray(move.point) || move.point.length !== 3) throw new TypeError(`Mesh edit ${index} (moves[${moveIndex}].point needs three grid indices)`);
+ const point = move.point.map((cell, axis) => integerInRange(cell, index, `moves[${moveIndex}].point`, 0, normalized.divisions[axis] - 1));
+ return { point, offset: checkedVector(move.offset, index, `moves[${moveIndex}].offset`, finiteNumber) };
+ });
+}
+
+function normalizeCurve(edit, normalized, index, { finiteNumber }) {
+ if (!Array.isArray(edit.path) || edit.path.length < 2 || edit.path.length > MAX_CURVE_POINTS) {
+ throw new TypeError(`Mesh edit ${index} (path needs 2 to ${MAX_CURVE_POINTS} points of three numbers)`);
+ }
+ normalized.path = edit.path.map(point => checkedVector(point, index, 'path', finiteNumber));
+ normalized.axis = edit.axis ?? 'x';
+ if (!Object.hasOwn(AXIS_NAMES, normalized.axis)) throw new TypeError(`Mesh edit ${index} (axis must be x, y or z)`);
+}
+
+function normalizeHook(edit, normalized, index, { finiteNumber }) {
+ normalized.center = checkedVector(edit.center ?? [0, 0, 0], index, 'center', finiteNumber);
+ normalized.radius = edit.radius === undefined ? 1 : finiteNumber(edit.radius, index, 'radius', { minimum: 0, maximum: 1e4, exclusiveMinimum: true });
+ normalized.translation = checkedVector(edit.translation ?? [0, 0, 0], index, 'translation', finiteNumber);
+ normalized.strength = edit.strength === undefined ? 1 : finiteNumber(edit.strength, index, 'strength', { minimum: 0, maximum: 1 });
+ normalized.falloff = edit.falloff ?? 'smooth';
+ if (!HOOK_FALLOFFS.includes(normalized.falloff)) throw new TypeError(`Mesh edit ${index} (falloff must be one of ${HOOK_FALLOFFS.join(', ')})`);
+}
+
+function normalizeWave(edit, normalized, index, { finiteNumber }) {
+ normalized.height = edit.height === undefined ? 0.5 : finiteNumber(edit.height, index, 'height', { minimum: -1e4, maximum: 1e4 });
+ normalized.width = edit.width === undefined ? 1.5 : finiteNumber(edit.width, index, 'width', { minimum: 0, maximum: 1e4, exclusiveMinimum: true });
+ normalized.narrowness = edit.narrowness === undefined ? 1.5 : finiteNumber(edit.narrowness, index, 'narrowness', { minimum: 0, maximum: 50 });
+ normalized.speed = edit.speed === undefined ? 0.25 : finiteNumber(edit.speed, index, 'speed', { minimum: -1e4, maximum: 1e4 });
+ normalized.time = edit.time === undefined ? 0 : finiteNumber(edit.time, index, 'time', { minimum: -1e6, maximum: 1e6 });
+ normalized.timeOffset = edit.timeOffset === undefined ? 0 : finiteNumber(edit.timeOffset, index, 'timeOffset', { minimum: -1e6, maximum: 1e6 });
+ const start = edit.start ?? [0, 0];
+ if (!Array.isArray(start) || start.length !== 2) throw new TypeError(`Mesh edit ${index} (start needs two numbers, x and y)`);
+ normalized.start = start.map(value => finiteNumber(value, index, 'start'));
+ normalized.cyclic = edit.cyclic ?? true;
+ normalized.normal = edit.normal ?? false;
+ if (typeof normalized.cyclic !== 'boolean' || typeof normalized.normal !== 'boolean') throw new TypeError(`Mesh edit ${index} (cyclic and normal must be booleans)`);
+ normalized.axes = edit.axes ?? 'xy';
+ if (!WAVE_AXES.includes(normalized.axes)) throw new TypeError(`Mesh edit ${index} (axes must be one of ${WAVE_AXES.join(', ')})`);
+}
+
+const NORMALIZERS = Object.freeze({ lattice: normalizeLattice, curve: normalizeCurve, hook: normalizeHook, wave: normalizeWave });
+const DEFORMERS = Object.freeze({ lattice: latticeDeform, curve: curveDeform, hook: hookDeform, wave: waveDeform });
+
+export const isDeformModifier = operation => Object.hasOwn(DEFORMERS, operation);
+
+export function normalizeDeformEdit(edit, normalized, index, helpers) {
+ NORMALIZERS[edit.op](edit, normalized, index, helpers);
+}
+
+export function runDeformEdit(mesh, edit) {
+ return { mesh: withPositions(mesh, DEFORMERS[edit.op](mesh, edit)), result: {} };
+}
diff --git a/src/mesh-modifiers.js b/src/mesh-modifiers.js
index ba32979a..3a7c7c7f 100644
--- a/src/mesh-modifiers.js
+++ b/src/mesh-modifiers.js
@@ -3,6 +3,7 @@ import { mergeByDistance } from './mesh-ops.js';
import { triangulateFaces, splitSharpEdges } from './mesh-restructure.js';
import { MODIFIER_OPERATIONS } from './mesh-operations.js';
import { normalizeGeneratorEdit, GENERATOR_RUNNERS } from './mesh-generator-modifiers.js';
+import { isDeformModifier, normalizeDeformEdit, runDeformEdit } from './mesh-deform-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).
@@ -49,6 +50,10 @@ export function normalizeModifierEdit(edit, normalized, index, { finiteNumber, c
normalizeGeneratorEdit(edit, normalized, index, { finiteNumber, integerInRange, checkedField });
return;
}
+ if (isDeformModifier(edit.op)) {
+ normalizeDeformEdit(edit, normalized, index, { finiteNumber, integerInRange });
+ return;
+ }
switch (edit.op) {
case 'weld':
normalized.distance = edit.distance === undefined ? 0.001 : finiteNumber(edit.distance, index, 'distance', { minimum: 0, maximum: 1e3, exclusiveMinimum: true });
@@ -176,6 +181,7 @@ function simpleDeformPositions(mesh, { mode, axis, angle, factor }) {
/** Run a modifier edit. Returns { mesh, result } where result holds the counts to report. */
export function runModifierEdit(mesh, edit, { maxVertices, maxFaces }) {
if (Object.hasOwn(GENERATOR_RUNNERS, edit.op)) return GENERATOR_RUNNERS[edit.op](mesh, edit, { maxVertices, maxFaces });
+ if (isDeformModifier(edit.op)) return runDeformEdit(mesh, edit);
switch (edit.op) {
case 'weld': {
const merged = mergeByDistance(mesh, edit.distance);
diff --git a/src/mesh-operations.js b/src/mesh-operations.js
index 86af55ba..12c7abab 100644
--- a/src/mesh-operations.js
+++ b/src/mesh-operations.js
@@ -15,6 +15,10 @@ export const MODIFIER_OPERATIONS = Object.freeze({
screw: { fields: ['axis', 'angle', 'steps', 'iterations', 'lift'], tags: [] },
wireframe: { fields: ['thickness', 'offset', 'evenOffset', 'replace'], tags: [] },
skin: { fields: ['radius'], tags: [] },
+ lattice: { fields: ['divisions', 'moves'], tags: [] },
+ curve: { fields: ['path', 'axis'], tags: [] },
+ hook: { fields: ['center', 'radius', 'translation', 'strength', 'falloff'], tags: [] },
+ wave: { fields: ['height', 'width', 'narrowness', 'speed', 'time', 'timeOffset', 'start', 'cyclic', 'axes', 'normal'], tags: [] },
});
export const MESH_EDIT_OPERATIONS = Object.freeze({
diff --git a/tests/fixtures/blender/cases.json b/tests/fixtures/blender/cases.json
index e28e5822..ce2ed760 100644
--- a/tests/fixtures/blender/cases.json
+++ b/tests/fixtures/blender/cases.json
@@ -149,6 +149,8 @@
{ "id": "wireframe-cube", "input": "cube", "edit": {"op":"wireframe","thickness":0.1} },
{ "id": "wireframe-cube-outside-keep", "input": "cube", "edit": {"op":"wireframe","thickness":0.1,"offset":-1,"replace":false} },
{ "id": "wireframe-quad-open", "input": "profile-quad", "edit": {"op":"wireframe","thickness":0.1} },
+ { "id": "wave-grid-ring", "input": "grid", "edit": {"op":"wave","start":[1.5,1.5],"time":2} },
+ { "id": "wave-grid-x-once", "input": "grid", "edit": {"op":"wave","axes":"x","cyclic":false,"time":4,"speed":0.5,"height":0.3,"width":1,"narrowness":2} },
{ "id": "decimate-bowl-half", "input": "bowl-open", "compare": "surface", "edit": {"op":"decimate","ratio":0.5} },
{ "id": "remesh-sphere", "input": "sphere-bumpy", "compare": "surface", "edit": {"op":"remesh","voxelSize":0.1} },
{ "id": "remesh-torus", "input": "torus-fine", "compare": "surface", "edit": {"op":"remesh","voxelSize":0.08} },
diff --git a/tests/fixtures/blender/golden.json b/tests/fixtures/blender/golden.json
index f9706c8c..71be2bd9 100644
--- a/tests/fixtures/blender/golden.json
+++ b/tests/fixtures/blender/golden.json
@@ -31998,6 +31998,190 @@
]
]
},
+ "wave-grid-ring": {
+ "vertexCount": 16,
+ "edgeCount": 24,
+ "faceCount": 9,
+ "faceSizes": {
+ "4": 9
+ },
+ "volume": 1.803343,
+ "area": 9.53366,
+ "positions": [
+ [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 0.0,
+ 1.0,
+ 0.03288
+ ],
+ [
+ 0.0,
+ 2.0,
+ 0.03288
+ ],
+ [
+ 0.0,
+ 3.0,
+ 0.0
+ ],
+ [
+ 1.0,
+ 0.0,
+ 0.03288
+ ],
+ [
+ 1.0,
+ 1.0,
+ 0.45084
+ ],
+ [
+ 1.0,
+ 2.0,
+ 0.45084
+ ],
+ [
+ 1.0,
+ 3.0,
+ 0.03288
+ ],
+ [
+ 2.0,
+ 0.0,
+ 0.03288
+ ],
+ [
+ 2.0,
+ 1.0,
+ 0.45084
+ ],
+ [
+ 2.0,
+ 2.0,
+ 0.45084
+ ],
+ [
+ 2.0,
+ 3.0,
+ 0.03288
+ ],
+ [
+ 3.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 3.0,
+ 1.0,
+ 0.03288
+ ],
+ [
+ 3.0,
+ 2.0,
+ 0.03288
+ ],
+ [
+ 3.0,
+ 3.0,
+ 0.0
+ ]
+ ]
+ },
+ "wave-grid-x-once": {
+ "vertexCount": 16,
+ "edgeCount": 24,
+ "faceCount": 9,
+ "faceSizes": {
+ "4": 9
+ },
+ "volume": 0.589011,
+ "area": 9.25479,
+ "positions": [
+ [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 0.0,
+ 1.0,
+ 0.0
+ ],
+ [
+ 0.0,
+ 2.0,
+ 0.0
+ ],
+ [
+ 0.0,
+ 3.0,
+ 0.0
+ ],
+ [
+ 1.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 1.0,
+ 1.0,
+ 0.0
+ ],
+ [
+ 1.0,
+ 2.0,
+ 0.0
+ ],
+ [
+ 1.0,
+ 3.0,
+ 0.0
+ ],
+ [
+ 2.0,
+ 0.0,
+ 0.29451
+ ],
+ [
+ 2.0,
+ 1.0,
+ 0.29451
+ ],
+ [
+ 2.0,
+ 2.0,
+ 0.29451
+ ],
+ [
+ 2.0,
+ 3.0,
+ 0.29451
+ ],
+ [
+ 3.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 3.0,
+ 1.0,
+ 0.0
+ ],
+ [
+ 3.0,
+ 2.0,
+ 0.0
+ ],
+ [
+ 3.0,
+ 3.0,
+ 0.0
+ ]
+ ]
+ },
"decimate-bowl-half": {
"faceCount": 592,
"volume": 4.097792,
diff --git a/tests/mesh-deform-modifiers.test.js b/tests/mesh-deform-modifiers.test.js
new file mode 100644
index 00000000..1d60433d
--- /dev/null
+++ b/tests/mesh-deform-modifiers.test.js
@@ -0,0 +1,99 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { box } from '../src/geometry.js';
+import { editMesh, validateTopology, meshFromGeometry, applyMeshEdits, evaluateMeshStack, normalizeMeshEdits } from '../src/mesh.js';
+import { createMeshData } from '../src/mesh-data.js';
+
+const cube = () => meshFromGeometry(box(0, 1));
+const run = (mesh, edit) => applyMeshEdits(mesh, [edit]).mesh;
+const near = (actual, expected, message) => assert.ok(Math.abs(actual - expected) < 1e-4, `${message}: ${actual} against ${expected}`);
+
+// A beam along x from 0 to 4, one unit square in section, split in four cells so a bend has something to bend.
+function beam() {
+ const positions = [];
+ for (let step = 0; step <= 4; step++) positions.push(step, -0.5, -0.5, step, 0.5, -0.5, step, 0.5, 0.5, step, -0.5, 0.5);
+ const faces = [];
+ for (let step = 0; step < 4; step++) {
+ for (let side = 0; side < 4; side++) {
+ const next = (side + 1) % 4;
+ faces.push([step * 4 + side, step * 4 + next, (step + 1) * 4 + next, (step + 1) * 4 + side]);
+ }
+ }
+ const faceOffsets = Uint32Array.from({ length: faces.length + 1 }, (_, index) => index * 4);
+ return createMeshData({ positions: Float32Array.from(positions), faceOffsets, cornerVertices: Uint32Array.from(faces.flat()) });
+}
+
+test('lattice moves a control point fully at its vertex and by the blend elsewhere, and keeps the topology', () => {
+ const moved = run(cube(), { op: 'lattice', divisions: [2, 2, 2], moves: [{ point: [1, 1, 1], offset: [0, 0, 1] }] });
+ validateTopology(editMesh(moved));
+ const heights = Array.from({ length: moved.vertexCount }, (_, vertex) => moved.positions[vertex * 3 + 2]);
+ near(Math.max(...heights), 1.5, 'the corner on the moved control point rises by the offset');
+ near(Math.min(...heights), -0.5, 'the opposite face does not move');
+ const threeWide = run(beam(), { op: 'lattice', divisions: [3, 2, 2], moves: [{ point: [1, 0, 0], offset: [0, 0, -1] }] });
+ near(threeWide.positions[2 * 4 * 3 + 2], -1.5, 'the vertex on the middle control point follows it');
+ near(threeWide.positions[2], -0.5, 'the end of the beam stays');
+});
+
+test('lattice refuses bad grids and moves with the limit in the message', () => {
+ assert.throws(() => normalizeMeshEdits([{ op: 'lattice', divisions: [9, 2, 2] }]), /divisions must be an integer from 2 to 8/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'lattice', divisions: [2, 2, 2], moves: [{ point: [2, 0, 0], offset: [0, 0, 1] }] }]), /point must be an integer from 0 to 1/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'lattice', moves: new Array(65).fill({ point: [0, 0, 0], offset: [0, 0, 0] }) }]), /at most 64/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'lattice', moves: [{ point: [0, 0, 0] }] }]), /offset needs three numbers/);
+});
+
+test('curve leaves a beam alone on a straight path along its axis and bends it along an arc', () => {
+ const straight = run(beam(), { op: 'curve', path: [[0, 0, 0], [4, 0, 0]], axis: 'x' });
+ straight.positions.forEach((value, index) => near(value, beam().positions[index], `straight vertex ${index}`));
+ const bent = run(beam(), { op: 'curve', path: [[0, 0, 0], [2, 0, 0], [3.5, 1.5, 0], [3.5, 3.5, 0]], axis: 'x' });
+ validateTopology(editMesh(bent));
+ const end = Array.from(bent.positions.subarray(16 * 3, 17 * 3));
+ assert.ok(end[1] > 1, `the far end turned up to y ${end[1]}`);
+ const sectionWidth = Math.hypot(bent.positions[17 * 3] - bent.positions[16 * 3], bent.positions[17 * 3 + 1] - bent.positions[16 * 3 + 1], bent.positions[17 * 3 + 2] - bent.positions[16 * 3 + 2]);
+ near(sectionWidth, 1, 'the cross section keeps its size');
+});
+
+test('curve names its limits', () => {
+ assert.throws(() => normalizeMeshEdits([{ op: 'curve', path: [[0, 0, 0]] }]), /path needs 2 to 64 points/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'curve', path: [[0, 0, 0], [1, 0, 0]], axis: 'q' }]), /axis must be x, y or z/);
+ assert.throws(() => run(beam(), { op: 'curve', path: [[1, 1, 1], [1, 1, 1]] }), /path has no length/);
+});
+
+test('hook pulls the vertices inside the radius by the falloff weight and none outside', () => {
+ const pulled = run(cube(), { op: 'hook', center: [0.5, 0.5, 0.5], radius: 0.5, translation: [0, 0, 2], falloff: 'constant' });
+ const raised = Array.from({ length: pulled.vertexCount }, (_, vertex) => pulled.positions[vertex * 3 + 2]).filter(value => value > 1);
+ assert.equal(raised.length, 1);
+ near(raised[0], 2.5, 'the one vertex at the centre moves the whole translation');
+ const soft = run(cube(), { op: 'hook', center: [0.5, 0.5, 0.5], radius: 1.2, translation: [0, 0, 1], strength: 0.5 });
+ assert.ok(soft.positions[2 + 3 * 6] > 0.5 && soft.positions[2 + 3 * 6] < 1.1);
+ assert.throws(() => normalizeMeshEdits([{ op: 'hook', radius: 0 }]), /radius must be a number above 0/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'hook', falloff: 'sharp' }]), /falloff must be one of smooth, linear, constant/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'hook', strength: 2 }]), /strength must be a number from 0 to 1/);
+});
+
+test('wave lifts vertices inside its ring along z, moves with time and can follow the normal', () => {
+ const flat = createMeshData({
+ positions: Float32Array.from([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]),
+ faceOffsets: Uint32Array.from([0, 4]),
+ cornerVertices: Uint32Array.from([0, 1, 2, 3]),
+ });
+ const early = run(flat, { op: 'wave', time: 0 });
+ assert.ok(early.positions[2] > 0, 'the vertex at the start is on the crest');
+ const later = run(flat, { op: 'wave', time: 40, cyclic: false });
+ assert.equal(later.positions[2], 0, 'the single ripple has left the face');
+ const alongNormal = run(flat, { op: 'wave', normal: true });
+ assert.ok(Math.abs(alongNormal.positions[2]) > 0 && alongNormal.positions[0] === 0);
+ assert.throws(() => normalizeMeshEdits([{ op: 'wave', axes: 'z' }]), /axes must be one of xy, x, y/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'wave', narrowness: 51 }]), /narrowness must be a number from 0 to 50/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'wave', start: [1] }]), /start needs two numbers/);
+});
+
+test('the deforming modifiers run as stack nodes', () => {
+ const outcome = evaluateMeshStack(beam(), [
+ { op: 'hook', center: [4, 0, 0], radius: 2, translation: [0, 1, 0] },
+ { op: 'wave' },
+ { op: 'lattice', moves: [{ point: [1, 1, 1], offset: [0, 0, 0.5] }] },
+ { op: 'curve', path: [[0, 0, 0], [4, 0, 0]] },
+ ]);
+ assert.equal(outcome.results.length, 4);
+ validateTopology(editMesh(outcome.mesh));
+});