Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Rebuild the machinery house on each quay crane of the hero port

Nguyen Xuan An9e67c64e04b8
diff --git a/docs/hero-loading.md b/docs/hero-loading.md
index e8d44baf..8d42ca01 100644
--- a/docs/hero-loading.md
+++ b/docs/hero-loading.md
@@ -26,6 +26,10 @@ A full world that fails to arrive or to build is asked for again after 4, 10 and
The options (`--near-pixels`, `--far-pixels` and others) are read by `parseArguments` in the script. The geometry the first view lacks lies outside the first 5 s of the flight, so `src/hero-lab/loop/hold.js` slows the flight from 2.5 s while the full world is pending and stops it at 5 s, until the full world is in (or has been given up on). The cost is that on a very slow link the frame is almost still for most of the wait (at 1.6 Mbit/s the first view appears at about 14 s and the swap lands at about 64 s); the alternative is holes at the edges of the picture, and the page before this change showed nothing at all for that time.
+## Fixing the world itself
+
+The first view is cut from the full world, so a flaw in the world shows in both. The quay cranes of the port were decimated when the world was exported, and the machinery house on each crane's rear girder collapsed into a four-triangle wedge. `scripts/fix-port-crane-rear.mjs` removes those wedges from `scene.rest.glb` and adds a real house to each crane (cladding with panel ribs, orange frame bands, a door, a ladder and a roof rail) and a cabinet on each A-frame, using only materials already in the file. Run it on `scene.rest.glb`, then rebuild the first view with `build-hero-first-view.mjs`. Every new house is its own mesh: the crop cuts a mesh in place from the pose of the first node that uses it, so a mesh shared by several nodes loses the geometry the others need.
+
## Measuring
```sh
diff --git a/public/showcase/port/scene.first.glb b/public/showcase/port/scene.first.glb
index e7350ef9..b01e5e6b 100644
Binary files a/public/showcase/port/scene.first.glb and b/public/showcase/port/scene.first.glb differ
diff --git a/public/showcase/port/scene.rest.glb b/public/showcase/port/scene.rest.glb
index af9d93e2..3e269459 100644
Binary files a/public/showcase/port/scene.rest.glb and b/public/showcase/port/scene.rest.glb differ
diff --git a/scripts/fix-port-crane-rear.mjs b/scripts/fix-port-crane-rear.mjs
new file mode 100644
index 00000000..bc4fdd0a
--- /dev/null
+++ b/scripts/fix-port-crane-rear.mjs
@@ -0,0 +1,382 @@
+// Rebuilds the machinery house on the rear girder of every ship-to-shore crane of the hero port, and the equipment cabinet on top of
+// each A-frame.
+//
+// node scripts/fix-port-crane-rear.mjs [--rest public/showcase/port/scene.rest.glb] [--dry-run]
+//
+// Why: the world export decimated the crane meshes, and the house of each crane (a 12-triangle box, 11.7 x 7.6 x 16.6 m) came out
+// as a 4-triangle tetrahedron with every texture coordinate at zero. It draws as a flat grey wedge that cuts through the orange
+// girder, with the roof vents and louvres floating beside it. The wedge is already in the world as first exported (commit
+// ab6cf7bd, before any hero script) and so in scene.rest.glb and scene.first.glb alike.
+//
+// What it does: finds those tetrahedra in the `sts_house` mesh of scene.rest.glb and removes them, then adds one machinery house
+// mesh (cladding with panel ribs, orange frame bands, a door, an access ladder, a roof rail) to six nodes, one per crane, and an
+// equipment cabinet on top of each A-frame. The new triangles use the materials already in the file, so the world gains no texture.
+// Rebuild the first view afterwards with `node scripts/build-hero-first-view.mjs`.
+// Running it twice is safe: a world that already has the houses is left alone.
+import { writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS, EXTMeshoptCompression } from '@gltf-transform/extensions';
+import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
+
+const SCRIPT_DIRECTORY = dirname(fileURLToPath(import.meta.url));
+export const DEFAULT_REST_PATH = resolve(SCRIPT_DIRECTORY, '..', 'public', 'showcase', 'port', 'scene.rest.glb');
+export const HOUSE_NODE_NAME = 'sts_machinery_house';
+export const APEX_NODE_NAME = 'sts_apex_cabinet';
+
+// The house of every crane sits on the same spot of the girder; only the crane's x differs. Metres, world axes (z grows toward the ship).
+export const HOUSE = {
+ halfWidth: 5.85,
+ floorY: 54.7,
+ roofY: 62.3,
+ rearZ: -52.4,
+ frontZ: -35.8,
+ roofThickness: 0.3,
+ roofOverhang: 0.2,
+};
+export const APEX = { beamY: 81.2, height: 2.0, halfWidth: 3.4, rearZ: -6.9, frontZ: -4.1 };
+const TEXTURE_TILE_METRES = 6;
+const DARK_STEEL_MATERIAL = 'rail_steel.001';
+const RAIL_MATERIAL = 'safety_yellow.001';
+const DEGENERATE_SEARCH = { minimumY: 54.0, maximumY: 62.6, minimumZ: -53, maximumZ: -35.3, halfWidth: 6.3 };
+
+const FACES = [
+ { name: 'right', axis: 0, sign: 1 },
+ { name: 'left', axis: 0, sign: -1 },
+ { name: 'top', axis: 1, sign: 1 },
+ { name: 'bottom', axis: 1, sign: -1 },
+ { name: 'front', axis: 2, sign: 1 },
+ { name: 'rear', axis: 2, sign: -1 },
+];
+
+class GeometryBucket {
+ constructor() {
+ this.positions = [];
+ this.normals = [];
+ this.uvs = [];
+ this.indices = [];
+ }
+
+ // An axis-aligned box. `skip` names the faces that stay closed off (not drawn); texture coordinates follow world position so the
+ // cladding tiles at the same scale on every face.
+ addBox(minimum, maximum, skip = ['bottom']) {
+ for (const face of FACES) {
+ if (skip.includes(face.name)) continue;
+ this.addFace(minimum, maximum, face);
+ }
+ }
+
+ addFace(minimum, maximum, face) {
+ const fixedValue = face.sign > 0 ? maximum[face.axis] : minimum[face.axis];
+ const [firstAxis, secondAxis] = [0, 1, 2].filter((axis) => axis !== face.axis);
+ const corners = [
+ [minimum[firstAxis], minimum[secondAxis]],
+ [maximum[firstAxis], minimum[secondAxis]],
+ [maximum[firstAxis], maximum[secondAxis]],
+ [minimum[firstAxis], maximum[secondAxis]],
+ ];
+ const normal = [0, 0, 0];
+ normal[face.axis] = face.sign;
+ const firstVertex = this.positions.length / 3;
+ for (const [first, second] of corners) {
+ const position = [0, 0, 0];
+ position[face.axis] = fixedValue;
+ position[firstAxis] = first;
+ position[secondAxis] = second;
+ this.positions.push(...position);
+ this.normals.push(...normal);
+ const horizontal = face.axis === 0 ? position[2] : position[0];
+ const vertical = face.axis === 1 ? position[2] : position[1];
+ this.uvs.push(horizontal / TEXTURE_TILE_METRES, vertical / TEXTURE_TILE_METRES);
+ }
+ // The corner order above runs counter-clockwise seen from +x and +z but from -y (the cross product of x and z points down),
+ // so flip it whenever the face looks the other way.
+ const counterClockwiseSign = face.axis === 1 ? -1 : 1;
+ const windingFlipped = face.sign !== counterClockwiseSign;
+ const order = windingFlipped ? [0, 2, 1, 0, 3, 2] : [0, 1, 2, 0, 2, 3];
+ for (const offset of order) this.indices.push(firstVertex + offset);
+ }
+
+ get triangleCount() {
+ return this.indices.length / 3;
+ }
+}
+
+// Everything of one house, in coordinates relative to the crane's centre line (x = 0) and absolute in y and z.
+export function buildMachineryHouse() {
+ const buckets = { sts_house: new GeometryBucket(), sts_paint: new GeometryBucket(), [DARK_STEEL_MATERIAL]: new GeometryBucket(), [RAIL_MATERIAL]: new GeometryBucket() };
+ const { halfWidth, floorY, roofY, rearZ, frontZ, roofThickness, roofOverhang } = HOUSE;
+ const wallTopY = roofY - roofThickness;
+ const cladding = buckets.sts_house;
+ const frame = buckets.sts_paint;
+ const dark = buckets[DARK_STEEL_MATERIAL];
+ const rail = buckets[RAIL_MATERIAL];
+
+ cladding.addBox([-halfWidth, floorY, rearZ], [halfWidth, wallTopY, frontZ]);
+ cladding.addBox([-halfWidth - roofOverhang, wallTopY, rearZ - roofOverhang], [halfWidth + roofOverhang, roofY, frontZ + roofOverhang]);
+
+ addPanelRibs(cladding, { halfWidth, floorY, wallTopY, rearZ, frontZ });
+ addFrameBands(frame, { halfWidth, floorY, wallTopY, rearZ, frontZ });
+ addDoor(frame, dark, { halfWidth, floorY, frontZ });
+ addLadder(dark, { halfWidth, floorY, roofY, frontZ });
+ addRoofRail(rail, { halfWidth, roofY, rearZ, frontZ });
+ return buckets;
+}
+
+function addPanelRibs(bucket, { halfWidth, floorY, wallTopY, rearZ, frontZ }) {
+ const ribWidth = 0.28;
+ const ribDepth = 0.12;
+ // On the long walls the ribs sit between the four louvre panels that are already in the world.
+ for (const sideSign of [-1, 1]) {
+ const wallX = sideSign * halfWidth;
+ for (const centreZ of [-48.35, -44.1, -39.85]) {
+ const near = sideSign > 0 ? wallX : wallX - ribDepth;
+ const far = sideSign > 0 ? wallX + ribDepth : wallX;
+ bucket.addBox([near, floorY, centreZ - ribWidth / 2], [far, wallTopY, centreZ + ribWidth / 2], ['bottom', sideSign > 0 ? 'left' : 'right']);
+ }
+ }
+ const endRibs = [{ wallZ: rearZ, sign: -1, positions: [-3.9, -1.3, 1.3, 3.9] }, { wallZ: frontZ, sign: 1, positions: [-1.3, 1.3] }];
+ for (const { wallZ, sign, positions } of endRibs) {
+ for (const centreX of positions) {
+ const near = sign > 0 ? wallZ : wallZ - ribDepth;
+ const far = sign > 0 ? wallZ + ribDepth : wallZ;
+ bucket.addBox([centreX - ribWidth / 2, floorY, near], [centreX + ribWidth / 2, wallTopY, far], ['bottom', sign > 0 ? 'rear' : 'front']);
+ }
+ }
+}
+
+// Orange corner posts, a skirt and an eave band tie the grey cladding to the crane's paint.
+function addFrameBands(bucket, { halfWidth, floorY, wallTopY, rearZ, frontZ }) {
+ const outset = 0.1;
+ const postSize = 0.4;
+ for (const sideSign of [-1, 1]) {
+ for (const [wallZ, endSign] of [[rearZ, -1], [frontZ, 1]]) {
+ const minimumX = sideSign > 0 ? halfWidth - postSize + outset : -halfWidth - outset;
+ const minimumZ = endSign > 0 ? wallZ - postSize + outset : wallZ - outset;
+ bucket.addBox([minimumX, floorY, minimumZ], [minimumX + postSize, wallTopY, minimumZ + postSize], ['bottom']);
+ }
+ }
+ const bands = [[floorY, floorY + 0.6], [wallTopY - 0.4, wallTopY]];
+ for (const [bottomY, topY] of bands) {
+ bucket.addBox([-halfWidth - outset, bottomY, rearZ - outset], [halfWidth + outset, topY, rearZ + 0.05], ['bottom']);
+ bucket.addBox([-halfWidth - outset, bottomY, frontZ - 0.05], [halfWidth + outset, topY, frontZ + outset], ['bottom']);
+ bucket.addBox([-halfWidth - outset, bottomY, rearZ], [-halfWidth + 0.05, topY, frontZ], ['bottom']);
+ bucket.addBox([halfWidth - 0.05, bottomY, rearZ], [halfWidth + outset, topY, frontZ], ['bottom']);
+ }
+}
+
+function addDoor(frameBucket, darkBucket, { floorY, frontZ }) {
+ const doorMinimumX = -4.45;
+ const doorMaximumX = -2.55;
+ const doorTopY = floorY + 3.3;
+ const frameWidth = 0.15;
+ const outset = 0.1;
+ darkBucket.addBox([doorMinimumX, floorY, frontZ], [doorMaximumX, doorTopY, frontZ + outset], ['bottom', 'rear']);
+ frameBucket.addBox([doorMinimumX - frameWidth, floorY, frontZ], [doorMinimumX, doorTopY + frameWidth, frontZ + outset + 0.02], ['bottom', 'rear']);
+ frameBucket.addBox([doorMaximumX, floorY, frontZ], [doorMaximumX + frameWidth, doorTopY + frameWidth, frontZ + outset + 0.02], ['bottom', 'rear']);
+ frameBucket.addBox([doorMinimumX, doorTopY, frontZ], [doorMaximumX, doorTopY + frameWidth, frontZ + outset + 0.02], ['bottom', 'rear']);
+}
+
+// A vertical ladder from the girder deck to the roof, rails standing off the wall on three brackets.
+function addLadder(bucket, { floorY, roofY, frontZ }) {
+ const centreX = 3.5;
+ const railSpacing = 0.5;
+ const railThickness = 0.08;
+ const standoff = 0.2;
+ const bottomY = floorY + 0.3;
+ const topY = roofY + 1.0;
+ for (const offset of [-railSpacing / 2, railSpacing / 2]) {
+ const x = centreX + offset;
+ bucket.addBox([x - railThickness / 2, bottomY, frontZ + standoff - railThickness / 2], [x + railThickness / 2, topY, frontZ + standoff + railThickness / 2], ['bottom', 'rear']);
+ }
+ for (let rungY = bottomY + 0.4; rungY < topY - 0.2; rungY += 0.45) {
+ bucket.addBox([centreX - railSpacing / 2, rungY, frontZ + standoff - 0.03], [centreX + railSpacing / 2, rungY + 0.05, frontZ + standoff + 0.03], ['bottom', 'rear']);
+ }
+ for (const bracketY of [bottomY + 0.8, (bottomY + topY) / 2, topY - 0.8]) {
+ bucket.addBox([centreX - railSpacing / 2 - 0.03, bracketY, frontZ], [centreX + railSpacing / 2 + 0.03, bracketY + 0.05, frontZ + standoff], ['bottom', 'rear']);
+ }
+}
+
+// A yellow hand rail round the roof edge, the way the cranes of a real terminal are fenced for roof work.
+function addRoofRail(bucket, { halfWidth, roofY, rearZ, frontZ }) {
+ const inset = 0.35;
+ const postSize = 0.08;
+ const postHeight = 1.1;
+ const minimumX = -halfWidth + inset;
+ const maximumX = halfWidth - inset;
+ const minimumZ = rearZ + inset;
+ const maximumZ = frontZ - inset;
+ const postPositions = [];
+ const alongZ = Math.round((maximumZ - minimumZ) / 4);
+ const alongX = Math.round((maximumX - minimumX) / 4);
+ for (let step = 0; step <= alongZ; step++) {
+ const z = minimumZ + ((maximumZ - minimumZ) * step) / alongZ;
+ postPositions.push([minimumX, z], [maximumX, z]);
+ }
+ for (let step = 1; step < alongX; step++) {
+ const x = minimumX + ((maximumX - minimumX) * step) / alongX;
+ postPositions.push([x, minimumZ], [x, maximumZ]);
+ }
+ for (const [x, z] of postPositions) {
+ bucket.addBox([x - postSize / 2, roofY, z - postSize / 2], [x + postSize / 2, roofY + postHeight, z + postSize / 2], ['bottom']);
+ }
+ const railThickness = 0.06;
+ for (const railY of [roofY + postHeight - railThickness, roofY + 0.55]) {
+ bucket.addBox([minimumX, railY, minimumZ], [maximumX, railY + railThickness, minimumZ + railThickness], ['bottom']);
+ bucket.addBox([minimumX, railY, maximumZ - railThickness], [maximumX, railY + railThickness, maximumZ], ['bottom']);
+ bucket.addBox([minimumX, railY, minimumZ], [minimumX + railThickness, railY + railThickness, maximumZ], ['bottom']);
+ bucket.addBox([maximumX - railThickness, railY, minimumZ], [maximumX, railY + railThickness, maximumZ], ['bottom']);
+ }
+}
+
+// The equipment cabinet on top of the A-frame's cross beam: a cladded box with an eave band, under the beacon.
+export function buildApexCabinet() {
+ const buckets = { sts_house: new GeometryBucket(), sts_paint: new GeometryBucket() };
+ const { beamY, height, halfWidth, rearZ, frontZ } = APEX;
+ buckets.sts_house.addBox([-halfWidth, beamY, rearZ], [halfWidth, beamY + height - 0.2, frontZ]);
+ buckets.sts_paint.addBox([-halfWidth - 0.1, beamY + height - 0.2, rearZ - 0.1], [halfWidth + 0.1, beamY + height, frontZ + 0.1], ['bottom']);
+ return buckets;
+}
+
+function nodeWorldVertex(node, accessor, index) {
+ const scale = node.getScale();
+ const translation = node.getTranslation();
+ const [x, y, z] = accessor.getElement(index, []);
+ return [x * scale[0] + translation[0], y * scale[1] + translation[1], z * scale[2] + translation[2]];
+}
+
+function assertNoRotation(node) {
+ const [x, y, z] = node.getRotation();
+ if (Math.abs(x) + Math.abs(y) + Math.abs(z) > 1e-6) throw new Error(`Node ${node.getName()} is rotated, and this script reads vertices as translated and scaled only.`);
+}
+
+// The triangles that make up a crane's collapsed house: every vertex inside the house box of that crane.
+export function findCollapsedHouseTriangles(houseNode, craneCentres) {
+ assertNoRotation(houseNode);
+ const primitive = houseNode.getMesh().listPrimitives()[0];
+ const positions = primitive.getAttribute('POSITION');
+ const indices = primitive.getIndices();
+ const found = [];
+ for (let triangle = 0; triangle < indices.getCount() / 3; triangle++) {
+ const vertices = [0, 1, 2].map((corner) => nodeWorldVertex(houseNode, positions, indices.getScalar(triangle * 3 + corner)));
+ const owner = craneCentres.find((centre) => vertices.every(([x, y, z]) => Math.abs(x - centre) <= DEGENERATE_SEARCH.halfWidth && y >= DEGENERATE_SEARCH.minimumY && y <= DEGENERATE_SEARCH.maximumY && z >= DEGENERATE_SEARCH.minimumZ && z <= DEGENERATE_SEARCH.maximumZ));
+ if (owner !== undefined) found.push({ triangle, centre: owner });
+ }
+ return found;
+}
+
+// The crane centres, read from the collapsed houses themselves: the middle of the x extent of the triangles at the house height.
+export function findCraneCentres(houseNode) {
+ assertNoRotation(houseNode);
+ const primitive = houseNode.getMesh().listPrimitives()[0];
+ const positions = primitive.getAttribute('POSITION');
+ const indices = primitive.getIndices();
+ const candidates = [];
+ for (let triangle = 0; triangle < indices.getCount() / 3; triangle++) {
+ const vertices = [0, 1, 2].map((corner) => nodeWorldVertex(houseNode, positions, indices.getScalar(triangle * 3 + corner)));
+ const atHouseHeight = vertices.every(([, y, z]) => y > 54 && y < 62.6 && z < -35 && z > -53);
+ const spansHouse = Math.max(...vertices.map(([x]) => x)) - Math.min(...vertices.map(([x]) => x)) > 5;
+ if (atHouseHeight && spansHouse) candidates.push(vertices);
+ }
+ const centres = [];
+ for (const vertices of candidates) {
+ const xs = vertices.map(([x]) => x);
+ const centre = (Math.min(...xs) + Math.max(...xs)) / 2;
+ if (!centres.some((known) => Math.abs(known - centre) < 8)) centres.push(centre);
+ }
+ return centres.sort((first, second) => first - second);
+}
+
+function hasApexBeam(paintNode, centre) {
+ const primitive = paintNode.getMesh().listPrimitives()[0];
+ const positions = primitive.getAttribute('POSITION');
+ let hits = 0;
+ for (let index = 0; index < positions.getCount(); index++) {
+ const [x, y, z] = nodeWorldVertex(paintNode, positions, index);
+ if (Math.abs(x - centre) <= 4.2 && y >= 78.6 && y <= 81.4 && z >= -7.1 && z <= -3.9) hits++;
+ }
+ return hits >= 8;
+}
+
+function createMeshFromBuckets(document, name, buckets) {
+ const mesh = document.createMesh(name);
+ const buffer = document.getRoot().listBuffers()[0];
+ const materialsByName = new Map(document.getRoot().listMaterials().map((material) => [material.getName(), material]));
+ for (const [materialName, bucket] of Object.entries(buckets)) {
+ if (bucket.triangleCount === 0) continue;
+ const material = materialsByName.get(materialName);
+ if (!material) throw new Error(`The world has no material ${materialName}, so ${name} cannot use it.`);
+ const position = document.createAccessor().setType('VEC3').setArray(new Float32Array(bucket.positions)).setBuffer(buffer);
+ const normal = document.createAccessor().setType('VEC3').setArray(new Float32Array(bucket.normals)).setBuffer(buffer);
+ const uv = document.createAccessor().setType('VEC2').setArray(new Float32Array(bucket.uvs)).setBuffer(buffer);
+ const indices = document.createAccessor().setType('SCALAR').setArray(new Uint16Array(bucket.indices)).setBuffer(buffer);
+ mesh.addPrimitive(document.createPrimitive().setAttribute('POSITION', position).setAttribute('NORMAL', normal).setAttribute('TEXCOORD_0', uv).setIndices(indices).setMaterial(material));
+ }
+ return mesh;
+}
+
+function removeTriangles(primitive, triangleNumbers) {
+ const indices = primitive.getIndices();
+ const removed = new Set(triangleNumbers);
+ const kept = [];
+ for (let triangle = 0; triangle < indices.getCount() / 3; triangle++) {
+ if (removed.has(triangle)) continue;
+ kept.push(indices.getScalar(triangle * 3), indices.getScalar(triangle * 3 + 1), indices.getScalar(triangle * 3 + 2));
+ }
+ const ArrayType = indices.getArray().constructor;
+ indices.setArray(new ArrayType(kept));
+}
+
+// Applies the fix to a document read from scene.rest.glb. Returns what it did; `changed` is false when the houses are already there.
+export function fixCraneRear(document) {
+ const nodes = document.getRoot().listNodes();
+ if (nodes.some((node) => node.getName() === HOUSE_NODE_NAME)) return { changed: false, reason: 'already fixed' };
+ const houseNode = nodes.find((node) => node.getName() === 'sts_house' && node.getMesh());
+ const paintNode = nodes.find((node) => node.getName() === 'sts_paint' && node.getMesh());
+ if (!houseNode || !paintNode) throw new Error('The world has no sts_house or sts_paint mesh: this is not the port rest file.');
+ const craneCentres = findCraneCentres(houseNode);
+ if (craneCentres.length === 0) throw new Error('No collapsed crane house found in sts_house; nothing to rebuild.');
+ const collapsed = findCollapsedHouseTriangles(houseNode, craneCentres);
+ removeTriangles(houseNode.getMesh().listPrimitives()[0], collapsed.map(({ triangle }) => triangle));
+
+ const scene = document.getRoot().listScenes()[0];
+ const apexCentres = [];
+ // One mesh per node, never one shared mesh: the first-view crop cuts a mesh in place by the pose of the node it visits first.
+ for (const centre of craneCentres) {
+ const houseMesh = createMeshFromBuckets(document, HOUSE_NODE_NAME, buildMachineryHouse());
+ scene.addChild(document.createNode(HOUSE_NODE_NAME).setMesh(houseMesh).setTranslation([centre, 0, 0]));
+ if (hasApexBeam(paintNode, centre)) {
+ const apexMesh = createMeshFromBuckets(document, APEX_NODE_NAME, buildApexCabinet());
+ scene.addChild(document.createNode(APEX_NODE_NAME).setMesh(apexMesh).setTranslation([centre, 0, 0]));
+ apexCentres.push(centre);
+ }
+ }
+ return { changed: true, craneCentres, apexCentres, removedTriangles: collapsed.length };
+}
+
+export async function createIo() {
+ await Promise.all([MeshoptDecoder.ready, MeshoptEncoder.ready]);
+ return new NodeIO()
+ .registerExtensions([...ALL_EXTENSIONS, EXTMeshoptCompression])
+ .registerDependencies({ 'meshopt.decoder': MeshoptDecoder, 'meshopt.encoder': MeshoptEncoder });
+}
+
+async function main(argv) {
+ const dryRun = argv.includes('--dry-run');
+ const restFlag = argv.indexOf('--rest');
+ const restPath = restFlag >= 0 ? resolve(argv[restFlag + 1]) : DEFAULT_REST_PATH;
+ const io = await createIo();
+ const document = await io.read(restPath);
+ const result = fixCraneRear(document);
+ if (!result.changed) {
+ console.log(JSON.stringify(result));
+ return;
+ }
+ document.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.FILTER });
+ const written = Buffer.from(await io.writeBinary(document));
+ if (!dryRun) writeFileSync(restPath, written);
+ console.log(JSON.stringify({ ...result, bytes: written.length, wrote: !dryRun, file: join('public', 'showcase', 'port', 'scene.rest.glb') }));
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main(process.argv.slice(2));
diff --git a/tests/hero-port-crane-rear.test.js b/tests/hero-port-crane-rear.test.js
new file mode 100644
index 00000000..01ea92cb
--- /dev/null
+++ b/tests/hero-port-crane-rear.test.js
@@ -0,0 +1,128 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { Document } from '@gltf-transform/core';
+import {
+ APEX,
+ APEX_NODE_NAME,
+ DEFAULT_REST_PATH,
+ HOUSE,
+ HOUSE_NODE_NAME,
+ buildApexCabinet,
+ buildMachineryHouse,
+ createIo,
+ findCraneCentres,
+ findCollapsedHouseTriangles,
+ fixCraneRear,
+} from '../scripts/fix-port-crane-rear.mjs';
+
+const CRANE_CENTRE = 10;
+
+function boundsOf(buckets) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (const bucket of Object.values(buckets)) {
+ for (let index = 0; index < bucket.positions.length; index += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], bucket.positions[index + axis]);
+ maximum[axis] = Math.max(maximum[axis], bucket.positions[index + axis]);
+ }
+ }
+ }
+ return { minimum, maximum };
+}
+
+// A world with one crane whose house collapsed into a tetrahedron (as in the export), plus the paint mesh with an A-frame beam.
+function createCollapsedWorld() {
+ const document = new Document();
+ const buffer = document.createBuffer();
+ const scene = document.createScene();
+ const materials = {};
+ for (const name of ['sts_house', 'sts_paint', 'rail_steel.001', 'safety_yellow.001']) materials[name] = document.createMaterial(name);
+
+ const tetrahedron = [
+ [CRANE_CENTRE - 5.7, 54.3, -35.7], [CRANE_CENTRE + 5.7, 62.2, -52.5], [CRANE_CENTRE - 5.6, 54.6, -52.6], [CRANE_CENTRE + 5.6, 62.0, -35.6],
+ [CRANE_CENTRE + 60, 20, 10], [CRANE_CENTRE + 61, 20, 10], [CRANE_CENTRE + 60, 21, 10],
+ ];
+ const houseIndices = [0, 1, 2, 3, 0, 1, 1, 3, 2, 3, 2, 0, 4, 5, 6];
+ const houseMesh = document.createMesh('house').addPrimitive(createPrimitive(document, buffer, tetrahedron, houseIndices, materials.sts_house));
+ scene.addChild(document.createNode('sts_house').setMesh(houseMesh));
+
+ const beamVertices = [];
+ for (let step = 0; step < 4; step++) beamVertices.push([CRANE_CENTRE - 3 + step * 2, 79.5, -6], [CRANE_CENTRE - 3 + step * 2, 80.5, -5]);
+ const paintMesh = document.createMesh('paint').addPrimitive(createPrimitive(document, buffer, beamVertices, [0, 1, 2], materials.sts_paint));
+ scene.addChild(document.createNode('sts_paint').setMesh(paintMesh));
+ return document;
+}
+
+function createPrimitive(document, buffer, vertices, indices, material) {
+ const position = document.createAccessor().setType('VEC3').setArray(new Float32Array(vertices.flat())).setBuffer(buffer);
+ const index = document.createAccessor().setType('SCALAR').setArray(new Uint16Array(indices)).setBuffer(buffer);
+ return document.createPrimitive().setAttribute('POSITION', position).setIndices(index).setMaterial(material);
+}
+
+test('the machinery house is a closed box inside the girder footprint, with every material the world already has', () => {
+ const buckets = buildMachineryHouse();
+ const { minimum, maximum } = boundsOf(buckets);
+ assert.ok(minimum[1] >= HOUSE.floorY - 1e-6, 'nothing below the girder deck');
+ assert.ok(maximum[1] - HOUSE.roofY < 1.3, 'only a hand rail rises above the roof');
+ assert.ok(minimum[2] > HOUSE.rearZ - 0.5 && maximum[2] < HOUSE.frontZ + 0.5);
+ assert.ok(maximum[0] <= HOUSE.halfWidth + 0.3 && minimum[0] >= -HOUSE.halfWidth - 0.3);
+ assert.deepEqual(Object.keys(buckets).sort(), ['rail_steel.001', 'safety_yellow.001', 'sts_house', 'sts_paint']);
+ assert.ok(buckets.sts_house.triangleCount >= 20, 'walls and roof of a box are at least ten quads');
+ const totalTriangles = Object.values(buckets).reduce((sum, bucket) => sum + bucket.triangleCount, 0);
+ assert.ok(totalTriangles < 1200, `the house stays light, got ${totalTriangles} triangles`);
+});
+
+test('house faces point outward and normals are unit length', () => {
+ for (const bucket of Object.values(buildMachineryHouse())) {
+ for (let triangle = 0; triangle < bucket.triangleCount; triangle++) {
+ const [first, second, third] = [0, 1, 2].map((corner) => bucket.indices[triangle * 3 + corner]);
+ const point = (vertex) => [0, 1, 2].map((axis) => bucket.positions[vertex * 3 + axis]);
+ const [a, b, c] = [first, second, third].map(point);
+ const edgeOne = b.map((value, axis) => value - a[axis]);
+ const edgeTwo = c.map((value, axis) => value - a[axis]);
+ const faceNormal = [edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1], edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2], edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0]];
+ const stored = [0, 1, 2].map((axis) => bucket.normals[first * 3 + axis]);
+ assert.ok(Math.abs(Math.hypot(...stored) - 1) < 1e-6);
+ const alignment = faceNormal[0] * stored[0] + faceNormal[1] * stored[1] + faceNormal[2] * stored[2];
+ assert.ok(alignment > 0, 'the winding agrees with the stored normal');
+ }
+ }
+});
+
+test('the apex cabinet sits on the A-frame beam', () => {
+ const { minimum, maximum } = boundsOf(buildApexCabinet());
+ assert.ok(Math.abs(minimum[1] - APEX.beamY) < 1e-6);
+ assert.ok(maximum[1] - APEX.beamY < 2.5);
+ assert.ok(maximum[0] - minimum[0] < 8.5, 'narrower than the cross beam');
+});
+
+test('fixCraneRear replaces a collapsed house with the machinery house and leaves other triangles alone', () => {
+ const document = createCollapsedWorld();
+ const houseNode = document.getRoot().listNodes().find((node) => node.getName() === 'sts_house');
+ assert.deepEqual(findCraneCentres(houseNode).map((centre) => Math.round(centre)), [CRANE_CENTRE]);
+ assert.equal(findCollapsedHouseTriangles(houseNode, [CRANE_CENTRE]).length, 4);
+
+ const result = fixCraneRear(document);
+ assert.equal(result.changed, true);
+ assert.equal(result.removedTriangles, 4);
+ assert.equal(houseNode.getMesh().listPrimitives()[0].getIndices().getCount(), 3, 'the unrelated triangle survives');
+ const houses = document.getRoot().listNodes().filter((node) => node.getName() === HOUSE_NODE_NAME);
+ const cabinets = document.getRoot().listNodes().filter((node) => node.getName() === APEX_NODE_NAME);
+ assert.equal(houses.length, 1);
+ assert.equal(cabinets.length, 1);
+ assert.deepEqual(houses[0].getTranslation().map(Math.round), [CRANE_CENTRE, 0, 0]);
+
+ assert.equal(fixCraneRear(document).changed, false, 'a second run changes nothing');
+});
+
+test('the committed port world has six machinery houses and no collapsed house', async () => {
+ const io = await createIo();
+ const document = await io.read(DEFAULT_REST_PATH);
+ assert.equal(fixCraneRear(document).changed, false);
+ const houses = document.getRoot().listNodes().filter((node) => node.getName() === HOUSE_NODE_NAME);
+ assert.equal(houses.length, 6);
+ const houseNode = document.getRoot().listNodes().find((node) => node.getName() === 'sts_house');
+ const craneCentres = houses.map((node) => node.getTranslation()[0]);
+ assert.equal(findCollapsedHouseTriangles(houseNode, craneCentres).length, 0, 'no sts_house triangle is left inside a house volume');
+});