3D engine that AI agents drive
Step cloth live and update a drawn part's vertices in place (closes #430)
Nguyen Xuan Anfb928ee24a95
diff --git a/changes/430.md b/changes/430.mdnew file mode 100644index 00000000..e1d2e5d0--- /dev/null+++ b/changes/430.md@@ -0,0 +1,2 @@+- Cloth steps live: `createCloth(positions, triangles, options)` returns a stepper with `step(dt)`, runtime `pin`/`unpin` with moving targets, `pinForce`, per-particle extra mass and tearing (`tearStretch`, `tearForce`, a readable `broken` list). `bakeCloth` is now a loop over it and records the same frames as before (closes #430).+- New addon `@codepawlhq/67js/addons/update-part-vertices` adds `renderer.updatePartVertices(part, positions, normals)`, which rewrites a rigid part's vertex buffers with `bufferSubData` instead of `replaceParts`. The core bundle does not change.diff --git a/changes/430.size.md b/changes/430.size.mdnew file mode 100644index 00000000..e4107799--- /dev/null+++ b/changes/430.size.md@@ -0,0 +1 @@+- scene:agent-scene+lazy: the live cloth stepper (pins, pin forces, extra mass, tearing) lives in the lazy cloth code that the baked cloth already loads, about 930 bytes gzip. No core entry or goal scene grew; the update-part-vertices addon is separate.diff --git a/docs/physics.md b/docs/physics.mdindex 9e9f4e30..008a20d2 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -469,6 +469,54 @@ The implementation uses `@dimforge/rapier3d-compat` version `0.21.0`, licensed uSources: [Rapier JavaScript setup](https://rapier.rs/docs/user_guides/javascript/getting_started_js/), [Rapier joints](https://rapier.rs/docs/user_guides/javascript/joints/) and [Rapier determinism](https://rapier.rs/docs/user_guides/javascript/determinism/).+## Live cloth++A game steps cloth one frame at a time, with pins that move and change while it runs. `createCloth(positions, triangles, options)` is the solver `bakeCloth` records from (`bakeCloth` is now a loop over it), so a live run and a baked recording of the same input give the same numbers, frame for frame. It lives in `src/cloth.js`; the recipe `cloth` section above still bakes ahead of time.++```js+import { createCloth } from '@codepawlhq/67js/addons/cloth';++// A 1 m square sheet, 33 x 33 particles, with two grippers holding two corners.+const cloth = createCloth(positions, triangles, { density: 0.2, bend: 0.1 });+const leftCorner = 0;+const rightCorner = 32;+cloth.pin(leftCorner, leftGripper.position);+cloth.pin(rightCorner, rightGripper.position);++function frame(deltaSeconds) {+ // Move the grippers first, then hand the targets to the sheet. Each step carries the pins there in even strides.+ cloth.pin(leftCorner, leftGripper.position);+ cloth.pin(rightCorner, rightGripper.position);+ cloth.step(deltaSeconds, { wind: [0, 0, 1] });+ const pull = cloth.pinForce(leftCorner);+ if (Math.hypot(...pull) > gripStrength) cloth.unpin(leftCorner); // the grip slips and the sheet falls on that side+ sheetGeometryPositions.set(cloth.positions);+}+```++- `step(deltaSeconds, { wind, colliders })` runs 4 substeps of 8 constraint passes. `wind` (m/s) and `colliders` replace the ones in the options for this step only; the other options are fixed at creation. `cloth.positions` is one `Float32Array`, 3 numbers a particle, rewritten in place by every step.+- `pin(index, position)` holds a particle at `position`, or where it is now when none is given. Calling it again moves the target, so a gripper that follows a hand calls it every frame. `unpin(index)` lets go; the particle keeps its velocity. `isPinned(index)` reads the state.+- `pinForce(index, out)` writes the force the cloth pulls the pinned particle with, in newtons, averaged over the last step: `out = [x, y, z]`, so its length is the load. It is an estimate taken from the corrections the solver made, not a measurement: a sheet hanging still from its top row loads the pins with roughly its weight (`cloth.particleMass * particleCount * 9.81`).+- `setExtraMass(index, kilograms)` hangs mass on a particle on top of `cloth.particleMass` (density times area, shared evenly). A heavy particle moves less when the constraints pull, so the sheet sags around it.+- Tearing: `tearStretch` (a stretch constraint breaks when its length passes this multiple of its rest length) and `tearForce` (it breaks when it carries more than this many newtons) are options; both default to never. The bend constraint across a broken edge breaks with it. `cloth.broken` lists them in order as `{ constraint, first, second, kind }`, where `first` and `second` are particle indices and `kind` is `'stretch'` or `'bend'`; `breakConstraint(edge)` tears one by hand. A broken constraint never heals, and the triangles are not removed: hide a triangle whose edge is in the list to show the tear.+- A particle index is a welded particle (`weldVertices` maps mesh vertices to them), as in `bakeCloth`.++## Deforming a drawn part in place++`renderer.updatePartVertices(part, positions, normals)` writes new vertex positions, and normals when given, into the buffers a rigid part already uses, with `bufferSubData`. It needs no `replaceParts`, no new geometry object and no new draw batch. Import `@codepawlhq/67js/addons/update-part-vertices` first; a scene that never deforms a mesh does not carry the code.++```js+import '@codepawlhq/67js/addons/update-part-vertices';++renderer.updatePartVertices(sheetPart, sheetPositions, sheetNormals);+renderer.render(frame);+```++- The vertex count cannot change, and the arrays are `Float32Array`s of 3 numbers a vertex. The values are copied into the part's geometry, so the geometry stays the truth, and every part that uses the same geometry deforms with it.+- It refuses skinned, morphed, crowd and level-of-detail parts. A textured part works, since only positions and normals move.+- The culling bounds and the shadow map follow the new positions.+- Per vertex a cloth steps on welded particles, so copy each vertex from its particle (`weldVertices(...).particleOfVertex`) and recompute normals (`recomputeNormals`) before the call.+## Recipe particles and hairA recipe `particles` section holds up to 4 systems (`src/particles.js`, `src/hair.js`, `src/agent-particles.js`). It needs no peer dependency and loads on demand with the `particles` module, so a scene without particles pays nothing. Blender's particle system has the same two kinds, Emitter and Hair.diff --git a/package.json b/package.jsonindex 191801ef..b7d89dbf 100644--- a/package.json+++ b/package.json@@ -106,6 +106,8 @@"./addons/gaussian-splats": "./build/gaussian-splats.js","./addons/replace-textured-parts": "./build/replace-textured-parts.js","./addons/texture-update": "./build/texture-update.js",+ "./addons/cloth": "./build/cloth.js",+ "./addons/update-part-vertices": "./build/update-part-vertices.js","./package.json": "./package.json"},"scripts": {diff --git a/src/cloth.js b/src/cloth.jsindex 65fc77c8..bbfa6ab4 100644--- a/src/cloth.js+++ b/src/cloth.js@@ -73,12 +73,16 @@ function buildConstraints(positions, triangles, particleCount, bendStiffness, stfor (const [, entry] of orderedEntries) {add(entry.first, entry.second, stretchStiffness);}+ const stretchCount = firsts.length;+ // The bend constraint across an edge, so tearing the edge can drop it too (-1 where the edge has none).+ const bendOfEdge = new Int32Array(stretchCount).fill(-1);if (bendStiffness > 0) {- for (const [, entry] of orderedEntries) {+ orderedEntries.forEach(([, entry], edge) => {if (entry.opposites.length === 2 && entry.opposites[0] !== entry.opposites[1]) {+ bendOfEdge[edge] = firsts.length;add(entry.opposites[0], entry.opposites[1], bendStiffness);}- }+ });}const restLengths = new Float64Array(firsts.length);for (let constraint = 0; constraint < firsts.length; constraint++) {@@ -86,7 +90,7 @@ function buildConstraints(positions, triangles, particleCount, bendStiffness, stconst b = seconds[constraint] * 3;restLengths[constraint] = Math.hypot(positions[a] - positions[b], positions[a + 1] - positions[b + 1], positions[a + 2] - positions[b + 2]);}- return { count: firsts.length, firsts: Uint32Array.from(firsts), seconds: Uint32Array.from(seconds), stiffnesses: Float64Array.from(stiffnesses), restLengths };+ return { count: firsts.length, stretchCount, bendOfEdge, firsts: Uint32Array.from(firsts), seconds: Uint32Array.from(seconds), stiffnesses: Float64Array.from(stiffnesses), restLengths };}// Rest area each particle represents (a third of its triangles), used to turn wind pressure into acceleration.@@ -152,9 +156,12 @@ function applyWind(state, wind, areas, triangles, secondsPerSubstep, density) {}}-function solveDistances(positions, inverseMasses, constraints) {+// Also adds up what each constraint pushed (impulses, kg m per unit particle mass) and what a pinned particle was pulled+// with (pinImpulses), because a particle with no inverse mass takes no correction but still feels the pull.+function solveDistances(positions, inverseMasses, constraints, impulses, pinImpulses) {const { count, firsts, seconds, stiffnesses, restLengths } = constraints;for (let constraint = 0; constraint < count; constraint++) {+ if (stiffnesses[constraint] === 0) continue;const first = firsts[constraint];const second = seconds[constraint];const weightSum = inverseMasses[first] + inverseMasses[second];@@ -166,7 +173,19 @@ function solveDistances(positions, inverseMasses, constraints) {const dz = positions[b + 2] - positions[a + 2];const length = Math.sqrt(dx * dx + dy * dy + dz * dz);if (length < 1e-12) continue;- const correction = stiffnesses[constraint] * (length - restLengths[constraint]) / (length * weightSum);+ const impulse = stiffnesses[constraint] * (length - restLengths[constraint]) / weightSum;+ const correction = impulse / length;+ impulses[constraint] += impulse;+ if (inverseMasses[first] === 0) {+ pinImpulses[a] += dx * correction;+ pinImpulses[a + 1] += dy * correction;+ pinImpulses[a + 2] += dz * correction;+ }+ if (inverseMasses[second] === 0) {+ pinImpulses[b] -= dx * correction;+ pinImpulses[b + 1] -= dy * correction;+ pinImpulses[b + 2] -= dz * correction;+ }positions[a] += dx * correction * inverseMasses[first];positions[a + 1] += dy * correction * inverseMasses[first];positions[a + 2] += dz * correction * inverseMasses[first];@@ -326,64 +345,121 @@ function checkWork(particleCount, constraintCount, triangleCount, colliderCount,}}+function setParticleInverseMass(cloth, particle) {+ const { inverseMasses, pinned, trackFixed, extraMasses, baseMass } = cloth;+ inverseMasses[particle] = pinned[particle] || trackFixed[particle] ? 0 : baseMass / (baseMass + extraMasses[particle]);+}++// Breaks a stretch constraint and the bend constraint across the same edge; both stop pulling at once.+function breakEdge(cloth, edge) {+ const { constraints, broken } = cloth;+ if (constraints.stiffnesses[edge] === 0) return;+ const bend = constraints.bendOfEdge[edge];+ for (const [constraint, kind] of [[edge, 'stretch'], [bend, 'bend']]) {+ if (constraint < 0 || constraints.stiffnesses[constraint] === 0) continue;+ constraints.stiffnesses[constraint] = 0;+ broken.push(Object.freeze({ constraint, first: constraints.firsts[constraint], second: constraints.seconds[constraint], kind }));+ }+}++function tearOverstretched(cloth, substepSeconds) {+ const { constraints, positions, tearStretch, tearForce, baseMass, impulses } = cloth;+ const { firsts, seconds, stiffnesses, restLengths, stretchCount } = constraints;+ const forceScale = baseMass / (substepSeconds * substepSeconds);+ for (let edge = 0; edge < stretchCount; edge++) {+ if (stiffnesses[edge] === 0) continue;+ const a = firsts[edge] * 3;+ const b = seconds[edge] * 3;+ const length = Math.hypot(positions[b] - positions[a], positions[b + 1] - positions[a + 1], positions[b + 2] - positions[a + 2]);+ if (length > restLengths[edge] * tearStretch || impulses[edge] * forceScale > tearForce) {+ breakEdge(cloth, edge);+ }+ }+}+/**- * Simulate one sheet. `positions` are world-space rest positions (3 numbers per particle), `triangles` index them.- * Options: pinned (particle indices that stay put), gravity, wind (m/s), stiffness and bend (0 to 1), density (kg/m2),- * damping (1/s), friction (0 to 1), thickness (m), colliders ({ kind: 'ball', center, radius },- * { kind: 'capsule', start, end, radius } or { kind: 'box', center, axes, halfExtents }), frameCount and framesPerSecond.- * `moving` follows a body that moves with time, sampled ahead as plain numbers so it can cross to a worker. One entry per- * substep (frame 1 substep 0 first): anchorTrack holds each anchor's target (3 numbers), colliderTrack each moving- * collider as a capsule (start 3, end 3, radius 1; a ball has start equal to end). A particle in anchorParticles with- * weight 1 sits on its target; a lower weight pulls it there by that fraction each iteration.- * { anchorParticles, anchorWeights, anchorTrack, colliderCount, colliderTrack }- * Returns the recorded frames: Float32Array of frameCount * particleCount * 3.+ * A sheet that steps one frame at a time, so pins, wind and colliders can change while it runs. It is the solver+ * `bakeCloth` records from: the same positions and options step to the same frames. Arguments and options are those of+ * `bakeCloth`, plus:+ * - tearStretch: a stretch constraint breaks when its length passes this multiple of its rest length (default never).+ * - tearForce: a stretch constraint breaks when the tension it carries passes this many newtons (default never).+ * Returns { positions, step(deltaSeconds, { wind, colliders }), pin(index, position), unpin(index), isPinned(index),+ * pinForce(index, out), setExtraMass(index, kilograms), breakConstraint(edge), broken, constraintCount, particleCount,+ * particleMass }. `positions` is a Float32Array of 3 numbers per particle, updated in place by every step.*/-export function bakeCloth(positions, triangles, options) {+export function createCloth(positions, triangles, options = {}) {const particleCount = positions.length / 3;const colliders = options.colliders ?? [];const moving = options.moving ?? null;const constraints = buildConstraints(positions, triangles, particleCount, options.bend ?? 0.1, options.stiffness ?? 0.9);- checkWork(particleCount, constraints.count, triangles.length / 3, colliders.length + (moving?.colliderCount ?? 0), options.frameCount);- const gravity = options.gravity ?? GRAVITY_DEFAULT;- const wind = options.wind ?? [0, 0, 0];+ checkWork(particleCount, constraints.count, triangles.length / 3, colliders.length + (moving?.colliderCount ?? 0), options.frameCount ?? 1);const density = options.density ?? 0.2;- const damping = options.damping ?? 0.3;- const friction = options.friction ?? 0.3;- const thickness = options.thickness ?? 0.01;- const hasWind = wind.some(component => component !== 0);- const frameSeconds = 1 / (options.framesPerSecond ?? 60);- const substepSeconds = frameSeconds / CLOTH_LIMITS.substeps;- const dampingFactor = Math.exp(-damping * substepSeconds);- const areas = hasWind ? particleAreas(positions, triangles, particleCount) : null;- const inverseMasses = new Float64Array(particleCount).fill(1);+ const areas = particleAreas(positions, triangles, particleCount);+ const totalArea = areas.reduce((sum, area) => sum + area, 0);+ const cloth = {+ constraints, baseMass: Math.max(totalArea * density / particleCount, 1e-9),+ inverseMasses: new Float64Array(particleCount).fill(1), extraMasses: new Float64Array(particleCount),+ pinned: new Uint8Array(particleCount), trackFixed: new Uint8Array(particleCount),+ pinTargets: Float64Array.from(positions), pinForces: new Float64Array(positions.length),+ impulses: new Float64Array(constraints.count), broken: [],+ positions: Float64Array.from(positions),+ tearStretch: options.tearStretch ?? Infinity, tearForce: options.tearForce ?? Infinity,+ };for (const particle of options.pinned ?? []) {- inverseMasses[particle] = 0;+ cloth.pinned[particle] = 1;}- const anchorStride = (moving?.anchorParticles.length ?? 0) * 3;- const colliderStride = (moving?.colliderCount ?? 0) * MOVING_COLLIDER_NUMBERS;moving?.anchorParticles.forEach((particle, anchor) => {- if (moving.anchorWeights[anchor] >= 1) inverseMasses[particle] = 0;+ if (moving.anchorWeights[anchor] >= 1) cloth.trackFixed[particle] = 1;});+ for (let particle = 0; particle < particleCount; particle++) {+ setParticleInverseMass(cloth, particle);+ }const state = {- particleCount, inverseMasses, positions: Float64Array.from(positions),+ particleCount, inverseMasses: cloth.inverseMasses, positions: cloth.positions,velocities: new Float64Array(positions.length), windScratch: new Float64Array(positions.length),};+ const gravity = options.gravity ?? GRAVITY_DEFAULT;+ const damping = options.damping ?? 0.3;+ const friction = options.friction ?? 0.3;+ const thickness = options.thickness ?? 0.01;const previous = new Float64Array(positions.length);- const frames = new Float32Array(options.frameCount * positions.length);- frames.set(Float32Array.from(positions), 0);- for (let frame = 1; frame < options.frameCount; frame++) {- for (let substep = 0; substep < CLOTH_LIMITS.substeps; substep++) {+ const stepStart = new Float64Array(positions.length);+ const pinImpulses = new Float64Array(positions.length);+ const publicPositions = Float32Array.from(positions);+ const anchorStride = (moving?.anchorParticles.length ?? 0) * 3;+ const colliderStride = (moving?.colliderCount ?? 0) * MOVING_COLLIDER_NUMBERS;+ let substepsDone = 0;++ function step(deltaSeconds, frame = {}) {+ const wind = frame.wind ?? options.wind ?? [0, 0, 0];+ const hasWind = wind.some(component => component !== 0);+ const stepColliders = frame.colliders ?? colliders;+ const substeps = CLOTH_LIMITS.substeps;+ const substepSeconds = deltaSeconds / substeps;+ const dampingFactor = Math.exp(-damping * substepSeconds);+ const tears = cloth.tearStretch !== Infinity || cloth.tearForce !== Infinity;+ const { inverseMasses, pinned, pinTargets } = cloth;+ stepStart.set(state.positions);+ pinImpulses.fill(0);+ for (let substep = 0; substep < substeps; substep++) {if (hasWind) applyWind(state, wind, areas, triangles, substepSeconds, density);previous.set(state.positions);- let activeColliders = colliders;+ let activeColliders = stepColliders;let anchorTargets = null;if (moving) {- const substepIndex = (frame - 1) * CLOTH_LIMITS.substeps + substep;- anchorTargets = moving.anchorTrack.subarray(substepIndex * anchorStride, (substepIndex + 1) * anchorStride);- activeColliders = colliders.concat(movingColliders(moving.colliderTrack, substepIndex * colliderStride, moving.colliderCount));+ anchorTargets = moving.anchorTrack.subarray(substepsDone * anchorStride, (substepsDone + 1) * anchorStride);+ activeColliders = stepColliders.concat(movingColliders(moving.colliderTrack, substepsDone * colliderStride, moving.colliderCount));followAnchors(state.positions, moving, anchorTargets, false);}+ // A pin travels to its target in even strides, so a fast gripper drags the cloth instead of teleporting.+ const progress = (substep + 1) / substeps;for (let particle = 0; particle < particleCount; particle++) {+ if (pinned[particle]) {+ for (let axis = 0; axis < 3; axis++) {+ const index = particle * 3 + axis;+ state.positions[index] = stepStart[index] + (pinTargets[index] - stepStart[index]) * progress;+ }+ }if (inverseMasses[particle] === 0) continue;for (let axis = 0; axis < 3; axis++) {const index = particle * 3 + axis;@@ -392,20 +468,116 @@ export function bakeCloth(positions, triangles, options) {}}for (let iteration = 0; iteration < CLOTH_LIMITS.iterations; iteration++) {- solveDistances(state.positions, inverseMasses, constraints);+ solveDistances(state.positions, inverseMasses, constraints, cloth.impulses, pinImpulses);if (moving) followAnchors(state.positions, moving, anchorTargets, true);collide(state, previous, activeColliders, thickness, friction);}+ if (tears) tearOverstretched(cloth, substepSeconds);+ cloth.impulses.fill(0);for (let index = 0; index < positions.length; index++) {state.velocities[index] = (state.positions[index] - previous[index]) / substepSeconds * dampingFactor;}+ substepsDone++;}if (!state.positions.every(Number.isFinite)) {throw new RangeError('Cloth became unstable (non-finite positions). Lower the wind, raise density or use a finer grid.');}- frames.set(Float32Array.from(state.positions), frame * positions.length);+ // An impulse (kg m) over a substep divided by the substep time is a force; average it over the substeps of this step.+ const forceScale = cloth.baseMass / (substeps * substepSeconds * substepSeconds);+ for (let index = 0; index < positions.length; index++) {+ cloth.pinForces[index] = pinImpulses[index] * forceScale;+ }+ publicPositions.set(state.positions);+ }++ function checkIndex(index) {+ if (!Number.isInteger(index) || index < 0 || index >= particleCount) {+ throw new RangeError(`Cloth particle ${index} does not exist; there are ${particleCount}.`);+ }+ }++ return {+ positions: publicPositions,+ particleCount,+ constraintCount: constraints.count,+ /** Mass of one particle in kilograms (density times area, shared evenly); `setExtraMass` adds to it. */+ particleMass: cloth.baseMass,+ /** Constraints that tore, in the order they broke: { constraint, first, second, kind: 'stretch' | 'bend' }. */+ broken: cloth.broken,+ step,+ /**+ * Hold a particle at `position` (default: where it is now). A pinned particle follows its target in even strides+ * over the next step, and the target can move again before every step.+ */+ pin(index, position) {+ checkIndex(index);+ const source = position ?? [state.positions[index * 3], state.positions[index * 3 + 1], state.positions[index * 3 + 2]];+ cloth.pinTargets[index * 3] = source[0];+ cloth.pinTargets[index * 3 + 1] = source[1];+ cloth.pinTargets[index * 3 + 2] = source[2];+ cloth.pinned[index] = 1;+ setParticleInverseMass(cloth, index);+ },+ /** Let go: the particle keeps the velocity it had and falls with the rest. */+ unpin(index) {+ checkIndex(index);+ cloth.pinned[index] = 0;+ setParticleInverseMass(cloth, index);+ },+ isPinned(index) {+ checkIndex(index);+ return cloth.pinned[index] === 1;+ },+ /**+ * The force the cloth pulls on a pinned particle with during the last step, in newtons, written to `out`+ * (x, y, z). Its length is the load the pin carries; a still sheet hung by its pins puts its weight on them.+ * It is an estimate from the constraint corrections of the solver, not a measurement.+ */+ pinForce(index, out = [0, 0, 0]) {+ checkIndex(index);+ out[0] = cloth.pinForces[index * 3];+ out[1] = cloth.pinForces[index * 3 + 1];+ out[2] = cloth.pinForces[index * 3 + 2];+ return out;+ },+ /** Hang `kilograms` on a particle on top of its own mass (0 removes it). */+ setExtraMass(index, kilograms) {+ checkIndex(index);+ cloth.extraMasses[index] = Math.max(kilograms, 0);+ setParticleInverseMass(cloth, index);+ },+ /** Tear one stretch constraint (and the bend across it) by hand; `constraint` counts from 0 over the edges. */+ breakConstraint(constraint) {+ if (!Number.isInteger(constraint) || constraint < 0 || constraint >= constraints.stretchCount) {+ throw new RangeError(`Cloth stretch constraint ${constraint} does not exist; there are ${constraints.stretchCount}.`);+ }+ breakEdge(cloth, constraint);+ },+ };+}++/**+ * Simulate one sheet. `positions` are world-space rest positions (3 numbers per particle), `triangles` index them.+ * Options: pinned (particle indices that stay put), gravity, wind (m/s), stiffness and bend (0 to 1), density (kg/m2),+ * damping (1/s), friction (0 to 1), thickness (m), colliders ({ kind: 'ball', center, radius },+ * { kind: 'capsule', start, end, radius } or { kind: 'box', center, axes, halfExtents }), frameCount and framesPerSecond.+ * `moving` follows a body that moves with time, sampled ahead as plain numbers so it can cross to a worker. One entry per+ * substep (frame 1 substep 0 first): anchorTrack holds each anchor's target (3 numbers), colliderTrack each moving+ * collider as a capsule (start 3, end 3, radius 1; a ball has start equal to end). A particle in anchorParticles with+ * weight 1 sits on its target; a lower weight pulls it there by that fraction each iteration.+ * { anchorParticles, anchorWeights, anchorTrack, colliderCount, colliderTrack }+ * Returns the recorded frames: Float32Array of frameCount * particleCount * 3.+ */+export function bakeCloth(positions, triangles, options) {+ const cloth = createCloth(positions, triangles, options);+ const framesPerSecond = options.framesPerSecond ?? 60;+ const frames = new Float32Array(options.frameCount * positions.length);+ frames.set(Float32Array.from(positions), 0);+ for (let frame = 1; frame < options.frameCount; frame++) {+ cloth.step(1 / framesPerSecond);+ frames.set(cloth.positions, frame * positions.length);}- return Object.freeze({ particleCount, frameCount: options.frameCount, framesPerSecond: options.framesPerSecond ?? 60, frames, constraintCount: constraints.count });+ return Object.freeze({ particleCount: cloth.particleCount, frameCount: options.frameCount, framesPerSecond, frames, constraintCount: cloth.constraintCount });}/** Write the particle positions at `time` into `target`, a linear blend of the two nearest recorded frames. */diff --git a/src/update-part-vertices.js b/src/update-part-vertices.jsnew file mode 100644index 00000000..8833887b--- /dev/null+++ b/src/update-part-vertices.js@@ -0,0 +1,63 @@+// Gives the renderer updatePartVertices: new vertex positions (and normals) for a part that already drew, written into+// its existing GPU buffers with bufferSubData. A deforming mesh such as cloth skips replaceParts, which would build a+// new geometry object and upload every buffer again. Importing this module adds the method to the renderer class (the+// pattern of texture-update.js), so a scene that never deforms a mesh does not carry the code.+import { Renderer67 } from './renderer.js';++function checkVertices(name, values, expectedLength, label) {+ if (!(values instanceof Float32Array) || values.length !== expectedLength) {+ throw new TypeError(`updatePartVertices ${name} must be a Float32Array of ${expectedLength} numbers (3 per vertex, the vertex count of ${label}).`);+ }+}++// The sphere around the box of the new positions: culling and shadow fitting read it, so a sheet that swings out of its+// first bounds is not culled while still on screen.+function boundingSphereOf(positions) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let index = 0; index < positions.length; index += 3) {+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], positions[index + axis]);+ maximum[axis] = Math.max(maximum[axis], positions[index + axis]);+ }+ }+ const center = minimum.map((value, axis) => (value + maximum[axis]) / 2);+ let radiusSquared = 0;+ for (let index = 0; index < positions.length; index += 3) {+ radiusSquared = Math.max(radiusSquared, (positions[index] - center[0]) ** 2 + (positions[index + 1] - center[1]) ** 2 + (positions[index + 2] - center[2]) ** 2);+ }+ return { center, radius: Math.sqrt(radiusSquared) };+}++/**+ * Replace the vertex positions, and the normals when given, of a rigid part the renderer already holds. The vertex+ * count cannot change. The values are copied into the part's geometry, so the geometry stays the truth, and the+ * geometry is shared by every part that uses it. Skinned, morphed, crowd and level-of-detail parts are refused.+ * Returns the part.+ */+export function updateRendererPartVertices(renderer, part, positions, normals) {+ const location = renderer.partLocations.get(part);+ if (!location) throw new Error(`Unknown part identity: ${part?.name}`);+ const geometry = location.geometry;+ if (part.geometry !== geometry) throw new Error(`Geometry changes require replaceParts: ${part.name}`);+ if (location.skin || location.morph || location.morphTargets || location.batch.crowd || part.lods) {+ throw new Error(`updatePartVertices takes rigid parts without level-of-detail sets: ${part.name}`);+ }+ checkVertices('positions', positions, geometry.positions.length, part.name);+ if (normals !== undefined) checkVertices('normals', normals, geometry.normals.length, part.name);+ const buffers = renderer.geometryBuffers.get(geometry);+ const context = renderer.context;+ for (const [field, values] of [['positions', positions], ['normals', normals]]) {+ if (!values) continue;+ if (values !== geometry[field]) geometry[field].set(values);+ context.bindBuffer(context.ARRAY_BUFFER, buffers.get(field));+ context.bufferSubData(context.ARRAY_BUFFER, 0, geometry[field]);+ }+ location.batch.bounds = boundingSphereOf(geometry.positions);+ renderer.shadowsDirty = true;+ return part;+}++Renderer67.prototype.updatePartVertices = function updatePartVertices(part, positions, normals) {+ return updateRendererPartVertices(this, part, positions, normals);+};diff --git a/tests/live-cloth.test.js b/tests/live-cloth.test.jsnew file mode 100644index 00000000..b970f528--- /dev/null+++ b/tests/live-cloth.test.js@@ -0,0 +1,153 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { bakeCloth, createCloth } from '../src/cloth.js';++// A square sheet in the plane y = 1, `size` particles a side, 0.1 m apart.+function sheetOf(size) {+ const positions = new Float32Array(size * size * 3);+ const triangles = [];+ for (let row = 0; row < size; row++) {+ for (let column = 0; column < size; column++) {+ const index = row * size + column;+ positions.set([column * 0.1, 1, row * 0.1], index * 3);+ if (row < size - 1 && column < size - 1) {+ triangles.push(index, index + 1, index + size, index + 1, index + size + 1, index + size);+ }+ }+ }+ return { positions, triangles: Uint32Array.from(triangles), size };+}++const FRAME = 1 / 60;++function runFrames(cloth, frames) {+ for (let frame = 0; frame < frames; frame++) cloth.step(FRAME);+}++test('stepping matches bakeCloth frame for frame with the same inputs', () => {+ const { positions, triangles, size } = sheetOf(10);+ const options = { pinned: [0, size - 1], wind: [0, 0, 1.5], colliders: [{ kind: 'ball', center: [0.45, 0.4, 0.45], radius: 0.25 }] };+ const recording = bakeCloth(positions, triangles, { ...options, frameCount: 40 });+ const cloth = createCloth(positions, triangles, options);+ const stride = positions.length;+ for (let frame = 1; frame < 40; frame++) {+ cloth.step(FRAME);+ assert.deepEqual(cloth.positions, recording.frames.subarray(frame * stride, (frame + 1) * stride), `frame ${frame}`);+ }+});++test('positions is one Float32Array updated in place', () => {+ const { positions, triangles } = sheetOf(5);+ const cloth = createCloth(positions, triangles, { pinned: [0] });+ const before = cloth.positions;+ const startY = before[(4 * 5 + 4) * 3 + 1];+ runFrames(cloth, 10);+ assert.equal(cloth.positions, before);+ assert.ok(before instanceof Float32Array);+ assert.ok(before[(4 * 5 + 4) * 3 + 1] < startY);+});++test('pin and unpin work at runtime', () => {+ const { positions, triangles, size } = sheetOf(6);+ const corner = size - 1;+ const cloth = createCloth(positions, triangles, { pinned: [0] });+ const cornerHeight = () => cloth.positions[corner * 3 + 1];+ cloth.pin(corner);+ assert.equal(cloth.isPinned(corner), true);+ runFrames(cloth, 60);+ assert.ok(Math.abs(cornerHeight() - 1) < 1e-6, 'a pinned corner stays where it was pinned');+ cloth.unpin(corner);+ assert.equal(cloth.isPinned(corner), false);+ runFrames(cloth, 30);+ assert.ok(cornerHeight() < 0.99, 'an unpinned corner falls');+ assert.throws(() => cloth.pin(size * size), RangeError);+});++test('a moving pin drags the cloth', () => {+ const { positions, triangles, size } = sheetOf(8);+ const left = 0;+ const right = size - 1;+ const cloth = createCloth(positions, triangles, { pinned: [left, right] });+ const middle = (Math.floor(size / 2) * size + Math.floor(size / 2)) * 3;+ const startX = cloth.positions[middle];+ for (let frame = 1; frame <= 60; frame++) {+ cloth.pin(left, [-0.002 * frame, 1, 0]);+ cloth.pin(right, [(size - 1) * 0.1 - 0.002 * frame, 1, 0]);+ cloth.step(FRAME);+ }+ assert.ok(Math.abs(cloth.positions[left * 3] - -0.12) < 1e-5, 'the pin reaches its target');+ assert.ok(cloth.positions[middle] < startX - 0.05, 'the middle of the sheet followed');+});++test('pinForce grows with load and balances the weight of a hanging sheet', () => {+ const { positions, triangles, size } = sheetOf(8);+ const top = Array.from({ length: size }, (unused, column) => column);+ const cloth = createCloth(positions, triangles, { pinned: top });+ const total = () => {+ const force = [0, 0, 0];+ let sum = 0;+ for (const pin of top) sum += cloth.pinForce(pin, force)[1];+ return sum;+ };+ runFrames(cloth, 240);+ const unloaded = total();+ const weight = cloth.particleMass * size * size * 9.81;+ assert.ok(unloaded < 0, 'the cloth pulls the pins down');+ // Hanging still, the pins hold the weight of the sheet; the solver is an estimate, so allow a wide band.+ assert.ok(Math.abs(unloaded) > weight * 0.5 && Math.abs(unloaded) < weight * 1.5, `${unloaded} N against ${weight} N of weight`);+ cloth.setExtraMass(size * size - 1, cloth.particleMass * size * size);+ runFrames(cloth, 240);+ assert.ok(Math.abs(total()) > Math.abs(unloaded) * 1.4, 'a heavy particle adds to what the pins carry');+});++test('tearing removes constraints past the threshold and lists them', () => {+ const { positions, triangles, size } = sheetOf(6);+ const cloth = createCloth(positions, triangles, { pinned: [0, size - 1], tearStretch: 1.4 });+ assert.deepEqual(cloth.broken, []);+ runFrames(cloth, 10);+ assert.equal(cloth.broken.length, 0, 'a sheet at rest does not tear');+ // Pull one corner far away from the other so the edges between them stretch past the limit.+ for (let frame = 1; frame <= 30; frame++) {+ cloth.pin(size - 1, [(size - 1) * 0.1 + 0.05 * frame, 1, 0]);+ cloth.step(FRAME);+ }+ assert.ok(cloth.broken.length > 0, 'stretched constraints broke');+ const [first] = cloth.broken;+ assert.ok(Number.isInteger(first.first) && Number.isInteger(first.second));+ assert.ok(['stretch', 'bend'].includes(first.kind));+ assert.equal(new Set(cloth.broken.map(entry => entry.constraint)).size, cloth.broken.length, 'each constraint is listed once');+ const intact = createCloth(positions, triangles, { pinned: [0, size - 1] });+ runFrames(intact, 10);+ assert.equal(intact.broken.length, 0);+});++test('tearForce breaks the edges that carry too much tension and breakConstraint tears by hand', () => {+ const { positions, triangles, size } = sheetOf(6);+ const top = Array.from({ length: size }, (unused, column) => column);+ const cloth = createCloth(positions, triangles, { pinned: top, tearForce: 0.0001 });+ cloth.setExtraMass(size * size - 1, 1);+ runFrames(cloth, 60);+ assert.ok(cloth.broken.some(entry => entry.kind === 'stretch'), 'a tiny force limit tears the loaded sheet');+ const manual = createCloth(positions, triangles, { pinned: [0] });+ manual.breakConstraint(0);+ assert.equal(manual.broken[0].constraint, 0);+ manual.breakConstraint(0);+ assert.equal(manual.broken.filter(entry => entry.constraint === 0).length, 1, 'breaking twice lists it once');+ assert.throws(() => manual.breakConstraint(-1), RangeError);+});++test('extra mass sags more', () => {+ const { positions, triangles, size } = sheetOf(8);+ const top = Array.from({ length: size }, (unused, column) => column);+ // The sheet hangs along z in the rest plane y = 1 and gravity pulls along y, so compare how far it dropped.+ const dropOf = extraKilograms => {+ const cloth = createCloth(positions, triangles, { pinned: top });+ const bottomMiddle = (size - 1) * size + Math.floor(size / 2);+ cloth.setExtraMass(bottomMiddle, extraKilograms);+ runFrames(cloth, 240);+ return 1 - cloth.positions[bottomMiddle * 3 + 1];+ };+ const light = dropOf(0);+ const heavy = dropOf(50);+ assert.ok(heavy > light, `${heavy} should sag more than ${light}`);+});diff --git a/tests/update-part-vertices.test.js b/tests/update-part-vertices.test.jsnew file mode 100644index 00000000..8342b1cc--- /dev/null+++ b/tests/update-part-vertices.test.js@@ -0,0 +1,61 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { Renderer67 } from '../src/renderer.js';+import '../src/update-part-vertices.js';++/** A WebGL2 stand-in that records buffer writes, with one rigid part already uploaded. */+function fakeRenderer() {+ const calls = [];+ const geometry = {+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),+ indices: new Uint32Array([0, 1, 2]),+ };+ const part = { name: 'sheet', geometry, material: { tag: 'standard' } };+ const context = {+ ARRAY_BUFFER: 34962,+ bindBuffer: (target, buffer) => calls.push(['bindBuffer', buffer]),+ bufferSubData: (target, offset, data) => calls.push(['bufferSubData', offset, Array.from(data)]),+ bufferData: () => calls.push(['bufferData']),+ createVertexArray: () => calls.push(['createVertexArray']),+ };+ const renderer = Object.create(Renderer67.prototype);+ renderer.context = context;+ renderer.shadowsDirty = false;+ const batch = { parts: [part], bounds: { center: [0.5, 0.5, 0], radius: 1 } };+ renderer.partLocations = new Map([[part, { batch, geometry }]]);+ renderer.geometryBuffers = new Map([[geometry, new Map([['positions', 'positionBuffer'], ['normals', 'normalBuffer']])]]);+ return { renderer, part, geometry, batch, calls };+}++test('updatePartVertices rewrites the drawn buffers without a new batch or geometry', () => {+ const { renderer, part, geometry, batch, calls } = fakeRenderer();+ const batchesBefore = batch;+ const positions = new Float32Array([0, 0, 5, 1, 0, 5, 0, 1, 5]);+ const normals = new Float32Array([1, 0, 0, 1, 0, 0, 1, 0, 0]);+ renderer.updatePartVertices(part, positions, normals);+ assert.deepEqual(calls, [+ ['bindBuffer', 'positionBuffer'], ['bufferSubData', 0, Array.from(positions)],+ ['bindBuffer', 'normalBuffer'], ['bufferSubData', 0, Array.from(normals)],+ ]);+ assert.equal(renderer.partLocations.get(part).batch, batchesBefore, 'the batch is the same one');+ assert.equal(renderer.partLocations.get(part).geometry, geometry, 'the geometry object is the same one');+ assert.deepEqual(Array.from(geometry.positions), Array.from(positions), 'the geometry holds the new truth');+ assert.equal(renderer.shadowsDirty, true);+ assert.ok(batch.bounds.center[2] === 5, 'culling bounds follow the new positions');+});++test('updatePartVertices leaves normals alone when none are given', () => {+ const { renderer, part, calls } = fakeRenderer();+ renderer.updatePartVertices(part, new Float32Array(9));+ assert.deepEqual(calls.map(call => call[0]), ['bindBuffer', 'bufferSubData']);+});++test('updatePartVertices refuses a changed vertex count, an unknown part and a skinned part', () => {+ const { renderer, part } = fakeRenderer();+ assert.throws(() => renderer.updatePartVertices(part, new Float32Array(12)), /3 per vertex/);+ assert.throws(() => renderer.updatePartVertices(part, [0, 0, 0, 0, 0, 0, 0, 0, 0]), TypeError);+ assert.throws(() => renderer.updatePartVertices({ name: 'other' }, new Float32Array(9)), /Unknown part/);+ renderer.partLocations.get(part).skin = {};+ assert.throws(() => renderer.updatePartVertices(part, new Float32Array(9)), /rigid/);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 8a7cebe6..c7847854 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -98,6 +98,8 @@ export default defineConfig({'compact-color': 'src/compact-color.js','gaussian-splats': 'src/gaussian-splats.js','texture-update': 'src/texture-update.js',+ cloth: 'src/cloth.js',+ 'update-part-vertices':'src/update-part-vertices.js','replace-textured-parts': 'src/replace-textured-parts.js',// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.'mcp/preview': 'scripts/agent-preview-browser.js',