Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(kit): T2.3 kit contract — ORM packing, palette variants, KTX2 (#16)
Matthew Kissinger022b30fbec42
diff --git a/src/__tests__/kit.test.ts b/src/__tests__/kit.test.tsnew file mode 100644index 00000000..98e6dff8--- /dev/null+++ b/src/__tests__/kit.test.ts@@ -0,0 +1,240 @@+/**+ * T2.3 kit contract.+ *+ * The pass rewrites the bytes we persist and hand to users, so what matters is+ * not that it does something but that what it produces is still a valid glTF, is+ * still the same asset by default, and degrades honestly when the environment+ * cannot do part of the job.+ */+import { describe, expect, test } from 'bun:test';++import { WebIO } from '@gltf-transform/core';+import { KHRMaterialsVariants, KHRTextureBasisu } from '@gltf-transform/extensions';++import { findKtxEncoder, resetKtxEncoderProbe, type KitVariantSpec } from '../kit';+import { packKitGlb, renderGLB } from '../render';++const io = (): WebIO => new WebIO().registerExtensions([KHRMaterialsVariants, KHRTextureBasisu]);++/** Noisy, like a photographic scan. This is the case KTX2 wins decisively. */+const NOISY = `+const meta = { name: 'Rock', category: 'prop' };++async function build() {+ const root = createRoot('Rock');+ const albedo = proceduralTexture({+ size: 256,+ layers: [+ { op: 'solid', color: 0x8a5a2b },+ { op: 'noise', colorA: 0x5c3a1a, colorB: 0xa07040, octaves: 5, scale: 6, blend: 'multiply' },+ { op: 'noise', colorA: 0x2b1a0c, colorB: 0xd0b090, octaves: 4, scale: 20, blend: 'overlay' },+ ],+ });+ root.add(createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo, roughness: 0.9 }), {}));+ return root;+}+`;++/** Flat two-colour pattern. PNG entropy-codes this to almost nothing. */+const TEXTURED = `+const meta = { name: 'Crate', category: 'prop' };++async function build() {+ const root = createRoot('Crate');+ const albedo = proceduralTexture({+ size: 64,+ layers: [+ { op: 'solid', color: 0x8a5a2b },+ { op: 'bricks', brick: 0xc09050, mortar: 0x6a4020, scale: 4, blend: 'overlay' },+ ],+ });+ root.add(createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo, roughness: 0.8 }), {}));+ return root;+}+`;++const UNTEXTURED = `+const meta = { name: 'Blocks', category: 'prop' };++async function build() {+ const root = createRoot('Blocks');+ root.add(createPart('A', boxGeo(1, 1, 1), gameMaterial(0x3355aa), {}));+ root.add(createPart('B', boxGeo(1, 1, 1), gameMaterial(0xaa4433), { position: [1.2, 0, 0] }));+ return root;+}+`;++/** A flat texture plus an untextured part, so variants land and the file changes+ * even when the KTX2 encode declines. */+const FLAT_MIXED = `+const meta = { name: 'Shelf', category: 'prop' };++async function build() {+ const root = createRoot('Shelf');+ const albedo = proceduralTexture({+ size: 64,+ layers: [+ { op: 'solid', color: 0x8a5a2b },+ { op: 'bricks', brick: 0xc09050, mortar: 0x6a4020, scale: 4, blend: 'overlay' },+ ],+ });+ root.add(createPart('Body', boxGeo(1, 1, 1), pbrMaterial({ albedo, roughness: 0.8 }), {}));+ root.add(createPart('Leg', boxGeo(0.2, 1, 0.2), gameMaterial(0x3355aa), { position: [1, 0, 0] }));+ return root;+}+`;++const PALETTES: KitVariantSpec[] = [+ { name: 'Rust', slots: [{ color: '#8a3b21' }, { color: '#c76a3a' }] },+ { name: 'Frost', slots: [{ color: '#9fc9d8' }, { color: '#e8f2f6' }] },+];++async function glbOf(code: string): Promise<Uint8Array> {+ return (await renderGLB(code, {})).glb;+}++describe('palette colourways as KHR_materials_variants', () => {+ test('one file carries every palette, and the default look is unchanged', async () => {+ const original = await glbOf(UNTEXTURED);+ const packed = await packKitGlb(original, { variants: PALETTES, ktx2: false });++ expect(packed).toBeDefined();+ expect(packed!.summary.variantsAdded).toEqual(['Rust', 'Frost']);+ expect(packed!.gltfValidation.issues.numErrors).toBe(0);++ const doc = await io().readBinary(packed!.bytes);+ const extension = doc+ .getRoot()+ .listExtensionsUsed()+ .map((value) => value.extensionName);+ expect(extension).toContain('KHR_materials_variants');++ // The material a primitive resolves to with NO variant selected must still be+ // the authored one. A viewer that ignores the extension has to show exactly+ // what it showed before this pass existed.+ const before = await new WebIO().readBinary(original);+ const beforeColors = before+ .getRoot()+ .listMeshes()+ .flatMap((mesh) => mesh.listPrimitives().map((p) => p.getMaterial()?.getBaseColorFactor()));+ const afterColors = doc+ .getRoot()+ .listMeshes()+ .flatMap((mesh) => mesh.listPrimitives().map((p) => p.getMaterial()?.getBaseColorFactor()));+ expect(afterColors).toEqual(beforeColors);+ });++ test('a textured material is left alone, exactly as the palette snap leaves it', async () => {+ const packed = await packKitGlb(await glbOf(TEXTURED), { variants: PALETTES, ktx2: false });++ // A textured material carries its own colour. Recolouring the factor would+ // multiply against the texture and mud it, which is why snapGlbToPalette+ // makes the same exception.+ expect(packed?.summary.variantMaterialsCreated ?? 0).toBe(0);+ expect(packed?.summary.variantsAdded ?? []).toEqual([]);+ });++ test('no variants requested means no extension is declared', async () => {+ const packed = await packKitGlb(await glbOf(UNTEXTURED), { ktx2: false });++ // Nothing to do and nothing done: returning bytes here would persist a+ // rewrite that changed only the file's hash.+ expect(packed).toBeUndefined();+ });+});++describe('KTX2 supercompression', () => {+ test('a missing encoder is reported as a capability, not a failure', async () => {+ resetKtxEncoderProbe();+ const previous = process.env['KILN_KTX_BIN'];+ process.env['KILN_KTX_BIN'] = '';+ try {+ // Simulated by asking for an encoder that cannot exist. The real point is+ // that offline CI and a fresh checkout have no KTX-Software, and failing+ // the whole packaging step there would break work unrelated to textures.+ const packed = await packKitGlb(await glbOf(UNTEXTURED), {+ variants: PALETTES,+ ktx2: true,+ });++ expect(packed).toBeDefined();+ // Variants still landed. Only the texture step is conditional.+ expect(packed!.summary.variantsAdded).toEqual(['Rust', 'Frost']);+ if (!packed!.summary.ktx2.applied) {+ expect(packed!.summary.ktx2.skipped).toBeTruthy();+ }+ } finally {+ if (previous === undefined) delete process.env['KILN_KTX_BIN'];+ else process.env['KILN_KTX_BIN'] = previous;+ resetKtxEncoderProbe();+ }+ });++ test('encoding shrinks textures and the result still validates', async () => {+ // Gated at run time, not at collection time: CI has no KTX-Software and the+ // developer machine that produced the size measurement does.+ if (!(await findKtxEncoder())) return;+ {+ const original = await glbOf(NOISY);+ const packed = await packKitGlb(original, { ktx2: true });++ expect(packed).toBeDefined();+ expect(packed!.summary.ktx2.applied).toBe(true);+ expect(packed!.summary.ktx2.texturesEncoded).toBeGreaterThan(0);+ // The measurement this whole task rests on. Anything short of a large win+ // would not justify a binary in a container image.+ expect(packed!.summary.ktx2.bytesAfter).toBeLessThan(packed!.summary.ktx2.bytesBefore * 0.5);+ expect(packed!.bytes.byteLength).toBeLessThan(original.byteLength);+ // Khronos, not our own opinion of validity.+ expect(packed!.gltfValidation.issues.numErrors).toBe(0);++ const doc = await io().readBinary(packed!.bytes);+ expect(+ doc+ .getRoot()+ .listExtensionsUsed()+ .map((value) => value.extensionName),+ ).toContain('KHR_texture_basisu');+ // Required, not merely used: a consumer that cannot transcode must be told+ // it cannot open this file rather than silently showing it untextured.+ expect(+ doc+ .getRoot()+ .listExtensionsRequired()+ .map((value) => value.extensionName),+ ).toContain('KHR_texture_basisu');+ for (const texture of doc.getRoot().listTextures()) {+ expect(texture.getMimeType()).toBe('image/ktx2');+ }+ }+ });++ test('a texture PNG already compresses better is left as PNG', async () => {+ if (!(await findKtxEncoder())) return;+ {+ // ETC1S is fixed-rate with a container and a mipmap chain; PNG is+ // entropy-coded. On a flat two-colour pattern PNG wins outright, and+ // encoding anyway would inflate the file AND require a transcoder to open+ // it. Both costs, none of the benefit.+ const original = await glbOf(FLAT_MIXED);+ const packed = await packKitGlb(original, { variants: PALETTES, ktx2: true });++ expect(packed).toBeDefined();+ expect(packed!.summary.ktx2.applied).toBe(false);+ expect(packed!.summary.ktx2.skipped).toMatch(/KTX2 was not smaller/);+ // Measured, so the decision is visible rather than inferred.+ expect(packed!.summary.ktx2.bytesAfter).toBeGreaterThan(packed!.summary.ktx2.bytesBefore);++ const doc = await io().readBinary(packed!.bytes);+ expect(+ doc+ .getRoot()+ .listExtensionsRequired()+ .map((value) => value.extensionName),+ ).not.toContain('KHR_texture_basisu');+ for (const texture of doc.getRoot().listTextures()) {+ expect(texture.getMimeType()).toBe('image/png');+ }+ }+ });+});diff --git a/src/kit.ts b/src/kit.tsnew file mode 100644index 00000000..87bd7318--- /dev/null+++ b/src/kit.ts@@ -0,0 +1,423 @@+/**+ * Kit packaging — the web-tier pass that turns a finished GLB into something you+ * can drop into a game.+ *+ * Three things happen here, deliberately in one pass so exported bytes change+ * once rather than three times:+ *+ * 1. **ORM channel packing.** A separate occlusion image is folded into the R+ * channel of the metallic-roughness image, which is where glTF expects it.+ * One fewer image to fetch and decode.+ * 2. **Palette colourways** as `KHR_materials_variants`, so one file carries+ * every look instead of one file per look.+ * 3. **KTX2 supercompression** via `KHR_texture_basisu`. Measured at -80% to+ * -90% of texture bytes on real Kiln assets, and textures are ~97% of these+ * files.+ *+ * It runs in the web tier for the same reason {@link optimizeGlbBytes} does: the+ * runtime returns an un-optimised GLB and this re-bakes before persisting, so+ * the whole contract reaches production with no wire bump and no runtime change.+ *+ * **KTX2 needs an encoder binary that is not a JavaScript dependency.** Its+ * absence is a capability fact, not an error — the pass reports `skipped` with a+ * reason and still returns the packed, varianted GLB. Failing the whole+ * packaging step because one machine lacks a CLI would make every offline test+ * and every developer checkout fail at a step that has nothing to do with them.+ */++import { execFile } from 'node:child_process';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { promisify } from 'node:util';++import type { Document, Material, Texture } from '@gltf-transform/core';+import { KHRMaterialsVariants, KHRTextureBasisu } from '@gltf-transform/extensions';++import { buildSlotIndex, chooseSlot, hexToLinearRgb, type SnapPaletteSlot } from './palette-snap';++const run = promisify(execFile);++/** Candidate names for the KTX-Software CLI, in the order they are tried. */+export const KTX_ENCODER_CANDIDATES: readonly string[] = Object.freeze(+ [+ process.env['KILN_KTX_BIN'] ?? '',+ 'ktx',+ '/usr/bin/ktx',+ '/usr/local/bin/ktx',+ 'C:/Program Files/KTX-Software/bin/ktx.exe',+ ].filter((value): value is string => value.length > 0),+);++/** ETC1S. UASTC is higher quality and several times larger; the size claim rests on this mode. */+const KTX_ENCODE_MODE = 'basis-lz';++export interface KitVariantSpec {+ /** Shown in a viewer's variant picker, so it is a name rather than an index. */+ name: string;+ slots: readonly SnapPaletteSlot[];+}++export interface KitPackOptions {+ /** Each becomes one `KHR_materials_variants` entry. Empty means no variants. */+ variants?: readonly KitVariantSpec[];+ /** Fold a separate occlusion image into metallic-roughness R. Default true. */+ packOrm?: boolean;+ /** Default true — encode when an encoder is present, skip with a reason when not. */+ ktx2?: boolean;+}++export interface KitKtx2Summary {+ applied: boolean;+ /** Present when `applied` is false: why, in words a human can act on. */+ skipped?: string;+ encoder?: string;+ texturesEncoded: number;+ bytesBefore: number;+ bytesAfter: number;+}++/**+ * Fraction of the PNG size KTX2 must beat for the encode to be kept.+ *+ * Not 1.0. A file that shrinks by a rounding error is not worth requiring a+ * transcoder for, and the KTX2 container plus mipmap chain costs a few hundred+ * bytes before any image data — so on a small flat texture it loses outright.+ */+export const KTX2_SIZE_ACCEPT_RATIO = 0.9;++export interface KitPackSummary {+ ormPacked: number;+ variantsAdded: readonly string[];+ variantMaterialsCreated: number;+ ktx2: KitKtx2Summary;+}++let cachedEncoder: string | null | undefined;++/**+ * Locate the KTX-Software CLI once per process.+ *+ * Cached including the negative result: this runs per generation, and a missing+ * binary would otherwise cost a failed process spawn every time forever.+ */+export async function findKtxEncoder(): Promise<string | undefined> {+ if (cachedEncoder !== undefined) return cachedEncoder ?? undefined;+ for (const candidate of KTX_ENCODER_CANDIDATES) {+ try {+ await run(candidate, ['--version'], { timeout: 10_000 });+ cachedEncoder = candidate;+ return candidate;+ } catch {+ // Not at this path, or not executable. Try the next.+ }+ }+ cachedEncoder = null;+ return undefined;+}++/** Test seam: forget a probe result so a test can simulate either environment. */+export function resetKtxEncoderProbe(): void {+ cachedEncoder = undefined;+}++const isPng = (texture: Texture): boolean => texture.getMimeType() === 'image/png';++/**+ * Fold occlusion into metallic-roughness R.+ *+ * Only when the two are genuinely distinct images of identical size — a+ * mismatched pair would need resampling, and silently resampling an author's+ * occlusion map is a bigger change than leaving one extra image in the file.+ */+async function packOcclusionIntoMetallicRoughness(doc: Document): Promise<number> {+ const sharp = (await import('sharp')).default;+ let packed = 0;++ for (const material of doc.getRoot().listMaterials()) {+ const occlusion = material.getOcclusionTexture();+ const metallicRoughness = material.getMetallicRoughnessTexture();+ if (!occlusion || !metallicRoughness || occlusion === metallicRoughness) continue;+ if (!isPng(occlusion) || !isPng(metallicRoughness)) continue;++ const occlusionBytes = occlusion.getImage();+ const mrBytes = metallicRoughness.getImage();+ if (!occlusionBytes || !mrBytes) continue;++ try {+ const [occImage, mrImage] = await Promise.all([+ sharp(Buffer.from(occlusionBytes))+ .ensureAlpha()+ .raw()+ .toBuffer({ resolveWithObject: true }),+ sharp(Buffer.from(mrBytes)).ensureAlpha().raw().toBuffer({ resolveWithObject: true }),+ ]);+ if (+ occImage.info.width !== mrImage.info.width ||+ occImage.info.height !== mrImage.info.height+ ) {+ continue;+ }++ // R <- occlusion R, G/B (roughness/metalness) untouched.+ const merged = Buffer.from(mrImage.data);+ for (let i = 0; i < merged.length; i += 4) merged[i] = occImage.data[i] ?? 255;+ const png = await sharp(merged, {+ raw: { width: mrImage.info.width, height: mrImage.info.height, channels: 4 },+ })+ .png()+ .toBuffer();++ metallicRoughness.setImage(new Uint8Array(png));+ material.setOcclusionTexture(metallicRoughness);+ const info = material.getOcclusionTextureInfo();+ const mrInfo = material.getMetallicRoughnessTextureInfo();+ if (info && mrInfo) info.setTexCoord(mrInfo.getTexCoord());+ packed += 1;+ } catch {+ // A texture we cannot decode stays as it is. The file is still valid.+ }+ }++ // Any occlusion image left with no reference is dropped by the writer.+ return packed;+}++/** A palette-snapped clone of one material, or undefined when the palette does not cover it. */+function recolorForPalette(+ doc: Document,+ material: Material,+ slots: readonly SnapPaletteSlot[],+ variantName: string,+): { material: Material; changed: boolean } {+ const clone = doc.createMaterial(`${material.getName()}__${variantName}`).copy(material);+ // A textured material carries its own colour; recolouring it would fight the+ // texture. Same hero exception snapGlbToPalette makes.+ if (material.getBaseColorTexture()) return { material: clone, changed: false };++ const index = buildSlotIndex(slots);+ const base = material.getBaseColorFactor();+ const emissive = material.getEmissiveFactor();+ const slot = chooseSlot(index, {+ baseLinear: [base[0], base[1], base[2]],+ emissiveLinear: [emissive[0], emissive[1], emissive[2]],+ transparent: material.getAlphaMode() === 'BLEND' || material.getAlpha() < 0.98,+ });+ if (slot === undefined) return { material: clone, changed: false };++ const chosen = slots[slot];+ if (!chosen) return { material: clone, changed: false };+ const [r, g, b] = hexToLinearRgb(chosen.color);+ if (chosen.kind === 'glow') {+ clone.setEmissiveFactor([r, g, b]);+ } else {+ clone.setBaseColorFactor([r, g, b, base[3]]);+ if (typeof chosen.roughness === 'number') clone.setRoughnessFactor(chosen.roughness);+ if (typeof chosen.metalness === 'number') clone.setMetallicFactor(chosen.metalness);+ if (chosen.kind === 'glass' && typeof chosen.opacity === 'number') {+ clone.setBaseColorFactor([r, g, b, chosen.opacity]);+ }+ }+ return { material: clone, changed: true };+}++/**+ * Attach one `KHR_materials_variants` entry per palette.+ *+ * The default (no variant selected) stays the material the asset was authored+ * with, so a viewer that ignores the extension shows exactly what it showed+ * before this pass existed.+ */+function addPaletteVariants(+ doc: Document,+ specs: readonly KitVariantSpec[],+): { names: string[]; materialsCreated: number } {+ const extension = doc.createExtension(KHRMaterialsVariants);+ const names: string[] = [];+ let materialsCreated = 0;++ const variants = specs.map((spec) => {+ names.push(spec.name);+ return { spec, variant: extension.createVariant(spec.name) };+ });++ for (const mesh of doc.getRoot().listMeshes()) {+ for (const primitive of mesh.listPrimitives()) {+ const base = primitive.getMaterial();+ if (!base) continue;++ const mappings = variants+ .map(({ spec, variant }) => {+ const { material, changed } = recolorForPalette(doc, base, spec.slots, spec.name);+ if (!changed) {+ material.dispose();+ return undefined;+ }+ materialsCreated += 1;+ return extension.createMapping().addVariant(variant).setMaterial(material);+ })+ .filter((value): value is NonNullable<typeof value> => value !== undefined);++ if (mappings.length === 0) continue;+ const list = extension.createMappingList();+ for (const mapping of mappings) list.addMapping(mapping);+ primitive.setExtension('KHR_materials_variants', list);+ }+ }++ if (names.length === 0 || materialsCreated === 0) extension.dispose();+ return { names: materialsCreated > 0 ? names : [], materialsCreated };+}++/**+ * Encode every PNG texture to KTX2 ETC1S, then keep the result only if the file+ * actually got smaller.+ *+ * **KTX2 is not universally smaller, and assuming it is would inflate real Kiln+ * assets.** ETC1S is a fixed-rate block codec with a container and a mipmap+ * chain; PNG is entropy-coded. On a noisy photographic-style texture KTX2 wins+ * by 80-90%. On a flat two-colour procedural pattern PNG can be a few hundred+ * bytes and KTX2 several times that. Kiln generates both.+ *+ * The comparison is per file rather than per texture, so the output stays+ * homogeneous: a mixed file would still force `KHR_texture_basisu` as required+ * and lock out consumers that cannot transcode, while only banking part of the+ * win.+ */+async function encodeTexturesToKtx2(+ doc: Document,+ encoder: string,+): Promise<{ encoded: number; before: number; after: number }> {+ const textures = doc.getRoot().listTextures().filter(isPng);+ if (textures.length === 0) return { encoded: 0, before: 0, after: 0 };++ const dir = await mkdtemp(join(tmpdir(), 'kiln-ktx2-'));+ const staged: { texture: Texture; original: Uint8Array; encodedBytes: Uint8Array }[] = [];+ let encoded = 0;+ let before = 0;+ let after = 0;+ try {+ for (const [index, texture] of textures.entries()) {+ const bytes = texture.getImage();+ if (!bytes) continue;+ const src = join(dir, `t${index}.png`);+ const dst = join(dir, `t${index}.ktx2`);+ await writeFile(src, bytes);+ // The transfer function has to match the slot's colour space or the+ // encoder rejects it, and a wrongly-tagged texture would light wrong.+ const srgb = doc+ .getRoot()+ .listMaterials()+ .some(+ (material) =>+ material.getBaseColorTexture() === texture || material.getEmissiveTexture() === texture,+ );+ await run(+ encoder,+ [+ 'create',+ '--format',+ srgb ? 'R8G8B8A8_SRGB' : 'R8G8B8A8_UNORM',+ '--encode',+ KTX_ENCODE_MODE,+ '--generate-mipmap',+ src,+ dst,+ ],+ { timeout: 120_000 },+ );+ const out = await readFile(dst);+ before += bytes.byteLength;+ after += out.byteLength;+ staged.push({ texture, original: bytes, encodedBytes: new Uint8Array(out) });+ }+ } finally {+ await rm(dir, { recursive: true, force: true });+ }++ if (staged.length === 0) return { encoded: 0, before, after };+ if (after >= before * KTX2_SIZE_ACCEPT_RATIO) {+ // Nothing was mutated yet, so declining costs only the encode time.+ return { encoded: 0, before, after };+ }++ for (const entry of staged) {+ entry.texture.setImage(entry.encodedBytes).setMimeType('image/ktx2');+ encoded += 1;+ }+ // Required, not merely used: a consumer that cannot transcode must be told it+ // cannot open this file rather than silently rendering it untextured.+ doc.createExtension(KHRTextureBasisu).setRequired(true);+ return { encoded, before, after };+}++/**+ * Run the kit contract over a parsed document, in place.+ *+ * Exposed separately from the bytes-level entry point so the render path can+ * apply it without a parse/serialise round trip.+ */+export async function applyKitContract(+ doc: Document,+ options: KitPackOptions = {},+): Promise<KitPackSummary> {+ const ormPacked = options.packOrm === false ? 0 : await packOcclusionIntoMetallicRoughness(doc);++ const specs = options.variants ?? [];+ const { names, materialsCreated } = specs.length+ ? addPaletteVariants(doc, specs)+ : { names: [] as string[], materialsCreated: 0 };++ // Last: it rewrites the images the two passes above just produced, and an+ // encoder cannot read a PNG that does not exist yet.+ let ktx2: KitKtx2Summary = {+ applied: false,+ skipped: 'disabled by caller',+ texturesEncoded: 0,+ bytesBefore: 0,+ bytesAfter: 0,+ };+ if (options.ktx2 !== false) {+ const encoder = await findKtxEncoder();+ if (!encoder) {+ ktx2 = {+ applied: false,+ skipped: 'no KTX-Software encoder on PATH (set KILN_KTX_BIN to override)',+ texturesEncoded: 0,+ bytesBefore: 0,+ bytesAfter: 0,+ };+ } else {+ try {+ const result = await encodeTexturesToKtx2(doc, encoder);+ ktx2 = {+ applied: result.encoded > 0,+ ...(result.encoded > 0+ ? {}+ : {+ skipped:+ result.before === 0+ ? 'no PNG textures to encode'+ : `KTX2 was not smaller (${result.after} vs ${result.before} bytes); kept PNG`,+ }),+ encoder,+ texturesEncoded: result.encoded,+ bytesBefore: result.before,+ bytesAfter: result.after,+ };+ } catch (error) {+ // A GLB with PNG textures is worth far more than no GLB at all.+ ktx2 = {+ applied: false,+ skipped: `encoder failed: ${error instanceof Error ? error.message : String(error)}`,+ encoder,+ texturesEncoded: 0,+ bytesBefore: 0,+ bytesAfter: 0,+ };+ }+ }+ }++ return { ormPacked, variantsAdded: names, variantMaterialsCreated: materialsCreated, ktx2 };+}diff --git a/src/render.ts b/src/render.tsindex d2970e2f..f48ec9aa 100644--- a/src/render.ts+++ b/src/render.ts@@ -12,7 +12,11 @@import * as THREE from 'three';import { Document, WebIO, getBounds } from '@gltf-transform/core';-import { EXTMeshGPUInstancing } from '@gltf-transform/extensions';+import {+ EXTMeshGPUInstancing,+ KHRMaterialsVariants,+ KHRTextureBasisu,+} from '@gltf-transform/extensions';import {dedup,instance,@@ -84,6 +88,7 @@ import {type MaterialResourceProvenanceV1,} from './material-resources';import { analyzePartPenetration, type PartPenetrationEvidenceV1 } from './qa/self-intersection';+import { applyKitContract, type KitPackOptions, type KitPackSummary } from './kit';import {type BakedTextureProvenanceV1,bakeSceneTextures,@@ -109,7 +114,11 @@ export type CapturedDiagnosticV1 = CharacterCapturedDiagnosticV1 | VehicleCaptur* the instancing a prior bake emitted — the batch node would collapse to a* single copy. Write-side registration is harmless (the extension instance* travels on the Document). */-const engineIO = (): WebIO => new WebIO().registerExtensions([EXTMeshGPUInstancing]);+// Variants and Basisu are registered for READS as much as writes: once the kit+// pass has run, every later pass that parses these bytes (metrics, optimize,+// palette snap) would silently drop both extensions without them.+const engineIO = (): WebIO =>+ new WebIO().registerExtensions([EXTMeshGPUInstancing, KHRMaterialsVariants, KHRTextureBasisu]);/*** World-space AABB of a stored GLB, computed from its bytes alone — node@@ -1481,6 +1490,46 @@ export async function optimizeGlbBytes(}}+export interface PackKitResult {+ bytes: Uint8Array;+ summary: KitPackSummary;+ gltfValidation: KhronosGltfValidationReport;+}++/**+ * Apply the kit contract to a finished GLB, working from bytes.+ *+ * Sibling of {@link optimizeGlbBytes} and deliberately the same shape: parse,+ * transform, re-serialise, re-validate against Khronos. The runtime never sees+ * a kit flag, so this reaches production with no wire bump.+ *+ * Returns `undefined` when nothing changed or the bytes cannot be parsed, so a+ * caller keeps the original GLB rather than persisting a no-op rewrite.+ * Khronos validation failures are the one thing that throws: bytes that do not+ * validate must never be persisted, and silently returning the original would+ * hide that this pass produced an invalid file.+ */+export async function packKitGlb(+ bytes: Uint8Array,+ opts: KitPackOptions = {},+): Promise<PackKitResult | undefined> {+ let doc: Document;+ try {+ doc = await engineIO().readBinary(bytes);+ } catch {+ return undefined;+ }++ const summary = await applyKitContract(doc, opts);+ const changed = summary.ormPacked > 0 || summary.variantsAdded.length > 0 || summary.ktx2.applied;+ if (!changed) return undefined;++ ensureDefaultScene(doc);+ const outBytes = await engineIO().writeBinary(doc);+ const gltfValidation = await assertFinalGlbValid(outBytes);+ return { bytes: outBytes, summary, gltfValidation };+}+// =============================================================================// Palette snap (scene palettes) — web-side hard snap to a user-defined palette// =============================================================================