3D engine that AI agents drive
Let a cloth go at the floor and hold it with static friction: a crumpled heap that rests (#866)
Nguyen Xuan An0d2bbb32a31a
diff --git a/changes/866-cloth-folds.md b/changes/866-cloth-folds.mdindex aa0845ad..449f1239 100644--- a/changes/866-cloth-folds.md+++ b/changes/866-cloth-folds.md@@ -1 +1 @@-- Cloth sheets take `bendModel: 'dihedral'` for many soft folds instead of one crease, `bendYield` and `bendSet` so a fold keeps its crease instead of being pulled flat again, self collision handles up to 5000 particles and runs about 3 times faster, and a 64 by 64 flag bakes a 4 second film in about 13 seconds (#866)+- Cloth sheets take `bendModel: 'dihedral'` for many soft folds instead of one crease, `bendYield` and `bendSet` so a fold keeps its crease instead of being pulled flat again, `staticFriction` so a layer rests on the floor or a slope below its friction angle, and `pinTo.releaseAt` to let a carried cloth go, self collision handles up to 5000 particles and runs about 3 times faster, and a 64 by 64 flag bakes a 4 second film in about 13 seconds (#866)diff --git a/changes/866-cloth-folds.size.md b/changes/866-cloth-folds.size.mdindex 02354af5..8f45af8e 100644--- a/changes/866-cloth-folds.size.md+++ b/changes/866-cloth-folds.size.md@@ -2,3 +2,4 @@- scene:agent-scene: the bendModel field and its error check- scene:agent-scene+lazy: the cloth kernel is lazy-loaded with the scene, so it carries the dihedral solver- goal:agent-scene: the bytes are the cloth bend model of #866, which bakes a 64 by 64 flag; the lazy chunk is the only part of the scene that grew by more than the field itself+- scene:agent-scene: the staticFriction and pinTo.releaseAt fields and their range checks (about 0.1 KB gzip); the static friction test in the contact loop is a few hundred bytes in the lazy cloth chunkdiff --git a/docs/physics.md b/docs/physics.mdindex 136ebe87..b8d99647 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -438,7 +438,7 @@ A recipe `cloth` section records deformable sheets with a position-based solver- Up to 64 moving balls and capsules, counting every bone. The node poses come from the recipe's motion tracks and IK; a physics ragdoll or body is not followed. Points are pushed out of the capsules, not whole triangles, so a coarse sheet can still cut a corner of a thin limb: use a finer grid than the limb is wide. A cape on the reference walker (24 by 24 grid, 5 s, about 2.5 s to bake on the dev machine) stays outside every limb capsule in `tests/cloth-moving.test.js`.- The bake runs when the scene is created: 60 frames a second, 4 substeps and 8 constraint passes a frame, constraints solved in a fixed order with no random numbers. `sample(time)` blends the two nearest frames, so the same time always gives the same positions and a seek backwards repeats them. Time zero is the authored sheet and a time past `duration` holds the last frame.- `bendModel: 'dihedral'` replaces the distance bend (`bendModel` default `'distance'`) with a bend that holds the angle between neighbouring triangles (position based dynamics, one Newton step per edge, solved on every second iteration). The distance bend gives one hard crease or a smooth tent; the dihedral bend gives many soft folds on a fine grid. `bend` 0.15 suits a 64 by 64 cloth; a higher value flattens the layer, a lower one raises spikes. It tears with its edge like the distance bend. Default scenes are unchanged byte for byte.-- `bendYield` (radians, 0 to pi, only with `bendModel: 'dihedral'`, off by default) and `bendSet` (0 to 1, default 0.1) make a fold keep its crease. The dihedral bend pulls every fold back toward the flat rest angle, so a cloth that crumples in the air slowly smooths out again on the floor. With `bendYield`, a bend further than that angle from its rest angle moves the rest angle `bendSet` of the excess toward the current angle each substep, so the cloth stops pulling that fold flat. The rest angle only moves to angles the sheet has had, the update is deterministic, and a scene without `bendYield` bakes the same bytes as before. `bendYield` 0.3 with `bendSet` 0.2 suits a 64 by 64 cloth; a lower yield sets creases sooner, a higher one keeps the cloth springier. Floor friction needs no extra field: the existing `friction` is applied on every solver iteration, so a sheet at rest on a floor tilted 20 degrees (friction 0.3) slides 1.3 mm in 1.5 s (`tests/cloth-bending.test.js`).+- `bendYield` (radians, 0 to pi, only with `bendModel: 'dihedral'`, off by default) and `bendSet` (0 to 1, default 0.1) make a fold keep its crease. The dihedral bend pulls every fold back toward the flat rest angle, so a cloth that crumples in the air slowly smooths out again on the floor. With `bendYield`, a bend further than that angle from its rest angle moves the rest angle `bendSet` of the excess toward the current angle each substep, so the cloth stops pulling that fold flat. The rest angle only moves to angles the sheet has had, the update is deterministic, and a scene without `bendYield` bakes the same bytes as before. `bendYield` 0.3 with `bendSet` 0.2 suits a 64 by 64 cloth; a lower yield sets creases sooner, a higher one keeps the cloth springier. `friction` alone only slows a slide: it removes that share of the sideways travel of each contact, so a layer still creeps. `staticFriction` (0 to 1, default 0, off) adds Coulomb static friction: a contact whose sideways travel in a substep is no more than `staticFriction` times the depth it was pushed out by is held completely, so a sheet rests on a slope below its friction angle (`staticFriction: 1` is 45 degrees: a sheet on a 25 degree slope moves 0 m in 2 s, and 0.33 m without it, `tests/cloth-friction.test.js`). It acts on the floor and colliders, not between layers of the sheet. `pinTo.releaseAt` (seconds, default never) lets the pinned edges go at that time, and they fall with the rest, so a cloth carried to the floor by a pole is left lying without a corner held up in the air.- Limits: 8 sheets, 16 fixed colliders, 64 moving ones, 10 seconds, 5000 particles a sheet, 3 million recorded particle positions and 500 million solver operations a bake (about 20 seconds; the old 150 million was measured at 18 ns an operation, the 64 by 64 flag measures about 50 ns). Larger input is rejected with the limit in the message. A 32 by 32 grid for 4 seconds bakes in about 1.4 s.- A seek replaces the sheet's part, so the renderer sees a topology change (`topologyRevision`); the MCP preview uses `replaceParts` and `scene_look` with `motionTime` repeats the same PNG bytes (`npm run smoke:agent-cloth`).- `scene_inspect` returns a `cloth` report: particles, triangles, pinned count and the final bounds of each sheet.@@ -446,7 +446,7 @@ A recipe `cloth` section records deformable sheets with a position-based solverSoft body films (`scripts/soft-body-film.mjs`, `tests/soft-body-film.test.js`): a jelly cube landing and a flag lowered into folds on itself, each one recipe that the test bakes twice and the preview script renders.- Jelly cube: a rounded box 0.5 m across (384 particles) dropped from 1.95 m, `softBody { shape: 0.15, pressure: 1 }`. It first rests on the floor at frame 48 (0.8 s) and is dented 0.0503 m (10 percent of its height) at frame 49, one step later, while its width grows from 0.5 m to 0.547 m; the frame before contact has no dent.-- Fine flag (`foldingFlagRecipe({ fine: true })`, `node scripts/render-soft-body-film.mjs <directory> --fine`): the same pole path on a 64 by 64 grid (4096 particles) for 4 s with `bendModel: 'dihedral'`, `bend: 0.15`, `bendYield: 0.3`, `bendSet: 0.2` and `damping: 3`. Without `bendYield` the folds made in the fall were pulled flat again: normal spread 0.65 at step 90 and 0.44 at rest, median height 2 mm, three folds along the middle row. With it, measured in `tests/soft-body-film.test.js` and the preview JSON: first touch at step 41, normal spread 0.433 mid fall, 0.639 at settling (step 82) and 0.788 at rest (step 239), highest point at rest 0.053 m, median 0.006 m, 90th percentile 0.020 m, and a line across the middle of the grid crosses 18 folds (row) and 27 (column) at settling and 29 and 42 at rest (height turns of more than 0.5 mm). Closest pair of particles not joined by an edge: 3.7 mm at the final step with self collision (0.7 mm without it), at least 1.66 mm in the sampled frames, the lowest being the first frame at the floor (the contact distance is the 2 mm thickness). Bake 11 to 16 s for 240 steps on the loaded dev machine. The look awaits the owner's review: the rest layer is a wide sheet with a ruffled end and one arch, not yet a heap of many large folds.+- Fine flag (`foldingFlagRecipe({ fine: true })`, `node scripts/render-soft-body-film.mjs <directory> --fine`): the same whip of the pole on a 64 by 64 grid (4096 particles) for 4 s with `bendModel: 'dihedral'`, `bend: 0.15`, `bendYield: 0.3`, `bendSet: 0.2`, `damping: 3`, `friction: 0.6` and `staticFriction: 1`. The pole lets go as it lands (`pinTo.releaseAt: 0.8`), so no corner stays held up like a tent and nothing drags the cloth flat; the cloth is left as a heap of 1.6 m2 of sheet in a footprint of about 1.2 by 0.4 m, and it keeps that shape. Without `bendYield` the folds were pulled flat again (normal spread 0.65 at step 90, 0.44 at rest). Measured in `tests/soft-body-film.test.js` and the preview JSON: first touch at step 41, normal spread 0.433 mid fall, 0.634 at settling (step 82) and 0.638 at rest (step 239), highest point at rest 0.102 m, median 0.012 m, 90th percentile 0.035 m, and a line across the middle of the grid crosses 20 folds (row) and 29 (column) at settling and 22 and 29 at rest (height turns of more than 0.5 mm). Closest pair of particles not joined by an edge: 3.5 mm at the final step with self collision (0.3 mm without it), at least 1.5 mm in the sampled frames, the lowest being the first frame at the floor (the contact distance is the 2 mm thickness). Bake 11 to 16 s for 240 steps on the loaded dev machine. The look awaits the owner's review.- Flag: a 38 by 38 grid (1444 particles, the most that fits the cloth work limit for a 3 s film), 1 m tall and 1.6 m wide, held by its two top corners (`pin: ['topLeft', 'topRight']`, `pinTo` a pole) so the free edge sags and billows instead of falling as a flat card. The pole whips 0.5 m from side to side and 0.4 m front to back while it drops 2 m in 0.8 s, so the sheet ripples in the air, then zig-zags 0.3 m from side to side while it moves 2 m across the floor, which pulls the cloth into a thin crumpled layer. The sheet sets `bend: 0.0002`, `stiffness: 0.6`, `damping: 1.5`, `friction: 0.4` and `thickness: 0.002`, so its self collision layers stack 4 mm apart (earlier rounds: 3.7 cm from the mesh-based radius and a 0.547 m block, then a flat card with a smooth sheet at rest, then one smooth ridge). Measured in the test: first touch at step 39; normal spread (0 flat, toward 1 scattered) is 0 at the start, 0.480 mid fall (step 27, the test fails below 0.25) and 0.674 at rest (fails below 0.5), the sheet bends 0.81 m out of its plane mid fall, and at the final step (179) the highest vertex is 0.0855 m above the floor (a small fold; the test fails above 0.1 m), half of the cloth lies under 0.0042 m and nine tenths of it under 0.0308 m (the test fails above 0.05 m). With `selfCollision: true` the closest pair of particles not joined by an edge is never under 1.8 mm apart in any sampled frame after touch (0.0021 m); the same film without it comes down to 0.2 mm. Those numbers come from the same bake the preview renders, and the film JSON (`soft-body-film.json`) records the highest, median and 90th percentile height at rest. The bake takes 7 to 17 s on the loaded dev machine (about 30 to 40 ms a step with self collision); the self collision limit is now 5000 particles and a 4 s film at 38 by 38 fits the work limit. The default bake takes about 3.5 s (19 ms a step with self collision) on a quiet machine: the self collision rewrite made it 3 times faster. The look is a red and cream striped cloth (a `graph` pattern, so every fold bends the stripes) on a mid grey floor under a low grazing key light (`environment.lightDirection`, fill and ambient lowered), framed from 5.4 m so the cloth fills about a fifth of the picture width.- Both films bake to the same bytes in every frame across two runs; the test compares every frame's vertex buffer.- Frame time, in milliseconds per solver step (the bake is one call, so this is its total over the steps, on a machine shared with other sessions, so read it as a range): jelly 6 to 9 ms a step over 120 steps, flag 30 to 40 ms a step over 180 steps (29 ms a step without self collision). Sampling a recorded frame for playback costs about 1.5 to 2 ms.diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 07182db5..3abd8131 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -638,7 +638,7 @@ const clothSheet = z.strictObject({pinGroup: z.string().max(48).optional(),pinTo: looseRecord.optional(),stiffnessGroup: z.string().max(48).optional(), softBody: looseRecord.optional(), selfCollision: z.boolean().optional(),- stiffness: unit.optional(), bend: unit.optional(), bendModel: z.enum(['distance', 'dihedral']).optional(), bendYield: z.number().min(0).max(Math.PI).optional(), bendSet: unit.optional(), density: positive.optional(), damping: nonnegative.optional(), friction: unit.optional(), thickness: nonnegative.optional(),+ stiffness: unit.optional(), bend: unit.optional(), bendModel: z.enum(['distance', 'dihedral']).optional(), bendYield: z.number().min(0).max(Math.PI).optional(), bendSet: unit.optional(), density: positive.optional(), damping: nonnegative.optional(), friction: unit.optional(), staticFriction: unit.optional(), thickness: nonnegative.optional(),});const cloth = z.strictObject({duration: z.number().min(0.1).max(10),diff --git a/scripts/soft-body-film.mjs b/scripts/soft-body-film.mjsindex 5cc73f97..1ca7388f 100644--- a/scripts/soft-body-film.mjs+++ b/scripts/soft-body-film.mjs@@ -63,20 +63,28 @@ export const FINE_FLAG_FILM_SECONDS = 4;const FINE_FLAG_SEGMENTS = 63;const FINE_FLAG_BEND = 0.15;// Creases stay: past 0.3 rad of bending the rest angle follows the cloth by a fifth of the excess a substep, so folds made in the fall are kept-// when the pole drags the sheet (without it the sheet pulls its folds flat again and ends as a smooth layer). Damping 3 calms the landing.-const FINE_FLAG_CREASE = { bendYield: 0.3, bendSet: 0.2, damping: 3 };+// (without it the sheet pulls its folds flat again and ends as a smooth layer). Damping 3 calms the landing. Static friction holds a layer+// where it lies on the floor, and the pole lets go as it lands, so no corner stays pinned up like a tent and the heap is left to rest.+const FINE_FLAG_CREASE = { bendYield: 0.3, bendSet: 0.2, damping: 3, friction: 0.6, staticFriction: 1 };+const FINE_FLAG_LANDING_SECONDS = 0.8;+// The camera frames the fall from afar, then moves in over the landing so the heap fills the picture.+const FINE_FLAG_CAMERA_TRACKS = [+ { kind: 'camera', property: 'eye', interpolation: 'SMOOTH', keyframes: [{ time: 0, value: [1.5, 1.2, 3.6] }, { time: 0.7, value: [1.5, 1.2, 3.6] }, { time: 1.3, value: [0.85, 0.75, 1.55] }, { time: 4, value: [0.85, 0.75, 1.55] }] },+ { kind: 'camera', property: 'target', interpolation: 'SMOOTH', keyframes: [{ time: 0, value: [0, 0.9, 0] }, { time: 0.7, value: [0, 0.9, 0] }, { time: 1.3, value: [0, 0.03, 0] }, { time: 4, value: [0, 0.03, 0] }] },+];// A deep red and cream striped cloth on a mid grey floor, lit by a grazing key from the side so every fold casts a shadow and bends the stripes.const FLAG_LOOK = { lightDirection: [-0.9, 0.3, 0.45], keyIntensity: 1.5, fillIntensity: 0.12, ambientIntensity: 0.15 };const FLAG_STRIPES = { type: 'graph', mapping: 'uv', resolution: 256, graph: { color: { layer: { base: [0.35, 0.015, 0.04], top: [0.85, 0.78, 0.62], mask: { wave: { frequency: 8, direction: 'v', shape: 'saw' } }, edge: 0.5, softness: 0.02 } } } };/*** A flag hung from a pole by its top edge. The pole swings from side to side while it falls, so the sheet ripples, lands on the floor and- * drags the cloth into a crumpled ridge on a thin layer. The sheet sets thickness 3.5 mm, which also sets the self collision radius,+ * is let go there, so the cloth settles as a crumpled heap that stays put (fine only; the 38 by 38 film drags it into a ridge). The sheet sets thickness 3.5 mm, which also sets the self collision radius,* so layers stack 6 mm apart instead of 3.7 cm.*/export function foldingFlagRecipe({ selfCollision = true, fine = false } = {}) {const seconds = fine ? FINE_FLAG_FILM_SECONDS : FLAG_FILM_SECONDS;- const keyframes = fine ? [...POLE_KEYFRAMES.slice(0, -1), { time: seconds, value: POLE_KEYFRAMES.at(-1).value }] : POLE_KEYFRAMES;+ const landing = POLE_KEYFRAMES.findIndex(keyframe => keyframe.time === FINE_FLAG_LANDING_SECONDS);+ const keyframes = fine ? [...POLE_KEYFRAMES.slice(0, landing + 1), { time: seconds, value: POLE_KEYFRAMES[landing].value }] : POLE_KEYFRAMES;const bending = fine ? { bendModel: 'dihedral', bend: FINE_FLAG_BEND, ...FINE_FLAG_CREASE } : { bend: 0.0002 };return baseRecipe({geometries: [{ id: 'flag', type: 'grid', segments: fine ? FINE_FLAG_SEGMENTS : 38 }],@@ -85,13 +93,13 @@ export function foldingFlagRecipe({ selfCollision = true, fine = false } = {}) {{ id: 'flag', geometry: 'flag', material: 'fabric', translation: [0, 1.5, 0], scale: [1.6, 1, 1] },{ id: 'pole', translation: [0, 2.0, 0] },],- motion: { duration: seconds, loop: false, tracks: [{ kind: 'node', id: 'pole', property: 'translation', interpolation: 'LINEAR', keyframes }] },- camera: { eye: [2.2, 1.7, 5.4], target: [0, 0.6, 0.8] },+ motion: { duration: seconds, loop: false, tracks: [{ kind: 'node', id: 'pole', property: 'translation', interpolation: 'LINEAR', keyframes }, ...(fine ? FINE_FLAG_CAMERA_TRACKS : [])] },+ camera: fine ? { eye: [1.5, 1.2, 3.6], target: [0, 0.9, 0], fov: 42 } : { eye: [2.2, 1.7, 5.4], target: [0, 0.6, 0.8] },floorColor: [0.28, 0.28, 0.3],environment: FLAG_LOOK,cloth: {duration: seconds,- sheets: [{ node: 'flag', pin: ['topLeft', 'topRight'], pinTo: { node: 'pole' }, selfCollision, stiffness: 0.6, damping: 1.5, ...bending, friction: 0.4, thickness: 0.002 }],+ sheets: [{ node: 'flag', pin: ['topLeft', 'topRight'], pinTo: fine ? { node: 'pole', releaseAt: FINE_FLAG_LANDING_SECONDS } : { node: 'pole' }, selfCollision, stiffness: 0.6, damping: 1.5, friction: 0.4, ...bending, thickness: 0.002 }],colliders: [{ node: 'ground', shape: 'box' }],},});diff --git a/src/agent-cloth.js b/src/agent-cloth.jsindex 39dd468e..aedea24b 100644--- a/src/agent-cloth.js+++ b/src/agent-cloth.js@@ -25,8 +25,8 @@ const PIN_EDGES = ['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'botconst COLLIDER_SHAPES = ['ball', 'box'];const MOVING_SHAPES = ['ball', 'capsule'];const CLOTH_FIELDS = ['duration', 'gravity', 'wind', 'fields', 'sheets', 'colliders'];-const SHEET_FIELDS = ['node', 'pin', 'pinGroup', 'pinTo', 'stiffnessGroup', 'softBody', 'selfCollision', 'stiffness', 'bend', 'bendModel', 'bendYield', 'bendSet', 'density', 'damping', 'friction', 'thickness'];-const PIN_TO_FIELDS = ['node', 'weight'];+const SHEET_FIELDS = ['node', 'pin', 'pinGroup', 'pinTo', 'stiffnessGroup', 'softBody', 'selfCollision', 'stiffness', 'bend', 'bendModel', 'bendYield', 'bendSet', 'density', 'damping', 'friction', 'staticFriction', 'thickness'];+const PIN_TO_FIELDS = ['node', 'weight', 'releaseAt'];const SOFT_BODY_FIELDS = ['shape', 'pressure', 'bounce'];// A stiffness group never goes fully limp: a zero weight would let its particles drift off.const MIN_GROUP_STIFFNESS = 0.05;@@ -89,6 +89,7 @@ function normalizeSheet(input, context, path) {throw invalidField(`${path}.pinTo.node`, target, 'a node other than the sheet itself, such as a pole or a hand');}sheet.pinTo = { node: target, weight: input.pinTo.weight === undefined ? 1 : finiteNumber(input.pinTo.weight, `${path}.pinTo.weight`, 0.01, 1) };+ if (input.pinTo.releaseAt !== undefined) sheet.pinTo.releaseAt = finiteNumber(input.pinTo.releaseAt, `${path}.pinTo.releaseAt`, 0, 3600);}if (input.bendModel !== undefined) {if (!BEND_MODELS.includes(input.bendModel)) throw invalidField(`${path}.bendModel`, input.bendModel, `one of ${BEND_MODELS.join(', ')}`);@@ -97,7 +98,7 @@ function normalizeSheet(input, context, path) {if (input.bendYield !== undefined && (input.bendModel ?? 'distance') !== 'dihedral') {throw invalidField(`${path}.bendYield`, input.bendYield, "used with bendModel 'dihedral' only; set bendModel to 'dihedral' or drop bendYield");}- const ranges = { stiffness: [0.01, 1], bend: [0, 1], density: [0.01, 10], damping: [0, 100], friction: [0, 1], thickness: [0, 0.5], bendYield: [0, Math.PI], bendSet: [0, 1] };+ const ranges = { stiffness: [0.01, 1], bend: [0, 1], density: [0.01, 10], damping: [0, 100], friction: [0, 1], staticFriction: [0, 1], thickness: [0, 0.5], bendYield: [0, Math.PI], bendSet: [0, 1] };for (const [field, [minimum, maximum]] of Object.entries(ranges)) {if (input[field] !== undefined) sheet[field] = finiteNumber(input[field], `${path}.${field}`, minimum, maximum);}@@ -400,6 +401,7 @@ function createMovingBodies(sheet, pinned, worldPositions, movingSetup, frameCoureturn {anchorParticles,anchorWeights: new Float64Array(anchorParticles.length).fill(sheet.pinTo?.weight ?? 1),+ releaseSubstep: sheet.pinTo?.releaseAt === undefined ? Infinity : Math.ceil(sheet.pinTo.releaseAt * FRAMES_PER_SECOND * CLOTH_LIMITS.substeps),anchorTrack: sheet.pinTo ? sampleAnchorTrack(sheet.pinTo, pinned, worldPositions, worldMatricesAt, times) : new Float64Array(0),colliderCount: specs.length,colliderTrack: movingSetup.colliderTrack,@@ -426,7 +428,7 @@ function bakeSheet(sheet, cloth, node, geometry, colliders, frameCount, movingSestiffnessWeights: stiffnessWeights(sheet, geometry, welded.representatives), softBody: sheet.softBody, selfCollision: sheet.selfCollision,gravity: cloth.gravity, wind: cloth.wind, fields: cloth.fields, stiffness: sheet.stiffness, bend: sheet.bend, bendModel: sheet.bendModel,bendYield: sheet.bendYield, bendSet: sheet.bendSet,- density: sheet.density, damping: sheet.damping, friction: sheet.friction, thickness: sheet.thickness,+ density: sheet.density, damping: sheet.damping, friction: sheet.friction, staticFriction: sheet.staticFriction, thickness: sheet.thickness,colliders, frameCount, framesPerSecond: FRAMES_PER_SECOND,}], bakeClothWithFields) });return { recording, welded, inverse: mat4.invert(mat4.create(), matrix), geometry, particleScratch: new Float32Array(recording.particleCount * 3), live: liveGeometry(geometry) };diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex edc74ff3..81a6d7f8 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -313,7 +313,7 @@ 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. Colliders { node, shape ball|box } fit geometry bounds; like sheets they are root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. Sheet pinGroup: a vertex group whose vertices (weight 0.5 or more) are held. Sheet pinTo { node, weight } rides pinned edges on a node. Sheet stiffnessGroup: vertex group whose weights scale stiffness (floor 0.05). Sheet softBody { shape 0-1 (0.2), pressure 0-3 (1), bounce 0-1 (0) }: shape matching plus a volume term; pressure needs a closed mesh, a node with an open mesh fails and says to set pressure 0. bounce is the share of its landing speed the body keeps when it turns around; lower shape or sheet stiffness makes a softer, deeper dent. Sheet bendModel distance (default) or dihedral: dihedral holds the angle between neighbouring triangles, so a fine sheet folds in many soft ripples instead of one crease; set bend about 0.15 with it. Sheet bendYield (radians, dihedral only, off by default) lets a fold keep its crease: past that bend angle the rest angle follows the cloth by bendSet (0-1, 0.1) of the excess each substep, so a crumpled sheet stays crumpled. Sheet selfCollision true: particles of the sheet push apart (radius 0.9 of half the shortest edge, or the sheet thickness when set, up to 5000 particles); cloth does not collide with other sheets.',+ notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Colliders { node, shape ball|box } fit geometry bounds; like sheets they are root nodes without a motion track or body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude }. Sheet pinGroup: a vertex group whose vertices (weight 0.5 or more) are held. Sheet pinTo { node, weight } rides pinned edges on a node. Sheet stiffnessGroup: vertex group whose weights scale stiffness (floor 0.05). Sheet softBody { shape 0-1 (0.2), pressure 0-3 (1), bounce 0-1 (0) }: shape matching plus a volume term; pressure needs a closed mesh, a node with an open mesh fails and says to set pressure 0. bounce is the share of its landing speed the body keeps when it turns around; lower shape or sheet stiffness makes a softer, deeper dent. Sheet bendModel distance (default) or dihedral: dihedral holds the angle between neighbouring triangles, so a fine sheet folds in many soft ripples instead of one crease; set bend about 0.15 with it. Sheet bendYield (radians, dihedral only, off by default) lets a fold keep its crease: past that bend angle the rest angle follows the cloth by bendSet (0-1, 0.1) of the excess each substep, so a crumpled sheet stays crumpled. Sheet pinTo.releaseAt (seconds, optional) lets the pinned edges go at that time and fall with the rest. Sheet staticFriction (0-1, 0) holds cloth still on a collider when its sideways travel is under that multiple of the contact depth, so it rests on a slope below its friction angle. Sheet selfCollision true: particles of the sheet push apart (radius 0.9 of half the shortest edge, or the sheet thickness when set, up to 5000 particles); cloth does not collide with other sheets.',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.diff --git a/src/cloth.js b/src/cloth.jsindex 340d55ea..daadf10f 100644--- a/src/cloth.js+++ b/src/cloth.js@@ -302,7 +302,7 @@ const PUSH_OUT = { ball: pushOutOfBall, capsule: pushOutOfCapsule, box: pushOutO// `contactNormals` (3 numbers per particle, or null) keeps the normal of the last collider each particle touched this// substep, so a bounce can send it back off the surface; it is zero where nothing was touched.-function collide(state, previous, colliders, thickness, friction, contactNormals) {+function collide(state, previous, colliders, thickness, friction, contactNormals, staticFriction = 0) {const { positions, inverseMasses, particleCount } = state;const point = [0, 0, 0];const normal = [0, 0, 0];@@ -313,6 +313,9 @@ function collide(state, previous, colliders, thickness, friction, contactNormalspoint[1] = positions[offset + 1];point[2] = positions[offset + 2];for (const collider of colliders) {+ const beforeX = point[0];+ const beforeY = point[1];+ const beforeZ = point[2];const touched = PUSH_OUT[collider.kind](point, collider, thickness, normal);if (!touched) continue;if (contactNormals) {@@ -323,8 +326,14 @@ function collide(state, previous, colliders, thickness, friction, contactNormals// Friction removes part of the sideways travel this substep, so cloth drags over a surface instead of skating.const travel = [point[0] - previous[offset], point[1] - previous[offset + 1], point[2] - previous[offset + 2]];const along = travel[0] * normal[0] + travel[1] * normal[1] + travel[2] * normal[2];+ // Static friction (Coulomb, as in position based dynamics): a sideways travel no longer than staticFriction times the depth the+ // contact pushed the particle out is held completely, so a layer rests on the floor and on a slope below its friction angle.+ const depth = Math.hypot(point[0] - beforeX, point[1] - beforeY, point[2] - beforeZ);+ const sideways = Math.hypot(travel[0] - along * normal[0], travel[1] - along * normal[1], travel[2] - along * normal[2]);+ const held = staticFriction > 0 && sideways <= staticFriction * depth;+ const grip = held ? 1 : friction;for (let axis = 0; axis < 3; axis++) {- point[axis] -= (travel[axis] - along * normal[axis]) * friction;+ point[axis] -= (travel[axis] - along * normal[axis]) * grip;}}positions[offset] = point[0];@@ -408,6 +417,14 @@ function followAnchors(positions, moving, targets, softOnly) {}}+// From its release substep on, the anchored particles are ordinary cloth: they keep their speed and fall with the rest.+function releaseAnchors(cloth, moving) {+ moving.anchorParticles.forEach(particle => {+ cloth.trackFixed[particle] = 0;+ setParticleInverseMass(cloth, particle);+ });+}+function checkWork(particleCount, constraintCount, triangleCount, colliderCount, frameCount, extraPerIteration = 0) {const work = frameCount * CLOTH_LIMITS.substeps * (CLOTH_LIMITS.iterations * (constraintCount + extraPerIteration) + triangleCount + particleCount * (colliderCount + 1));if (particleCount > CLOTH_LIMITS.maxParticles) {@@ -528,6 +545,8 @@ function tearOverstretched(cloth, substepSeconds) {* `bakeCloth` records from: the same positions and options step to the same frames. Arguments and options are those of* `bakeCloth`, plus:* - bendYield (radians, needs bendModel 'dihedral') and bendSet (0 to 1, default 0.1): past that bend angle a fold keeps bendSet of the excess as its new rest angle each substep, so creases stay (default off: the sheet pulls its folds flat).+ * - staticFriction (0 to 1, default 0): sideways travel up to this multiple of the contact depth is held completely on a collider, so cloth rests on a slope below its friction angle.+ * - moving.releaseSubstep (default never): the substep from which the anchors are let go.* - 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),@@ -585,6 +604,7 @@ export function createCloth(positions, triangles, options = {}) {const gravity = options.gravity ?? GRAVITY_DEFAULT;const damping = options.damping ?? 0.3;const friction = options.friction ?? 0.3;+ const staticFriction = checkUnit(options.staticFriction ?? 0, 'staticFriction', 1);const thickness = options.thickness ?? 0.01;const previous = new Float64Array(positions.length);const contactNormals = extras.bounce > 0 ? new Float64Array(positions.length) : null;@@ -596,6 +616,7 @@ export function createCloth(positions, triangles, options = {}) {const anchorStride = (moving?.anchorParticles.length ?? 0) * 3;const colliderStride = (moving?.colliderCount ?? 0) * MOVING_COLLIDER_NUMBERS;let substepsDone = 0;+ let anchorsReleased = false;function step(deltaSeconds, frame = {}) {const wind = frame.wind ?? options.wind ?? [0, 0, 0];@@ -614,10 +635,14 @@ export function createCloth(positions, triangles, options = {}) {previous.set(state.positions);let activeColliders = stepColliders;let anchorTargets = null;+ if (moving && !anchorsReleased && substepsDone >= moving.releaseSubstep) {+ releaseAnchors(cloth, moving);+ anchorsReleased = true;+ }if (moving) {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);+ if (!anchorsReleased) 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;@@ -644,8 +669,8 @@ export function createCloth(positions, triangles, options = {}) {solveDistances(state.positions, inverseMasses, constraints, cloth.impulses, pinImpulses);if (constraints.dihedrals && iteration % DIHEDRAL_EVERY === 0) solveDihedrals(state.positions, inverseMasses, constraints.dihedrals);extras.duringIteration(state.positions, inverseMasses);- if (moving) followAnchors(state.positions, moving, anchorTargets, true);- collide(state, previous, activeColliders, thickness, friction, contactNormals);+ if (moving && !anchorsReleased) followAnchors(state.positions, moving, anchorTargets, true);+ collide(state, previous, activeColliders, thickness, friction, contactNormals, staticFriction);}if (bendYield !== null) setDihedralCreases(state.positions, constraints.dihedrals, bendYield, bendSet);if (tears) tearOverstretched(cloth, substepSeconds);diff --git a/tests/cloth-friction.test.js b/tests/cloth-friction.test.jsnew file mode 100644index 00000000..1428c754--- /dev/null+++ b/tests/cloth-friction.test.js@@ -0,0 +1,81 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createCloth } from '../src/cloth.js';+import { createAgentScene } from '../src/agent-scene.js';+import './support/load-agent-scene-modules.mjs';+import { foldingFlagRecipe } from '../scripts/soft-body-film.mjs';++// A 5 by 5 grid, 0.2 m across, lying on a slope tilted `degrees` about the Z axis and 2 mm above its top face (the box is 1 m thick).+function sheetOnSlope(degrees) {+ const angle = degrees * Math.PI / 180;+ const segments = 4;+ const side = segments + 1;+ const along = [Math.cos(angle), -Math.sin(angle), 0];+ const up = [Math.sin(angle), Math.cos(angle), 0];+ const positions = new Float64Array(side * side * 3);+ for (let row = 0; row < side; row++) {+ for (let column = 0; column < side; column++) {+ const x = (column / segments - 0.5) * 0.2;+ const z = (row / segments - 0.5) * 0.2;+ positions.set([along[0] * x + up[0] * 0.502, along[1] * x + up[1] * 0.502, z], (row * side + column) * 3);+ }+ }+ const triangles = [];+ for (let row = 0; row < segments; row++) {+ for (let column = 0; column < segments; column++) {+ const corner = row * side + column;+ triangles.push(corner, corner + side, corner + 1, corner + 1, corner + side, corner + side + 1);+ }+ }+ const slope = { kind: 'box', center: [0, 0, 0], axes: [along, up, [0, 0, 1]], halfExtents: [3, 0.5, 3] };+ return { positions, triangles: Uint32Array.from(triangles), slope };+}++// How far the sheet's centre slides along the slope in `seconds`.+function slideAlongSlope(degrees, seconds, options) {+ const { positions, triangles, slope } = sheetOnSlope(degrees);+ const cloth = createCloth(positions, triangles, { colliders: [slope], thickness: 0.002, ...options });+ const centre = () => cloth.positions.reduce((sum, value, index) => (index % 3 === 0 ? sum + value : sum), 0) / cloth.particleCount;+ const start = centre();+ for (let step = 0; step < seconds * 60; step++) cloth.step(1 / 60);+ return Math.abs(centre() - start) / Math.cos(degrees * Math.PI / 180);+}++test('static friction holds a sheet on a slope below the friction angle and lets it slide above it', context => {+ const held = slideAlongSlope(25, 2, { staticFriction: 1, friction: 0.05 });+ const slidingWithout = slideAlongSlope(25, 2, { friction: 0.05 });+ const slidingSteep = slideAlongSlope(60, 2, { staticFriction: 1, friction: 0.05 });+ context.diagnostic(`slid ${held.toFixed(4)} m at 25 degrees with static friction, ${slidingWithout.toFixed(3)} m without, ${slidingSteep.toFixed(3)} m at 60 degrees with it`);+ assert.ok(held < 0.005, `a 25 degree slope with staticFriction 1 holds the sheet (slid ${held} m)`);+ assert.ok(slidingWithout > 0.1, `without static friction the sheet slides (${slidingWithout} m)`);+ assert.ok(slidingSteep > 0.1, `above the friction angle (45 degrees) the sheet still slides (${slidingSteep} m)`);+ assert.equal(slideAlongSlope(25, 2, { staticFriction: 1, friction: 0.05 }), held, 'it is deterministic');+});++test('a recipe sheet takes staticFriction and pinTo.releaseAt, and a pin let go falls with the rest', () => {+ const recipe = foldingFlagRecipe({ fine: true });+ recipe.geometries[0].segments = 8;+ const sheet = recipe.cloth.sheets[0];+ assert.equal(sheet.staticFriction, 1);+ assert.equal(sheet.pinTo.releaseAt, 0.8);+ const heightOfCorner = (releaseAt, time) => {+ recipe.cloth.sheets[0].pinTo = { node: 'pole', ...(releaseAt === undefined ? {} : { releaseAt }) };+ recipe.cloth.sheets[0].selfCollision = false;+ const scene = createAgentScene(recipe);+ scene.sampleMotion(time);+ const positions = scene.parts.find(part => part.name === 'flag').geometry.positions;+ let highest = -Infinity;+ for (let index = 1; index < positions.length; index += 3) highest = Math.max(highest, positions[index]);+ return highest;+ };+ // Held, the top edge rides the pole; released at 0.2 s it falls free, so the highest point at 0.5 s differs.+ const held = heightOfCorner(undefined, 0.5);+ const released = heightOfCorner(0.2, 0.5);+ assert.notEqual(held, released, 'letting go changes where the sheet ends');+ assert.equal(heightOfCorner(0.2, 0.5), released, 'it is deterministic');+ recipe.cloth.sheets[0].staticFriction = 2;+ assert.throws(() => createAgentScene(recipe), /staticFriction/);+ recipe.cloth.sheets[0].staticFriction = 1;+ recipe.cloth.sheets[0].pinTo = { node: 'pole', releaseAt: -1 };+ assert.throws(() => createAgentScene(recipe), /releaseAt/);+});diff --git a/tests/soft-body-film.test.js b/tests/soft-body-film.test.jsindex 08a300c0..5f18e721 100644--- a/tests/soft-body-film.test.js+++ b/tests/soft-body-film.test.js@@ -106,6 +106,15 @@ test('a 64 by 64 flag with dihedral bending and creases folds softly, keeps itsconst settling = touch * 2;const spreadSettling = normalSpread(film.frames[settling], indices);assert.ok(spreadAtRest >= spreadSettling - 0.05, `the flag is as crumpled at rest (${spreadAtRest}) as at settling (${spreadSettling}), within 0.05`);+ // The heap rests: nothing is pinned or pushed after the landing, so the layer 1 s after settling is the layer at the end (it used to spread flat again).+ const spreadLater = normalSpread(film.frames[settling + 60], indices);+ assert.ok(Math.abs(spreadAtRest - spreadLater) < 0.03, `the heap keeps its shape from 1 s after settling to the end (spread ${spreadLater} then ${spreadAtRest})`);+ const footprint = axis => {+ const values = [];+ for (let index = axis; index < film.frames[last].length; index += 3) values.push(film.frames[last][index]);+ return Math.max(...values) - Math.min(...values);+ };+ assert.ok(footprint(2) < 0.7, `the cloth lies as a compact heap, under 0.7 m deep (the sheet is 1 m tall), got ${footprint(2)} m`);const foldsAtRest = foldCrossings(film.frames[last], 64);assert.ok(foldsAtRest.row >= 15 && foldsAtRest.column >= 15, `a line across the rest layer crosses many folds (row ${foldsAtRest.row}, column ${foldsAtRest.column})`);@@ -114,8 +123,8 @@ test('a 64 by 64 flag with dihedral bending and creases folds softly, keeps itsrestHeights.sort((low, high) => low - high);const heightAt = share => restHeights[Math.floor(share * (restHeights.length - 1))];const highest = restHeights.at(-1);- assert.ok(highest < 0.08, `the rest layer is under 8 cm at its highest point, got ${highest} m`);- assert.ok(heightAt(0.5) > 0.003 && heightAt(0.5) < 0.012, `half of the cloth lies within 1.2 cm of the floor but not pressed flat (over 3 mm), got ${heightAt(0.5)} m`);+ assert.ok(highest < 0.12, `the rest heap is under 12 cm at its highest point, got ${highest} m`);+ assert.ok(heightAt(0.5) > 0.003 && heightAt(0.5) < 0.016, `half of the cloth lies within 1.6 cm of the floor but not pressed flat (over 3 mm), got ${heightAt(0.5)} m`);assert.ok(highest < heightAt(0.9) * 6, `no spike: the highest point (${highest} m) stays within 6 times the 90th percentile (${heightAt(0.9)} m)`);let closest = Infinity;