3D engine that AI agents drive
Particles: Coulomb sliding friction, damped spin, debris defaults (issue #614)
Nguyen Xuan Anbe22f30a2c7c
diff --git a/docs/physics.md b/docs/physics.mdindex ef86ae96..cdcaaa81 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -555,7 +555,7 @@ A recipe `particles` section holds up to 4 systems (`src/particles.js`, `src/hai- A hair system (`type: "hair"`) grows `count` strands from area-weighted seeded points of a `surface` node into its own `node` (the surface is only read, so several systems can share one). A strand is a triangular tube of 1 to 8 segments tapering to 15 percent, leaning off the surface normal by `lean`, bending with `droop`, and swaying by `sway` metres along the horizontal wind at `swayRate` hertz. Without `sway` the mesh is built once.- Both kinds replace their node's part at each sampled time, so the renderer sees a topology change. `npm run smoke:agent-particles` seeks sparks and hair through the MCP preview, repeats the PNG bytes after a seek back and checks that a second session renders the same bytes.- `scene_inspect` returns a `particles` report: per emitter the particle count, vertices per particle, `maxAlive` and `endsAt`; per hair system the strands, segments and vertices per strand.-- Collision (#614): `colliders` lists up to 8 static root nodes (4096 triangles in total, read only); particles bounce off their triangles and the floor plane with `bounce` (0 to 1; 0 sticks where it lands) and `friction` (0 to 1 along the surface at each bounce, 0.2). A particle on a collider, a force field or a bounce is stepped at 1/120 s from its birth with the path tested against the triangles, so a fast particle cannot tunnel through a thin mesh. A bounce slower than 0.25 m/s slides, and a slow slider settles. `spin` (deg/s, a number or [min, max]) turns each particle about a seeded axis until it settles. `color` ([r,g,b] at birth, [r,g,b] at death) and `alpha` (a number or [birth, death]) become vertex colours; the renderer has no per-vertex alpha, so alpha multiplies the colour: a particle fades toward black, which reads as a fade on a dark background but does not become see-through. Whole steps are remembered per particle, so playback costs one frame of steps and a seek back replays from birth, with the same bytes. Measured with 2000 particles of 60 s bouncing on a box: a seek to the end took about 0.5 s and playback about 3.5 ms a frame; most particles settle early, a particle under a field that never settles costs its whole age at every seek back.+- Collision (#614): `colliders` lists up to 8 static root nodes (4096 triangles in total, read only); particles bounce off their triangles and the floor plane with `bounce` (0 to 1; 0 sticks where it lands; 0.3 with colliders, 0 on a floor alone) and `friction` (0 to 1, 0.5): Coulomb friction removes friction times the normal impulse from the speed along the surface, so a slider slows and stops, and spin is damped by each contact. A particle on a collider, a force field or a bounce is stepped at 1/120 s from its birth with the path tested against the triangles, so a fast particle cannot tunnel through a thin mesh. A bounce slower than 0.4 m/s is zeroed (no micro-bounces), so the particle slides, and a slow slider settles. `spin` (deg/s, a number or [min, max]) turns each particle about a seeded axis until it settles. `color` ([r,g,b] at birth, [r,g,b] at death) and `alpha` (a number or [birth, death]) become vertex colours; the renderer has no per-vertex alpha, so alpha multiplies the colour: a particle fades toward black, which reads as a fade on a dark background but does not become see-through. Whole steps are remembered per particle, so playback costs one frame of steps and a seek back replays from birth, with the same bytes. Measured with 2000 particles of 60 s bouncing on a box: a seek to the end took about 0.5 s and playback about 3.5 ms a frame; most particles settle early, a particle under a field that never settles costs its whole age at every seek back.- Not included: collision between particles, collision with a moving node, particles that follow a moving node, hair collision, combing, clumping, children, hair on a skinned surface, UVs on hair (so textured materials do not apply) and fur shading.- Measured on the dev machine: creating a scene with 4000 box particles (96000 vertices) takes about 57 ms, and each seek takes 8 to 15 ms; the test bounds a seek at 150 ms.diff --git a/src/agent-particles.js b/src/agent-particles.jsindex 785a8f8a..0c709faa 100644--- a/src/agent-particles.js+++ b/src/agent-particles.js@@ -13,6 +13,9 @@ const EMITTER_FIELDS = ['shape', 'position', 'halfExtents', 'radius'];const EMITTER_SHAPES = ['point', 'box', 'sphere', 'disc'];const SCALE_MODES = ['constant', 'shrink', 'grow'];const DEFAULT_GRAVITY = Object.freeze([0, -9.81, 0]);+// Defaults that read as debris: a bounce keeps 30 percent of the speed (the first release of collision stuck at 0 without colliders and had no default with them), friction 0.5.+const DEBRIS_BOUNCE = 0.3;+const DEBRIS_FRICTION = 0.5;const POSITION_LIMIT = 10000;const MAX_SEED = 0xffffffff;@@ -265,7 +268,7 @@ function collisionSurfaceOf(system, nodes, geometries) {}function prepareEmitter(system, node, template, forces, colliders) {- const systemForces = { ...forces, drag: system.drag, floor: system.floor, bounce: system.bounce ?? 0, friction: system.friction ?? 0.2, colliders };+ const systemForces = { ...forces, drag: system.drag, floor: system.floor, bounce: system.bounce ?? (colliders ? DEBRIS_BOUNCE : 0), friction: system.friction ?? DEBRIS_FRICTION, colliders };const launches = createParticleLaunches({ ...system, spreadRadians: system.spread * Math.PI / 180, forces: systemForces });return {node,diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex e8e8a3a5..7e153295 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -288,7 +288,7 @@ export const AGENT_SCENE_CAPABILITIES = 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).',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)',- collision: 'colliders [node ids], bounce 0-1, friction 0-1, spin deg/s, color [[r,g,b] birth, [r,g,b] death], alpha [birth, death].',+ collision: 'colliders [node ids], bounce 0-1 (0.3 with colliders), friction 0-1 (0.5), spin deg/s, color [[r,g,b] birth, [r,g,b] death], alpha [birth, death].',notes: 'Pure function of seed, index and time; raising count keeps earlier ones. No hair collision.',limits: Object.freeze({ maxSystems: 4, maxParticlesPerSystem: 2000, maxParticles: 4000, maxVertices: 100000, maxLifetime: 60 }),}),diff --git a/src/particles.js b/src/particles.jsindex b3cce02c..a7b5fa1e 100644--- a/src/particles.js+++ b/src/particles.js@@ -20,7 +20,9 @@ export const PARTICLE_LIMITS = Object.freeze({const NO_DRAG_THRESHOLD = 1e-6;// A bounce slower than this (m/s) is not a bounce: the particle slides along the surface, or settles when it is slow too.-const REST_SPEED = 0.25;+const REST_SPEED = 0.4;+// How strongly a sliding contact pulls the spin down, per second and unit of friction.+const SPIN_COUPLING = 20;const CONTACT_OFFSET = 1e-4;const SEED_MIXER = 0x9e3779b1;@@ -129,6 +131,8 @@ export function createParticleLaunches(settings) {velocity: Float64Array.from(velocity),steps: new Int32Array(count),resting: new Uint8Array(count),+ // Angle and rate of the spin: damped by contact, so it is stepped with the position.+ spin: Float64Array.from({ length: count * 2 }, (unused, slot) => slot % 2 ? spinRate[slot >> 1] : spinStart[slot >> 1]),};return launches;}@@ -213,32 +217,52 @@ function earliestContact(forces, from, to) {}// Handles a contact. Without bounce the particle sticks where it touched. With bounce the normal speed is reflected and-// scaled by `bounce`, the speed along the surface by `1 - friction`. Returns true when the particle has come to rest.-function resolveContact(forces, position, velocity, from, to) {+// scaled by `bounce`. Coulomb friction removes `friction` times the normal impulse from the speed along the surface+// (a particle resting under gravity loses friction * g per second, so a slider slows and stops, never glides). The spin+// is damped by the same contact. Returns true when the particle has come to rest.+function resolveContact(forces, position, velocity, from, to, spin, step) {for (let axis = 0; axis < 3; axis++) {position[axis] = from[axis] + (to[axis] - from[axis]) * contact.fraction;}if (contact.onFloor) position[1] = forces.floor;if (!(forces.bounce > 0)) {+ spin[1] = 0;return true;}const normal = contact.normal;const inward = velocity[0] * normal[0] + velocity[1] * normal[1] + velocity[2] * normal[2];const rebound = inward < 0 ? -inward * forces.bounce : 0;const outward = rebound < REST_SPEED ? 0 : rebound;- const keep = 1 - forces.friction;+ const tangent = [0, 0, 0];+ let tangentSpeed = 0;+ for (let axis = 0; axis < 3; axis++) {+ tangent[axis] = velocity[axis] - normal[axis] * inward;+ tangentSpeed += tangent[axis] * tangent[axis];+ }+ tangentSpeed = Math.sqrt(tangentSpeed);+ const impulse = Math.abs(Math.min(inward, 0)) + outward;+ const keep = tangentSpeed > 0 ? Math.max(0, 1 - forces.friction * impulse / tangentSpeed) : 0;let sliding = 0;for (let axis = 0; axis < 3; axis++) {- const along = (velocity[axis] - normal[axis] * inward) * keep;+ const along = tangent[axis] * keep;velocity[axis] = along + normal[axis] * outward;position[axis] += normal[axis] * CONTACT_OFFSET;sliding += along * along;}- return outward === 0 && Math.sqrt(sliding) < REST_SPEED;+ // A bounce cuts the spin by friction at once; rolling contact keeps pulling it down while it slides.+ spin[1] *= outward > 0 ? 1 - forces.friction : Math.max(0, 1 - forces.friction * SPIN_COUPLING * step);+ const atRest = outward === 0 && Math.sqrt(sliding) < REST_SPEED;+ if (atRest) spin[1] = 0;+ if (!atRest) {+ // The rest of the step is spent moving along the response velocity, so a slider keeps its distance.+ for (let axis = 0; axis < 3; axis++) position[axis] += velocity[axis] * step * (1 - contact.fraction);+ }+ return atRest;}// One semi-implicit Euler step under gravity, drag toward the wind and every force field. Returns true at rest.-function stepParticle(forces, position, velocity, step, fieldTime) {+function stepParticle(forces, position, velocity, spin, step, fieldTime) {+ spin[0] += spin[1] * step;for (let axis = 0; axis < 3; axis++) {scratchAcceleration[axis] = forces.gravity[axis] + forces.drag * (forces.wind[axis] - velocity[axis]);}@@ -251,7 +275,7 @@ function stepParticle(forces, position, velocity, step, fieldTime) {scratchTo[axis] = position[axis] + velocity[axis] * step;}if (earliestContact(forces, scratchFrom, scratchTo)) {- return resolveContact(forces, position, velocity, scratchFrom, scratchTo);+ return resolveContact(forces, position, velocity, scratchFrom, scratchTo, spin, step);}for (let axis = 0; axis < 3; axis++) position[axis] = scratchTo[axis];return false;@@ -271,12 +295,15 @@ function trackedState(launches, index, forces, age, target) {}track.steps[index] = 0;track.resting[index] = 0;+ track.spin[index * 2] = launches.spinStart[index];+ track.spin[index * 2 + 1] = launches.spinRate[index];}const position = track.position.subarray(index * 3, index * 3 + 3);const velocity = track.velocity.subarray(index * 3, index * 3 + 3);+ const spin = track.spin.subarray(index * 2, index * 2 + 2);while (track.steps[index] < wholeSteps && !track.resting[index]) {const fieldTime = launches.birth[index] + track.steps[index] * stepSeconds;- if (stepParticle(forces, position, velocity, stepSeconds, fieldTime)) {+ if (stepParticle(forces, position, velocity, spin, stepSeconds, fieldTime)) {track.resting[index] = 1;launches.landing[index] = (track.steps[index] + 1) * stepSeconds;}@@ -285,16 +312,19 @@ function trackedState(launches, index, forces, age, target) {if (track.resting[index]) {track.steps[index] = wholeSteps;for (let axis = 0; axis < 3; axis++) target.position[axis] = position[axis];+ target.angle = spin[0];return;}// The last partial step is not remembered.const partialPosition = [position[0], position[1], position[2]];const partialVelocity = [velocity[0], velocity[1], velocity[2]];+ const partialSpin = [spin[0], spin[1]];const remainder = age - wholeSteps * stepSeconds;if (remainder > 1e-9) {- stepParticle(forces, partialPosition, partialVelocity, remainder, launches.birth[index] + wholeSteps * stepSeconds);+ stepParticle(forces, partialPosition, partialVelocity, partialSpin, remainder, launches.birth[index] + wholeSteps * stepSeconds);}for (let axis = 0; axis < 3; axis++) target.position[axis] = partialPosition[axis];+ target.angle = partialSpin[0];}function scaleAtLife(mode, lifeFraction) {@@ -327,6 +357,7 @@ export function particleStateAt(launches, index, forces, scaleMode, time, targetconst landed = launches.landing[index];const effectiveAge = Math.min(age, landed);target.motionAge = effectiveAge;+ target.angle = launches.hasSpin ? launches.spinStart[index] + launches.spinRate[index] * effectiveAge : 0;for (let component = 0; component < 3; component++) {target.position[component] = launches.origin[index * 3 + component] +displacement(launches.velocity[index * 3 + component], forces.gravity[component], forces.wind[component], forces.drag, effectiveAge);@@ -379,7 +410,7 @@ export function buildParticleMesh(template, launches, forces, scaleMode, time, lfor (let index = 0; index < launches.count; index++) {particleStateAt(launches, index, forces, scaleMode, time, state);if (launches.hasSpin) {- rotationMatrix(launches.spinAxis.subarray(index * 3, index * 3 + 3), launches.spinStart[index] + launches.spinRate[index] * state.motionAge, matrix);+ rotationMatrix(launches.spinAxis.subarray(index * 3, index * 3 + 3), state.angle, matrix);}if (colors) {const alpha = look.alpha ? look.alpha[0] + (look.alpha[1] - look.alpha[0]) * state.fraction : 1;diff --git a/tests/particle-collision.test.js b/tests/particle-collision.test.jsindex e590c8f1..456428e1 100644--- a/tests/particle-collision.test.js+++ b/tests/particle-collision.test.js@@ -62,7 +62,7 @@ test('a bounce keeps its energy ratio: the first apex is about the bounce square});test('without bounce a particle sticks where it lands, on the top face', () => {- const scene = createAgentScene(dropRecipe({}));+ const scene = createAgentScene(dropRecipe({ bounce: 0 }));const [early, late] = [1.5, 5].map(time => traceOf(scene, [time])[0]);assert.ok(Math.abs(early[1] - SLAB_TOP) < 1e-3, `rests at ${early[1]}`);assert.deepEqual(late, early, 'a stuck particle does not move again');@@ -214,3 +214,22 @@ test('stepping from birth every frame stays cheap enough for long lives, and placonst coldSeek = performance.now() - coldStart;assert.ok(playback < 20000 && coldSeek < 20000, `playback ${playback.toFixed(0)} ms for 121 frames, cold seek to the end ${coldSeek.toFixed(0)} ms`);});++test('Coulomb friction stops a slider after about v squared over two mu g, and a settled particle stops turning', () => {+ const forces = { gravity: [0, -9.81, 0], wind: [0, 0, 0], fields: [], drag: 0, floor: 0, bounce: 0.3, friction: 0.5 };+ const settings = { count: 1, seed: 1, emitter: { shape: 'point', position: [0, 0.0005, 0], halfExtents: [0, 0, 0], radius: 0 }, lifetime: [8, 8], speed: [3, 3], direction: [1, 0, 0], spreadRadians: 0, size: [1, 1], spin: [400, 400], forces };+ const launches = createParticleLaunches(settings);+ const state = { position: [0, 0, 0], scale: 0 };+ const [early, late] = [3, 6].map(time => {+ particleStateAt(launches, 0, forces, 'constant', time, state);+ return { x: state.position[0], angle: state.angle };+ });+ assert.ok(early.x > 0.8 && early.x < 1, `slid ${early.x} m, expected about 0.9`);+ assert.deepEqual(late, early, 'the slider is at rest and no longer turns');+});++test('the default bounce with colliders reads as debris', () => {+ const heights = traceOf(createAgentScene(dropRecipe({})), frames).map(center => center[1]);+ const rise = Math.max(...heights.slice(65, 100)) - SLAB_TOP;+ assert.ok(rise > 0 && rise < 0.3, `default bounce rebounds ${rise} m from a 1.9 m drop`);+});