Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Make the folding flag film behave like cloth: thin layers, dragged to the floor (#696)

Nguyen Xuan An7bab16dd57a5
diff --git a/changes/696-thin-cloth-layers.md b/changes/696-thin-cloth-layers.md
new file mode 100644
index 00000000..e5218378
--- /dev/null
+++ b/changes/696-thin-cloth-layers.md
@@ -0,0 +1 @@
+- A cloth sheet with `selfCollision: true` and its own `thickness` stacks folded layers `2 x thickness` apart (never past half the shortest edge), so a flag dropped to the floor lies as a thin crumpled layer; sheets that set no thickness are unchanged (#696)
diff --git a/changes/696-thin-cloth-layers.size.md b/changes/696-thin-cloth-layers.size.md
new file mode 100644
index 00000000..5d3bb443
--- /dev/null
+++ b/changes/696-thin-cloth-layers.size.md
@@ -0,0 +1,3 @@
+- entry:cloth: the self collision radius reads the sheet thickness, a four-line helper, so thin cloth can fold in layers 1 cm apart instead of about 4 cm.
+- tool-cost: the scene_capabilities cloth note gains nine words saying that thickness sets the self collision radius.
+- goal:agent-scene: 12 bytes of capability text tell agents that a sheet's thickness sets the self collision layer spacing, which they need to build a thin folded cloth.
diff --git a/docs/physics.md b/docs/physics.md
index e717a500..0a93eecc 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -430,7 +430,7 @@ A recipe `cloth` section records deformable sheets with a position-based solver
- `{ "attach": "leftHand", "shape": "ball", "radius": 0.08, "offset": [0, 0, 0] }` is a ball on a node. `{ "attach": "upperArm", "shape": "capsule", "to": "lowerArm", "radius": 0.05 }` runs a capsule from one node (plus `offset`) to another (plus `toOffset`). Radius 0.001 to 10 m.
- `{ "armature": "rig", "radiusFraction": 0.2, "exclude": ["head"] }` adds one capsule per bone, head to tail, the radius a fraction (0.02 to 0.5, default 0.2) of the bone length as the ragdoll fits it. A bone with no length is skipped.
- A sheet's `stiffnessGroup: "sleeve"` names a vertex group whose weights scale stretch and bend stiffness per vertex; a constraint is as stiff as the softer of its two ends, and a weight under 0.05 counts as 0.05 so the vertex does not drift off.
- - `selfCollision: true` makes the sheet's own particles push each other apart, so cloth folded over itself stays in layers instead of passing through. The contact radius is 0.9 of half the shortest edge, a spatial hash keeps it near linear, two particles joined by an edge are skipped, and a sheet over 2000 particles fails with the count and the fix. It is per particle, so a layer can still slip between particles on a mesh much coarser than the fold. The fold test (`tests/soft-body.test.js`) keeps every unjoined pair at least 0.8 of the contact distance apart; without it the same fold interpenetrates.
+ - `selfCollision: true` makes the sheet's own particles push each other apart, so cloth folded over itself stays in layers instead of passing through. The contact radius is 0.9 of half the shortest edge, or the sheet's `thickness` when the sheet sets one (never above half the shortest edge), so a thin cloth on a coarse grid stacks its layers 2 x thickness apart instead of about 4 cm; a scene that sets no thickness keeps the old radius byte for byte (`tests/cloth-self-collision-thickness.test.js`). a spatial hash keeps it near linear, two particles joined by an edge are skipped, and a sheet over 2000 particles fails with the count and the fix. It is per particle, so a layer can still slip between particles on a mesh much coarser than the fold. The fold test (`tests/soft-body.test.js`) keeps every unjoined pair at least 0.8 of the contact distance apart; without it the same fold interpenetrates.
- `softBody: { "shape": 0.2, "pressure": 1 }` turns the sheet node into a jelly: `shape` (0 to 1) pulls every particle toward the best rigid fit of the rest shape (shape matching, rotation extracted with a warm-started iteration), and `pressure` (0 to 3) is a volume constraint that holds that multiple of the rest volume. Use 1 for a jelly that keeps its volume and squashes on impact; below 1 the body deflates to that volume before it lands (0.85 is a body 15 percent smaller from the first frame), above 1 it inflates. Pressure needs a closed mesh (every edge in two triangles) and fails naming the open edge otherwise; set `pressure: 0` to keep only shape matching. A box or sphere geometry is closed. It rests on the colliders like cloth and bakes to the same frames every run.
- A sheet on a mesh geometry can hold chosen vertices with `pinGroup: "hem"`, the name of a vertex group made by a `vertex_group` mesh edit; vertices of weight 0.5 or more are pinned, on their own or together with `pin`. An unknown name fails and lists the groups the mesh has.
- A sheet's `pinTo: { "node": "chest", "weight": 1 }` makes the pinned edges (`pin`) ride that node, keeping their rest offset in its space. Weight 1 holds them on the node; 0.01 to under 1 pulls them toward it by that fraction on every pass, so they sag and lag.
@@ -443,10 +443,10 @@ A recipe `cloth` section records deformable sheets with a position-based solver
Soft 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.
-- Flag: a 24 by 24 grid, 1 m tall, hung by its top edge from a pole (`pinTo`) that drops 2.35 m, so the cloth piles on the floor with `selfCollision: true`. The pile is 0.547 m tall. The closest pair of particles not joined by an edge ends 7.9 mm apart; the same film without self collision ends 0.5 mm apart (layers merged).
+- Flag: a 24 by 24 grid, 1 m tall, hung by its top edge from a pole (`pinTo`) that swings out and down to the floor in 1.5 s, drags the cloth flat, then pushes back 0.4 m. The sheet sets `thickness: 0.005`, so its self collision layers stack 1 cm apart (the earlier film used the mesh-based 3.7 cm, left the pole held 0.25 m up, and piled a block 0.547 m tall). First touch is at step 66 (1.1 s); the final frame (step 239, 4 s) has every vertex under 0.0467 m above the floor, spread over 1.6 m by 0.8 m, with one rolled fold at the near edge. With `selfCollision: true` the closest pair of particles not joined by an edge is never under 5 mm apart in any sampled frame after touch (0.0096 m at the lowest sample); the same film without it comes down to 0.3 mm (layers merged).
- 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 2.5 to 6.8 ms a step over 120 steps, flag 20 to 37 ms a step over 150 steps (5.5 ms a step without self collision, 625 particles). Sampling a recorded frame for playback costs about 1 to 1.5 ms.
-- `node scripts/render-soft-body-film.mjs <folder>` (run it through gpu-lock) writes a 960 by 540, 60 fps preview MP4 of each film (one video frame per simulation step, so frame N is step N), stills at contact and at the deepest dent, `jelly-cube-compare.png` (both side by side with the measured width and height drawn on it) and `soft-body-film.json` with every number, its unit and its step. It needs `npm run build:lib` first. No default changes.
+- 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 27 to 29 ms a step over 240 steps (16 ms a step without self collision, 625 particles). Sampling a recorded frame for playback costs about 1.5 to 2 ms.
+- `node scripts/render-soft-body-film.mjs <folder>` (run it through gpu-lock) writes a 960 by 540, 60 fps preview MP4 of each film (one video frame per simulation step, so frame N is step N), stills at contact and at the deepest dent for the jelly and at mid fall, first touch and final rest for the flag, `jelly-cube-compare.png` (both side by side with the measured width and height drawn on it) and `soft-body-film.json` with every number, its unit and its step. It needs `npm run build:lib` first. No default changes.
Blender comparison (`scripts/blender-cloth.py`, Blender 5.2.2, default stiffness, mass set from the same kg/m2; `tests/cloth-blender.test.js`):
diff --git a/scripts/render-soft-body-film.mjs b/scripts/render-soft-body-film.mjs
index aa1f9807..bd53e814 100644
--- a/scripts/render-soft-body-film.mjs
+++ b/scripts/render-soft-body-film.mjs
@@ -10,7 +10,7 @@ import { setTimeout as delay } from 'node:timers/promises';
import { createAgentScene } from '../src/agent-scene.js';
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
-import { FILM_FRAMES_PER_SECOND, axisRange, foldingFlagRecipe, jellyCubeRecipe, measureLanding, recordFilm, unjoinedMinimumDistance } from './soft-body-film.mjs';
+import { FILM_FRAMES_PER_SECOND, FLAG_FILM_SECONDS, axisRange, foldingFlagRecipe, jellyCubeRecipe, measureLanding, recordFilm, unjoinedMinimumDistance } from './soft-body-film.mjs';
const PREVIEW = { width: 960, height: 540, fps: FILM_FRAMES_PER_SECOND };
const FONT_FILE = 'C\\:/Windows/Fonts/arial.ttf';
@@ -92,10 +92,12 @@ async function main() {
await mkdir(outputDirectory, { recursive: true });
const jellyFrames = 120;
- const flagFrames = 150;
+ const flagFrames = FLAG_FILM_SECONDS * FILM_FRAMES_PER_SECOND;
const jelly = filmNumbers(jellyCubeRecipe(), 'cube', jellyFrames);
const landing = measureLanding(jelly.record.frames, axisRange(jelly.record.frames[0], 1).extent);
const flag = filmNumbers(foldingFlagRecipe(), 'flag', flagFrames);
+ const flagTouch = measureLanding(flag.record.frames, axisRange(flag.record.frames[0], 1).extent).contact;
+ const flagMidFall = Math.round(flagTouch * 0.7);
const flagHash = flag.record.hashes[flagFrames - 1];
const jobsDirectory = join(tmpdir(), `67js-soft-body-film-${process.pid}`);
@@ -110,7 +112,7 @@ async function main() {
});
const flagFiles = await renderFilm(call, outputDirectory, {
name: 'folding-flag', recipe: foldingFlagRecipe(), nodeId: 'flag', frameCount: flagFrames, videoSeconds: flagFrames / FILM_FRAMES_PER_SECOND,
- stillTimes: { folded: (flagFrames - 1) / FILM_FRAMES_PER_SECOND },
+ stillTimes: { 'mid-fall': flagMidFall / FILM_FRAMES_PER_SECOND, 'first-touch': flagTouch / FILM_FRAMES_PER_SECOND, 'final-rest': (flagFrames - 1) / FILM_FRAMES_PER_SECOND },
});
const restFrame = jelly.record.frames[0];
const atContact = cubeSize(jelly.record.frames[landing.contact]);
@@ -141,6 +143,8 @@ dent ${landing.maxDentDepth.toFixed(4)} m`,
finalStep: lastFlagStep,
finalTimeSeconds: seconds(lastFlagStep),
restHeightMeters: meters(axisRange(flag.record.frames[0], 1).extent),
+ midFallStep: flagMidFall,
+ firstTouchStep: flagTouch,
pileHeightMeters: meters(axisRange(flag.record.frames[lastFlagStep], 1).extent),
closestUnjoinedGapMeters: {
atStep: lastFlagStep,
diff --git a/scripts/soft-body-film.mjs b/scripts/soft-body-film.mjs
index 2bc00b74..8aef3fc7 100644
--- a/scripts/soft-body-film.mjs
+++ b/scripts/soft-body-film.mjs
@@ -41,7 +41,22 @@ export function jellyCubeRecipe() {
});
}
-/** A flag hung from a pole by its top edge; the pole drops 2.35 m so the cloth piles into folds on the floor. */
+// The pole's path: a swing out and down so the flag ripples, a drag across the floor to lay it flat, then a short push back that crumples the near end.
+const POLE_KEYFRAMES = [
+ { time: 0, value: [0, 2.6, 0] },
+ { time: 0.3, value: [0, 2.6, 0] },
+ { time: 0.9, value: [0.25, 1.2, 0.4] },
+ { time: 1.5, value: [0, 0.012, 1] },
+ { time: 2.2, value: [0, 0.012, 1.3] },
+ { time: 3.2, value: [0, 0.012, 0.9] },
+ { time: 4, value: [0, 0.012, 0.9] },
+];
+export const FLAG_FILM_SECONDS = 4;
+
+/**
+ * A flag hung from a pole by its top edge. The pole swings down to the floor and drags the cloth flat, so it ends as a thin layer with
+ * a fold. The sheet sets thickness 5 mm, which also sets the self collision radius, so layers stack 1 cm apart instead of 3.7 cm.
+ */
export function foldingFlagRecipe({ selfCollision = true } = {}) {
return baseRecipe({
geometries: [{ id: 'flag', type: 'grid', segments: 24 }],
@@ -50,11 +65,11 @@ export function foldingFlagRecipe({ selfCollision = true } = {}) {
{ id: 'flag', geometry: 'flag', material: 'fabric', translation: [0, 2.1, 0], scale: [1.6, 1, 1] },
{ id: 'pole', translation: [0, 2.6, 0] },
],
- motion: { duration: 3, loop: false, tracks: [{ kind: 'node', id: 'pole', property: 'translation', interpolation: 'LINEAR', keyframes: [{ time: 0, value: [0, 2.6, 0] }, { time: 0.3, value: [0, 2.6, 0] }, { time: 1.6, value: [0, 0.25, 0] }, { time: 3, value: [0, 0.25, 0] }] }] },
- camera: { eye: [0.7, 0.8, 3.0], target: [0, 0.5, 0] },
+ motion: { duration: FLAG_FILM_SECONDS, loop: false, tracks: [{ kind: 'node', id: 'pole', property: 'translation', interpolation: 'LINEAR', keyframes: POLE_KEYFRAMES }] },
+ camera: { eye: [1.1, 1.1, 4.3], target: [0, 0.75, 0.4] },
cloth: {
- duration: 3,
- sheets: [{ node: 'flag', pin: ['top'], pinTo: { node: 'pole' }, selfCollision, stiffness: 0.9, bend: 0.2, damping: 1 }],
+ duration: FLAG_FILM_SECONDS,
+ sheets: [{ node: 'flag', pin: ['top'], pinTo: { node: 'pole' }, selfCollision, stiffness: 0.9, bend: 0.01, damping: 2.5, friction: 0.25, thickness: 0.005 }],
colliders: [{ node: 'ground', shape: 'box' }],
},
});
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index c82bff0f..6e17a610 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -312,7 +312,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) }: shape matching plus a volume term; pressure needs a closed mesh, a node with an open mesh fails and says to set pressure 0. Sheet selfCollision true: particles of the sheet push apart (radius 0.9 of half the shortest edge, up to 2000 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) }: shape matching plus a volume term; pressure needs a closed mesh, a node with an open mesh fails and says to set pressure 0. 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 2000 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.js
index 7a805fe3..4a82363e 100644
--- a/src/cloth.js
+++ b/src/cloth.js
@@ -51,6 +51,11 @@ function edgeKey(first, second, particleCount) {
}
// Stretch constraints along every edge, bend constraints between the far corners of two triangles sharing an edge.
+// A sheet that sets its own thickness gets contact layers that thick (never past the longest radius); without one the radius follows the mesh, as before.
+function defaultSelfCollisionRadius(longest, thickness) {
+ return thickness > 0 ? Math.min(thickness, longest) : longest * 0.9;
+}
+
function buildConstraints(positions, triangles, particleCount, bendStiffness, stretchStiffness, stiffnessWeights = null) {
const edgeNeighbours = new Map();
for (let corner = 0; corner < triangles.length; corner += 3) {
@@ -393,7 +398,7 @@ function prepareExtras(options, positions, triangles, particleCount, constraints
throw new RangeError(`Cloth selfCollision handles ${SELF_COLLISION_LIMITS.maxParticles} particles at most; this sheet has ${particleCount}. Use a coarser grid or drop selfCollision.`);
}
const longest = maxSelfCollisionRadius(constraints);
- const radius = selfCollision === true ? longest * 0.9 : selfCollision.radius;
+ const radius = selfCollision === true ? defaultSelfCollisionRadius(longest, options.thickness) : selfCollision.radius;
if (!(radius > 0 && radius <= longest)) {
throw new RangeError(`Cloth selfCollision.radius must be above 0 and at most ${longest.toPrecision(4)} (half the shortest edge); found ${radius}. Use a smaller radius or true.`);
}
diff --git a/tests/cloth-self-collision-thickness.test.js b/tests/cloth-self-collision-thickness.test.js
new file mode 100644
index 00000000..aa62ebc4
--- /dev/null
+++ b/tests/cloth-self-collision-thickness.test.js
@@ -0,0 +1,53 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createCloth } from '../src/cloth.js';
+
+const GROUND = { kind: 'box', center: [0, -1, 0], axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], halfExtents: [5, 1, 5] };
+const SPACING = 0.1;
+const SIDE = 5;
+
+// Two separate 5 by 5 sheets, the second hung 0.15 m straight above the first, so they land on each other.
+function twoStackedSheets() {
+ const perSheet = SIDE * SIDE;
+ const positions = new Float32Array(perSheet * 2 * 3);
+ const triangles = [];
+ for (let sheet = 0; sheet < 2; sheet++) {
+ const height = 0.05 + sheet * 0.15;
+ for (let row = 0; row < SIDE; row++) {
+ for (let column = 0; column < SIDE; column++) {
+ positions.set([column * SPACING, height, row * SPACING], (sheet * perSheet + row * SIDE + column) * 3);
+ }
+ }
+ for (let row = 0; row < SIDE - 1; row++) {
+ for (let column = 0; column < SIDE - 1; column++) {
+ const corner = sheet * perSheet + row * SIDE + column;
+ triangles.push(corner, corner + SIDE, corner + SIDE + 1, corner, corner + SIDE + 1, corner + 1);
+ }
+ }
+ }
+ return { positions, triangles: Uint32Array.from(triangles), perSheet };
+}
+
+function restingGap(options) {
+ const { positions, triangles, perSheet } = twoStackedSheets();
+ const cloth = createCloth(positions, triangles, { colliders: [GROUND], selfCollision: true, damping: 3, ...options });
+ for (let step = 0; step < 240; step++) cloth.step(1 / 60);
+ const middle = (SIDE * SIDE - 1) / 2;
+ return cloth.positions[(perSheet + middle) * 3 + 1] - cloth.positions[middle * 3 + 1];
+}
+
+test('a sheet that sets its thickness stacks layers 2 x thickness apart; without it the layers keep the mesh-based gap', () => {
+ const byDefault = restingGap({});
+ const thin = restingGap({ thickness: 0.01 });
+ assert.ok(Math.abs(byDefault - SPACING * 0.9) < 0.01, `default layers rest ${byDefault} m apart, near 0.9 x the edge length`);
+ assert.ok(Math.abs(thin - 0.02) < 0.004, `thickness 0.01 layers rest ${thin} m apart, near 0.02`);
+});
+
+test('a thickness beyond half the shortest edge is capped, so layers never fight the edge springs', () => {
+ const capped = restingGap({ thickness: 0.4 });
+ assert.ok(capped <= SPACING + 1e-3, `layers rest ${capped} m apart, at most one edge length`);
+});
+
+test('the thick-layer bake is deterministic', () => {
+ assert.equal(restingGap({ thickness: 0.01 }), restingGap({ thickness: 0.01 }));
+});
diff --git a/tests/soft-body-film.test.js b/tests/soft-body-film.test.js
index dda1b7ad..107fa06c 100644
--- a/tests/soft-body-film.test.js
+++ b/tests/soft-body-film.test.js
@@ -1,12 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAgentScene } from '../src/agent-scene.js';
-import { FILM_FRAMES_PER_SECOND, axisRange, foldingFlagRecipe, jellyCubeRecipe, measureLanding, recordFilm, unjoinedMinimumDistance } from '../scripts/soft-body-film.mjs';
+import { FILM_FRAMES_PER_SECOND, FLAG_FILM_SECONDS, axisRange, foldingFlagRecipe, jellyCubeRecipe, measureLanding, recordFilm, unjoinedMinimumDistance } from '../scripts/soft-body-film.mjs';
// Film tests for #696: each film is one recipe baked twice. The frames must match byte for byte, and the numbers a viewer
-// would see (the landing, the dent, the layers of the fold) are measured from the baked vertices, not read off a picture.
+// would see (the landing, the dent, the height and layers of the fold) are measured from the baked vertices, not read off a picture.
const JELLY_FRAMES = 120;
-const FLAG_FRAMES = 150;
+const FLAG_FRAMES = FLAG_FILM_SECONDS * FILM_FRAMES_PER_SECOND;
+const FLAG_SAMPLE_EVERY = 12;
function milliseconds(value) {
return Number(value.toFixed(2));
}
@@ -36,7 +37,7 @@ test('measureLanding names the problem when the body never reaches the floor', (
assert.throws(() => measureLanding(airborne, 1), /never reached the floor within 1 frames/);
});
-test('a flag lowered into folds is byte-identical across two bakes and keeps its layers apart', context => {
+test('a flag dropped by its pole falls to the floor and ends as a thin layer whose folds keep their layers apart', context => {
const first = recordFilm(foldingFlagRecipe(), 'flag', FLAG_FRAMES);
const second = recordFilm(foldingFlagRecipe(), 'flag', FLAG_FRAMES);
assert.deepEqual(first.hashes, second.hashes, 'two bakes of the same recipe give the same bytes in every frame');
@@ -45,15 +46,26 @@ test('a flag lowered into folds is byte-identical across two bakes and keeps its
const indices = createAgentScene(foldingFlagRecipe()).parts.find(part => part.name === 'flag').geometry.indices;
const restHeight = axisRange(first.frames[0], 1).extent;
- const pileHeight = axisRange(first.frames[last], 1).extent;
- assert.ok(pileHeight < restHeight * 0.6, `the flag folds from ${restHeight} m to a pile ${pileHeight} m tall`);
+ const touch = measureLanding(first.frames, restHeight).contact;
+ assert.ok(touch > 30 && touch < 90, `the hanging flag first touches the floor within frames 30 to 90, got ${touch}`);
+ const midFall = Math.round(touch * 0.7);
+ assert.ok(axisRange(first.frames[midFall], 1).extent > restHeight * 0.6, 'mid fall the flag is still hanging in the air');
+
+ const finalRange = axisRange(first.frames[last], 1);
+ assert.ok(finalRange.high < 0.055, `the flag ends no more than 5.5 cm above the floor, got ${finalRange.high} m`);
+ assert.ok(axisRange(first.frames[last], 2).extent > 0.7, 'the flag lies spread over the floor, not stacked in one place');
+
const without = recordFilm(foldingFlagRecipe({ selfCollision: false }), 'flag', FLAG_FRAMES);
- const gap = unjoinedMinimumDistance(first.frames[last], indices);
- const gapWithout = unjoinedMinimumDistance(without.frames[last], indices);
- assert.ok(gap > gapWithout * 5, `layers stay apart with self collision (${gap} m) and merge without it (${gapWithout} m)`);
- assert.ok(gap > 0.005, `the closest unjoined pair is ${gap} m apart`);
+ let closestWith = Infinity;
+ let closestWithout = Infinity;
+ for (let frame = touch; frame < FLAG_FRAMES; frame += FLAG_SAMPLE_EVERY) {
+ closestWith = Math.min(closestWith, unjoinedMinimumDistance(first.frames[frame], indices));
+ closestWithout = Math.min(closestWithout, unjoinedMinimumDistance(without.frames[frame], indices));
+ }
+ assert.ok(closestWith > 0.005, `with self collision no two unjoined particles come within 5 mm in any sampled frame (closest ${closestWith} m)`);
+ assert.ok(closestWithout < closestWith * 0.9, `without self collision the layers come closer (${closestWithout} m)`);
const bake = first.bakeMilliseconds;
- context.diagnostic(`flag: pile ${pileHeight.toFixed(3)} m from ${restHeight.toFixed(3)} m, closest unjoined pair ${gap.toFixed(4)} m (${gapWithout.toFixed(4)} m without self collision)`);
+ context.diagnostic(`flag: touch at frame ${touch}, final height ${finalRange.high.toFixed(4)} m from ${restHeight.toFixed(3)} m, closest unjoined pair ${closestWith.toFixed(4)} m (${closestWithout.toFixed(4)} m without self collision)`);
context.diagnostic(`flag: bake ${milliseconds(bake)} ms for ${FLAG_FRAMES} steps (${milliseconds(bake / FLAG_FRAMES)} ms a step with self collision, ${milliseconds(without.bakeMilliseconds / FLAG_FRAMES)} ms without)`);
});