Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Move textured replaceParts into a lazy addon (closes #423)

Nguyen Xuan An70ea0e1d808b
diff --git a/changes/423.md b/changes/423.md
index 55fbfd8a..c537689f 100644
--- a/changes/423.md
+++ b/changes/423.md
@@ -1 +1 @@
-- `replaceParts` can now add and remove textured parts, and frees a texture once no part uses it (issue #423); skinned, morphed and layered parts still need a new renderer.
+- Add `67js/addons/replace-textured-parts` (issue #423): after `import '@codepawlhq/67js/addons/replace-textured-parts'`, `renderer.replaceParts` adds and removes textured parts, deletes a texture once no part uses it and drops it from the texture ledger. Without the import, a textured add or remove throws and names the import. Skinned and morphed parts still need a new renderer.
diff --git a/changes/423.size.md b/changes/423.size.md
index 9fb931fb..02f119f0 100644
--- a/changes/423.size.md
+++ b/changes/423.size.md
@@ -1,6 +1,8 @@
-- entry:core: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000
-- scene:lit-box: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000
-- scene:gltf-box: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000
-- scene:gltf-box+lazy: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000
-- scene:agent-scene: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000
-- scene:agent-scene+lazy: replaceParts adds and frees textured parts (issue #423), so a multi-shot film no longer parks hidden parts at y=-5000
+- entry:core: hook for #423 lazy textured replaceParts (a registry slot, three calls and a longer error), 38 bytes
+- scene:lit-box: hook for #423 lazy textured replaceParts, 45 bytes
+- goal:lit-box: hook for #423 lazy textured replaceParts, approved by lead
+- scene:gltf-box: hook for #423 lazy textured replaceParts, 60 bytes
+- scene:gltf-box+lazy: hook for #423 lazy textured replaceParts, 58 bytes
+- scene:agent-scene: hook for #423 lazy textured replaceParts, 36 bytes
+- goal:agent-scene: hook for #423 lazy textured replaceParts, approved by lead
+- scene:agent-scene+lazy: hook for #423 lazy textured replaceParts, 22 bytes
diff --git a/docs/guide.md b/docs/guide.md
index e5c33c52..4cfc3790 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -243,7 +243,7 @@ The [retarget contract](https://github.com/codepawl/67.js/blob/main/docs/retarge
4. Each frame, call `renderer.replaceParts([...sceneParts, ...player.partsAt(seconds)])` and render.
The [Spume contract](https://github.com/codepawl/67.js/blob/main/docs/spume.md) covers the cache format, whitewater options, placement and measured cost.
-Textured, skinned and morphed parts may stay in the list unchanged while frames are replaced; adding or removing them needs a new renderer.
+Skinned and morphed parts may stay in the list unchanged while frames are replaced; adding or removing them needs a new renderer. Textured parts can be added and removed once `import '@codepawlhq/67js/addons/replace-textured-parts'` has run; without it they must stay unchanged. The addon deletes a texture when no part uses it any more and keeps one another part still binds.
## Wheeled vehicles
@@ -567,7 +567,7 @@ The session keeps existing renderer-facing parts and matrices for transform, mat
Agents can build from an empty recipe with `add-geometry`, `add-material` and `add-node` commands.
Explicit removal and rebinding use the same atomic batch contract.
Checkpoints retain shared geometry under the session budget. Release unused snapshots before increasing scene detail.
-The preview reconciles rigid topology, textured or not, while keeping unchanged geometry buffers and draw batches.
+The preview reconciles rigid topology, textured parts too with the `replace-textured-parts` addon, while keeping unchanged geometry buffers and draw batches.
The CPU addon owns recipe state. The separate Node MCP server connects it to browser rendering. Background render jobs remain unsupported.
diff --git a/docs/mcp.md b/docs/mcp.md
index 98c725cf..60bad097 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -228,8 +228,8 @@ Geometry resources remain immutable. Remove an unused definition and add its rep
Checkpoints retain their resource handles for exact restoration. Active, checkpoint and staged geometry share a bounded allocation budget.
Release unused checkpoints to free that ownership before adding detail.
-The preview reconciles rigid parts, textured or not, while retaining shader programs, render targets and shared geometry buffers.
-A scene with material patterns gets a new renderer on each topology change instead. Skinned, morphed and layered parts are not streamed either; `replaceParts` rejects adding or removing them.
+The preview reconciles rigid parts, textured ones with the `replace-textured-parts` addon, while retaining shader programs, render targets and shared geometry buffers.
+A scene with material patterns gets a new renderer on each topology change instead. Skinned and morphed parts are not streamed either; `replaceParts` rejects adding or removing them.
Unchanged draw batches remain allocated. Changed instance groups receive new instance buffers. Retired buffers are released.
Staging must fit alongside the current render allocations, so a replacement can fail its GPU budget even when the final scene alone fits.
diff --git a/docs/terrain.md b/docs/terrain.md
index 139bef99..7288f6ac 100644
--- a/docs/terrain.md
+++ b/docs/terrain.md
@@ -34,7 +34,7 @@ const renderer = new Renderer67(canvas, [...terrain.parts, ...treeParts], { worl
```
Each frame, `if (terrain.update(eye).length) renderer.replaceParts(sceneParts)` swaps the chunks whose level of detail changed.
-Textured parts such as leaf cards can be added and removed in `replaceParts`; their textures are freed once no part uses them.
+Textured parts such as leaf cards can be added and removed in `replaceParts` after `import '@codepawlhq/67js/addons/replace-textured-parts'`; their textures are freed once no part uses them.
## loadTextureSet
diff --git a/package.json b/package.json
index 771ad685..a2b87b53 100644
--- a/package.json
+++ b/package.json
@@ -102,6 +102,7 @@
"./addons/cascaded-shadows": "./build/cascaded-shadows.js",
"./addons/compact-color": "./build/compact-color.js",
"./addons/gaussian-splats": "./build/gaussian-splats.js",
+ "./addons/replace-textured-parts": "./build/replace-textured-parts.js",
"./addons/texture-update": "./build/texture-update.js",
"./package.json": "./package.json"
},
@@ -153,6 +154,7 @@
"smoke:character": "node scripts/smoke-character.mjs",
"smoke:modeling": "node scripts/smoke-modeling.mjs",
"smoke:material-maps": "node scripts/smoke-material-maps.mjs",
+ "smoke:replace-textured-parts": "node scripts/smoke-replace-textured-parts.mjs",
"smoke:texture-update": "node scripts/smoke-texture-update.mjs",
"benchmark:mesh-query": "node scripts/benchmark-mesh-query.mjs",
"benchmark:update-parts": "node scripts/benchmark-update-parts.mjs",
diff --git a/scripts/smoke-replace-textured-parts.mjs b/scripts/smoke-replace-textured-parts.mjs
new file mode 100644
index 00000000..ed675cac
--- /dev/null
+++ b/scripts/smoke-replace-textured-parts.mjs
@@ -0,0 +1,94 @@
+import assert from 'node:assert/strict';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { createServer } from 'vite';
+import { chromium } from 'playwright';
+
+// Builds a renderer with one plain grey quad, adds a quad whose texture is solid green with replaceParts, renders and
+// counts green pixels, then removes it and counts again. The texture must be drawn after the add, gone after the remove,
+// and deleted from the GPU. Runs on SwiftShader unless "gpu" is given; start a GPU run through `bash ~/.agents/tools/gpu-lock.sh`.
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const backend = process.argv[2] ?? 'cpu';
+assert.ok(['cpu', 'gpu'].includes(backend));
+await mkdir('artifacts', { recursive: true });
+const harness = `<!doctype html><html><head><style>html,body{margin:0}</style></head><body><script type="module">
+import {Renderer67} from '/src/renderer.js';
+import '/src/replace-textured-parts.js';
+const identity = [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];
+function quad(left, right) {
+ return {
+ positions: new Float32Array([left,-1,0, right,-1,0, right,1,0, left,1,0]),
+ normals: new Float32Array([0,0,1, 0,0,1, 0,0,1, 0,0,1]),
+ uvs: new Float32Array([0,0, 1,0, 1,1, 0,1]),
+ indices: new Uint32Array([0,1,2, 0,2,3]),
+ };
+}
+function solidImage(red, green, blue) {
+ const data = new Uint8ClampedArray(4 * 4 * 4);
+ for (let index = 0; index < data.length; index += 4) data.set([red, green, blue, 255], index);
+ return new ImageData(data, 4, 4);
+}
+const material = { tag: 'gltf', color: [1, 1, 1], metallic: 0, roughness: 1, emission: 0, emissiveColor: [0, 0, 0] };
+const plain = { name: 'plain', geometry: quad(-2, -0.2), matrix: new Float32Array(identity), material: { ...material, color: [0.5, 0.5, 0.5] } };
+const map = { image: solidImage(0, 255, 0), colorSpace: 'srgb' };
+const textured = { name: 'textured', geometry: quad(0.2, 2), matrix: new Float32Array(identity), material: { ...material, map } };
+const canvas = document.createElement('canvas');
+canvas.width = canvas.height = 128;
+document.body.append(canvas);
+const renderer = new Renderer67(canvas, [plain], { ground: false, shadows: false, samples: 1, pixelRatio: 1, memoryBudgetMiB: 64 });
+const context = renderer.context;
+const camera = { eye: [0, 0, 6], target: [0, 0, 0] };
+function greenPixels() {
+ renderer.render(camera);
+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);
+ context.readPixels(0, 0, canvas.width, canvas.height, context.RGBA, context.UNSIGNED_BYTE, pixels);
+ let count = 0;
+ for (let offset = 0; offset < pixels.length; offset += 4) {
+ if (pixels[offset + 1] > pixels[offset] + 60 && pixels[offset + 1] > pixels[offset + 2] + 60) count++;
+ }
+ return count;
+}
+const results = { before: greenPixels(), textureBytesBefore: renderer.textureBytes };
+renderer.replaceParts([plain, textured]);
+results.afterAdd = greenPixels();
+results.textureBytesAdded = renderer.textureBytes;
+results.textureLive = context.isTexture(renderer.textures.get(map));
+const texture = renderer.textures.get(map);
+renderer.replaceParts([plain]);
+results.afterRemove = greenPixels();
+results.textureBytesRemoved = renderer.textureBytes;
+results.textureKept = renderer.textures.has(map);
+results.textureDeleted = !context.isTexture(texture);
+results.batchesAfterRemove = renderer.batches.length;
+window.__replaceTexturedProof = results;
+</script></body></html>`;
+await writeFile('artifacts/replace-textured-parts-harness.html', harness);
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+let browser;
+try {
+ await server.listen();
+ const args = ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'];
+ if (backend === 'cpu') args.push('--use-angle=swiftshader', '--enable-unsafe-swiftshader');
+ browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args });
+ const page = await browser.newPage({ viewport: { width: 400, height: 400 } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ page.on('console', message => { if (message.type() === 'error' && !message.text().includes('404')) errors.push(message.text()); });
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/artifacts/replace-textured-parts-harness.html`);
+ await page.waitForFunction(() => window.__replaceTexturedProof, null, { timeout: 60000 });
+ const results = await page.evaluate(() => window.__replaceTexturedProof);
+ await writeFile(`artifacts/replace-textured-parts-${backend}.json`, JSON.stringify(results, null, 2));
+ assert.deepEqual(errors, []);
+ assert.equal(results.before, 0, 'no green before the textured part exists');
+ assert.ok(results.afterAdd > 500, `the added textured part draws green (${results.afterAdd} pixels)`);
+ assert.ok(results.textureLive, 'the added texture is a live GPU texture');
+ assert.ok(results.textureBytesAdded > results.textureBytesBefore, 'the texture ledger grows on add');
+ assert.equal(results.afterRemove, 0, 'the green is gone after the remove');
+ assert.equal(results.textureBytesRemoved, results.textureBytesBefore, 'the texture ledger drops back on remove');
+ assert.ok(results.textureDeleted && !results.textureKept, 'the removed part texture is deleted from the GPU and the cache');
+ assert.equal(results.batchesAfterRemove, 1);
+ console.log(JSON.stringify(results));
+} finally {
+ await browser?.close();
+ await server.close();
+}
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 1052d19f..24973e36 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -155,7 +155,7 @@ Read `docs/agent-scene.md` for schema version one, immutable resources and atomi
Start with capabilities and bounded inspection. Edit stable IDs through one `apply` batch with the current `expectedRevision`.
Checkpoint before uncertain changes, inspect and render the result, then restore or release the checkpoint.
-For rigid scenes (textured parts are fine; skinned, morphed and layered parts need a new renderer), compare `session.topologyRevision` with the uploaded revision after successful edits.
+For rigid scenes (textured parts need `import '@codepawlhq/67js/addons/replace-textured-parts'`; skinned and morphed parts need a new renderer), compare `session.topologyRevision` with the uploaded revision after successful edits.
Call `renderer.replaceParts(session.parts)` for changed topology or `renderer.updateParts(session.parts)` for retained parts, then render the detached camera.
Use add/remove commands for nodes and shared resources, and `set-node` geometry/material fields for rebinding.
diff --git a/src/renderer.js b/src/renderer.js
index 939e3c78..797c3c3a 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -19,7 +19,7 @@ import { MaterialSnapshot } from './material-snapshot.js';
import { fittedFogDensity } from './fog-fit.js';
import { InstanceSelection, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from './render-culling.js';
import { resolveShadowLight, shadowBiasPerSlope } from './shadow-light.js';
-import { requireDeformationSupport, textureUpdateSupport } from './shader-registry.js';
+import { requireDeformationSupport, texturedReplaceSupport, textureUpdateSupport } from './shader-registry.js';
const SHADOW_MAP_SIZE = 2048;
// Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.
@@ -102,13 +102,7 @@ function renderPass(material) {
}
function partNeedsFullUpload(part) {
- return Boolean(part.skin || part.morph || part.crowd || part.material.layers || part.geometry.morphTargets || part.geometry.skinIndices);
-}
-
-// The texture descriptors a batch binds. Layer and splat maps are included so a texture they share is never freed.
-function batchTextureDescriptors(batch) {
- const state = batch.mapState;
- return [...state.slice(0, 5), state[14], ...Object.values(state[18] ?? {}), state[17]?.maskMap].filter(Boolean);
+ return Boolean(part.skin || part.morph || part.geometry.morphTargets || part.geometry.skinIndices || hasMaterialMap(part.material) && !texturedReplaceSupport.begin);
}
function batchPass(batch) {
@@ -1019,7 +1013,7 @@ export class Renderer67 {
return batch;
}
- /** Reconcile immutable rigid geometry, textured or not, without rebuilding programs or render targets. */
+ /** Reconcile immutable rigid, untextured geometry without rebuilding programs or render targets. */
replaceParts(parts) {
if (!Array.isArray(parts) || new Set(parts).size !== parts.length) {
throw new TypeError('Scene parts must be an array with distinct object identities.');
@@ -1050,16 +1044,16 @@ export class Renderer67 {
}
return { group, batch: null };
});
- // Skinned, morphed, crowd and splat-layer batches own pose and layer resources that are not reconciled here; they stay valid only while retained unchanged.
+ // Skinned and morphed batches stay valid only while retained unchanged. Textured ones need the replace-textured-parts addon to be added or dropped.
for (const item of replacements) {
if (!item.batch && item.group.some(partNeedsFullUpload)) {
- throw new Error('replaceParts can add or change only rigid parts. Keep skinned, morphed, crowd and layered parts unchanged so their batches are retained.');
+ throw new Error('replaceParts can add or change only rigid, untextured parts. Keep textured, skinned and morphed parts unchanged, or import replace-textured-parts to add textured ones.');
}
}
for (const [part, location] of this.partLocations) {
if (retained.has(location.batch)) continue;
- if (location.skin || location.morph || location.morphTargets || location.skinIndices || location.batch.crowd || location.batch.splat) {
- throw new Error(`replaceParts can remove or regroup only existing rigid parts; ${part.name} is skinned, morphed or layered and needs a new renderer.`);
+ if (location.skin || location.morph || location.morphTargets || location.skinIndices || (location.mapState.slice(0, 5).some(Boolean) && !texturedReplaceSupport.begin)) {
+ throw new Error(`replaceParts can remove or regroup only existing rigid, untextured parts; ${part.name} is textured, skinned or morphed and needs a new renderer.`);
}
}
const newGeometryBytes = [...geometries].filter(geometry => !this.geometryBuffers.has(geometry)).reduce((total, geometry) => total + geometryBufferBytes(geometry), 0);
@@ -1073,7 +1067,7 @@ export class Renderer67 {
const previousBuffers = [...this.buffers];
const previousGeometryBytes = this.geometryBytes;
const previousGeometryBuffers = new Map(this.geometryBuffers);
- const previousTextures = new Map(this.textures);
+ const settleTextures = texturedReplaceSupport.begin?.(this);
const stagedLocations = new Map();
const stagedBatches = [];
this.partLocations = stagedLocations;
@@ -1106,7 +1100,7 @@ export class Renderer67 {
this.buffers = previousBuffers;
this.geometryBytes = previousGeometryBytes;
this.geometryBuffers = previousGeometryBuffers;
- this.dropTextures([...this.textures.keys()].filter(descriptor => !previousTextures.has(descriptor)));
+ settleTextures?.();
this.partLocations = previousLocations;
throw error;
}
@@ -1126,10 +1120,7 @@ export class Renderer67 {
}
for (const buffer of releasedBuffers) this.context.deleteBuffer(buffer);
this.buffers = this.buffers.filter(buffer => !releasedBuffers.has(buffer));
- const bound = new Set(stagedBatches.flatMap(batchTextureDescriptors));
- const added = [...this.textures.keys()].filter(descriptor => descriptor && !previousTextures.has(descriptor));
- const unbound = this.batches.flatMap(batchTextureDescriptors).filter(descriptor => !bound.has(descriptor) && this.textures.has(descriptor));
- this.textureBytes += added.reduce((total, descriptor) => total + textureDescriptorInfo(descriptor).bytes, 0) - this.dropTextures(unbound);
+ settleTextures?.(this.batches, stagedBatches);
this.geometryBytes = [...geometries].reduce((total, geometry) => total + geometryBufferBytes(geometry), 0) + renderParts.length * INSTANCE_STRIDE * 4;
this.batches = stagedBatches;
this.partCount = parts.length;
@@ -1140,17 +1131,6 @@ export class Renderer67 {
return parts.length;
}
- // Deletes textures no batch binds any more and returns the bytes they held.
- dropTextures(descriptors) {
- let bytes = 0;
- for (const descriptor of new Set(descriptors)) {
- this.context.deleteTexture(this.textures.get(descriptor));
- this.textures.delete(descriptor);
- bytes += textureDescriptorInfo(descriptor).bytes;
- }
- return bytes;
- }
-
createSkinTexture(cache, identity, matrices, groupSize) {
if (cache.has(identity)) return cache.get(identity);
const context = this.context;
diff --git a/src/replace-textured-parts.js b/src/replace-textured-parts.js
new file mode 100644
index 00000000..f63c1a5f
--- /dev/null
+++ b/src/replace-textured-parts.js
@@ -0,0 +1,41 @@
+// Lets renderer.replaceParts add and remove textured parts. Importing this module registers the texture bookkeeping
+// that replaceParts runs around its batch swap (the pattern of texture-update.js), so a scene that never streams
+// textured parts does not carry it.
+//
+// A texture is deleted, and its bytes leave the texture ledger, once no kept or new batch binds it. A texture that
+// another part still binds stays. Skinned and morphed parts are still not reconciled by replaceParts.
+import { textureDescriptorInfo } from './renderer.js';
+import { texturedReplaceSupport } from './shader-registry.js';
+
+// Every texture descriptor a batch binds, including layer and splat-mask maps, so a texture they share is never freed.
+export function batchTextureDescriptors(batch) {
+ const state = batch.mapState;
+ return [...state.slice(0, 5), state[14], ...Object.values(state[18] ?? {}), state[17]?.maskMap].filter(Boolean);
+}
+
+function deleteTextures(renderer, descriptors) {
+ let bytes = 0;
+ for (const descriptor of new Set(descriptors)) {
+ renderer.context.deleteTexture(renderer.textures.get(descriptor));
+ renderer.textures.delete(descriptor);
+ bytes += textureDescriptorInfo(descriptor).bytes;
+ }
+ return bytes;
+}
+
+texturedReplaceSupport.begin = renderer => {
+ const previousTextures = new Map(renderer.textures);
+ // The shared white texture has a null key and the renderer owns it; only descriptors uploaded during the replace are new.
+ const uploadedDuringReplace = () => [...renderer.textures.keys()].filter(descriptor => descriptor && !previousTextures.has(descriptor));
+ // Called without batches, it rolls the replace back; with the batches before and after, it settles the ledger.
+ return (previousBatches, nextBatches) => {
+ if (!nextBatches) {
+ deleteTextures(renderer, uploadedDuringReplace());
+ return;
+ }
+ const bound = new Set(nextBatches.flatMap(batchTextureDescriptors));
+ const unbound = previousBatches.flatMap(batchTextureDescriptors).filter(descriptor => !bound.has(descriptor) && renderer.textures.has(descriptor));
+ const addedBytes = uploadedDuringReplace().reduce((total, descriptor) => total + textureDescriptorInfo(descriptor).bytes, 0);
+ renderer.textureBytes += addedBytes - deleteTextures(renderer, unbound);
+ };
+};
diff --git a/src/shader-registry.js b/src/shader-registry.js
index 3732e3c4..dd88627c 100644
--- a/src/shader-registry.js
+++ b/src/shader-registry.js
@@ -18,6 +18,9 @@ export const viewTransformShader = {};
// texture-update.js sets update(renderer, descriptor, update): the body of renderer.updateTexture.
export const textureUpdateSupport = {};
+// replace-textured-parts.js sets begin(renderer) for replaceParts; it returns settle(previousBatches, nextBatches), which rolls back when called with no arguments.
+export const texturedReplaceSupport = {};
+
// splat-shader.js sets the JavaScript half of the splat ground material: validate, textureBytes, resolveSize,
// packParameters and buildPixels. The renderer calls them only for a material with layers.
const splatSupport = {};
diff --git a/tests/renderer-topology.test.js b/tests/renderer-topology.test.js
index bc7eaa39..f129fc2a 100644
--- a/tests/renderer-topology.test.js
+++ b/tests/renderer-topology.test.js
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { mat4 } from 'gl-matrix';
import { box, sphere } from '../src/geometry.js';
import { Renderer67 } from '../src/renderer.js';
+import '../src/replace-textured-parts.js';
function part(name, geometry) {
return { name, geometry, matrix: mat4.create(), material: { tag: 'surface', color: [0.5, 0.6, 0.7], metallic: 0, roughness: 0.5 } };
diff --git a/tests/replace-textured-parts-import.test.js b/tests/replace-textured-parts-import.test.js
new file mode 100644
index 00000000..fd4b5564
--- /dev/null
+++ b/tests/replace-textured-parts-import.test.js
@@ -0,0 +1,17 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4 } from 'gl-matrix';
+import { box } from '../src/geometry.js';
+import { Renderer67 } from '../src/renderer.js';
+
+// This file never imports the replace-textured-parts addon, so the core has no texture bookkeeping registered.
+test('adding a textured part without the addon names the import to add', () => {
+ const renderer = Object.create(Renderer67.prototype);
+ renderer.groundPart = null;
+ renderer.batching = true;
+ renderer.geometryBuffers = new Map();
+ renderer.partLocations = new Map();
+ const geometry = { ...box(), uvs: new Float32Array(box().positions.length / 3 * 2) };
+ const textured = { name: 'textured', geometry, matrix: mat4.create(), material: { tag: 'surface', color: [1, 1, 1], metallic: 0, roughness: 0.5, map: { image: { width: 1, height: 1 } } } };
+ assert.throws(() => renderer.replaceParts([textured]), /import replace-textured-parts/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 10087ee3..658eaf33 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -97,6 +97,7 @@ export default defineConfig({
'compact-color': 'src/compact-color.js',
'gaussian-splats': 'src/gaussian-splats.js',
'texture-update': 'src/texture-update.js',
+ 'replace-textured-parts': 'src/replace-textured-parts.js',
// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.
'mcp/preview': 'scripts/agent-preview-browser.js',
},