Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Store showcase textures once across the parts of a split world (part of #455)

Nguyen Xuan An7ed3fafde2da
diff --git a/changes/455-shared-textures.md b/changes/455-shared-textures.md
new file mode 100644
index 00000000..c8760034
--- /dev/null
+++ b/changes/455-shared-textures.md
@@ -0,0 +1,3 @@
+- A texture that both parts of a split showcase world use is now stored, downloaded and decoded once (part of #455). `scripts/split-showcase-glb.mjs` keeps such a texture in the first part only; the rest holds a 1x1 stand-in image and the same key in the texture's `extras.sharedTexture`. `loadGltf` and `parseGltf` take `options.sharedTextures` (made by the new `createSharedTextures()`): a texture with a key already decoded by an earlier file is reused, so the parts of all files bind the same texture descriptors and the renderer uploads and counts each once. The split script also warns when an image still sits in both parts, and writes the draw-order ranks as runs (`partRankRuns`, about 9 KB less JSON in the airport rest).
+- Measured in headless Chrome on a local `vite preview` build, cache off, 5 Mbps (`scripts/measure-showcase-load.mjs`). Airport: 18.87 to 18.15 MB for the whole world (one-piece GLB: 18.10 MB), texture memory 196 to 161 MiB (one-piece: 161 MiB), first frame 4.2-4.5 s (was 4.5 s), final frame 27.4-28.2 s (was 29.4 s). Port (13.43 MB, 447 MiB) and datacenter (14.08 MB, 196 MiB) share no texture between parts and hold the same. The final frame of all three worlds is byte-identical to main at the same camera (maximum difference 0).
+- The 0.05 MB the airport still sends over the one-piece GLB is the split's own cost: the 33 KB first-frame sky preview and 8 KB of JSON that both parts carry. No texture travels twice.
diff --git a/public/showcase/airport/scene.glb b/public/showcase/airport/scene.glb
index cc4a6f21..9c2f23dd 100644
Binary files a/public/showcase/airport/scene.glb and b/public/showcase/airport/scene.glb differ
diff --git a/public/showcase/airport/scene.rest.glb b/public/showcase/airport/scene.rest.glb
index d1333648..8bc59638 100644
Binary files a/public/showcase/airport/scene.rest.glb and b/public/showcase/airport/scene.rest.glb differ
diff --git a/public/showcase/datacenter/scene.glb b/public/showcase/datacenter/scene.glb
index 600f4a4c..8a706964 100644
Binary files a/public/showcase/datacenter/scene.glb and b/public/showcase/datacenter/scene.glb differ
diff --git a/public/showcase/datacenter/scene.rest.glb b/public/showcase/datacenter/scene.rest.glb
index e5e22e78..f089806e 100644
Binary files a/public/showcase/datacenter/scene.rest.glb and b/public/showcase/datacenter/scene.rest.glb differ
diff --git a/public/showcase/port/scene.glb b/public/showcase/port/scene.glb
index 2e942984..51a7c34b 100644
Binary files a/public/showcase/port/scene.glb and b/public/showcase/port/scene.glb differ
diff --git a/public/showcase/port/scene.rest.glb b/public/showcase/port/scene.rest.glb
index 303cf54f..050e4e6d 100644
Binary files a/public/showcase/port/scene.rest.glb and b/public/showcase/port/scene.rest.glb differ
diff --git a/scripts/split-showcase-glb.mjs b/scripts/split-showcase-glb.mjs
index cd34aafb..e3f7208c 100644
--- a/scripts/split-showcase-glb.mjs
+++ b/scripts/split-showcase-glb.mjs
@@ -10,6 +10,7 @@
// and every kept node keeps its transform. The one thing rewritten is the shared meshopt index stream. Its indices are decoded,
// cut per accessor and encoded again (a lossless step), because one stream serves every mesh and cannot be cut in its
// compressed form. A mesh used by several nodes goes to one part together with all of its nodes, so instancing survives.
+import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -24,6 +25,9 @@ const BINARY_CHUNK = 0x004e4942;
const MESHOPT = 'EXT_meshopt_compression';
const PREVIEW_SKY_WIDTH = 128;
const PREVIEW_SKY_HEIGHT = 64;
+// A 1x1 PNG that stands in for a shared texture's image in every file but the first. The page never decodes it: the later file
+// takes the texture the first file decoded, found by the key in the texture's extras.sharedTexture.
+const STAND_IN_IMAGE = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
// The nodes (by name) that make the first part. They are the ground and the hero the default camera frames; every other
// node goes to the rest. A name picks every node that carries it.
@@ -93,6 +97,8 @@ function collectTextureIndices(value, found) {
}
}
+const STAND_IN = Symbol('stand-in image');
+
class SourceWorld {
constructor(buffer) {
({ json: this.json, binary: this.binary } = readGlb(buffer));
@@ -146,9 +152,22 @@ class SourceWorld {
return this.json.bufferViews[viewIndex].extensions?.[MESHOPT]?.mode === 'TRIANGLES';
}
+ // Identifies a texture by what it shows: the bytes of its image and its sampler, so equal textures match across the parts.
+ textureKey(oldTexture) {
+ const texture = this.json.textures[oldTexture];
+ const view = this.json.bufferViews[this.json.images[texture.source].bufferView];
+ const start = view.byteOffset ?? 0;
+ const hash = createHash('sha1');
+ hash.update(this.binary.subarray(start, start + view.byteLength));
+ hash.update(JSON.stringify(this.json.samplers?.[texture.sampler] ?? null));
+ return hash.digest('hex').slice(0, 16);
+ }
+
// The part holding exactly these nodes (mesh-carrying nodes) plus their ancestors; returns { json, binary }.
// `keepPrimitive(meshIndex, primitive)` picks the primitives of each mesh that this part draws; a node left with none is dropped.
- extract(requestedNodeIndices, keepPrimitive = () => true) {
+ // `share.keys` are the texture keys that more than one part uses. This part tags them with extras.sharedTexture; when
+ // `share.stripImages` is set it also swaps their images for the stand-in, so the bytes travel in the first part only.
+ extract(requestedNodeIndices, keepPrimitive = () => true, share = { keys: new Set(), stripImages: false }) {
const source = this.json;
const meshNodeIndices = requestedNodeIndices.filter(index => source.meshes[source.nodes[index].mesh].primitives.some(primitive => keepPrimitive(source.nodes[index].mesh, primitive)));
const keptNodes = new Set();
@@ -229,14 +248,20 @@ class SourceWorld {
const imageMap = new Map();
const samplerOrder = [];
const samplerMap = new Map();
- const textures = textureOrder.map(oldTexture => {
+ const textureKeys = textureOrder.map(oldTexture => this.textureKey(oldTexture));
+ const textures = textureOrder.map((oldTexture, position) => {
const texture = structuredClone(source.textures[oldTexture]);
if (texture.extensions) throw new Error('The splitter does not handle texture extensions.');
- if (!imageMap.has(texture.source)) {
- imageMap.set(texture.source, imageOrder.length);
- imageOrder.push(texture.source);
+ let imageSource = texture.source;
+ if (share.keys.has(textureKeys[position])) {
+ texture.extras = { ...texture.extras, sharedTexture: textureKeys[position] };
+ if (share.stripImages) imageSource = STAND_IN;
+ }
+ if (!imageMap.has(imageSource)) {
+ imageMap.set(imageSource, imageOrder.length);
+ imageOrder.push(imageSource);
}
- texture.source = imageMap.get(texture.source);
+ texture.source = imageMap.get(imageSource);
if (texture.sampler !== undefined) {
if (!samplerMap.has(texture.sampler)) {
samplerMap.set(texture.sampler, samplerOrder.length);
@@ -328,6 +353,11 @@ class SourceWorld {
return accessor;
});
const images = imageOrder.map(oldImage => {
+ if (oldImage === STAND_IN) {
+ const view = { buffer: 0, byteOffset: appendBinary(STAND_IN_IMAGE), byteLength: STAND_IN_IMAGE.length };
+ output.views.push(view);
+ return { mimeType: 'image/png', bufferView: output.views.length - 1 };
+ }
const image = structuredClone(source.images[oldImage]);
if (image.uri) throw new Error('The splitter does not handle images with a uri.');
image.bufferView = copyView(image.bufferView);
@@ -357,16 +387,20 @@ class SourceWorld {
const sceneRoots = (source.scenes[source.scene ?? 0].nodes).filter(root => nodeMap.has(root)).map(root => nodeMap.get(root));
const keptNodeSet = new Set(meshNodeIndices);
- const partRanks = [];
+ // Ranks as runs of consecutive values, [[first, count], ...]: a part keeps long stretches of the draw order.
+ const partRankRuns = [];
this.drawOrder.forEach((entry, rank) => {
- if (keptNodeSet.has(entry.nodeIndex) && keepPrimitive(source.nodes[entry.nodeIndex].mesh, entry.primitive)) partRanks.push(rank);
+ if (!keptNodeSet.has(entry.nodeIndex) || !keepPrimitive(source.nodes[entry.nodeIndex].mesh, entry.primitive)) return;
+ const lastRun = partRankRuns.at(-1);
+ if (lastRun && lastRun[0] + lastRun[1] === rank) lastRun[1] += 1;
+ else partRankRuns.push([rank, 1]);
});
const json = {
asset: source.asset,
extensionsUsed: source.extensionsUsed,
extensionsRequired: source.extensionsRequired,
scene: 0,
- scenes: [{ ...source.scenes[source.scene ?? 0], nodes: sceneRoots, extras: { partRanks } }],
+ scenes: [{ ...source.scenes[source.scene ?? 0], nodes: sceneRoots, extras: { partRankRuns } }],
nodes,
meshes,
materials,
@@ -378,7 +412,7 @@ class SourceWorld {
if (textures.length) json.textures = textures;
if (images.length) json.images = images;
if (samplers.length) json.samplers = samplers;
- return { json, binary: Buffer.concat(output.binaryChunks) };
+ return { json, binary: Buffer.concat(output.binaryChunks), textureKeys };
}
}
@@ -449,9 +483,30 @@ if (!firstNodes.length) throw new Error('No node matches the first part names.')
// A hero mesh can hand its fine detail (by material name) to the rest, so the first part stays small.
const laterMaterials = new Set(LATER_MATERIAL_NAMES[options.worldId] ?? []);
const isLaterPrimitive = primitive => laterMaterials.has(world.json.materials[primitive.material]?.name);
-const first = writeGlb(...Object.values(world.extract(firstNodes, (mesh, primitive) => !isLaterPrimitive(primitive))));
-const rest = writeGlb(...Object.values(world.extract([...firstNodes, ...restNodes], (mesh, primitive) => !firstMeshes.has(mesh) || isLaterPrimitive(primitive))));
-console.log(`${options.worldId}: first ${first.length} bytes (${firstNodes.length} nodes), rest ${rest.length} bytes (${restNodes.length} nodes), source ${readFileSync(options.source).length} bytes`);
+const keepInFirst = (mesh, primitive) => !isLaterPrimitive(primitive);
+const keepInRest = (mesh, primitive) => !firstMeshes.has(mesh) || isLaterPrimitive(primitive);
+// A texture both parts use is stored in the first part only; the rest takes it by key once the first part has decoded it.
+const firstTextureKeys = new Set(world.extract(firstNodes, keepInFirst).textureKeys);
+const sharedKeys = new Set(world.extract([...firstNodes, ...restNodes], keepInRest).textureKeys.filter(key => firstTextureKeys.has(key)));
+const firstPart = world.extract(firstNodes, keepInFirst, { keys: sharedKeys, stripImages: false });
+const restPart = world.extract([...firstNodes, ...restNodes], keepInRest, { keys: sharedKeys, stripImages: true });
+// Every image's bytes must travel once across the parts; this names any that still travel twice.
+function imageHashes({ json, binary }) {
+ return new Map((json.images ?? []).map(image => {
+ const view = json.bufferViews[image.bufferView];
+ const bytes = binary.subarray(view.byteOffset ?? 0, (view.byteOffset ?? 0) + view.byteLength);
+ return [createHash('sha1').update(bytes).digest('hex'), bytes.length];
+ }));
+}
+const firstImages = imageHashes(firstPart);
+const duplicatedImages = [...imageHashes(restPart)].filter(([hash, length]) => firstImages.has(hash) && length > STAND_IN_IMAGE.length);
+if (duplicatedImages.length) {
+ const bytes = duplicatedImages.reduce((total, [, length]) => total + length, 0);
+ console.warn(`${options.worldId}: ${duplicatedImages.length} images (${bytes} bytes) are stored in both parts.`);
+}
+const first = writeGlb(firstPart.json, firstPart.binary);
+const rest = writeGlb(restPart.json, restPart.binary);
+console.log(`${options.worldId}: first ${first.length} bytes (${firstNodes.length} nodes), rest ${rest.length} bytes (${restNodes.length} nodes), source ${readFileSync(options.source).length} bytes, ${sharedKeys.size} shared textures`);
if (!options.dryRun) {
const directory = join(SHOWCASE_DIRECTORY, options.worldId);
writeFileSync(join(directory, 'scene.glb'), first);
diff --git a/src/gltf-decode.js b/src/gltf-decode.js
index 6820a450..9684ffdd 100644
--- a/src/gltf-decode.js
+++ b/src/gltf-decode.js
@@ -95,7 +95,7 @@ function normalizedWeights(weights) {
* The result has the shape the Renderer67 conversion in gltf.js reads. Nothing here imports three.js: Draco, meshopt
* and KTX2 decoders arrive as `decoders` objects that the caller supplies.
*/
-export async function decodeGltf({ document, glbBinary, resourceBytes, decoders, limits, imageTargets = new Map() }) {
+export async function decodeGltf({ document, glbBinary, resourceBytes, decoders, limits, imageTargets = new Map(), sharedTextures }) {
const releasers = [];
const usedNames = new Map();
const nodeCache = new Map();
@@ -175,6 +175,11 @@ export async function decodeGltf({ document, glbBinary, resourceBytes, decoders,
async function loadTexture(textureIndex) {
if (textures.has(textureIndex)) return textures.get(textureIndex);
const definition = document.textures[textureIndex];
+ // A texture that several files of one world carry is stored in the first file only; later files hold a stand-in image and
+ // the same key, and take the texture the first file decoded.
+ const shareKey = definition.extras?.sharedTexture;
+ const shared = shareKey && sharedTextures?.get(shareKey);
+ if (shared) return shared;
const sampler = document.samplers?.[definition.sampler] ?? {};
const { image, isCompressedTexture, format, mipmaps } = await loadTextureImage(definition);
const texture = {
@@ -188,6 +193,7 @@ export async function decodeGltf({ document, glbBinary, resourceBytes, decoders,
magFilter: sampler.magFilter ?? 9729,
};
textures.set(textureIndex, texture);
+ if (shareKey) sharedTextures?.set(shareKey, texture);
return texture;
}
diff --git a/src/gltf.js b/src/gltf.js
index 5eb6325c..f5b1ad42 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -980,6 +980,16 @@ function convertMaterial(source, limits, maps, definition = {}) {
return material;
}
+/**
+ * Shared state for the files of one world that split a texture between them. Pass the same object as `options.sharedTextures` to
+ * every parseGltf or loadGltf call, first file first: a texture whose definition carries `extras.sharedTexture` is decoded once, and
+ * a later file with the same key reuses it, so the parts of all files bind the same texture descriptors.
+ * The first file owns the decoded images; keep its asset alive while the later files are in use.
+ */
+export function createSharedTextures() {
+ return Object.assign(new Map(), { descriptors: new Map() });
+}
+
/** Parse a bounded glTF 2.0 asset into Renderer67 parts. Draco and KTX2 decoders come from options.decoders; meshopt decodes in a chunk that loads on demand, unless options.decoders.meshopt replaces it. */
export async function parseGltf(data, options = {}) {
const limits = limitsFor(options);
@@ -1007,7 +1017,7 @@ export async function parseGltf(data, options = {}) {
}
let gltf;
try {
- gltf = await decodeGltf({ document, glbBinary: binaryChunk(data), resourceBytes, decoders, limits, imageTargets: textureScaling.targetByImageIndex });
+ gltf = await decodeGltf({ document, glbBinary: binaryChunk(data), resourceBytes, decoders, limits, imageTargets: textureScaling.targetByImageIndex, sharedTextures: options.sharedTextures });
if (resampler) warnings.push(...resampler.apply(gltf, limits));
const parts = [];
const bindings = [];
@@ -1016,7 +1026,7 @@ export async function parseGltf(data, options = {}) {
const geometries = new Map();
const morphMetadata = new Map();
const materials = new Map();
- const maps = new Map();
+ const maps = options.sharedTextures?.descriptors ?? new Map();
const nodes = [];
const meshNamesWithIgnoredAlpha = new Set();
const lightNodes = [];
diff --git a/src/showcase-download.js b/src/showcase-download.js
index d614e45c..08dd4e3b 100644
--- a/src/showcase-download.js
+++ b/src/showcase-download.js
@@ -65,10 +65,15 @@ export async function downloadBlob(url, { meter, name, type, signal }) {
return new Blob(chunks, { type });
}
-/** The rank list the split script writes into a GLB's scene extras, or null when the file has none. Reads the JSON chunk only. */
+/**
+ * The rank list the split script writes into a GLB's scene extras, or null when the file has none. Reads the JSON chunk only.
+ * The script stores it as runs of consecutive ranks, `partRankRuns: [[first, count], ...]`, which keeps the JSON small.
+ */
export async function readPartRanks(blob) {
const header = new DataView(await blob.slice(0, 20).arrayBuffer());
const jsonLength = header.getUint32(12, true);
const document = JSON.parse(await blob.slice(20, 20 + jsonLength).text());
- return document.scenes?.[document.scene ?? 0]?.extras?.partRanks ?? null;
+ const extras = document.scenes?.[document.scene ?? 0]?.extras;
+ if (!extras?.partRankRuns) return extras?.partRanks ?? null;
+ return extras.partRankRuns.flatMap(([first, count]) => Array.from({ length: count }, (unused, offset) => first + offset));
}
diff --git a/src/showcase.js b/src/showcase.js
index 1f5107a8..c9611ac0 100644
--- a/src/showcase.js
+++ b/src/showcase.js
@@ -3,7 +3,7 @@ import './brand.js';
import './showcase.css';
import './pointer-light.js';
import { Renderer67 } from './renderer.js';
-import { loadGltf } from './gltf.js';
+import { createSharedTextures, loadGltf } from './gltf.js';
import { loadHdri } from './hdri.js';
import { createCascadedShadows } from './cascaded-shadows.js';
import { applyWaterReflection, attachWaterReflection } from './water-reflection.js';
@@ -242,7 +242,7 @@ function inWholeWorldOrder(files) {
// Adds the other parts of a staged world once they have downloaded, then swaps the first frame's small sky for the full one.
async function finishWorld(world) {
- const { request, description, asset, detachReflection, remainingDownloads, abort } = world;
+ const { request, description, asset, sharedTextures, detachReflection, remainingDownloads, abort } = world;
const isCurrent = () => request === loadingRequest;
try {
const [remainingModels, fullMap] = await remainingDownloads;
@@ -250,7 +250,7 @@ async function finishWorld(world) {
const files = [{ parts: asset.parts, ranks: world.ranks }];
for (const [index, model] of remainingModels.entries()) {
const baseUrl = new URL('.', new URL(description.glbRest[index], location.href)).href;
- const remaining = await loadGltf(model, { baseUrl, ...(description.gltfOptions ?? {}) });
+ const remaining = await loadGltf(model, { baseUrl, sharedTextures, ...(description.gltfOptions ?? {}) });
files.push({ parts: remaining.parts, ranks: await readPartRanks(model) });
}
if (!isCurrent()) return;
@@ -315,7 +315,8 @@ async function selectScene(id) {
previewUrl ? loadSky(skyUrl) : null,
]);
remainingDownloads.catch(() => {});
- const asset = await loadGltf(model, { baseUrl: new URL('.', glbUrl).href, ...(description.gltfOptions ?? {}) });
+ const sharedTextures = createSharedTextures();
+ const asset = await loadGltf(model, { baseUrl: new URL('.', glbUrl).href, sharedTextures, ...(description.gltfOptions ?? {}) });
if (request !== loadingRequest) return;
renderer?.dispose();
const rendererOptions = description.renderer ?? {};
@@ -349,7 +350,7 @@ async function selectScene(id) {
}
progressLabel = `Loading the rest of ${SCENE_LABELS[id]}`;
showProgress(progressLabel, meter);
- finishWorld({ id, request, description, asset, ranks: await readPartRanks(model), detachReflection, remainingDownloads, abort });
+ finishWorld({ id, request, description, asset, sharedTextures, ranks: await readPartRanks(model), detachReflection, remainingDownloads, abort });
} catch (error) {
if (request !== loadingRequest) return;
markPressedTab(currentId);
diff --git a/tests/gltf-shared-textures.test.js b/tests/gltf-shared-textures.test.js
new file mode 100644
index 00000000..3cdaa3a4
--- /dev/null
+++ b/tests/gltf-shared-textures.test.js
@@ -0,0 +1,93 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { inflateSync } from 'node:zlib';
+import { mat4 } from 'gl-matrix';
+import { exportGlb } from '../src/export.js';
+import { createSharedTextures, parseGltf } from '../src/gltf.js';
+import { box } from '../src/geometry.js';
+
+// Node has no image decoder: decode the exporter's PNGs (unfiltered rows) so parseGltf sees real pixels.
+globalThis.self = globalThis;
+let decodedImageCount = 0;
+globalThis.createImageBitmap = async blob => {
+ decodedImageCount += 1;
+ const bytes = Buffer.from(await blob.arrayBuffer());
+ const width = bytes.readUInt32BE(16);
+ const height = bytes.readUInt32BE(20);
+ const channels = bytes[25] === 6 ? 4 : 3;
+ const compressed = [];
+ for (let offset = 8; offset < bytes.length;) {
+ const length = bytes.readUInt32BE(offset);
+ if (bytes.toString('latin1', offset + 4, offset + 8) === 'IDAT') compressed.push(bytes.subarray(offset + 8, offset + 8 + length));
+ offset += 12 + length;
+ }
+ const raw = inflateSync(Buffer.concat(compressed));
+ const data = new Uint8Array(width * height * 4).fill(255);
+ for (let row = 0; row < height; row++) {
+ for (let column = 0; column < width; column++) {
+ for (let channel = 0; channel < channels; channel++) {
+ data[(row * width + column) * 4 + channel] = raw[row * (width * channels + 1) + 1 + column * channels + channel];
+ }
+ }
+ }
+ return { width, height, data, close() {} };
+};
+
+const IMAGE_SIZE = 4;
+
+function mapDescriptor(seed) {
+ const data = new Uint8ClampedArray(IMAGE_SIZE * IMAGE_SIZE * 4);
+ for (let texel = 0; texel < IMAGE_SIZE * IMAGE_SIZE; texel++) {
+ data.set([(texel * 16 + seed) % 256, (texel * 7 + seed * 3) % 256, (seed * 29) % 256, 255], texel * 4);
+ }
+ return { image: { width: IMAGE_SIZE, height: IMAGE_SIZE, data }, wrapS: 10497, wrapT: 10497, magFilter: 9729, minFilter: 9729, colorSpace: 'srgb', uvChannel: 0 };
+}
+
+function texturedBox(seed) {
+ const geometry = box();
+ geometry.uvs = new Float32Array((geometry.positions.length / 3) * 2).map((unused, index) => (index % 5) / 5);
+ return { name: 'Box', geometry, matrix: mat4.create(), material: { color: [1, 1, 1], metallic: 0, roughness: 0.5, map: mapDescriptor(seed) } };
+}
+
+// Tags every texture of a GLB with the key the world splitter writes into extras.sharedTexture.
+function tagSharedTexture(glb, key) {
+ const buffer = Buffer.from(glb);
+ const jsonLength = buffer.readUInt32LE(12);
+ const json = JSON.parse(buffer.subarray(20, 20 + jsonLength).toString('utf8'));
+ json.textures.forEach(texture => { texture.extras = { sharedTexture: key }; });
+ const jsonBytes = Buffer.from(JSON.stringify(json), 'utf8');
+ const jsonPadded = Buffer.concat([jsonBytes, Buffer.alloc((4 - (jsonBytes.length % 4)) % 4, 0x20)]);
+ const binaryChunk = buffer.subarray(20 + jsonLength);
+ const header = Buffer.from(buffer.subarray(0, 20));
+ header.writeUInt32LE(12 + 8 + jsonPadded.length + binaryChunk.length, 8);
+ header.writeUInt32LE(jsonPadded.length, 12);
+ const rebuilt = Buffer.concat([header, jsonPadded, binaryChunk]);
+ return rebuilt.buffer.slice(rebuilt.byteOffset, rebuilt.byteOffset + rebuilt.length);
+}
+
+test('a texture with the same shared key in two files is decoded once and both files bind one descriptor', async () => {
+ const sharedTextures = createSharedTextures();
+ const firstFile = tagSharedTexture(exportGlb([texturedBox(1)]), 'ground');
+ // The later file carries a different stand-in image under the same key; it must never be decoded.
+ const laterFile = tagSharedTexture(exportGlb([texturedBox(2)]), 'ground');
+ decodedImageCount = 0;
+ const first = await parseGltf(firstFile, { sharedTextures });
+ const later = await parseGltf(laterFile, { sharedTextures });
+ assert.equal(decodedImageCount, 1);
+ assert.equal(later.parts[0].material.map, first.parts[0].material.map);
+ assert.deepEqual(Array.from(later.parts[0].material.map.image.data), Array.from(mapDescriptor(1).image.data));
+});
+
+test('without shared state, or with different keys, each file decodes its own texture', async () => {
+ const firstFile = tagSharedTexture(exportGlb([texturedBox(1)]), 'ground');
+ const laterFile = tagSharedTexture(exportGlb([texturedBox(2)]), 'roof');
+ decodedImageCount = 0;
+ const sharedTextures = createSharedTextures();
+ const first = await parseGltf(firstFile, { sharedTextures });
+ const later = await parseGltf(laterFile, { sharedTextures });
+ assert.equal(decodedImageCount, 2);
+ assert.notEqual(later.parts[0].material.map, first.parts[0].material.map);
+ const alone = await parseGltf(laterFile);
+ assert.equal(decodedImageCount, 3);
+ assert.deepEqual(Array.from(alone.parts[0].material.map.image.data), Array.from(mapDescriptor(2).image.data));
+});