Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Cut repeated bakes in the slowest test files (#995)

Nguyen Xuan An395beec3900f
diff --git a/scripts/soft-body-film.mjs b/scripts/soft-body-film.mjs
index 1ca7388f..54cb5610 100644
--- a/scripts/soft-body-film.mjs
+++ b/scripts/soft-body-film.mjs
@@ -150,7 +150,8 @@ export function clothVertices(scene, node, time) {
/**
* Bakes a recipe and samples every frame. Returns the world vertex buffer of each frame, a hash of each frame, and
- * the milliseconds of the whole bake (scene creation plus the first sample) and of every later sample.
+ * the milliseconds of the whole bake (scene creation plus the first sample) and of every later sample, and the triangle indices of the
+ * cloth node so a caller does not bake the recipe again just to read them.
*/
export function recordFilm(recipe, nodeId, frameCount) {
const node = recipe.nodes.find(candidate => candidate.id === nodeId);
@@ -165,7 +166,8 @@ export function recordFilm(recipe, nodeId, frameCount) {
sampleMilliseconds.push(performance.now() - sampleStarted);
}
const hashes = frames.map(frame => createHash('sha256').update(Buffer.from(frame.buffer)).digest('hex'));
- return { frames, hashes, bakeMilliseconds, sampleMilliseconds };
+ const indices = scene.parts.find(part => part.name === node.id).geometry.indices;
+ return { frames, hashes, bakeMilliseconds, sampleMilliseconds, indices };
}
/** Lowest, highest and extent of a vertex buffer along one axis (0 x, 1 y, 2 z). */
diff --git a/tests/agent-bake.test.js b/tests/agent-bake.test.js
index a4fc1180..1af13853 100644
--- a/tests/agent-bake.test.js
+++ b/tests/agent-bake.test.js
@@ -6,6 +6,13 @@ import { normalizeAgentBake } from '../src/agent-bake.js';
import { BAKE_PRESETS } from '../src/agent-scene-capabilities.js';
import { closedRoom, closedRoomWithoutBake, lightmapBytes } from './support/agent-bake-rooms.mjs';
+// One baked room for the tests that only read a scene (inspect, parts, bytes) or call an apply that throws. A test that edits a scene makes its own.
+let sharedRoom = null;
+function sharedBakedRoom() {
+ sharedRoom ??= createAgentScene(closedRoom());
+ return sharedRoom;
+}
+
test('bake presets and fields resolve to plain numbers within their ranges', () => {
assert.deepEqual(normalizeAgentBake({ preset: 'fine' }), { ...BAKE_PRESETS.fine, probes: 'room' });
assert.deepEqual(normalizeAgentBake({}), { ...BAKE_PRESETS.standard, probes: 'room' });
@@ -25,7 +32,7 @@ test('bake rejects hostile and out of range fields', () => {
});
test('a recipe bake lights the room with lightmaps and reports its time and skipped parts', () => {
- const scene = createAgentScene(closedRoom());
+ const scene = sharedBakedRoom();
const bake = scene.inspect().bake;
assert.equal(bake.reused, false);
assert.ok(Number.isFinite(bake.seconds) && bake.seconds >= 0);
@@ -42,7 +49,7 @@ test('a recipe bake lights the room with lightmaps and reports its time and skip
});
test('the same recipe gives the same lightmap bytes', () => {
- const first = createAgentScene(closedRoom());
+ const first = sharedBakedRoom();
const second = createAgentScene(closedRoom());
for (const name of ['floor', 'back', 'block']) {
const firstBytes = lightmapBytes(first.parts.find(part => part.name === name));
@@ -81,14 +88,14 @@ test('moving a part, changing a light or changing the bake runs it again, and cl
});
test('a failed bake leaves the scene as it was', () => {
- const scene = createAgentScene(closedRoom());
+ const scene = sharedBakedRoom();
assert.throws(() => scene.apply([{ type: 'set-bake', bake: { samples: 5000 } }], { expectedRevision: 0 }));
assert.equal(scene.revision, 0);
assert.equal(scene.inspect().bake.samples, BAKE_PRESETS.draft.samples);
});
test('a bake names the local volumes it leaves out and a scene without volumes reports as before', () => {
- const plain = createAgentScene(closedRoom()).inspect().bake;
+ const plain = sharedBakedRoom().inspect().bake;
assert.equal(plain.skippedLocalVolumes, undefined);
assert.equal(plain.warnings, undefined);
diff --git a/tests/cloth-moving.test.js b/tests/cloth-moving.test.js
index ed7e7e36..f5327b51 100644
--- a/tests/cloth-moving.test.js
+++ b/tests/cloth-moving.test.js
@@ -11,9 +11,9 @@ import { CAPE, CAPE_THICKNESS, WALK_SECONDS, walkingCapeRecipe } from './support
const FRAMES_PER_SECOND = 60;
const PENETRATION_TOLERANCE = 0.002;
-// World matrices of the walker's nodes at a time, composed here from the motion sampler so the check does not lean on the cloth module's pose code.
-function createPoser(recipe) {
- const exported = createAgentScene(recipe).exportRecipe();
+// World matrices of the walker's nodes at a time (read from a scene still at its authored pose, so there is no second cloth bake), composed here from the motion sampler so the check does not lean on the cloth module's pose code.
+function createPoser(scene) {
+ const exported = scene.exportRecipe();
const nodes = [...exported.armatures.flatMap(armatureNodes), ...exported.nodes];
const byId = new Map(nodes.map(node => [node.id, node]));
const sampler = compileAgentMotion(exported.motion, { ...exported, nodes });
@@ -81,7 +81,7 @@ function capeWorldVertices(scene, nodeId = 'cape') {
function walkMeasure(cloth) {
const recipe = walkingCapeRecipe(cloth);
const scene = createAgentScene(recipe);
- const poser = createPoser(recipe);
+ const poser = createPoser(scene);
const rest = capeWorldVertices(scene);
let deepest = Infinity;
let travelled = 0;
@@ -110,7 +110,7 @@ test('a cape pinned to a walking humanoid never enters the limb capsules in a 5
test('the pinned top edge stays on the chest while the walker moves', () => {
const scene = createAgentScene(walkingCapeRecipe(CAPE));
- const poser = createPoser(walkingCapeRecipe(CAPE));
+ const poser = createPoser(scene);
const offsets = [];
for (const time of [0, 1.7, 4.2]) {
scene.sampleMotion(time);
diff --git a/tests/native-fallback-job.test.js b/tests/native-fallback-job.test.js
index 79f25e58..ccc6cde2 100644
--- a/tests/native-fallback-job.test.js
+++ b/tests/native-fallback-job.test.js
@@ -58,8 +58,8 @@ test('a native job without the native tracer runs the cpu backend with the same
{ skip: (!hasBuild && 'run npm run build:lib first') || (!hasBrowser && 'no Chrome'), timeout: 600000 }, async context => {
const workDirectory = await mkdtemp(join(tmpdir(), '67js-native-fallback-'));
context.after(() => rm(workDirectory, { recursive: true, force: true }));
- const cpu = await renderDemoRoom('cpu', workDirectory);
- const native = await renderDemoRoom('native', workDirectory);
+ // The two renders share nothing (own server, own job folder, own image file), so they run side by side.
+ const [cpu, native] = await Promise.all([renderDemoRoom('cpu', workDirectory), renderDemoRoom('native', workDirectory)]);
assert.equal(native.report.backend, 'cpu');
assert.match(native.report.backendNote, /switched off by JS67_NATIVE_TRACER=off.*cpu backend ran instead/);
assert.equal(cpu.report.backendNote, undefined);
diff --git a/tests/soft-body-film.test.js b/tests/soft-body-film.test.js
index 5f18e721..093d12a8 100644
--- a/tests/soft-body-film.test.js
+++ b/tests/soft-body-film.test.js
@@ -1,7 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
-import { createAgentScene } from '../src/agent-scene.js';
import { FILM_FRAMES_PER_SECOND, FINE_FLAG_FILM_SECONDS, FLAG_FILM_SECONDS, axisRange, foldCrossings, foldingFlagRecipe, jellyCubeRecipe, measureLanding, normalSpread, 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
@@ -9,6 +8,14 @@ import { FILM_FRAMES_PER_SECOND, FINE_FLAG_FILM_SECONDS, FLAG_FILM_SECONDS, axis
const JELLY_FRAMES = 120;
const FLAG_FRAMES = FLAG_FILM_SECONDS * FILM_FRAMES_PER_SECOND;
const FLAG_SAMPLE_EVERY = 12;
+// The default 38 by 38 flag films are baked once per file and shared by the flag test and the digest test. Each is a pure function of its
+// recipe (the determinism test below bakes a second copy on purpose), so a second bake in the digest test would only repeat the same work.
+const flagFilms = new Map();
+function flagFilm(options = {}) {
+ const key = JSON.stringify(options);
+ if (!flagFilms.has(key)) flagFilms.set(key, recordFilm(foldingFlagRecipe(options), 'flag', FLAG_FRAMES));
+ return flagFilms.get(key);
+}
function milliseconds(value) {
return Number(value.toFixed(2));
}
@@ -39,13 +46,13 @@ test('measureLanding names the problem when the body never reaches the floor', (
});
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 first = flagFilm();
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');
const last = FLAG_FRAMES - 1;
assert.ok(Buffer.from(first.frames[last].buffer).equals(Buffer.from(second.frames[last].buffer)));
- const indices = createAgentScene(foldingFlagRecipe()).parts.find(part => part.name === 'flag').geometry.indices;
+ const indices = first.indices;
const restHeight = axisRange(first.frames[0], 1).extent;
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}`);
@@ -73,7 +80,7 @@ test('a flag dropped by its pole falls to the floor and ends as a thin layer who
assert.ok(heightAt(0.9) > 0.02, `a tenth of the cloth stands in folds above 2 cm, got ${heightAt(0.9)} 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 without = flagFilm({ selfCollision: false });
let closestWith = Infinity;
let closestWithout = Infinity;
for (let frame = touch; frame < FLAG_FRAMES; frame += FLAG_SAMPLE_EVERY) {
@@ -92,7 +99,7 @@ test('a 64 by 64 flag with dihedral bending and creases folds softly, keeps its
const frameCount = FINE_FLAG_FILM_SECONDS * FILM_FRAMES_PER_SECOND;
const recipe = foldingFlagRecipe({ fine: true });
const film = recordFilm(recipe, 'flag', frameCount);
- const indices = createAgentScene(recipe).parts.find(part => part.name === 'flag').geometry.indices;
+ const indices = film.indices;
const last = frameCount - 1;
assert.equal(film.frames[0].length / 3, 64 * 64, 'the sheet has 4096 particles');
@@ -139,7 +146,7 @@ test('a 64 by 64 flag with dihedral bending and creases folds softly, keeps its
test('the default flag films keep their exact frames (sha256 over every frame of the 38 by 38 flag, with and without self collision)', () => {
const digestOf = options => {
- const record = recordFilm(foldingFlagRecipe(options), 'flag', FLAG_FRAMES);
+ const record = flagFilm(options);
const digest = createHash('sha256');
record.hashes.forEach(frameDigest => digest.update(frameDigest));
return digest.digest('hex');