3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Keep spray droplets on the strongest crests with groupThreshold (#2040)
Nguyen Xuan Ana3e1b6bc13c3
diff --git a/changes/2040.md b/changes/2040.mdindex 75ffb7ab..2d5c17f1 100644--- a/changes/2040.md+++ b/changes/2040.md@@ -1 +1 @@-- An `ocean` edit with `spray: true` writes a `spray` vertex group and surface velocity vector, and a mesh particle emitter takes `velocityFrom: "spray"` (with `velocityScale`), so droplets leave crests that are rising with the sea's velocity (#2040).+- An `ocean` edit with `spray: true` writes a `spray` vertex group and surface velocity vector, and a mesh particle emitter takes `velocityFrom: "spray"` (with `velocityScale`, and `groupThreshold` to keep to the strongest crests), so droplets leave crests that are rising with the sea's velocity (#2040).diff --git a/docs/physics.md b/docs/physics.mdindex e64b482d..edc1368e 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -441,10 +441,10 @@ An `ocean` edit with `spray: true` writes the vertex group `spray` and the vecto{ "geometries": [{ "id": "sea", "type": "mesh", "base": { "type": "box", "bevel": 0 },"edits": [{ "op": "subdivide", "levels": 5 }, { "op": "ocean", "windSpeed": 12, "choppiness": 2, "spray": true }] }],"particles": { "systems": [{ "node": "droplet", "count": 400, "speed": [0, 1], "lifetime": [0.6, 1.4],- "emitter": { "shape": "mesh", "mesh": "surface", "from": "vertices", "group": "spray", "velocityFrom": "spray", "velocityScale": 2 } }] } }+ "emitter": { "shape": "mesh", "mesh": "surface", "from": "vertices", "group": "spray", "groupThreshold": 0.3, "scale": "shrink", "velocityFrom": "spray", "velocityScale": 2 } }] } }```-`velocityFrom` (the name of a vector on the emitter mesh; `from` "surface" or "vertices") adds that velocity, times `velocityScale` (1, -1000 to 1000) and in world space, to every particle. A name the mesh lacks is an error that lists the vectors it has. The foam must fold for there to be spray, so a sea with `choppiness` 0 sprays nowhere. The emitter reads the sea at the edit's `time`: droplets do not follow an `oceanTime` track, and there is no bow-spray emitter on a `boat` yet. The same seed gives the same droplets.+`velocityFrom` (the name of a vector on the emitter mesh; `from` "surface" or "vertices") adds that velocity, times `velocityScale` (1, -1000 to 1000) and in world space, to every particle. A name the mesh lacks is an error that lists the vectors it has. `groupThreshold` (0 to 1, default 0, needs `group`) keeps the emitter off weakly painted water: only points where the group weighs at least that much emit, so spray comes from the crests and not from the whole foamy triangle around them. The foam must fold for there to be spray, so a sea with `choppiness` 0 sprays nowhere. The emitter reads the sea at the edit's `time`: droplets do not follow an `oceanTime` track, and there is no bow-spray emitter on a `boat` yet. The same seed gives the same droplets.## Fracture and breakable gluediff --git a/src/agent-particles.js b/src/agent-particles.jsindex 9552d93d..2b5dae46 100644--- a/src/agent-particles.js+++ b/src/agent-particles.js@@ -17,7 +17,7 @@ const SPARK_PRESETS = Object.freeze({explosion: Object.freeze({ count: 800, speed: [6, 24], spread: 180, lifetime: [0.5, 2], size: [0.006, 0.014], drag: 0.9, emitter: Object.freeze({ shape: 'sphere', radius: 0.2 }) }),});const HAIR_FIELDS = ['type', 'node', 'surface', 'seed', 'count', 'length', 'segments', 'width', 'droop', 'lean', 'sway', 'swayRate'];-const EMITTER_FIELDS = ['shape', 'position', 'halfExtents', 'radius', 'mesh', 'from', 'group', 'sharpAngle', 'normalSpeed', 'velocityFrom', 'velocityScale'];+const EMITTER_FIELDS = ['shape', 'position', 'halfExtents', 'radius', 'mesh', 'from', 'group', 'sharpAngle', 'normalSpeed', 'velocityFrom', 'velocityScale', 'groupThreshold'];const EMITTER_SHAPES = ['point', 'box', 'sphere', 'disc', 'mesh'];const ORIENT_MODES = ['none', 'random', 'normal'];const SCALE_MODES = ['constant', 'shrink', 'grow'];@@ -69,6 +69,12 @@ function normalizeMeshEmitter(input, emitter, context, path) {if (input.normalSpeed !== undefined) {emitter.normalSpeed = finiteNumber(input.normalSpeed, `${path}.normalSpeed`, -1000, 1000);}+ if (input.groupThreshold !== undefined) {+ if (!emitter.group) {+ throw invalidField(`${path}.groupThreshold`, input.groupThreshold, `left out unless ${path}.group names a vertex group, such as "spray"`);+ }+ emitter.groupThreshold = finiteNumber(input.groupThreshold, `${path}.groupThreshold`, 0, 1);+ }normalizeVelocitySource(input, emitter, from, path);}@@ -108,7 +114,7 @@ function normalizeEmitter(input, context, path) {if (shape === 'mesh') {normalizeMeshEmitter(input, emitter, context, path);} else {- for (const field of ['mesh', 'from', 'group', 'sharpAngle', 'normalSpeed', 'velocityFrom', 'velocityScale']) {+ for (const field of ['mesh', 'from', 'group', 'sharpAngle', 'normalSpeed', 'velocityFrom', 'velocityScale', 'groupThreshold']) {if (input[field] !== undefined) throw invalidField(`${path}.${field}`, input[field], `left out unless ${path}.shape is "mesh"`);}}@@ -498,7 +504,7 @@ function meshSourceOf(system, nodes, geometries, systemIndex) {const sharpAngle = emitter.sharpAngle ?? null;const sourceMatrix = nodeMatrix(sourceNode);const vectors = emitter.velocityFrom ? velocityVectorOf(emitter, geometry, sourceMatrix, emitterPath) : null;- const source = createMeshSource(world.positions, world.normals, geometry.indices, emitter.from, weights, sharpAngle, vectors);+ const source = createMeshSource(world.positions, world.normals, geometry.indices, emitter.from, weights, sharpAngle, vectors, emitter.groupThreshold ?? 0);if (!source) {const groupNote = emitter.group ? ` and some weight in vertex group "${emitter.group}"` : '';throw invalidField(`${emitterPath}.mesh`, emitter.mesh, `a node whose mesh has triangles with some area${groupNote}, because emitter.from is "${emitter.from}"`);diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 56047066..5292d6af 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -359,7 +359,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({}),// 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 geometry is the particle shape; its transform does not move them. Fields (defaults): node, seed (1), count (100), rate (per second; omit: burst at 0), start (alias delay: seconds before the first birth, 0), stop (seconds, after start: nothing is born at or after it), 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|mesh, position, halfExtents, radius; mesh: mesh node, group (vertex group weighting surface, vertices or edges), from surface (area weighted)|vertices|edges (length weighted)|volume (closed mesh), sharpAngle (degrees, edges only: keep open or bent edges), normalSpeed m/s along the normal, velocityFrom (name of a mesh vector such as spray from the ocean; surface or vertices) with velocityScale (1, -1000 to 1000) adds that velocity to each particle }, instances [node ids, up to 8: each particle draws one], orient none|random|normal (mesh surface, vertices or edges), scale constant|shrink|grow, drag (1/s, 0), floor (world y they land on).',+ emitter: 'System node geometry is the particle shape; its transform does not move them. Fields (defaults): node, seed (1), count (100), rate (per second; omit: burst at 0), start (alias delay: seconds before the first birth, 0), stop (seconds, after start: nothing is born at or after it), 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|mesh, position, halfExtents, radius; mesh: mesh node, group (vertex group weighting surface, vertices or edges), groupThreshold 0-1 (0: only points where the group weighs at least this emit), from surface (area weighted)|vertices|edges (length weighted)|volume (closed mesh), sharpAngle (degrees, edges only: keep open or bent edges), normalSpeed m/s along the normal, velocityFrom (name of a mesh vector such as spray from the ocean; surface or vertices) with velocityScale (1, -1000 to 1000) adds that velocity to each particle }, instances [node ids, up to 8: each particle draws one], orient none|random|normal (mesh surface, vertices or edges), scale constant|shrink|grow, drag (1/s, 0), floor (world y they 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.',sparks: 'type sparks (preset explosion, delay s): cooling streaks; node material tag unlit; docs/physics.md',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)',diff --git a/src/particle-emitter-mesh.js b/src/particle-emitter-mesh.jsindex afe8fd49..1280ede3 100644--- a/src/particle-emitter-mesh.js+++ b/src/particle-emitter-mesh.js@@ -49,7 +49,15 @@ function vectorAt(vectors, vertex, axis) {return vectors[vertex * 3 + axis];}-function surfaceSampler(triangles, vectors) {+const MAX_THRESHOLD_TRIES = 24;++// The weights with everything under `threshold` set to 0, so a triangle or vertex that is only faintly in the group emits nothing.+function thresholded(weights, threshold) {+ if (!weights || !(threshold > 0)) return weights;+ return Float32Array.from(weights, weight => (weight >= threshold ? weight : 0));+}++function surfaceSampler(triangles, vectors, weights, threshold) {const cumulative = [];let total = 0;for (const triangle of triangles) {@@ -67,14 +75,22 @@ function surfaceSampler(triangles, vectors) {else high = middle;}const triangle = triangles[low];- const root = Math.sqrt(random());- const along = random();+ let root = Math.sqrt(random());+ let along = random();+ // A point in a triangle with one painted corner is only painted near that corner: draw again until the interpolated weight reaches the threshold.+ for (let attempt = 0; weights && threshold > 0 && attempt < MAX_THRESHOLD_TRIES; attempt++) {+ const interpolated = weights[triangle.vertices[0]] * (1 - root) + weights[triangle.vertices[1]] * root * (1 - along) + weights[triangle.vertices[2]] * root * along;+ if (interpolated >= threshold) break;+ root = Math.sqrt(random());+ along = random();+ }const weightB = root * (1 - along);const weightC = root * along;const weightA = 1 - root;const point = [0, 1, 2].map(axis => triangle.a[axis] * weightA + triangle.b[axis] * weightB + triangle.c[axis] * weightC);const velocity = vectors ? [0, 1, 2].map(axis => vectorAt(vectors, triangle.vertices[0], axis) * weightA + vectorAt(vectors, triangle.vertices[1], axis) * weightB + vectorAt(vectors, triangle.vertices[2], axis) * weightC) : undefined;- return { point, normal: triangle.normal, velocity };+ const weight = weights ? weights[triangle.vertices[0]] * weightA + weights[triangle.vertices[1]] * weightB + weights[triangle.vertices[2]] * weightC : undefined;+ return { point, normal: triangle.normal, velocity, weight };};}@@ -224,17 +240,20 @@ function edgeSampler(positions, indices, weights, sharpAngle) {* for a volume. `weights` is an optional vertex group (one weight per vertex) for the surface, vertices and edges modes.* `sharpAngle` (degrees, edges mode only) keeps the edges that are open or bend more than that. `vectors` is an optional* per-vertex velocity (three floats per vertex, such as the ocean's spray) for the surface and vertices modes: each- * sample then also returns `velocity`, interpolated across the triangle. Returns null when the+ * sample then also returns `velocity`, interpolated across the triangle, and a surface sample returns the `weight` of the group at its point. `threshold` (0 to 1, default 0) drops the weights under it,+ * and on a surface every point must reach it too, so only the strongly painted part of the group emits. Returns null when the* mesh cannot supply the mode (no area, no triangles, no edge left, or a group that weighs nothing).*/-export function createMeshSource(positions, normals, indices, mode, weights = null, sharpAngle = null, vectors = null) {+export function createMeshSource(positions, normals, indices, mode, weights = null, sharpAngle = null, vectors = null, threshold = 0) {+ const rawWeights = weights;+ weights = thresholded(weights, threshold);const triangles = trianglesOf(positions, indices, weights);if (!triangles.length) return null;let sampler = null;if (mode === 'vertices') sampler = vertexSampler(positions, normals, weights, vectors);else if (mode === 'edges') sampler = edgeSampler(positions, indices, weights, sharpAngle);else if (mode === 'volume') sampler = volumeSampler(triangles, positions);- else sampler = surfaceSampler(triangles, mode === 'surface' ? vectors : null);+ else sampler = surfaceSampler(triangles, mode === 'surface' ? vectors : null, rawWeights, threshold);if (!sampler) return null;return Object.freeze({mode,diff --git a/tests/ocean-spray.test.js b/tests/ocean-spray.test.jsindex cf59fc4d..d5af0deb 100644--- a/tests/ocean-spray.test.js+++ b/tests/ocean-spray.test.js@@ -4,6 +4,7 @@ import assert from 'node:assert/strict';import { createMeshData, applyMeshEdits } from '../src/mesh.js';import { vertexGroupWeights, VECTOR_PREFIX } from '../src/mesh-data.js';import { createAgentScene } from '../src/agent-scene.js';+import { extractRender } from '../src/mesh-render.js';import { createMeshSource } from '../src/particle-emitter-mesh.js';const SEA = { op: 'ocean', seed: 3, windSpeed: 12, size: 2, resolution: 4, choppiness: 2, time: 1.5 };@@ -145,3 +146,31 @@ test('a surface sample interpolates the vertex vectors across its triangle', ()assert.ok(Math.abs(velocity[0] - 3 * point[0]) < 1e-9 && Math.abs(velocity[2] - 3 * point[2]) < 1e-9, 'the vector grows with the point toward its corner');}});++// Spawn points of a surface emitter over a rough sea, split by the spray weight at the point.+function sprayWeightsOfSpawns(threshold) {+ const grid = flatGrid(24, 4);+ const sea = applyMeshEdits(grid, [{ ...SEA, spray: true }]).mesh;+ const { geometry } = extractRender(sea);+ const source = createMeshSource(geometry.positions, geometry.normals, geometry.indices, 'surface', geometry.vertexGroups.spray, null, geometry.vertexVectors.spray, threshold);+ let state = 777;+ const random = () => (state = (state * 1664525 + 1013904223) % 4294967296) / 4294967296;+ return Array.from({ length: 1500 }, () => source.sample(random).weight);+}++test('a group threshold keeps spawn points off the weakly sprayed water', () => {+ const faint = weights => weights.filter(weight => weight < 0.3).length;+ const without = sprayWeightsOfSpawns(0);+ const withThreshold = sprayWeightsOfSpawns(0.3);+ assert.ok(faint(without) > 150, `${faint(without)} of 1500 spawn points sit under spray weight 0.3 without a threshold`);+ assert.equal(faint(withThreshold), 0, 'no spawn point under the threshold');+ assert.ok(withThreshold.every(weight => weight >= 0.3));+});++test('groupThreshold needs a group and stays between 0 and 1', () => {+ const failure = (emitter, pattern) => assert.throws(() => createAgentScene(seaRecipe(emitter)), pattern);+ const ungrouped = seaRecipe({ groupThreshold: 0.3 });+ delete ungrouped.particles.systems[0].emitter.group;+ assert.throws(() => createAgentScene(ungrouped), /emitter.groupThreshold[^]*group/);+ failure({ groupThreshold: 2 }, /emitter\.groupThreshold/);+});