Skip to content

armgit / kiln

Public Imported from GitHub
0

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.

fix(delivery): preserve review channels and measured runtime diagnostics

Matt Kissinger8fb45b76aaa7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 40bf11cd..22514102 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,11 +7,20 @@ does not publish a package.
## Unreleased
+- Add optional game delivery roles, colliders, anchors, kit ports, surface bakes,
+ budgets, solid assertions, atlas packing and a compressed Three.js runtime target.
+ These describe explicit delivery choices; they do not impose an asset style or
+ require every mesh to be closed.
- Adapt the non-rock organic helpers contributed by [FaberVi (Vincenzo Fabiano)](https://github.com/FaberVi)
in [#141](https://github.com/instruktlabs/kiln/pull/141): metaball surfaces, field
composition, sampled paths, tapered tubes, curls and smoothing. Maintainer
integration corrects sampling, recipes, input validation and unsafe count arithmetic while
retaining the original blend default. See the [provenance record](docs/reviews/2026-10-16-organic-adoption.md).
+- Preserve vertex colors and additional UV channels in review reconstruction and
+ custom capture derivatives; measure draw diagnostics on Meshopt runtime exports;
+ retain bounded topology facts when an explicit solid assertion fails.
+- Document quantized skin transforms and consumer-owned LOD selection, and bring
+ demonstrated authoring and harness lessons into maintained workspace guidance.
## 1.2.3 (2026-10-12)
diff --git a/docs/delivery-contract.md b/docs/delivery-contract.md
index fd57a2f7..01efe741 100644
--- a/docs/delivery-contract.md
+++ b/docs/delivery-contract.md
@@ -66,6 +66,16 @@ attribute names, so shaders read `_edge` and `_cavity`.
under `part` is closed, manifold and outward. `geometryDiagnostics(geometry).solid`
reports the same facts and the signed volume.
+Across the evaluator boundary, `REQUIRE_SOLID` retains measurements for at most four
+failing meshes, the total failure count and a truncation flag. A numeric locator
+such as `root.children[0].children[2]` identifies the mesh in the authored build
+root before export. The tool error includes closure, manifoldness, orientation and
+edge counts. Follow the child order in the retained source to inspect that mesh;
+the failed build has no exported inspection artifact. Names and exception text
+are not forwarded. A locator deeper than 64 levels is omitted, while its measured
+facts remain. This is diagnostic evidence for explicitly marked parts, not a new
+universal requirement that every mesh be closed.
+
## Integration manifest fields
`inspectGlbIntegration(bytes)`, render results and CLI `render --json` receipts add
@@ -112,14 +122,31 @@ batches. See [export profiles](export-profiles.md#threejs-runtime-target).
Consumer rules that follow from it:
-- **Read geometry through its node.** Quantized positions are normalized integers;
- the node's matrix restores metres. A bare geometry re-parented into your own mesh
- drops that scale. `delivery.nodeScale` lists every such node.
+- **Keep the loaded mesh and its transforms.** Quantized positions are normalized
+ integers. Static mesh node transforms restore metres; `delivery.nodeScale` lists
+ those node changes. For skinned meshes, the quantizer folds dequantization into
+ the skin's inverse bind matrices instead. Keep the loaded skeleton, bind matrices
+ and hierarchy together. Copying bare geometry into a new mesh, or replacing the
+ inverse bind matrices with the editable asset's matrices, loses that correction.
- **Collider transforms are exact.** A collider's proxy mesh moves to a child named
`<collider>_Proxy`, so the collider node's scale is still its size.
- **Custom attributes stay float.** `_EDGE` and `_CAVITY` are never quantized.
- **Find nodes by role, not by name alone.** three's `GLTFLoader` makes object names
unique, so an asset root that shares the scene's name loads with a numeric suffix.
+- **Choose LOD levels in the consumer.** `GLTFLoader` preserves `MSFT_lod` extension
+ data but does not create a `THREE.LOD` controller or automatically switch levels.
+ LOD0 is attached to the scene. Read its `userData.gltfExtensions.MSFT_lod.ids`,
+ resolve lower tiers with `gltf.parser.getDependency('node', id)`, and install them
+ under the appropriate authored parent. Your application chooses one active tier
+ using the retained `MSFT_screencoverage` policy or its own documented policy.
+ Do not show all levels together. A final impostor marker does not implement
+ billboarding or distance-based switching.
+
+`src/__tests__/runtime-three-export.test.ts` qualifies static geometry, role data,
+instancing, explicit lower-tier selection and a quantized skin through Three's
+`GLTFLoader` with `MeshoptDecoder`. The skin test compares rest and two posed
+world-space vertex sets within 1 mm on its four-metre fixture. It is a focused
+consumer regression, not acceptance of every rig, animation or game integration.
## Worked example
diff --git a/package.json b/package.json
index b7a2ae46..f72ae1fd 100644
--- a/package.json
+++ b/package.json
@@ -287,6 +287,7 @@
"docs/chatgpt.md",
"docs/collections.md",
"docs/community-exporter.md",
+ "docs/delivery-contract.md",
"docs/engine-handoff.md",
"docs/examples.md",
"docs/export-profiles.md",
diff --git a/scripts/consumer-documentation.test.mjs b/scripts/consumer-documentation.test.mjs
new file mode 100644
index 00000000..511eccd0
--- /dev/null
+++ b/scripts/consumer-documentation.test.mjs
@@ -0,0 +1,21 @@
+import { expect, test } from 'bun:test';
+import { readFile } from 'node:fs/promises';
+import { relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = fileURLToPath(new URL('../', import.meta.url));
+
+test('consumer guides include the documentation they link to in the package', async () => {
+ const manifest = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8'));
+ const guides = manifest.files.filter((path) => path.startsWith('docs/'));
+ for (const guide of guides) {
+ const source = new URL(guide, new URL('../', import.meta.url));
+ const body = await readFile(source, 'utf8');
+ for (const [, href] of body.matchAll(/\]\(([^)\s]+)\)/g)) {
+ if (/^(?:[a-z]+:|\/|#)/i.test(href)) continue;
+ const target = relative(root, fileURLToPath(new URL(href, source))).replaceAll('\\', '/');
+ if (!target.startsWith('docs/') || !target.endsWith('.md')) continue;
+ expect(guides, `${guide} links to unpackaged guide ${target}`).toContain(target);
+ }
+ }
+});
diff --git a/skills/kiln-author-asset/references/export-profiles.md b/skills/kiln-author-asset/references/export-profiles.md
index 2c1116aa..f384cb23 100644
--- a/skills/kiln-author-asset/references/export-profiles.md
+++ b/skills/kiln-author-asset/references/export-profiles.md
@@ -45,8 +45,37 @@ unsupported UV transforms and destination feature support still need qualificati
Neither setting automatically enables mesh merging, geometry simplification, Draco,
Meshopt or KTX2 compression. Those require separate choices and validation.
+### Optional Three.js runtime target
+
+The runtime profile also accepts `target: "three"` (CLI `--target three`). This is
+a third choice, separate from the build converter: it derives the saved GLB using
+Meshopt compression and quantization, and batches explicitly marked repeated
+instances. Read the current Discovery export capability and the packaged
+`docs/delivery-contract.md` and `docs/export-profiles.md` for its exact contract.
+Plain `--profile runtime` keeps the byte-preserving geometry policy described below;
+the additional target changes geometry encoding and can change hierarchy.
+
+Use this target only for a consumer configured with Meshopt decoding. Preserve
+loaded node transforms, skeletons and inverse bind matrices: they restore quantized
+positions to the intended dimensions. A loader does not automatically implement
+Kiln's LOD selection, collider behavior, anchors or kit snapping. Test those in the
+destination application when requested. Retain the editable asset and compare
+dimensions, colors, animation poses and the target's delivery receipt, not file size
+alone. A skipped draw assessment is unmeasured, never a passing performance result.
+
## CLI
+### Optional game delivery semantics
+
+Discover collider, anchor, kit, surface-bake and budget helpers when the request
+needs them. Add semantic roles for the consumer's intended interactions; the roles
+do not implement physics, snapping or gameplay. Standalone decorative assets do
+not need anchors, projects or a kit declaration. Use `requireSolid` only for a part
+explicitly intended to satisfy that topology contract. These choices describe the
+requested asset, not a required modeling style.
+
+### Export commands
+
From an asset workspace, using the IDs returned by `save` or `assets`:
```sh
@@ -60,6 +89,9 @@ node kiln.mjs export ASSET_ID REVISION_ID --profile editable --format glb --out
node kiln.mjs export ASSET_ID REVISION_ID --profile runtime --out mech.glb
# mech.glb
# mech.kiln-metadata.json
+
+# Optional Three.js derivative, with a machine-readable export receipt.
+node kiln.mjs export ASSET_ID REVISION_ID --profile runtime --target three --out mech-three.glb --json
```
Runtime requires GLB format and an output ending in `.glb`. Bundle/source formats
@@ -116,6 +148,10 @@ glTF exporter or decode/re-encode textures.
## What runtime changes
+This section describes runtime **without** `target: "three"`. The optional target
+adds the transformations described above and records them in the sidecar's
+`delivery` block.
+
Only `scenes[].extras.kilnReviewClipsV1` is moved into the JSON sidecar. It contains
Kiln's authored animation review vocabulary, including advisory tracks that might not
have valid native glTF targets. Native `animations` remain authoritative for playback.
diff --git a/skills/kiln-qa-asset/SKILL.md b/skills/kiln-qa-asset/SKILL.md
index 792f73c4..f5955bff 100644
--- a/skills/kiln-qa-asset/SKILL.md
+++ b/skills/kiln-qa-asset/SKILL.md
@@ -22,6 +22,15 @@ Read validation/build findings and export warnings. MCP render and inspection re
Distinguish expected open sheets from invalid solid topology. `geometryDiagnostics` reports boundary edges, non-manifold edges, orientation conflicts and degenerates; it does not prove absence of self-intersection. A capped loft, shell-like surface, or sampled field is not automatically a manufacturing-grade solid.
+Use `requireSolid` only on parts whose intended use requires closed, manifold,
+outward geometry. It is an explicit build assertion, not a rule for every mesh or
+an asset-name heuristic. Its error retains bounded topology measurements and
+numeric child locators in the authored build root; use the retained source's child
+order to find a failure, since a failed build has no exported inspection artifact.
+An open card, cloth sheet or intentionally open shell can be valid for its purpose.
+Keep budget and palette observations separate from requirements explicitly requested
+by the user; strict budget enforcement is opt-in.
+
An intentional boundary can use `markOpenShell(part, 'specific reason')`. Read the
overlap report's acknowledgment and reason; this is an explicit measurement limit,
not a clean result. Closed components are unioned before measuring overlap;
diff --git a/src/__tests__/draw-diagnostics.test.ts b/src/__tests__/draw-diagnostics.test.ts
index 71dd15cc..8d916219 100644
--- a/src/__tests__/draw-diagnostics.test.ts
+++ b/src/__tests__/draw-diagnostics.test.ts
@@ -3,6 +3,8 @@ import { Document, type Material, type Primitive } from '@gltf-transform/core';
import { KHRNodeVisibility } from '@gltf-transform/extensions';
import { analyzeDrawDiagnostics, inspectDrawDiagnostics } from '../draw-diagnostics';
import { createGltfIO } from '../gltf-io';
+import { deliverThreeRuntimeGlb } from '../asset-export';
+import { MeshoptDecoder } from 'meshoptimizer';
function fixture() {
const doc = new Document();
@@ -36,6 +38,66 @@ function fixture() {
return { doc, scene, material, primitive, node, buffer };
}
+interface TestGlbJson {
+ bufferViews: Array<{
+ extensions?: { EXT_meshopt_compression?: { count: number; mode: string } };
+ }>;
+}
+function replaceGlbJson(bytes: Uint8Array, edit: (json: TestGlbJson) => void): Uint8Array {
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const oldLength = header.getUint32(12, true);
+ const json = JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + oldLength)));
+ edit(json);
+ const encoded = new TextEncoder().encode(JSON.stringify(json));
+ const length = Math.ceil(encoded.length / 4) * 4;
+ const result = new Uint8Array(bytes.length - oldLength + length);
+ result.set(bytes.subarray(0, 20));
+ const resultHeader = new DataView(result.buffer);
+ resultHeader.setUint32(8, result.length, true);
+ resultHeader.setUint32(12, length, true);
+ result.fill(32, 20, 20 + length);
+ result.set(encoded, 20);
+ result.set(bytes.subarray(20 + oldLength), 20 + length);
+ return result;
+}
+
+test('draw diagnostics decode the exact meshopt runtime export', async () => {
+ const f = fixture();
+ f.node('A');
+ f.node('B').setTranslation([2, 0, 0]);
+ const runtime = await deliverThreeRuntimeGlb(await createGltfIO().writeBinary(f.doc));
+ await MeshoptDecoder.ready;
+ const independentlyDecoded = await createGltfIO()
+ .registerDependencies({ 'meshopt.decoder': MeshoptDecoder })
+ .readBinary(runtime.glb);
+ const report = await inspectDrawDiagnostics(runtime.glb);
+ expect(report.status).toBe('assessed');
+ expect(report.currentDraws).toBe(2);
+ expect(report).toEqual(analyzeDrawDiagnostics(independentlyDecoded));
+});
+
+test('draw diagnostics bound meshopt expansion before decoding and reject malformed streams', async () => {
+ const f = fixture();
+ f.node('A');
+ const runtime = await deliverThreeRuntimeGlb(await createGltfIO().writeBinary(f.doc));
+ const oversized = replaceGlbJson(runtime.glb, (json) => {
+ const view = json.bufferViews.find((v) => v.extensions?.EXT_meshopt_compression)!;
+ view.extensions!.EXT_meshopt_compression!.count = 64 * 1024 * 1024;
+ });
+ expect(await inspectDrawDiagnostics(oversized)).toMatchObject({
+ status: 'skipped',
+ reason: 'input-limit',
+ });
+ const malformed = replaceGlbJson(runtime.glb, (json) => {
+ const view = json.bufferViews.find((v) => v.extensions?.EXT_meshopt_compression)!;
+ view.extensions!.EXT_meshopt_compression!.mode = 'INVALID';
+ });
+ expect(await inspectDrawDiagnostics(malformed)).toMatchObject({
+ status: 'skipped',
+ reason: 'unreadable-glb',
+ });
+});
+
test('draw estimates use actual rigid groups, layouts and locks and never change the input', async () => {
const f = fixture();
f.node('A');
diff --git a/src/__tests__/runtime-three-export.test.ts b/src/__tests__/runtime-three-export.test.ts
index 235e66a9..182c0e10 100644
--- a/src/__tests__/runtime-three-export.test.ts
+++ b/src/__tests__/runtime-three-export.test.ts
@@ -177,6 +177,16 @@ describe('three runtime target', () => {
expect(ids).toHaveLength(1);
const level = (await gltf.parser.getDependency('node', ids[0]!)) as THREE.Object3D;
expect(level.name).toBe('Lamp_LOD1');
+ expect(scene.getObjectByName('Lamp_LOD1')).toBeUndefined();
+ expect(lamp).not.toBeInstanceOf(THREE.LOD);
+ // GLTFLoader does not choose a level. An application must attach and select it.
+ lamp.parent!.add(level);
+ lamp.visible = false;
+ level.visible = true;
+ scene.updateMatrixWorld(true);
+ const cardBounds = new THREE.Box3().setFromObject(level, true);
+ expect(cardBounds.getSize(new THREE.Vector3()).x).toBeCloseTo(0.2, 3);
+ expect(cardBounds.getCenter(new THREE.Vector3()).y).toBeCloseTo(3.1, 3);
});
test('KTX2 runs only through an injected encoder and the GLB library helper is equivalent', async () => {
@@ -224,4 +234,68 @@ describe('three runtime target', () => {
exportAssetGlb(assetRecord(new Uint8Array(rendered.glb)), { target: 'three' }),
).rejects.toThrow(/runtime/);
});
+
+ test('quantized skin retains rest and posed world-space vertices through GLTFLoader', async () => {
+ const root = new THREE.Group();
+ root.position.set(3, 2, -4);
+ const geometry = new THREE.BoxGeometry(2, 4, 1);
+ const positions = geometry.getAttribute('position');
+ const indices: number[] = [];
+ const weights: number[] = [];
+ for (let i = 0; i < positions.count; i++) {
+ const upper = positions.getY(i) > 0;
+ indices.push(upper ? 1 : 0, 0, 0, 0);
+ weights.push(1, 0, 0, 0);
+ }
+ geometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(indices, 4));
+ geometry.setAttribute('skinWeight', new THREE.Float32BufferAttribute(weights, 4));
+ const mesh = new THREE.SkinnedMesh(geometry, new THREE.MeshStandardMaterial());
+ mesh.name = 'Skin';
+ const base = new THREE.Bone();
+ base.name = 'Base';
+ const tip = new THREE.Bone();
+ tip.name = 'Tip';
+ tip.position.y = 1;
+ base.add(tip);
+ mesh.add(base);
+ root.add(mesh);
+ root.updateMatrixWorld(true);
+ mesh.bind(new THREE.Skeleton([base, tip]));
+ const source = await renderSceneToGLB(root, {
+ gltfExporter: 'three',
+ optimize: 'off',
+ derivative: true,
+ });
+ const runtime = await deliverThreeRuntimeGlb(source.bytes);
+ const loaded = await loadWithGltfLoader(runtime.glb);
+ const skin = find(loaded.scene, 'Skin') as THREE.SkinnedMesh;
+ expect(skin.isSkinnedMesh).toBe(true);
+ expect(skin.geometry.getAttribute('position').normalized).toBe(true);
+ // Skin dequantization is folded into inverse bind matrices, not a nodeScale entry.
+ expect(runtime.delivery.nodeScale.some((entry) => entry.node.includes('Skin'))).toBe(false);
+ expect(skin.skeleton.boneInverses[0]!.equals(mesh.skeleton.boneInverses[0]!)).toBe(false);
+ const sample = (scene: THREE.Object3D, target: THREE.SkinnedMesh) => {
+ scene.updateMatrixWorld(true);
+ target.skeleton.update();
+ return Array.from({ length: target.geometry.getAttribute('position').count }, (_, i) =>
+ target.getVertexPosition(i, new THREE.Vector3()).applyMatrix4(target.matrixWorld),
+ );
+ };
+ for (const angle of [0, 0.35, 0.7]) {
+ tip.rotation.z = angle;
+ find(loaded.scene, 'Tip').rotation.z = angle;
+ const expected = sample(root, mesh);
+ const actual = sample(loaded.scene, skin);
+ expect(actual).toHaveLength(expected.length);
+ // Vertex reordering is allowed; every exported point must remain within 1 mm.
+ for (const point of actual)
+ expect(Math.min(...expected.map((candidate) => candidate.distanceTo(point)))).toBeLessThan(
+ 0.001,
+ );
+ for (const point of expected)
+ expect(Math.min(...actual.map((candidate) => candidate.distanceTo(point)))).toBeLessThan(
+ 0.001,
+ );
+ }
+ });
});
diff --git a/src/__tests__/solid-diagnostics.test.ts b/src/__tests__/solid-diagnostics.test.ts
index 3d7ecaeb..20334292 100644
--- a/src/__tests__/solid-diagnostics.test.ts
+++ b/src/__tests__/solid-diagnostics.test.ts
@@ -15,7 +15,8 @@ import {
import { geometryDiagnostics } from '../geometry';
import { buildSandboxGlobals } from '../primitives';
import { renderGLBInProcess, renderSceneToGLB } from '../render';
-import { REQUIRE_SOLID_KEY, requireSolid } from '../require-solid';
+import { REQUIRE_SOLID_KEY, requireSolid, assertRequiredSolids } from '../require-solid';
+import { RequiredSolidError } from '../evaluator/solid-diagnostic';
function flipped(geometry: THREE.BufferGeometry, faces?: (face: number) => boolean) {
const copy = geometry.clone();
@@ -54,6 +55,29 @@ describe('geometryDiagnostics solid section', () => {
});
describe('requireSolid', () => {
+ test('a deep failure keeps measured facts without an unbounded locator', () => {
+ const root = new THREE.Group();
+ let parent = root;
+ for (let i = 0; i < 65; i++) {
+ const group = new THREE.Group();
+ parent.add(group);
+ parent = group;
+ }
+ const part = new THREE.Mesh(new THREE.PlaneGeometry());
+ parent.add(part);
+ requireSolid(part);
+ try {
+ assertRequiredSolids(root);
+ throw new Error('expected failure');
+ } catch (error) {
+ expect(error).toBeInstanceOf(RequiredSolidError);
+ expect((error as RequiredSolidError).solid).toMatchObject({
+ total: 1,
+ truncated: false,
+ meshes: [{ childPath: null, closed: false, boundaryEdges: 4 }],
+ });
+ }
+ });
test('marks a part and is a sandbox helper', () => {
const part = new THREE.Mesh(new THREE.BoxGeometry());
expect(requireSolid(part)).toBe(part);
diff --git a/src/draw-diagnostics.ts b/src/draw-diagnostics.ts
index e5b94690..5c8ebaef 100644
--- a/src/draw-diagnostics.ts
+++ b/src/draw-diagnostics.ts
@@ -306,7 +306,32 @@ export async function inspectDrawDiagnostics(
): Promise<DrawDiagnostics> {
if (bytes.byteLength > MAX_BYTES) return skipped('input-limit');
try {
- return analyzeDrawDiagnostics(await createGltfIO().readBinary(bytes), options);
+ const io = createGltfIO();
+ const json = await io.binaryToJSON(bytes);
+ let expandedBytes = 0;
+ let compressed = false;
+ // The extension allocates count * byteStride before invoking its decoder. Bound
+ // that allocation before readJSON, rather than only inspecting the decoded document.
+ for (const view of json.json.bufferViews ?? []) {
+ const extension = view.extensions?.['EXT_meshopt_compression'] as
+ | { count?: number; byteStride?: number }
+ | undefined;
+ compressed ||= extension !== undefined;
+ const length = extension
+ ? (extension.count ?? Number.NaN) * (extension.byteStride ?? Number.NaN)
+ : view.byteLength;
+ if (!Number.isSafeInteger(length) || length < 0) return skipped('unreadable-glb');
+ expandedBytes += length;
+ if (expandedBytes > MAX_BYTES) return skipped('input-limit');
+ }
+ if (compressed) {
+ // Decoder ownership stays with this host diagnostic, not every deterministic
+ // engine reader. No network, renderer or provider is involved.
+ const { MeshoptDecoder } = await import('meshoptimizer');
+ await MeshoptDecoder.ready;
+ io.registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
+ }
+ return analyzeDrawDiagnostics(await io.readJSON(json), options);
} catch {
return skipped('unreadable-glb');
}
diff --git a/src/evaluator/handler.ts b/src/evaluator/handler.ts
index 7c244f6a..1e4defe8 100644
--- a/src/evaluator/handler.ts
+++ b/src/evaluator/handler.ts
@@ -1,4 +1,9 @@
import { programErrorDiagnostic, type AuthoringDiagnostic } from './authoring-diagnostic';
+import {
+ RequiredSolidError,
+ validSolidFailureDetails,
+ type SolidFailureDetails,
+} from './solid-diagnostic';
import type { RenderGlbOptions, RenderResult } from '../render';
import { renderGLBInProcess } from '../render';
import { AssetQaBlockedError } from '../qa/run';
@@ -29,6 +34,7 @@ function failure(
code: EvaluatorOutcomeCode,
diagnostic?: AuthoringDiagnostic,
qa?: Extract<WireEvaluatorResultV2, { ok: false }>['error']['qa'],
+ solid?: SolidFailureDetails,
): Extract<WireEvaluatorResultV2, { ok: false }> {
return {
version: EVALUATOR_RESULT_VERSION,
@@ -39,6 +45,7 @@ function failure(
message: evaluatorOutcomeMessage(code),
...(qa ? { qa } : {}),
...(diagnostic ? { diagnostic } : {}),
+ ...(solid ? { solid } : {}),
},
};
}
@@ -101,7 +108,15 @@ export async function evaluateEvaluatorRequestV2(
} else if (error instanceof EvaluatorPortError && error.code === 'DEADLINE_EXCEEDED') {
wire = failure(request.requestId, 'DEADLINE_EXCEEDED');
} else {
- wire = failure(request.requestId, 'EXECUTION_REJECTED', programErrorDiagnostic(error));
+ wire = failure(
+ request.requestId,
+ 'EXECUTION_REJECTED',
+ programErrorDiagnostic(error),
+ undefined,
+ error instanceof RequiredSolidError && validSolidFailureDetails(error.solid)
+ ? error.solid
+ : undefined,
+ );
}
} finally {
clearTimeout(timer);
diff --git a/src/evaluator/protocol.ts b/src/evaluator/protocol.ts
index 7237b246..e1503b68 100644
--- a/src/evaluator/protocol.ts
+++ b/src/evaluator/protocol.ts
@@ -22,6 +22,11 @@ import {
} from '../material-library-node';
import { canonicalMaterialJson, type MaterialLibraryPayload } from '../material-library';
import { rebuildOptionsSchema } from '../rebuild-options';
+import {
+ solidFailureAdvice,
+ validSolidFailureDetails,
+ type SolidFailureDetails,
+} from './solid-diagnostic';
export const EVALUATOR_REQUEST_VERSION = 'kiln.evaluator.request.v2' as const;
export const EVALUATOR_RESULT_VERSION = 'kiln.evaluator.result.v2' as const;
@@ -120,12 +125,13 @@ export class EvaluatorPortError extends Error {
readonly code: EvaluatorOutcomeCode,
message = evaluatorOutcomeMessage(code),
readonly diagnostic?: AuthoringDiagnostic,
+ readonly solid?: SolidFailureDetails,
) {
// A rejection with a closed cause carries that cause's advice; one without carries
// the engine's generic advice (decision 24). The wire message itself never changes.
super(
diagnostic
- ? `${message} ${authoringDiagnosticAdvice(diagnostic)}`
+ ? `${message} ${authoringDiagnosticAdvice(diagnostic)}${solidFailureAdvice(solid)}`
: code === 'EXECUTION_REJECTED'
? `${message} ${EXECUTION_REJECTED_ADVICE}`
: message,
@@ -159,6 +165,7 @@ export type EvaluatorResultV2 =
code: EvaluatorOutcomeCode;
message: string;
diagnostic?: AuthoringDiagnostic;
+ solid?: SolidFailureDetails;
qa?: {
report: AssetQaReport;
stage: 'scene' | 'final-glb';
@@ -407,7 +414,7 @@ export function decodeEvaluatorResultV2(
if (value.render !== undefined) return fail('result');
if (
!isRecord(value.error) ||
- !hasExactKeys(value.error, ['code', 'message', 'qa', 'diagnostic'])
+ !hasExactKeys(value.error, ['code', 'message', 'qa', 'diagnostic', 'solid'])
) {
return fail('result');
}
@@ -473,6 +480,11 @@ export function decodeEvaluatorResultV2(
value.error.diagnostic !== 'SKIN_BINDING_ARGUMENT'))
)
return fail('result');
+ if (
+ value.error.solid !== undefined &&
+ (value.error.diagnostic !== 'REQUIRE_SOLID' || !validSolidFailureDetails(value.error.solid))
+ )
+ return fail('result');
if (value.error.qa !== undefined) {
if (
value.error.code !== 'QA_BLOCKED' ||
@@ -655,7 +667,12 @@ export function createEvaluatorPortV2(
result.error.qa.gltfValidation,
);
}
- throw new EvaluatorPortError(result.error.code, undefined, result.error.diagnostic);
+ throw new EvaluatorPortError(
+ result.error.code,
+ undefined,
+ result.error.diagnostic,
+ result.error.solid,
+ );
}
return result.render;
},
diff --git a/src/evaluator/require-solid-diagnostic.test.ts b/src/evaluator/require-solid-diagnostic.test.ts
new file mode 100644
index 00000000..a5bba83d
--- /dev/null
+++ b/src/evaluator/require-solid-diagnostic.test.ts
@@ -0,0 +1,120 @@
+import { expect, test } from 'bun:test';
+import { evaluateEvaluatorRequestV2 } from './handler';
+import {
+ createEvaluatorRequestV2,
+ createEvaluatorPortV2,
+ decodeEvaluatorResultV2,
+} from './protocol';
+import { createKilnProgramToolRegistry } from '../tools/registry';
+import { renderGLBViaSubprocess } from './subprocess';
+
+const code = `function build(){
+ const root=createRoot('PRIVATE_ROOT');
+ const group=new THREE.Group();root.add(group);
+ for(let i=0;i<6;i++) createPart('PRIVATE_PART_'+i,new THREE.CylinderGeometry(1,1,2,12,1,true),gameMaterial(0x888888),{parent:group});
+ requireSolid(group);return root;
+}`;
+const request = () => createEvaluatorRequestV2({ requestId: 'solid', code }).json;
+
+test('required-solid failures cross the evaluator with bounded measured facts and child indices', async () => {
+ const wire = await evaluateEvaluatorRequestV2(request());
+ const result = decodeEvaluatorResultV2(wire, 16 * 1024 * 1024);
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected rejection');
+ expect(result.error).toMatchObject({
+ diagnostic: 'REQUIRE_SOLID',
+ solid: {
+ total: 6,
+ truncated: true,
+ meshes: [
+ { childPath: [0, 0], closed: false, manifold: true, boundaryEdges: 24 },
+ { childPath: [0, 1] },
+ { childPath: [0, 2] },
+ { childPath: [0, 3] },
+ ],
+ },
+ });
+ expect(wire).not.toContain('PRIVATE_');
+ const port = createEvaluatorPortV2((json) => evaluateEvaluatorRequestV2(json));
+ const render = createKilnProgramToolRegistry({ evaluatorPort: port }).find(
+ (tool) => tool.name === 'kiln_render',
+ )!;
+ const output = (await render.run({ code })) as { ok: boolean; error: string };
+ expect(output.ok).toBe(false);
+ expect(output.error).toContain('root.children[0].children[0]');
+ expect(output.error).toContain('boundaryEdges=24');
+ expect(output.error).not.toContain('PRIVATE_');
+});
+
+test('solid details reject extra text, malformed locators and unbounded counts', async () => {
+ const original = JSON.parse(await evaluateEvaluatorRequestV2(request()));
+ type MutableFailure = {
+ error: {
+ diagnostic: string;
+ solid: {
+ total: number;
+ truncated: boolean;
+ meshes: Record<string, unknown>[];
+ };
+ };
+ };
+ const changes: ((value: MutableFailure) => void)[] = [
+ (value) => {
+ value.error.solid.meshes[0]!.message = 'PRIVATE';
+ },
+ (value) => {
+ value.error.solid.meshes[0]!.childPath = ['PRIVATE'];
+ },
+ (value) => {
+ value.error.solid.meshes[0]!.boundaryEdges = -1;
+ },
+ (value) => {
+ value.error.solid.total = 1e100;
+ },
+ (value) => {
+ value.error.solid.meshes.push(value.error.solid.meshes[0]!);
+ },
+ (value) => {
+ value.error.diagnostic = 'TUBE_RADIUS';
+ },
+ (value) => {
+ value.error.solid.truncated = false;
+ },
+ (value) => {
+ value.error.solid.meshes[0]!.childPath = Array(65).fill(0);
+ },
+ (value) => {
+ value.error.solid.meshes[0]!.orientation = { toString: 'outward' };
+ },
+ ];
+ for (const change of changes) {
+ const value = structuredClone(original);
+ change(value);
+ expect(() => decodeEvaluatorResultV2(JSON.stringify(value), 16 * 1024 * 1024)).toThrow();
+ }
+});
+
+test('a thrown lookalike does not forward solid details or authored text', async () => {
+ const wire = await evaluateEvaluatorRequestV2(
+ createEvaluatorRequestV2({
+ requestId: 'spoof',
+ code: `function build(){throw {diagnostic:'REQUIRE_SOLID',solid:{message:'PRIVATE'},message:'PRIVATE'};}`,
+ }).json,
+ );
+ expect(JSON.parse(wire).error.solid).toBeUndefined();
+ expect(wire).not.toContain('PRIVATE');
+});
+
+test('the built worker retains required-solid measurements through the subprocess error', async () => {
+ try {
+ await renderGLBViaSubprocess(code);
+ throw new Error('expected required-solid rejection');
+ } catch (error) {
+ expect(error).toMatchObject({
+ diagnostic: 'REQUIRE_SOLID',
+ solid: { total: 6, truncated: true },
+ });
+ expect(String(error)).toContain('root.children[0].children[0]');
+ expect(String(error)).not.toContain('PRIVATE_');
+ }
+});
diff --git a/src/evaluator/solid-diagnostic.ts b/src/evaluator/solid-diagnostic.ts
new file mode 100644
index 00000000..8277cd92
--- /dev/null
+++ b/src/evaluator/solid-diagnostic.ts
@@ -0,0 +1,86 @@
+import { AuthoringDiagnosticError } from './authoring-diagnostic';
+
+/** Measured engine facts only. No scene names, source text or exception messages. */
+export interface SolidFailureMesh {
+ /** Zero-based child indices from the authored root; null when deeper than 64 nodes. */
+ childPath: number[] | null;
+ closed: boolean;
+ manifold: boolean;
+ orientation: 'outward' | 'inward' | 'mixed';
+ boundaryEdges: number;
+ nonManifoldEdges: number;
+ orientationConflicts: number;
+}
+export interface SolidFailureDetails {
+ total: number;
+ truncated: boolean;
+ meshes: SolidFailureMesh[];
+}
+export const MAX_SOLID_FAILURE_MESHES = 4;
+export const MAX_SOLID_FAILURE_PATH = 64;
+
+export class RequiredSolidError extends AuthoringDiagnosticError {
+ constructor(
+ readonly solid: SolidFailureDetails,
+ message: string,
+ ) {
+ super('REQUIRE_SOLID', message);
+ }
+}
+
+const record = (value: unknown): value is Record<string, unknown> =>
+ value !== null && typeof value === 'object' && !Array.isArray(value);
+const keys = (value: Record<string, unknown>, names: string[]) =>
+ Object.keys(value).length === names.length && names.every((name) => Object.hasOwn(value, name));
+const count = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
+
+export function validSolidFailureDetails(value: unknown): value is SolidFailureDetails {
+ if (
+ !record(value) ||
+ !keys(value, ['total', 'truncated', 'meshes']) ||
+ !count(value.total) ||
+ value.total < 1 ||
+ !Array.isArray(value.meshes) ||
+ value.meshes.length !== Math.min(value.total, MAX_SOLID_FAILURE_MESHES) ||
+ value.truncated !== value.total > value.meshes.length
+ )
+ return false;
+ return value.meshes.every(
+ (mesh) =>
+ record(mesh) &&
+ keys(mesh, [
+ 'childPath',
+ 'closed',
+ 'manifold',
+ 'orientation',
+ 'boundaryEdges',
+ 'nonManifoldEdges',
+ 'orientationConflicts',
+ ]) &&
+ (mesh.childPath === null ||
+ (Array.isArray(mesh.childPath) &&
+ mesh.childPath.length <= MAX_SOLID_FAILURE_PATH &&
+ mesh.childPath.every(count))) &&
+ typeof mesh.closed === 'boolean' &&
+ typeof mesh.manifold === 'boolean' &&
+ typeof mesh.orientation === 'string' &&
+ ['outward', 'inward', 'mixed'].includes(mesh.orientation) &&
+ count(mesh.boundaryEdges) &&
+ count(mesh.nonManifoldEdges) &&
+ count(mesh.orientationConflicts),
+ );
+}
+
+/** Only format validated facts, using engine-owned labels and numeric locators. */
+export function solidFailureAdvice(value: SolidFailureDetails | undefined): string {
+ if (!value || !validSolidFailureDetails(value)) return '';
+ const rows = value.meshes.map((mesh) => {
+ const locator =
+ mesh.childPath === null
+ ? 'mesh beyond the 64-level locator limit'
+ : `root${mesh.childPath.map((index) => `.children[${index}]`).join('')}`;
+ return `${locator}: closed=${mesh.closed}, manifold=${mesh.manifold}, orientation=${mesh.orientation}, boundaryEdges=${mesh.boundaryEdges}, nonManifoldEdges=${mesh.nonManifoldEdges}, orientationConflicts=${mesh.orientationConflicts}`;
+ });
+ return ` Required solid measurements (${value.meshes.length} of ${value.total} failing meshes): ${rows.join('; ')}. Child indices locate nodes in the authored build root before export; names are not forwarded. Read the retained source and check that node's geometryDiagnostics().solid.`;
+}
diff --git a/src/evaluator/subprocess.ts b/src/evaluator/subprocess.ts
index 1032293f..ee20c1ab 100644
--- a/src/evaluator/subprocess.ts
+++ b/src/evaluator/subprocess.ts
@@ -4,6 +4,7 @@ import {
type AuthoringDiagnostic,
} from './authoring-diagnostic';
import { spawn, type SpawnOptions } from 'node:child_process';
+import { solidFailureAdvice, type SolidFailureDetails } from './solid-diagnostic';
import { fileURLToPath } from 'node:url';
import type { RenderGlbOptions, RenderResult } from '../render';
import { AssetQaBlockedError } from '../qa/run';
@@ -49,12 +50,13 @@ export class EvaluatorSubprocessError extends Error {
code: EvaluatorOutcomeCode,
message: string,
readonly diagnostic?: AuthoringDiagnostic,
+ readonly solid?: SolidFailureDetails,
) {
// As EvaluatorPortError: a closed cause's advice, or the generic advice for a bare
// EXECUTION_REJECTED (decision 24); the wire message itself never changes.
super(
diagnostic
- ? `${message} ${authoringDiagnosticAdvice(diagnostic)}`
+ ? `${message} ${authoringDiagnosticAdvice(diagnostic)}${solidFailureAdvice(solid)}`
: code === 'EXECUTION_REJECTED'
? `${message} ${EXECUTION_REJECTED_ADVICE}`
: message,
@@ -272,6 +274,7 @@ export async function renderGLBViaProcessLaunch(
result.error.code,
evaluatorOutcomeMessage(result.error.code),
result.error.diagnostic,
+ result.error.solid,
),
);
return;
diff --git a/src/require-solid.ts b/src/require-solid.ts
index 380c05d1..67607262 100644
--- a/src/require-solid.ts
+++ b/src/require-solid.ts
@@ -10,6 +10,12 @@
import type * as THREE from 'three';
import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';
import { geometryDiagnostics } from './geometry';
+import {
+ RequiredSolidError,
+ MAX_SOLID_FAILURE_MESHES,
+ MAX_SOLID_FAILURE_PATH,
+ type SolidFailureMesh,
+} from './evaluator/solid-diagnostic';
/** The engine-owned userData key a marked part carries. */
export const REQUIRE_SOLID_KEY = 'kilnRequireSolid';
@@ -37,7 +43,9 @@ const marked = (node: THREE.Object3D): boolean => {
*/
export function assertRequiredSolids(root: THREE.Object3D): void {
const problems: string[] = [];
- const visit = (node: THREE.Object3D): void => {
+ const meshes: SolidFailureMesh[] = [];
+ let total = 0;
+ const visit = (node: THREE.Object3D, childPath: number[]): void => {
if (node.visible === false) return;
const mesh = node as THREE.Mesh;
if (mesh.isMesh && marked(mesh) && mesh.geometry?.getAttribute('position')) {
@@ -53,14 +61,30 @@ export function assertRequiredSolids(root: THREE.Object3D): void {
? `winding is mixed (${report.orientationConflicts} conflicting edges)`
: `faces point inward (signed volume ${solid.signedVolume.toPrecision(4)})`,
);
- if (reasons.length) problems.push(`${mesh.name || '(unnamed mesh)'}: ${reasons.join(', ')}`);
+ if (reasons.length) {
+ total++;
+ if (meshes.length < MAX_SOLID_FAILURE_MESHES) {
+ problems.push(`${mesh.name || '(unnamed mesh)'}: ${reasons.join(', ')}`);
+ meshes.push({
+ childPath: childPath.length <= MAX_SOLID_FAILURE_PATH ? childPath : null,
+ closed: solid.closed,
+ manifold: solid.manifold,
+ orientation: solid.orientation,
+ boundaryEdges: report.boundaryEdges,
+ nonManifoldEdges: report.nonManifoldEdges,
+ orientationConflicts: report.orientationConflicts,
+ });
+ }
+ }
}
- for (const child of node.children) visit(child);
+ node.children.forEach((child, index) => {
+ visit(child, [...childPath, index]);
+ });
};
- visit(root);
- if (problems.length)
- throw new AuthoringDiagnosticError(
- 'REQUIRE_SOLID',
- `requireSolid: ${problems.length} marked mesh(es) are not closed, manifold, outward solids: ${problems.slice(0, 4).join('; ')}${problems.length > 4 ? '; ...' : ''}.`,
+ visit(root, []);
+ if (total)
+ throw new RequiredSolidError(
+ { total, truncated: total > meshes.length, meshes },
+ `requireSolid: ${total} marked mesh(es) are not closed, manifold, outward solids: ${problems.join('; ')}${total > meshes.length ? '; ...' : ''}.`,
);
}
diff --git a/src/runtime-three.ts b/src/runtime-three.ts
index e0f25e7d..efae96a4 100644
--- a/src/runtime-three.ts
+++ b/src/runtime-three.ts
@@ -11,9 +11,10 @@
* Kept: `_EDGE`/`_CAVITY` and every other underscore attribute (as float32, never quantized),
* semantic roles and kit extras, hidden collider nodes, anchors, ports and `MSFT_lod` chains.
* A collider node keeps its authored transform: its proxy mesh moves to a child first, so the
- * dequantization transform lands on that child instead of the collider's size. Every other
- * quantized mesh carries its dequantization on a node; the report names each one, because a
- * consumer that re-parents a bare geometry drops it.
+ * dequantization transform lands on that child instead of the collider's size. Static mesh
+ * dequantization is recorded in nodeScale; skinned meshes instead retain it in their inverse
+ * bind matrices. Consumers must preserve the loaded node, skeleton and bind transforms,
+ * rather than re-parenting bare geometry.
*/
import {
type Document,
diff --git a/src/tools/__tests__/camera-integration.test.ts b/src/tools/__tests__/camera-integration.test.ts
index ce501b8c..822acbba 100644
--- a/src/tools/__tests__/camera-integration.test.ts
+++ b/src/tools/__tests__/camera-integration.test.ts
@@ -3,8 +3,68 @@ import { createHash } from 'node:crypto';
import { createKilnProgramToolRegistry } from '../registry';
import { encodePng } from '../../views';
import type { PbrRenderRequest } from '../../composer/render-port';
+import { createGltfIO } from '../../gltf-io';
+import { trustedInProcessEvaluatorPortV2 } from '../../evaluator';
const code =
"const meta={name:'box',category:'prop'};function build(){const r=createRoot('Root');createPart('Body',boxGeo(1,1,1),gameMaterial('#888888'),{parent:r});return r;}";
+
+test('inspection preserves an evaluator colored GLB regardless of the host authored exporter default', async () => {
+ const previous = process.env.KILN_GLTF_EXPORTER;
+ const colored = `function build(){const root=createRoot('Colored');const g=boxGeo(1,1,1);
+ g.setAttribute('color',new THREE.Float32BufferAttribute(new Array(g.getAttribute('position').count).fill([0,0.5,1]).flat(),3));
+ createPart('Body',g,new THREE.MeshStandardMaterial({vertexColors:true}),{parent:root});return root;}`;
+ try {
+ process.env.KILN_GLTF_EXPORTER = 'legacy';
+ const requests: PbrRenderRequest[] = [];
+ const tools = createKilnProgramToolRegistry({
+ cacheCaptures: false,
+ evaluatorPort: {
+ render: (source, options, controls) =>
+ trustedInProcessEvaluatorPortV2.render(
+ source,
+ { ...options, gltfExporter: 'three' },
+ controls,
+ ),
+ },
+ evaluatorProfile: 'evaluator-required',
+ viewRenderPort: async (req) => {
+ requests.push(req);
+ const width = req.width ?? req.size!,
+ height = req.height ?? req.size!;
+ return {
+ ok: true,
+ rendererId: 'gpu:test',
+ cameras: req.cameras,
+ width,
+ height,
+ viewsPng: (req.cameras ?? req.viewDirs ?? [0]).map(() =>
+ encodePng(new Uint8Array(width * height * 3), width, height),
+ ),
+ derivativeFidelity: {
+ materialFaithful: true,
+ inputGlbSha256: `sha256:${createHash('sha256').update(req.glb).digest('hex')}`,
+ },
+ };
+ },
+ });
+ const result = (await tools
+ .find((d) => d.name === 'kiln_inspect')!
+ .run({ code: colored, part: 'Body' })) as Record<string, unknown>;
+ expect(result.ok).toBe(true);
+ expect(requests).toHaveLength(1);
+ const primitive = (await createGltfIO().readBinary(requests[0]!.glb))
+ .getRoot()
+ .listMeshes()[0]!
+ .listPrimitives()[0]!;
+ const colors = primitive.getAttribute('COLOR_0');
+ expect(colors).not.toBeNull();
+ expect(Array.from(colors!.getArray()!).slice(0, 3)).toEqual([0, 0.5, 1]);
+ expect(result.viewFidelity).toMatchObject({ materialFaithful: true, exactArtifact: false });
+ } finally {
+ if (previous === undefined) delete process.env.KILN_GLTF_EXPORTER;
+ else process.env.KILN_GLTF_EXPORTER = previous;
+ }
+});
test('public references render mixed exact cameras and expose separate images', async () => {
const defs = createKilnProgramToolRegistry();
const render = defs.find((d) => d.name === 'kiln_render')!;
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 2641d905..1231b7cf 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -509,6 +509,9 @@ async function renderDerivativeCell(
// and adjudicated. Submitting it for judgement a second time fails on the
// round trip rather than on the asset: see `derivative` in render.ts.
derivative: true,
+ // Review reconstruction preserves vertex colors and secondary UVs; the legacy
+ // authored exporter does not carry those channels into the GPU derivative.
+ gltfExporter: 'three',
requirements: toolRequirements(context).binding,
});
const { cameraFromBounds, measureBounds } = await import('../views');
diff --git a/src/views/__tests__/camera-sdk.test.ts b/src/views/__tests__/camera-sdk.test.ts
index 23bbe78c..91c608c3 100644
--- a/src/views/__tests__/camera-sdk.test.ts
+++ b/src/views/__tests__/camera-sdk.test.ts
@@ -1,9 +1,59 @@
import { test, expect } from 'bun:test';
-import { Group, Mesh, BoxGeometry, MeshStandardMaterial } from 'three';
+import { Group, Mesh, BoxGeometry, MeshStandardMaterial, Float32BufferAttribute } from 'three';
+import { createGltfIO } from '../../gltf-io';
import { renderSceneToGLB } from '../../render';
import { captureViewsViaPort } from '../port';
import { encodePng } from '../png';
import { createHash } from 'node:crypto';
+
+test('advanced capture preserves vertex colors in the exact derivative sent to the GPU', async () => {
+ const root = new Group();
+ const geometry = new BoxGeometry();
+ const colors = new Float32Array(geometry.getAttribute('position').count * 3);
+ for (let i = 0; i < colors.length; i++) colors[i] = (i % 3) / 2;
+ geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
+ const material = new MeshStandardMaterial({ vertexColors: true, color: '#8090a0' });
+ root.add(new Mesh(geometry, material));
+ const rendered = await renderSceneToGLB(root, { gltfExporter: 'three', derivative: true });
+ let received: Uint8Array | undefined;
+ const out = await captureViewsViaPort(
+ async (req) => {
+ received = req.glb;
+ return {
+ ok: true,
+ rendererId: 'gpu:test',
+ cameras: req.cameras,
+ width: req.width,
+ height: req.height,
+ viewsPng: [encodePng(new Uint8Array(128 * 128 * 3), 128, 128)],
+ derivativeFidelity: {
+ materialFaithful: true,
+ inputGlbSha256: `sha256:${createHash('sha256').update(req.glb).digest('hex')}`,
+ },
+ };
+ },
+ rendered.bytes,
+ 5000,
+ { version: 'kiln.capture.v1', shots: [{}], size: 128 },
+ );
+ expect(out.ok).toBe(true);
+ expect(received).toBeDefined();
+ const primitive = (await createGltfIO().readBinary(received!))
+ .getRoot()
+ .listMeshes()[0]!
+ .listPrimitives()[0]!;
+ expect(primitive.getAttribute('COLOR_0')).not.toBeNull();
+ expect(Array.from(primitive.getAttribute('COLOR_0')!.getArray()!)).toEqual(Array.from(colors));
+ expect(primitive.getMaterial()!.getBaseColorFactor().slice(0, 3)).toEqual(
+ material.color.toArray(),
+ );
+ if (out.ok) {
+ expect(out.derivativeReceipts?.[0]?.exactArtifact).toBe(false);
+ expect(out.derivativeReceipts?.[0]?.inputGlbSha256).toBe(
+ `sha256:${createHash('sha256').update(received!).digest('hex')}`,
+ );
+ }
+});
test('SDK advanced capture sends isolated derivative with explicit cameras and returns receipts', async () => {
const root = new Group();
root.name = 'Root';
diff --git a/src/views/__tests__/glb.test.ts b/src/views/__tests__/glb.test.ts
index b8d2c939..2272a416 100644
--- a/src/views/__tests__/glb.test.ts
+++ b/src/views/__tests__/glb.test.ts
@@ -2,6 +2,8 @@ import { createHash } from 'node:crypto';
import { describe, expect, spyOn, test } from 'bun:test';
import { Document, WebIO } from '@gltf-transform/core';
import { EXTMeshGPUInstancing, KHRTextureBasisu } from '@gltf-transform/extensions';
+import type { Mesh, MeshStandardMaterial } from 'three';
+import sharp from 'sharp';
import * as renderModule from '../../render';
import {
@@ -71,6 +73,103 @@ function triangleDocument(
}
describe('GLB-native geometry-flat view input', () => {
+ test.each([3, 4] as const)(
+ 'review retains normalized %i-component vertex colors and material factors',
+ async (size) => {
+ const doc = triangleDocument({ alpha: 0.4 });
+ const values =
+ size === 3
+ ? [255, 0, 64, 0, 128, 255, 32, 255, 0]
+ : [255, 0, 64, 255, 0, 128, 255, 128, 32, 255, 0, 0];
+ doc
+ .getRoot()
+ .listMeshes()[0]!
+ .listPrimitives()[0]!
+ .setAttribute(
+ 'COLOR_0',
+ doc
+ .createAccessor()
+ .setType(size === 3 ? 'VEC3' : 'VEC4')
+ .setNormalized(true)
+ .setArray(Uint8Array.from(values))
+ .setBuffer(doc.getRoot().listBuffers()[0]!),
+ );
+ const loaded = await loadGlbReviewScene(await io().writeBinary(doc));
+ const mesh = loaded.root.getObjectByName('Triangle')!.children[0] as Mesh;
+ const color = mesh.geometry.getAttribute('color');
+ expect(color?.itemSize).toBe(size);
+ expect(Array.from(color.array)).toEqual(values.map((v) => Math.fround(v / 255)));
+ const material = mesh.material as MeshStandardMaterial;
+ expect(material.vertexColors).toBe(true);
+ expect(material.color.toArray()).toEqual([0.25, 0.5, 0.75]);
+ expect(material.opacity).toBe(0.4);
+ expect(material.transparent).toBe(true);
+ const derivative = await renderModule.renderSceneToGLB(loaded.root, {
+ gltfExporter: 'three',
+ derivative: true,
+ optimize: 'off',
+ });
+ const preserved = (await io().readBinary(derivative.bytes))
+ .getRoot()
+ .listMeshes()[0]!
+ .listPrimitives()[0]!
+ .getAttribute('COLOR_0')!;
+ expect(preserved.getElementSize()).toBe(size);
+ expect(Array.from(preserved.getArray()!)).toEqual(Array.from(color.array));
+ },
+ );
+
+ test('review retains secondary UVs used by a texture channel', async () => {
+ const doc = triangleDocument({ texture: true });
+ doc
+ .getRoot()
+ .listTextures()[0]!
+ .setImage(
+ await sharp({
+ create: { width: 1, height: 1, channels: 4, background: '#ff0000' },
+ })
+ .png()
+ .toBuffer(),
+ );
+ const primitive = doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!;
+ for (let channel = 0; channel < 4; channel++) {
+ primitive.setAttribute(
+ `TEXCOORD_${channel}`,
+ doc
+ .createAccessor()
+ .setType('VEC2')
+ .setArray(new Float32Array([channel, 0, channel + 1, 0, channel, 1]))
+ .setBuffer(doc.getRoot().listBuffers()[0]!),
+ );
+ }
+ primitive.getMaterial()!.getBaseColorTextureInfo()!.setTexCoord(2);
+ const loaded = await loadGlbReviewScene(await io().writeBinary(doc));
+ const mesh = loaded.root.getObjectByName('Triangle')!.children[0] as Mesh;
+ expect((mesh.material as MeshStandardMaterial).map!.channel).toBe(2);
+ for (let channel = 0; channel < 4; channel++) {
+ expect(
+ Array.from(mesh.geometry.getAttribute(channel ? `uv${channel}` : 'uv')?.array ?? []),
+ ).toEqual([channel, 0, channel + 1, 0, channel, 1]);
+ }
+ const derivative = await renderModule.renderSceneToGLB(loaded.root, {
+ gltfExporter: 'three',
+ derivative: true,
+ optimize: 'off',
+ });
+ const result = await io().readBinary(derivative.bytes);
+ const output = result.getRoot().listMeshes()[0]!.listPrimitives()[0]!;
+ expect(output.getMaterial()!.getBaseColorTextureInfo()!.getTexCoord()).toBe(2);
+ for (let channel = 0; channel < 4; channel++)
+ expect(Array.from(output.getAttribute(`TEXCOORD_${channel}`)!.getArray()!)).toEqual([
+ channel,
+ 0,
+ channel + 1,
+ 0,
+ channel,
+ 1,
+ ]);
+ });
+
test('shared mesh resources retain owning node names in primitive QA repair hints', async () => {
const doc = triangleDocument();
const first = doc.getRoot().listNodes()[0]!.setName('ChainLink_A');
diff --git a/src/views/glb.ts b/src/views/glb.ts
index 91643379..c085942b 100644
--- a/src/views/glb.ts
+++ b/src/views/glb.ts
@@ -686,13 +686,21 @@ function reviewSceneFromDocument(
new BufferAttribute(Float32Array.from(decodedAccessor(normal)), 3),
);
}
- const uv = primitive.getAttribute('TEXCOORD_0');
- if (uv) {
+ // Texture bindings retain their UV channel, so retain the matching vertex data too.
+ for (let channel = 0; channel < 4; channel++) {
+ const uv = primitive.getAttribute(`TEXCOORD_${channel}`);
+ if (uv)
+ geometry.setAttribute(
+ channel ? `uv${channel}` : 'uv',
+ new BufferAttribute(Float32Array.from(decodedAccessor(uv)), 2),
+ );
+ }
+ const color = primitive.getAttribute('COLOR_0');
+ if (color)
geometry.setAttribute(
- 'uv',
- new BufferAttribute(Float32Array.from(decodedAccessor(uv)), 2),
+ 'color',
+ new BufferAttribute(Float32Array.from(decodedAccessor(color)), color.getElementSize()),
);
- }
const tangent = primitive.getAttribute('TANGENT');
if (tangent) {
geometry.setAttribute(
@@ -768,6 +776,7 @@ function reviewSceneFromDocument(
);
}
const threeMaterial = new MeshStandardMaterial({
+ vertexColors: color !== null,
opacity: flat.opacity,
transparent: flat.alphaMode === 'BLEND',
alphaTest: flat.alphaMode === 'MASK' ? flat.alphaCutoff : 0,
diff --git a/src/views/port.ts b/src/views/port.ts
index 9e23e602..ddf8f069 100644
--- a/src/views/port.ts
+++ b/src/views/port.ts
@@ -216,7 +216,7 @@ export async function captureViewsViaPort(
// An isolated shot hides the other meshes; send the GPU only what it may draw.
const derivative = await renderSceneToGLB(
withoutHiddenMeshes(input.root as import('three').Object3D),
- { derivative: true },
+ { derivative: true, gltfExporter: 'three' },
);
const result = await captureViewPngsViaPort(
port,