3D engine that AI agents drive
Add the ocean mesh modifier: seeded spectrum sea with choppiness and a foam vertex group (issue #599)
Nguyen Xuan Anc3256ff8e229
diff --git a/changes/599-ocean.md b/changes/599-ocean.mdnew file mode 100644index 00000000..7a13a03c--- /dev/null+++ b/changes/599-ocean.md@@ -0,0 +1 @@+- Ocean modifier: the `ocean` mesh edit and stack node turn a flat grid into a seeded sea (Phillips spectrum for the wind, `choppiness`, `size`, `seed`, `time`) and write the vertex group `foam` where the surface folds. The same seed and time give identical vertices. Part of #599.diff --git a/changes/599-ocean.size.md b/changes/599-ocean.size.mdnew file mode 100644index 00000000..b22b2024--- /dev/null+++ b/changes/599-ocean.size.md@@ -0,0 +1,2 @@+- entry:mesh: the ocean modifier is about 1.2 KB gzip of mesh code that agents cannot get any other way.+- scene:agent-scene+lazy: the ocean modifier lives in the lazy part, which holds the whole mesh engine.diff --git a/docs/mesh.md b/docs/mesh.mdindex d3f9bffb..661cf135 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -218,7 +218,7 @@ Normals stay those of the base mesh. Test: `tests/mesh-shape-keys.test.js`.### Whole-mesh modifiers-`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `bounding_box`, `convex_hull`, `weighted_normal` and `smooth_by_angle` take no selection and no name, and work as edits or stack nodes. Their fields and defaults are plain data in `MESH_MODIFIER_NOTES` (`src/agent-scene-capabilities.js`), which `scene_capabilities` returns as `meshModifiers`; the code is in `src/mesh-modifiers.js` and `src/mesh-restructure.js`.+`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `bounding_box`, `convex_hull`, `ocean`, `weighted_normal` and `smooth_by_angle` take no selection and no name, and work as edits or stack nodes. Their fields and defaults are plain data in `MESH_MODIFIER_NOTES` (`src/agent-scene-capabilities.js`), which `scene_capabilities` returns as `meshModifiers`; the code is in `src/mesh-modifiers.js` and `src/mesh-restructure.js`.| op | fields | does || --- | --- | --- |@@ -239,6 +239,7 @@ Normals stay those of the base mesh. Test: `tests/mesh-shape-keys.test.js`.| `smooth_by_angle` | `angle` (30), `ignoreSharp` (false) | Marks edges bending more than the angle sharp and the others smooth, over the geometry `smoothAngle`; sharp edges made by hand, and the 12 of a box, stay sharp unless `ignoreSharp` is set. || `bounding_box` | none | Replaces the mesh with the axis-aligned box around all its vertices: 8 vertices and 6 quads. Tags and attributes are dropped. || `convex_hull` | none | Replaces the mesh with its convex hull, outward triangles on the extreme vertices only, from at most 8192 vertices. A mesh whose vertices lie on one line or in one plane has no hull and is refused. Tags and attributes are dropped. |+| `ocean` | `axis` (y, the up axis), `windSpeed` (10 m/s, above 0 to 60), `direction` (0 degrees from +x toward +z), `choppiness` (1, 0 to 4), `size` (100 m, 1 to 10000), `seed` (0), `time` (0 s), `resolution` (8, 1 to 16) | A seeded sea like Blender's Ocean modifier, without the FFT: a sum of travelling waves on a lattice of wave vectors with a Phillips spectrum for the wind, so the surface repeats every `size` metres and the same seed and time give identical vertices. Waves lift the up axis; choppiness pulls vertices toward the crests along the other two. The squeeze of that move is written as the vertex group `foam` (0 flat, 1 folded). Waves cost (2 x resolution + 1)^2 - 1 per vertex, capped at 50 million evaluations. |`triangulate` and `edge_split` check their output size before building it, against the same vertex and face limits as the other edits. Each op has cases in `tests/fixtures/blender/cases.json` and matches Blender 5.2 with no listed difference. `screw` and `wireframe` have cases in the same fixtures (the volume of the open screw strips differs by winding, listed in `differences.json`); `wave` matches Blender on two cases; `skin`, `lattice`, `curve` and `hook` are not compared with Blender, because each needs a second object there. The two normal modifiers are tested by their own properties, because the Blender comparison does not measure normals. Not yet: `shrinkwrap` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.diff --git a/docs/parity.md b/docs/parity.mdindex 12e3a098..a709d279 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -115,7 +115,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Physics > Dynamic Paint Modifier | missing | No equivalent. | | || Modeling > Modifiers > Physics > Explode Modifier | missing | No equivalent. | | || Modeling > Modifiers > Physics > Fluid Modifier | partial | `addons/spume` plays back a liquid baked outside the browser. Decision (#63): no browser liquid solver, see docs/physics.md "Decision". | [spume](../tests/spume.test.js) | #63 |-| Modeling > Modifiers > Physics > Ocean Modifier | missing | No equivalent. | | |+| Modeling > Modifiers > Physics > Ocean Modifier | partial | `ocean` edit and stack node: seeded Phillips-spectrum sea (wind speed, direction, size, seed, time), choppiness and a `foam` vertex group from the folding of the surface. Same seed and time give identical vertices (CPU, no FFT, a lattice of up to 33 x 33 wave vectors). No spray, no baked cache, no GPU path, no depth or damping, no repeat count and no foam or spray bake. Not compared against Blender output. | [mesh-ocean](../tests/mesh-ocean.test.js) | #599 || Modeling > Modifiers > Physics > Particle Instance Modifier | partial | An emitter system repeats its node's mesh once per particle. There is no choice of instanced object with rotation, no collection and no moving source. | [particles](../tests/particles.test.js) | #63 || Modeling > Modifiers > Physics > Particle System Modifier | partial | Recipe `particles`: seeded emitters (point, box, sphere, disc) with gravity, drag, wind, a floor and size over life, and hair strands from a surface. A seek is a closed-form evaluation, so it repeats exactly. Force fields (`fields`), no collision beyond a floor, no children or hair dynamics, and no comparison against Blender was run. See docs/physics.md. | [particles](../tests/particles.test.js) | #63 || Modeling > Modifiers > Physics > Soft Body Modifier | missing | Not built: a closed mesh needs volume or shape-matching constraints, closed-mesh input checks and a recipe field with schema and capability text, which was not measured to fit the 1.5 KB gzip limit. | | #62 |diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 235f7fde..78c8e438 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -152,37 +152,38 @@ export const MESH_MODIFIER_NOTES = Object.freeze({lattice: 'divisions [2,2,2] (2-8) control points over the mesh bounds; moves up to 64 of {point:[i,j,k], offset:[x,y,z]}; trilinear blend.',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: 'vertices within radius 1 of center [0,0,0] move by translation [0,0,0] times strength 0-1 (1); falloff smooth, 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.',+ wave: 'a gaussian ripple of height 0.5 along z (normal true: along the vertex normal) travelling from start [0,0] over axes xy (default), x or y; width 1.5, narrowness 0-50 (1.5), speed 0.25 per frame, time 0 (a frame), timeOffset 0, cyclic true repeats it. Matches Blender Wave.',weighted_normal: 'corner normals weighted by face area ^ (weight/50), weight 1-100 (50), smoothed across edges under angle 30 that are not sharp. Put it last in the stack.',smooth_by_angle: 'edges bending over angle 30 (0-180) become sharp, others smooth, over smoothAngle; ignoreSharp true also clears hand-made sharp edges.',bounding_box: 'becomes its axis-aligned box.',convex_hull: 'becomes its convex hull, up to 8192 vertices.',+ ocean: 'seeded sea: lifts axis (y) by waves of windSpeed 10 m/s (0-60) toward direction 0 deg, size 100 m (repeats), seed 0, time 0 s, resolution 8 (1-16); choppiness 1 (0-4) pulls points to crests. Writes group foam.',});// Vertex colors and groups. Details stay here so the tool schemas stay small.export const MESH_ATTRIBUTE_NOTES = Object.freeze({- vertex_group: 'name (required) sets the weights 0-1 of the vertices of the selected faces; the rest keep theirs (0 in a new group). One of weight (1), field (number expression) or gradient { axis x|y|z, range [low, high], weights [atLow, atHigh] }. Max 32 groups. displace takes group: name and scales each move by the weight; cloth takes pinGroup. Put it after shape edits: a stack node that rebuilds the mesh drops groups.',+ vertex_group: 'name (required) sets the weights 0-1 of the vertices of the selected faces; the rest keep theirs (0 in a new group). One of weight (1), field (number expression) or gradient { axis x|y|z, range [low, high], weights [atLow, atHigh] }. Max 32 groups. displace takes group: name (scales each move); cloth takes pinGroup. Put it after shape edits: a stack node that rebuilds the mesh drops groups.',vertex_color: 'sets the corner colors (0-1, linear, white until set) of the selected faces. One of color [r, g, b], field (vector expression of the vertex) or gradient { axis, range [low, high], colors [[r,g,b] atLow, [r,g,b] atHigh] }. Drawn, written as COLOR_0 in a GLB, and multiplies the material color.',});// Shape keys on a recipe mesh. Details stay here so the tool schemas stay small.export const MESH_SHAPE_KEY_NOTES = Object.freeze({- shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are vertex-moving mesh edits (set_position, displace, sculpt, simple_deform, lattice, hook...) run after the stack. value (0, 0 to 1) is the weight without motion. Each key is a glTF morph target. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes }; a GLB export writes targets, names (mesh.extras.targetNames) and weights.',+ shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets: { select, offset: [x,y,z], falloff } moves like translate; edits: vertex-moving edits (set_position, displace, sculpt, simple_deform, lattice, hook...) run after the stack. value (0, 0-1) is the weight. Each key is a glTF morph target; animate it by a motion track { kind: "morph", id: <key name>, property: "weight", keyframes }; GLB export writes targets, names and weights.',});// Organic shaping edits. Details stay here so the tool schemas stay small.export const MESH_SCULPT_NOTES = Object.freeze({- sculpt: 'strokes run in order on the vertices of the selected faces; other vertices stay, so a tag confines them. A stroke has type inflate (along the vertex normal), displace (along direction, needed) or smooth (strength 0 to 1), center and radius, strength in mesh units (negative pushes in). Falloff is smooth to zero at the radius.',- shrinkwrap: 'target is a primitive record placed by translation, rotation and scale. mode nearest (default) moves each selected vertex to the closest point; project moves it along direction (needed) to the first hit. offset (default 0) stands it off along the normal, on the side it came from. maxDistance limits the search; onMiss error (default) or keep. For a decal, use enough grid cells to follow the curve, then solidify.',+ sculpt: 'strokes run in order on the vertices of the selected faces; a tag confines them. A stroke has type inflate (along the vertex normal), displace (along direction, needed) or smooth (strength 0-1), center and radius, strength in mesh units (negative pushes in). Falloff is smooth to zero at the radius.',+ shrinkwrap: 'target is a primitive record placed by translation, rotation and scale. mode nearest (default) moves each selected vertex to the closest point; project moves it along direction (needed) to the first hit. offset (0) stands it off along the normal. maxDistance limits the search; onMiss error (default) or keep. For a decal, use enough cells to follow the curve, then solidify.',});export const AGENT_SCENE_CAPABILITIES = Object.freeze({format: '67js.scene', schemaVersion: 1,geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'mesh']),- camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, default 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its width and height. fStop (0.7 to 64) turns on depth of field focused on target; 1.4 or lower is full blur, and effects.depthOfField.blur must stay 0. Orthographic and shifted cameras render with the rasterizer, not the path tracer.',+ camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its size. fStop (0.7-64) turns on depth of field focused on target; 1.4 or lower is full blur; effects.depthOfField.blur must stay 0. Orthographic and shifted cameras use the rasterizer, not the path tracer.',terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius} with no surface inside; radius a few cells or more.',- placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start, on a decoded copy of its own; scene_apply set-motion tracks move the node as usual and scene time seeks the clip. Copies of one asset share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy of its own (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds its wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',- navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a node translation track with interpolation LINEAR. radius 0.3 m is how far the walker position stays from holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y, such as half the walker height.',+ placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start on a decoded copy; set-motion tracks move the node and scene time seeks the clip. Copies share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy (fields as motion.drive, docs/vehicle.md; no tail-light glow). scene_inspect assets adds wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',+ navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a translation track with interpolation LINEAR. radius 0.3 m keeps the walker off holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the walk or speed (1.4 m/s); lift raises y (half the walker height).',meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),meshModifiers: MESH_MODIFIER_NOTES,@@ -284,12 +285,12 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({cloth: Object.freeze({sheetGeometry: 'grid { segments 1-64 }: unit sheet in XY facing +Z, sized by node scale; any triangle mesh works',defaults: Object.freeze({ stiffness: 0.9, bend: 0.1, density: 0.2, damping: 0.3, friction: 0.3, thickness: 0.01, colliderShape: 'box' }),- notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges are of the local bounds. Colliders { node, shape ball|box } are fixed fits to geometry bounds and, like sheets, root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. Sheet pinGroup names a sheet vertex group whose vertices (weight 0.5 or more) are held. Sheet pinTo { node, weight } rides pinned edges on a node. No self collision.',+ notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges follow the local bounds. Colliders { node, shape ball|box } fit geometry bounds and, like sheets, are root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. pinGroup names a vertex group whose vertices (weight 0.5+) are held. pinTo { node, weight } rides pinned edges on a node. No self collision.',limits: Object.freeze({ maxSheets: 8, maxColliders: 16, maxMovingColliders: 64, maxDuration: 10, maxParticles: 5000, framesPerSecond: 60, substeps: 4, iterations: 8 }),}),// Recipe particles: closed-form from seeded launch values, so any time is computed directly and a seek never replays.particles: Object.freeze({- emitter: 'System node keeps its geometry as the particle shape; node transform does not move particles. Fields (defaults): node, seed (1), count (100), rate (per second; omit for a burst at 0), lifetime, speed, size (each number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc, position, halfExtents, radius }, scale constant|shrink|grow, drag (1/s, 0), floor (world y particles land on).',+ emitter: 'System node keeps its geometry as the particle shape; node transform does not move particles. Fields (default): node, seed (1), count (100), rate (per s; omit for a burst at 0), lifetime, speed, size (number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc, position, halfExtents, radius }, scale constant|shrink|grow, drag (1/s, 0), floor (world y particles land on).',hair: 'type hair grows strands from a read-only root surface node into node (its own geometry is ignored). Fields (defaults): surface, seed, count, length (m, number or [min, max], 0.1), segments (1-8, 4), width (m, 0.004), droop (0.5), lean (0.2), sway (tip travel m, off), swayRate (Hz, 0.5). Tapering tubes, no UVs.',sectionFields: 'systems, gravity ([0,-9.81,0]), wind (m/s; moves emitter particles only with drag > 0, and sets the hair sway direction), fields (also cloth; wind, turbulence, vortex, drag, magnet: docs/physics.md)',notes: 'Pure function of seed, index and time; raising count keeps earlier ones. No collision but the floor, no bounce, rotation, colour or alpha; no hair collision.',@@ -299,7 +300,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({bake: Object.freeze({fields: 'preset, or samples (1-256), bounces (1-8), texelsPerUnit (1-12) over it; irradianceGrid true or 8-48 nodes: a baked grid of bounced diffuse light in place of lightmaps (opt in, static); gridFog true adds the fog (sunlit closed rooms; dark shafts too bright); probes room by default, false for none, or up to 4 {position, radius?}. Same recipe, same bytes.',presets: BAKE_PRESETS,- notes: 'Bounced light from point, spot, area and key lights. Reruns when parts, lights, materials or bake change. Skips alpha, skin, morph, hair, cloth (bake.skipped). A preset shrinks to fit, never refuses (bake.used, bake.reduction); explicit settings fail over maxPathWork or past maxSeconds. No environment map or specular. Probes: specular only, none in glTF.',+ notes: 'Bounced light from point, spot, area and key lights; reruns when parts, lights, materials or bake change. Skips alpha, skin, morph, hair, cloth (bake.skipped). A preset shrinks to fit, never refuses (bake.used, bake.reduction); explicit settings fail over maxPathWork or past maxSeconds. No environment map or specular. Probes: specular only, none in glTF.',limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, workerMaxSeconds: BAKE_WORKER_MAXIMUM_SECONDS, maxPathWork: BAKE_EXPLICIT_PATH_WORK_LIMIT, maxPointLights: MAX_POINT_LIGHTS }),}),motionLook: Object.freeze({diff --git a/src/mesh-modifiers.js b/src/mesh-modifiers.jsindex 334ac628..718d89b1 100644--- a/src/mesh-modifiers.js+++ b/src/mesh-modifiers.js@@ -59,6 +59,10 @@ export function normalizeModifierEdit(edit, normalized, index, { finiteNumber, cnormalizeDeformEdit(edit, normalized, index, { finiteNumber, integerInRange });return;}+ if (Object.hasOwn(REGISTERED_NORMALIZERS, edit.op)) {+ REGISTERED_NORMALIZERS[edit.op](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 });@@ -186,6 +190,11 @@ function simpleDeformPositions(mesh, { mode, axis, angle, factor }) {/** Run a modifier edit. Returns { mesh, result } where result holds the counts to report. */// Modifiers that other modules supply (mesh-hull-modifiers.js registers itself), so a bundle that never runs one does not carry its code.const REGISTERED_RUNNERS = Object.create(null);+const REGISTERED_NORMALIZERS = Object.create(null);++export function registerModifierNormalizer(operation, normalizer) {+ REGISTERED_NORMALIZERS[operation] = normalizer;+}export function registerModifierRunner(operation, runner) {REGISTERED_RUNNERS[operation] = runner;diff --git a/src/mesh-ocean-modifier.js b/src/mesh-ocean-modifier.jsnew file mode 100644index 00000000..3b0f30f8--- /dev/null+++ b/src/mesh-ocean-modifier.js@@ -0,0 +1,135 @@+import { GROUP_PREFIX, createMeshData } from './mesh-data.js';+import { seededRandom } from './mesh-fields.js';+import { registerModifierNormalizer, registerModifierRunner } from './mesh-modifiers.js';++// Ocean modifier: a deterministic spectrum displacement like Blender's Ocean modifier, without the FFT. The sea is a sum of+// travelling waves on a lattice of wave vectors, so the surface repeats exactly every `size` metres. Each wave has an+// amplitude from the Phillips spectrum for the wind (damped for the smallest waves), a seeded random gaussian and a seeded+// phase, and travels at the deep water speed, so the same seed and time give the same vertices on every run.+// The waves lift the up axis; `choppiness` also pulls vertices toward the crests along the horizontal axes. The squeeze of+// the surface (the Jacobian of that horizontal move) becomes the vertex group `foam`: 0 where the surface is not squeezed+// and 1 where it folds over itself.++export const MAX_OCEAN_RESOLUTION = 16;+export const MAX_OCEAN_WORK = 50_000_000;+const GRAVITY = 9.81;+const SIGNIFICANT_HEIGHT_PER_WIND_SQUARED = 0.21;+const FOAM_START = 0.75;+const FOAM_FULL = 0.25;+const CHANNEL_GAUSSIAN_RADIUS = 40;+const CHANNEL_GAUSSIAN_ANGLE = 41;+const CHANNEL_PHASE = 42;+const UP_AXES = Object.freeze({ x: 0, y: 1, z: 2 });+const MAX_SEED = 0x7fffffff;++function windSpectrum(waveNumber, alignment, windSpeed) {+ const largestWave = windSpeed * windSpeed / GRAVITY;+ const smallestWave = largestWave / 1000;+ const spectrum = Math.exp(-1 / (waveNumber * largestWave) ** 2) / waveNumber ** 4 * alignment * alignment;+ return spectrum * Math.exp(-((waveNumber * smallestWave) ** 2));+}++function gaussian(key, seed) {+ const radius = Math.sqrt(-2 * Math.log(Math.max(seededRandom(key, CHANNEL_GAUSSIAN_RADIUS, seed), 1e-12)));+ return radius * Math.cos(2 * Math.PI * seededRandom(key, CHANNEL_GAUSSIAN_ANGLE, seed));+}++/**+ * The waves of a sea: wave vector (waveX, waveZ along the two horizontal axes), amplitude, phase and angular frequency.+ * The amplitudes are scaled so the significant wave height (4 standard deviations of the height) is+ * 0.21 * windSpeed^2 / g, the height of a fully developed sea.+ */+export function oceanWaves({ windSpeed, direction, size, seed, resolution }) {+ const windX = Math.cos(direction * Math.PI / 180);+ const windZ = Math.sin(direction * Math.PI / 180);+ const waves = [];+ let variance = 0;+ const step = 2 * Math.PI / size;+ for (let row = -resolution; row <= resolution; row++) {+ for (let column = -resolution; column <= resolution; column++) {+ if (row === 0 && column === 0) continue;+ const waveX = column * step;+ const waveZ = row * step;+ const waveNumber = Math.hypot(waveX, waveZ);+ const alignment = (waveX * windX + waveZ * windZ) / waveNumber;+ const amplitude = Math.sqrt(windSpectrum(waveNumber, alignment, windSpeed)) * gaussian(waves.length, seed);+ variance += amplitude * amplitude / 2;+ waves.push({+ waveX, waveZ, waveNumber, amplitude,+ phase: seededRandom(waves.length, CHANNEL_PHASE, seed) * 2 * Math.PI,+ frequency: Math.sqrt(GRAVITY * waveNumber),+ });+ }+ }+ const targetHeight = SIGNIFICANT_HEIGHT_PER_WIND_SQUARED * windSpeed * windSpeed / GRAVITY / 4;+ const scale = variance > 0 ? targetHeight / Math.sqrt(variance) : 0;+ for (const wave of waves) wave.amplitude *= scale;+ return waves;+}++/** Height, horizontal move and foam of the sea at one rest point and time. */+export function oceanSurfaceAt(waves, restX, restZ, time, choppiness) {+ let height = 0;+ let moveX = 0;+ let moveZ = 0;+ let squeezeXX = 0;+ let squeezeZZ = 0;+ let squeezeXZ = 0;+ for (const wave of waves) {+ const angle = wave.waveX * restX + wave.waveZ * restZ - wave.frequency * time + wave.phase;+ const sine = Math.sin(angle);+ const cosine = Math.cos(angle);+ const directionX = wave.waveX / wave.waveNumber;+ const directionZ = wave.waveZ / wave.waveNumber;+ height += wave.amplitude * cosine;+ moveX -= choppiness * directionX * wave.amplitude * sine;+ moveZ -= choppiness * directionZ * wave.amplitude * sine;+ const slope = choppiness * wave.amplitude * wave.waveNumber * cosine;+ squeezeXX -= directionX * directionX * slope;+ squeezeZZ -= directionZ * directionZ * slope;+ squeezeXZ -= directionX * directionZ * slope;+ }+ const jacobian = (1 + squeezeXX) * (1 + squeezeZZ) - squeezeXZ * squeezeXZ;+ const foam = Math.min(1, Math.max(0, (FOAM_START - jacobian) / (FOAM_START - FOAM_FULL)));+ return { height, moveX, moveZ, foam };+}++/** Displace every vertex by the sea and write the vertex group `foam`; `axis` is the up axis of the sea. */+export function oceanMesh(mesh, { axis, windSpeed, direction, choppiness, size, seed, time, resolution }) {+ const waves = oceanWaves({ windSpeed, direction, size, seed, resolution });+ if (waves.length * mesh.vertexCount > MAX_OCEAN_WORK) {+ throw new RangeError(`ocean would make ${waves.length * mesh.vertexCount} wave evaluations, over the limit of ${MAX_OCEAN_WORK}. Lower resolution or use a coarser grid.`);+ }+ const up = UP_AXES[axis];+ const first = (up + 1) % 3;+ const second = (up + 2) % 3;+ const positions = new Float32Array(mesh.positions);+ const foam = new Float32Array(mesh.vertexCount);+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const surface = oceanSurfaceAt(waves, positions[vertex * 3 + first], positions[vertex * 3 + second], time, choppiness);+ positions[vertex * 3 + up] += surface.height;+ positions[vertex * 3 + first] += surface.moveX;+ positions[vertex * 3 + second] += surface.moveZ;+ foam[vertex] = surface.foam;+ }+ const attributes = { ...mesh.attributes, point: { ...mesh.attributes.point, [`${GROUP_PREFIX}foam`]: { data: foam, size: 1 } } };+ return createMeshData({+ positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes,+ });+}++function normalizeOcean(edit, normalized, index, { finiteNumber, integerInRange }) {+ normalized.axis = edit.axis ?? 'y';+ if (!Object.hasOwn(UP_AXES, normalized.axis)) throw new TypeError(`Mesh edit ${index} (axis must be x, y or z)`);+ normalized.windSpeed = edit.windSpeed === undefined ? 10 : finiteNumber(edit.windSpeed, index, 'windSpeed', { minimum: 0, maximum: 60, exclusiveMinimum: true });+ normalized.direction = edit.direction === undefined ? 0 : finiteNumber(edit.direction, index, 'direction', { minimum: -3600, maximum: 3600 });+ normalized.choppiness = edit.choppiness === undefined ? 1 : finiteNumber(edit.choppiness, index, 'choppiness', { minimum: 0, maximum: 4 });+ normalized.size = edit.size === undefined ? 100 : finiteNumber(edit.size, index, 'size', { minimum: 1, maximum: 10_000 });+ normalized.seed = edit.seed === undefined ? 0 : integerInRange(edit.seed, index, 'seed', 0, MAX_SEED);+ normalized.time = edit.time === undefined ? 0 : finiteNumber(edit.time, index, 'time', { minimum: -1e6, maximum: 1e6 });+ normalized.resolution = edit.resolution === undefined ? 8 : integerInRange(edit.resolution, index, 'resolution', 1, MAX_OCEAN_RESOLUTION);+}++registerModifierNormalizer('ocean', normalizeOcean);+registerModifierRunner('ocean', (mesh, edit) => ({ mesh: oceanMesh(mesh, edit), result: {} }));diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex b7624d1c..4b2fc752 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -23,6 +23,7 @@ export const MODIFIER_OPERATIONS = /* @__PURE__ */ Object.freeze({smooth_by_angle: { fields: ['angle', 'ignoreSharp'], tags: [] },bounding_box: { fields: [], tags: [] },convex_hull: { fields: [], tags: [] },+ ocean: { fields: ['axis', 'windSpeed', 'direction', 'choppiness', 'size', 'seed', 'time', 'resolution'], tags: [] },});export const MESH_EDIT_OPERATIONS = /* @__PURE__ */ Object.freeze({diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex 9b9e6060..1e014e6d 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -25,6 +25,7 @@ import { createTriangleSurfaceIndex } from './mesh-query.js';import './mesh-field-surfaces.js';import './field-rotation.js';import './mesh-hull-modifiers.js';+import './mesh-ocean-modifier.js';import { remeshMesh, remeshGridSize, MAX_REMESH_RESOLUTION } from './mesh-remesh.js';import {MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES, SCULPT_STROKE_TYPES, MAX_SCULPT_STROKES, SHRINKWRAP_MODES,diff --git a/tests/mesh-ocean.test.js b/tests/mesh-ocean.test.jsnew file mode 100644index 00000000..fc9b1c83--- /dev/null+++ b/tests/mesh-ocean.test.js@@ -0,0 +1,90 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { createMeshData, applyMeshEdits } from '../src/mesh.js';+import { vertexGroupWeights } from '../src/mesh-data.js';+import { oceanWaves, oceanSurfaceAt } from '../src/mesh-ocean-modifier.js';+import { MESH_MODIFIER_NOTES } from '../src/agent-scene-capabilities.js';++// A flat square of cells x cells quads in the x-z plane, centred on the origin.+function flatGrid(cells, extent) {+ const columns = cells + 1;+ const positions = new Float32Array(columns * columns * 3);+ for (let row = 0; row < columns; row++) {+ for (let column = 0; column < columns; column++) {+ positions.set([(column / cells - 0.5) * extent, 0, (row / cells - 0.5) * extent], (row * columns + column) * 3);+ }+ }+ const faceOffsets = new Uint32Array(cells * cells + 1);+ const cornerVertices = new Uint32Array(cells * cells * 4);+ for (let row = 0; row < cells; row++) {+ for (let column = 0; column < cells; column++) {+ const face = row * cells + column;+ const corner = row * columns + column;+ faceOffsets[face + 1] = (face + 1) * 4;+ cornerVertices.set([corner, corner + 1, corner + columns + 1, corner + columns], face * 4);+ }+ }+ return createMeshData({ positions, faceOffsets, cornerVertices });+}++function ocean(overrides = {}) {+ return { op: 'ocean', seed: 7, time: 1.5, ...overrides };+}++test('the same seed and time give identical vertices and foam', () => {+ const grid = flatGrid(24, 60);+ const first = applyMeshEdits(grid, [ocean()]).mesh;+ const second = applyMeshEdits(grid, [ocean()]).mesh;+ assert.deepEqual(Array.from(first.positions), Array.from(second.positions));+ assert.deepEqual(Array.from(vertexGroupWeights(first, 'foam')), Array.from(vertexGroupWeights(second, 'foam')));+ assert.ok(first.positions.some((value, index) => value !== grid.positions[index]), 'the sea moved the vertices');+});++test('another seed or another time gives another sea', () => {+ const grid = flatGrid(12, 60);+ const base = Array.from(applyMeshEdits(grid, [ocean()]).mesh.positions);+ assert.notDeepEqual(Array.from(applyMeshEdits(grid, [ocean({ seed: 8 })]).mesh.positions), base);+ assert.notDeepEqual(Array.from(applyMeshEdits(grid, [ocean({ time: 2.5 })]).mesh.positions), base);+});++test('the surface repeats every size metres and lifts the up axis only without choppiness', () => {+ const waves = oceanWaves({ windSpeed: 12, direction: 30, size: 80, seed: 3, resolution: 6 });+ const here = oceanSurfaceAt(waves, 5, -9, 2, 0);+ const shifted = oceanSurfaceAt(waves, 85, 71, 2, 0);+ assert.ok(Math.abs(here.height - shifted.height) < 1e-9);+ assert.equal(here.moveX, 0);+ assert.equal(here.moveZ, 0);+});++test('the significant wave height follows the wind and foam stays between 0 and 1', () => {+ const grid = flatGrid(40, 100);+ const { mesh } = applyMeshEdits(grid, [ocean({ windSpeed: 12, choppiness: 2, size: 100 })]);+ const heights = Array.from({ length: mesh.vertexCount }, (_, vertex) => mesh.positions[vertex * 3 + 1]);+ const mean = heights.reduce((sum, height) => sum + height, 0) / heights.length;+ const deviation = Math.sqrt(heights.reduce((sum, height) => sum + (height - mean) ** 2, 0) / heights.length);+ const expected = 0.21 * 12 * 12 / 9.81 / 4;+ assert.ok(deviation > expected * 0.3 && deviation < expected * 2.5, `height deviation ${deviation} against ${expected}`);+ const foam = vertexGroupWeights(mesh, 'foam');+ assert.ok(foam.every(weight => weight >= 0 && weight <= 1));+ assert.ok(foam.some(weight => weight > 0), 'strong choppiness folds some crests');+});++test('the up axis can be z, and bad fields are refused with the edit number', () => {+ const grid = flatGrid(4, 20);+ const { mesh } = applyMeshEdits(grid, [ocean({ axis: 'z', choppiness: 0 })]);+ assert.ok(Array.from({ length: mesh.vertexCount }, (_, vertex) => mesh.positions[vertex * 3 + 2]).some(value => value !== 0));+ assert.deepEqual(Array.from({ length: mesh.vertexCount }, (_, vertex) => mesh.positions[vertex * 3 + 1]), Array.from({ length: mesh.vertexCount }, (_, vertex) => grid.positions[vertex * 3 + 1]));+ for (const bad of [{ windSpeed: 0 }, { windSpeed: 61 }, { resolution: 17 }, { seed: -1 }, { size: 0 }, { axis: 'w' }, { choppiness: 5 }]) {+ assert.throws(() => applyMeshEdits(grid, [ocean(bad)]), TypeError, JSON.stringify(bad));+ }+ assert.throws(() => applyMeshEdits(grid, [ocean({ wind: 3 })]), TypeError);+});++test('a sea over too many vertices is refused before it runs', () => {+ const grid = flatGrid(250, 100);+ assert.throws(() => applyMeshEdits(grid, [ocean({ resolution: 16 })]), RangeError);+});++test('the capability notes describe the ocean modifier', () => {+ assert.match(MESH_MODIFIER_NOTES.ocean, /foam/);+});