Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Preserve editable GLB colors UVs and HDR emission

Nguyen Xuan An77fdb5b82d91
diff --git a/.gitignore b/.gitignore
index 617a546e..78905426 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,6 +11,7 @@ public/gltf-morph.md
public/morph-targets.md
public/skinning.md
public/physics.md
+public/export-glb.md
artifacts/
.env
.env.*
diff --git a/README.md b/README.md
index 968a11c5..c2ac606a 100644
--- a/README.md
+++ b/README.md
@@ -169,6 +169,7 @@ The source trailer includes an [offline physics recording](docs/film-physics.md)
The source renderer also supports [relative GPU morph targets](docs/morph-targets.md) for position and normal changes before skinning, including deterministic eyelid animation in the film. This feature is not in the published `0.3.3` package.
The source [glTF morph bridge](docs/gltf-morph.md) preserves relative targets, independent instance weights and linear, step or cubic weight animations.
+The source [GLB exporter](docs/export-glb.md) preserves opaque vertex colors, UVs and independent HDR emission alongside static morph snapshots.
The trailer's rigid actor joints now use authored clips, with attached headwear and hands moving together.
The [optional asset addon](docs/gltf.md) loads glTF/GLB meshes, base-color textures, opaque vertex colors and rigid node animation.
diff --git a/docs/capability-audit.md b/docs/capability-audit.md
index 0efc11da..67d0633f 100644
--- a/docs/capability-audit.md
+++ b/docs/capability-audit.md
@@ -25,6 +25,7 @@ The Blender references describe authoring capabilities. Their interpolation and
| Camera authoring | Absolute-time paths, target tracking, roll, focal-length conversion and aspect-aware film subject framing integrated in source | Focus control, editing, automatic animated bounds, package release | Reviewed moving shot previews across aspect ratios |
| Film authoring | Scene-specific shot list and player | Shared timeline, shot editing, transitions, audio cues | Edited timeline seeks and exports deterministically |
| Asset import | Opaque glTF meshes, five material maps, rigid, skeletal and morph weight animation integrated in source | Tangent morphs, generated morph normals, transparency, compression, streaming, package release | Blender fixtures preserve geometry, materials, and animation |
+| Asset export | Static GLB transforms, RGB vertex colors, UVs, relative morphs and active HDR emission integrated in source | Skeletons, clips, textures, procedural materials and scene environments, package release | Source and imported assets preserve data and reproduce reference rendered fixtures |
| Materials | Factors and five PBR texture channels integrated in source | Layered materials, advanced extensions, authored tangents, package verification | Reference material scenes and texture budget checks |
| Lighting | Directional shadows, configurable key/fill/ambient strength and eight local point lights integrated in source | Local shadows, spot/area lights, HDR environments, baked lighting, reflection probes; package release | Reference lighting scenes, stable shadows, and measured render cost |
| Image rendering | HDR, bloom, grading, MSAA, FXAA | Depth of field, motion blur, temporal sampling, render passes | Reviewed stills and moving previews with measured artifacts |
diff --git a/docs/export-glb.md b/docs/export-glb.md
new file mode 100644
index 00000000..be2a42ea
--- /dev/null
+++ b/docs/export-glb.md
@@ -0,0 +1,99 @@
+# Editable static GLB export
+
+`exportGlb(parts)` returns a self-contained GLB `ArrayBuffer` for the current static scene.
+`downloadGlb(parts)` saves that same snapshot through the browser.
+The exporter stores each part matrix as a root node transform.
+It preserves shared geometry accessors and shared meshes when materials match.
+The extended channels and HDR emission exist in the source checkout, but not in the published `0.3.3` package.
+
+```js
+const geometry = box();
+geometry.colors = new Float32Array(geometry.positions.length).fill(0.5);
+geometry.uvs = new Float32Array(geometry.positions.length / 3 * 2);
+const part = {
+ name: 'Editable surface',
+ geometry,
+ matrix: mat4.create(),
+ material: {
+ color: [0.2, 0.4, 0.6],
+ metallic: 0,
+ roughness: 0.7,
+ emissiveColor: [1, 0.1, 0.05],
+ emission: 8,
+ },
+};
+const binary = exportGlb([part]);
+```
+
+## Stored channels
+
+| Input | GLB data | Rules |
+| --- | --- | --- |
+| `geometry.positions` | `POSITION`, Float32 `VEC3` | Nonempty finite XYZ vectors. |
+| `geometry.normals` | `NORMAL`, Float32 `VEC3` | One finite unit vector per vertex, with length tolerance `0.001`. |
+| `geometry.indices` | Unsigned integer `SCALAR` | Nonempty `Uint32Array` of triangles with valid vertex indices. |
+| `geometry.colors` | `COLOR_0`, Float32 `VEC3` | Optional opaque linear RGB multipliers within `[0,1]`. |
+| `geometry.uvs` | `TEXCOORD_0`, Float32 `VEC2` | Optional finite coordinates, including values outside `[0,1]`. |
+| `geometry.morphTargets` | Relative `POSITION` and `NORMAL` accessors | One to 64 targets with matching Float32 channel counts. |
+| `part.morph.weights` | Independent `node.weights` | Current finite signed Float32 weights. |
+
+Every vertex channel must match the position count.
+Typed arrays can reference a subsection of a larger buffer.
+The exporter stores only that subsection and preserves its Float32 values.
+Colors multiply the base material color in linear space, following the [glTF geometry specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes).
+UV coordinates remain editable even though this exporter rejects textures.
+
+## Materials and emission
+
+`material.color` and `material.emissiveColor` contain three linear RGB components within `[0,1]`.
+`metallic` and `roughness` must each lie within `[0,1]`.
+`emission` defaults to zero and must be finite, nonnegative, and representable as Float32.
+An omitted `emissiveColor` uses `material.color`.
+
+Positive emission keeps the emissive RGB factor separate from its scalar intensity.
+A positive intensity other than one uses [KHR_materials_emissive_strength](https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_emissive_strength).
+The file requires that extension so unsupported viewers cannot silently reinterpret its radiance.
+An intensity of one uses the core emissive factor without an extension.
+Zero emission writes a black emissive factor without an extension.
+The snapshot does not preserve a dormant emissive color when its intensity is zero.
+
+The exporter validates every part before constructing accessors or allocating the GLB binary.
+Malformed channels, factors, matrices, morph pairs, and indices throw errors instead of undergoing conversion or clamping.
+
+Matrices must contain 16 finite Float32-representable values and have an affine last row.
+Their Float32 linear columns must have nonzero lengths and represent rotation with independent scales.
+Shear fails when normalized column dot products exceed `8 * 2 ** -23`, allowing Float32 rotation rounding.
+Zero scales and scales that collapse to Float32 zero fail before allocation.
+Negative scales remain valid.
+
+## Design choice
+
+| Design | Editing and fidelity | Cost |
+| --- | --- | --- |
+| Vertex accessors and standard material factors | Preserves RGB, UV, morph channels, and active emission independently. | Stores the authored channels once per shared geometry. |
+| Bake appearance into textures | Requires a texture bake and obscures authored vertex colors and material factors. | Requires texture support, UV baking, and image storage. |
+
+The exporter uses accessors because its callers already supply editable vertex data.
+A texture bake introduces a separate asset pipeline and cannot preserve the same source channels.
+
+## Limits
+
+Skinning and all material texture channels throw explicit unsupported errors.
+The snapshot retains current morph weights but does not serialize animation clips or skeletons.
+It stores opaque metallic roughness materials without renderer tags, procedural weathering, custom shaders, lighting, cameras, or postprocessing.
+It does not promise identical rendered pixels across tools.
+Materials tagged `unlit` still export through this documented metallic roughness snapshot contract.
+
+The [Blender glTF workflow](https://docs.blender.org/manual/en/5.3/addons/scene_gltf2.html) supports vertex colors, UV coordinates, shape keys, and emissive strength.
+These editable fields remain available to compatible tools after import.
+
+## Render verification
+
+`node scripts/smoke-glb-fidelity.mjs 960 540` compares source parts and imported GLB parts through the built modules in native Chrome.
+The fixture covers the film head, a cube with RGB multipliers and UVs outside `[0,1]`, and independent HDR emission.
+At 960 by 540 and 540 by 960, all three source and imported images matched exactly on the RTX 3060.
+Every draw reported zero WebGL errors.
+
+The original exporter lost vertex channels and produced maximum channel differences of 31, 194 and 185 in those respective fixtures.
+Each draw uses one renderer, which is disposed before the next draw.
+These measurements establish fidelity for the fixtures, not identical rendering across tools or recognizable character quality.
diff --git a/docs/gltf-morph.md b/docs/gltf-morph.md
index 2941c847..7076a46f 100644
--- a/docs/gltf-morph.md
+++ b/docs/gltf-morph.md
@@ -118,7 +118,9 @@ The fixture exports the film portrait as a static GLB, appends explicit weight-a
It compares open and closed eyelid pixels at an unchanged head pose, checks exact backward-seek reproduction and retains GPU resources across 60 updates.
Wide and portrait runs report WebGL errors and the renderer memory estimate.
The fixture verifies imported deformation, not character likeness or cinematic quality.
-The exporter still omits vertex colors and UVs, so this fixture is not a lossless asset round trip.
+
+The source [exporter](export-glb.md) now preserves vertex colors, UVs and independent HDR emission.
+The fixture does not preserve procedural shaders or scene environments, so it is not a complete asset round trip.
`node scripts/smoke-gltf-skin-morph.mjs` imports a GLB containing both bone and weight channels through the built package entry points.
It isolates morph pixels at a fixed skin pose, verifies exact reverse seeks, retains all three deformation textures and checks disposal.
diff --git a/docs/gltf.md b/docs/gltf.md
index 42701cd3..1b652b78 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -66,6 +66,7 @@ Materials preserve linear `color`, `metallic`, `roughness`, and `emissiveColor`
`emission` contains the emissive intensity.
The `gltf` tag uses standard PBR shading without studio finish overrides.
An emissive-strength extension preserves its intensity.
+The source [exporter](export-glb.md) preserves opaque colors, UVs and active HDR emission when creating static GLB snapshots.
A base color texture adds this descriptor:
diff --git a/docs/morph-targets.md b/docs/morph-targets.md
index 0bc6e37b..fb7bc45b 100644
--- a/docs/morph-targets.md
+++ b/docs/morph-targets.md
@@ -133,7 +133,8 @@ The export contains editable targets and a static pose, rather than baked vertex
It does not serialize animation clips. Skinning and material textures still fail explicitly at export.
The source importer opens these snapshots. Morph import requires authored base normals and rejects tangent targets.
-The exporter still omits vertex colors and UV attributes. This is not a complete asset roundtrip.
+The source [exporter](export-glb.md) also preserves opaque vertex colors, UVs and independent active HDR emission.
+Skinning, textures, procedural shaders and animation clips still prevent a complete asset roundtrip.
The output follows [glTF morph target and node weight semantics](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#morph-targets).
Export tests inspect the serialized accessors and load the GLB with the independent Three.js loader.
diff --git a/package.json b/package.json
index dfe7bd25..5d23e6bf 100644
--- a/package.json
+++ b/package.json
@@ -34,7 +34,8 @@
"docs/volumetric.md",
"docs/film-physics.md",
"docs/morph-targets.md",
- "docs/gltf-morph.md"
+ "docs/gltf-morph.md",
+ "docs/export-glb.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
diff --git a/public/llms.txt b/public/llms.txt
index 5a724754..084185d7 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -78,6 +78,10 @@ The current source adds GPU skinning, relative POSITION/NORMAL morphs, weight an
Read `docs/skinning.md`, `docs/morph-targets.md`, `docs/gltf-morph.md` and `docs/physics.md` in the matching checkout before using these features.
Source morphs require authored base normals. Tangent targets and per-target flat normal generation remain unsupported.
+The source GLB exporter preserves opaque linear vertex colors, UVs and independent HDR emission with current morph weights.
+Read `docs/export-glb.md` in the matching checkout. Exported GLBs contain a static pose, not serialized animation clips or skeletons.
+Texture export remains unsupported and fails explicitly. Procedural shaders and scene environments are not serialized into glTF materials.
+
GLB support excludes transparent and double-sided materials and compressed geometry. Unsupported features require visible errors.
The optional GLB decoder uses Three.js GLTFLoader. The renderer remains 67.js.
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index b1bcb39c..648fc9b4 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -35,7 +35,7 @@ await copyFile(resolve(root, 'build-browser/67.module.js'), resolve(releases, me
await copyFile(resolve(root, 'CHANGELOG.md'), resolve(root, 'public/changelog.md'));
await copyFile(resolve(root, 'docs/guide.md'), resolve(root, 'public/guide.md'));
await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));
-for (const name of ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md']) {
+for (const name of ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md', 'export-glb.md']) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
}
diff --git a/scripts/smoke-glb-fidelity.mjs b/scripts/smoke-glb-fidelity.mjs
new file mode 100644
index 00000000..8f232bd2
--- /dev/null
+++ b/scripts/smoke-glb-fidelity.mjs
@@ -0,0 +1,116 @@
+import assert from 'node:assert/strict';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+await mkdir('artifacts', { recursive: true });
+const width = Number(process.argv[2] ?? 960);
+const height = Number(process.argv[3] ?? 540);
+const label = process.argv[4] ?? 'current';
+const browser = await chromium.launch({
+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
+ headless: true,
+ args: ['--enable-webgl', '--ignore-gpu-blocklist'],
+});
+try {
+ const page = await browser.newPage({ viewport: { width, height } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.route('**/glb-fidelity-smoke.html', route => route.fulfill({
+ contentType: 'text/html', body: `<canvas style="width:${width}px;height:${height}px;display:block"></canvas>`,
+ }));
+ await page.goto('http://127.0.0.1:5173/glb-fidelity-smoke.html');
+ const results = await page.evaluate(async () => {
+ const { Renderer67, exportGlb, box, sphere } = await import('/build/67.module.js');
+ const { createFilmScenes } = await import('/build/film.js');
+ const { parseGltf } = await import('/build/gltf.js');
+ const canvas = document.querySelector('canvas');
+ const portrait = createFilmScenes().portrait;
+ const headJoint = portrait.parts.find(part => part.name === 'Continuous sculpted head').actorJoint;
+ const headParts = portrait.parts.filter(part => part.actorJoint === headJoint);
+ const identity = () => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ const colored = box();
+ colored.colors = new Float32Array(colored.positions.length);
+ const uvStorage = new Float32Array(colored.positions.length / 3 * 2 + 4);
+ colored.uvs = uvStorage.subarray(2, uvStorage.length - 2);
+ for (let vertex = 0; vertex < colored.positions.length / 3; vertex++) {
+ colored.colors.set(vertex % 2 ? [0.02, 0.7, 0.1] : [0.8, 0.02, 0.08], vertex * 3);
+ colored.uvs.set([vertex % 3 - 1.25, vertex % 4 + 0.125], vertex * 2);
+ }
+ const pbr = { color: [1, 1, 1], metallic: 0, roughness: 0.6, emission: 0 };
+ const cases = [
+ { name: 'film-head', parts: headParts, environment: portrait.environment,
+ frame: { eye: [0, 1.72, 0.72], target: [0, 1.7, 0], fov: 36 } },
+ { name: 'vertex-color-uv', parts: [{ name: 'Colored cube', geometry: colored, material: pbr, matrix: identity() }],
+ frame: { eye: [2, 1.5, 3], target: [0, 0, 0], fov: 40 } },
+ { name: 'hdr-emission', parts: [{ name: 'Warm emission, blue base', geometry: sphere(32, 24), matrix: identity(),
+ material: { color: [0.01, 0.04, 0.2], emissiveColor: [1, 0.08, 0.005], emission: 5, metallic: 0, roughness: 0.7 } }],
+ frame: { eye: [2, 1, 3], target: [0, 0, 0], fov: 40 } },
+ ];
+ const reports = [];
+ function draw(parts, entry) {
+ const renderer = new Renderer67(canvas, parts, {
+ world: true, ground: false, samples: 2, pixelRatio: 1, hdr: true, memoryBudgetMiB: 96,
+ environment: entry.environment,
+ });
+ renderer.render({ ...entry.frame, time: 0, effects: { grain: 0, bloom: { strength: 0 } } });
+ const context = renderer.context;
+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);
+ context.readPixels(0, 0, canvas.width, canvas.height, context.RGBA, context.UNSIGNED_BYTE, pixels);
+ const image = canvas.toDataURL('image/png');
+ const memory = renderer.memoryPlan;
+ const glError = context.getError();
+ const info = context.getExtension('WEBGL_debug_renderer_info');
+ const gpu = info ? context.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unavailable';
+ renderer.dispose();
+ return { pixels, image, memory, glError, gpu };
+ }
+ for (const entry of cases) {
+ const bytes = exportGlb(entry.parts);
+ const asset = await parseGltf(bytes);
+ const source = draw(entry.parts, entry);
+ const imported = draw(asset.parts, entry);
+ let maximum = 0;
+ let total = 0;
+ let changed = 0;
+ for (let index = 0; index < source.pixels.length; index++) {
+ const difference = Math.abs(source.pixels[index] - imported.pixels[index]);
+ maximum = Math.max(maximum, difference);
+ total += difference;
+ if (difference) changed++;
+ }
+ const channelsMatch = entry.parts.every((part, index) => ['colors', 'uvs'].every(channel => {
+ if (!part.geometry[channel]) return true;
+ const decoded = asset.parts[index].geometry[channel];
+ return decoded?.length === part.geometry[channel].length && part.geometry[channel].every((value, offset) => value === decoded[offset]);
+ }));
+ reports.push({
+ name: entry.name, partCount: entry.parts.length, glbBytes: bytes.byteLength, channelsMatch,
+ maximumDifference: maximum, meanDifference: total / source.pixels.length, changedChannels: changed,
+ sourceGlError: source.glError, importedGlError: imported.glError, gpu: imported.gpu,
+ sourceMemory: source.memory, importedMemory: imported.memory,
+ sourceImage: source.image, importedImage: imported.image,
+ });
+ asset.dispose();
+ }
+ return reports;
+ });
+ for (const result of results) {
+ for (const kind of ['source', 'imported']) {
+ await writeFile(`artifacts/glb-${label}-${result.name}-${width}x${height}-${kind}.png`, Buffer.from(result[`${kind}Image`].split(',')[1], 'base64'));
+ delete result[`${kind}Image`];
+ }
+ }
+ await writeFile(`artifacts/glb-fidelity-${label}-${width}x${height}.json`, JSON.stringify(results, null, 2));
+ console.log(JSON.stringify(results, null, 2));
+ assert.deepEqual(errors, []);
+ for (const result of results) {
+ assert.equal(result.sourceGlError, 0);
+ assert.equal(result.importedGlError, 0);
+ assert.equal(result.channelsMatch, true, `${result.name} discarded vertex channels.`);
+ assert.ok(result.maximumDifference <= 4 && result.meanDifference < 0.005, `${result.name} changed rendered pixels beyond normal rounding tolerance.`);
+ }
+} finally {
+ await browser.close();
+}
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index fef8ec96..fcf06529 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -43,10 +43,12 @@ assert.equal(typeof Renderer67, 'function');
assert.equal(MAX_MORPH_TARGETS, 64);
assert.ok(createMorphPose(64).weights instanceof Float32Array);
const morphGeometry = box();
+morphGeometry.colors = new Float32Array(morphGeometry.positions.length).fill(0.75);
+morphGeometry.uvs = new Float32Array(morphGeometry.positions.length / 3 * 2).fill(-0.25);
morphGeometry.morphTargets = [{ positions: new Float32Array(morphGeometry.positions.length).fill(0.125) }];
const morphPose = createMorphPose(1);
morphPose.weights[0] = -0.5;
-const morphSnapshot = exportGlb([{ name: 'packed morph', geometry: morphGeometry, morph: morphPose, matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { color: [0.5, 0.5, 0.5], metallic: 0, roughness: 0.7, emission: 0 } }]);
+const morphSnapshot = exportGlb([{ name: 'packed morph', geometry: morphGeometry, morph: morphPose, matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { color: [0.5, 0.5, 0.5], emissiveColor: [1, 0.25, 0], metallic: 0, roughness: 0.7, emission: 4 } }]);
const morphHeader = new DataView(morphSnapshot);
const morphDocument = JSON.parse(new TextDecoder().decode(new Uint8Array(morphSnapshot, 20, morphHeader.getUint32(12, true))));
assert.deepEqual(morphDocument.nodes[0].weights, [-0.5]);
@@ -55,6 +57,10 @@ const importedMorph = await parseGltf(morphSnapshot);
assert.equal(importedMorph.parts.length, 1);
assert.deepEqual(Array.from(importedMorph.parts[0].morph.weights), [-0.5]);
assert.deepEqual(importedMorph.parts[0].geometry.morphTargets[0].positions, morphGeometry.morphTargets[0].positions);
+assert.deepEqual(importedMorph.parts[0].geometry.colors, morphGeometry.colors);
+assert.deepEqual(importedMorph.parts[0].geometry.uvs, morphGeometry.uvs);
+assert.deepEqual(importedMorph.parts[0].material.emissiveColor, [1, 0.25, 0]);
+assert.equal(importedMorph.parts[0].material.emission, 4);
importedMorph.dispose();
assert.throws(() => new Renderer67({}, [], { environment: { pointLights: Array(9).fill({ position: [0, 1, 0] }) } }), /at most/, 'Packed renderer must validate light limits before requesting a GPU context.');
assert.ok(box().positions.length > 0);
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 6dd82e36..b873ed87 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -32,6 +32,7 @@ Each geometry and texture descriptor identity pair becomes one instanced batch.
Explodable parts also provide `assembly: { layer: 'exterior' | 'interior', section: 'front-panel', offset: [0, 0, 1.7], detailOffset: [0.1, 0.05, 0.3] }`.
Both offsets are world-space translations. The shader applies `offset * amount + detailOffset * smoothstep(0.3, 1, amount)`.
The group separates first. Small components separate during the second stage.
+
Keep each section's offsets consistent so fasteners follow their panel. Base matrices remain assembled.
Changing assembly amount refreshes shadows while reusing the same shadow texture and geometry buffers.
@@ -56,16 +57,19 @@ Interpolated numeric tags can change by tiny amounts and select the wrong shadin
An outdoor renderer receives `world: true`, `ground: false` and the scene environment.
The environment provides `fogColor`, `fogDensity`, `skyTop`, `skyBottom`, `lightDirection` and optional `daylight`.
The sky colors are display RGB. Fog colors are linear RGB.
+
Local `environment.pointLights` support eight world-space sources with inverse-square falloff.
Each light provides `position` and optional `color`, `intensity`, `radius` and `range`.
`keyIntensity`, `fillIntensity` and `ambientIntensity` independently scale existing lighting.
Read the checkout's `docs/lighting.md` for defaults, numeric limits and frame overrides.
Point lights currently cast no local shadows. Radius limits attenuation without creating an area emitter.
+
Source-only `environment.volumeFog` receives directional scattering and shadows in one bounded volume.
It requires an opaque renderer with `{ hdr: true, depth: true }` and negotiated HDR support.
Read `docs/volumetric.md` for controls, resource cost and limitations before authoring fog.
`frame.environment.volumeFog` replaces the entire constructor fog object, with defaults for omitted fields.
Use absolute frame time for reproducible density drift. Local point lights do not scatter in fog yet.
+
`part.castShadow: false` omits a mesh from shadows while leaving it visible and opaque.
Changing its casting regime requires a new renderer. Shadow-casting groups use separate batches.
@@ -92,13 +96,19 @@ Camera FOV uses degrees. Film time must be finite and independent of the wall cl
Animation changes existing part matrices and materials. `renderer.updateParts(changedParts)` uploads them through retained instance buffers.
New part, geometry or texture descriptor identities require a new renderer.
+
Source morph parts add `geometry.morphTargets: [{ positions, normals }]` and `morph: createMorphPose(count)`.
Targets contain static relative Float32 XYZ deltas, not absolute vertices. At least one channel is present.
Change retained `part.morph.weights`, then call `renderer.updateParts()` to commit the pose.
-Separate pose identities split batches; repeated parts can share static target geometry.
+Separate pose identities split batches. Repeated parts can share static target geometry.
+
Morphs run before skinning and use standard materials. Read `docs/morph-targets.md` for numeric limits and memory costs.
-Source `exportGlb(parts)` preserves morph target deltas and current node weights as a static GLB snapshot; it does not serialize animation clips.
+
+Source `exportGlb(parts)` preserves relative morph targets and current weights as a static GLB snapshot.
+It preserves opaque linear RGB vertex colors, UVs and active independent HDR emission. Read `docs/export-glb.md` for limits.
+It does not serialize animation clips, procedural shaders or scene environments.
Skinning and textured materials still reject at export. Check the decoder's capabilities before importing shape keys.
+
The optional `{ shadows: false }` update option suits flat scenes without moving shadow casters.
`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.
diff --git a/src/export.js b/src/export.js
index e7b3e849..a30ab4a2 100644
--- a/src/export.js
+++ b/src/export.js
@@ -1,12 +1,107 @@
-import { validateMorphGeometry } from './morph.js';
+import { validateMorphGeometry, validateMorphPose } from './morph.js';
+
+const EMISSIVE_STRENGTH = 'KHR_materials_emissive_strength';
+const COMPONENT_COUNTS = { SCALAR: 1, VEC2: 2, VEC3: 3 };
+
+function validateFloatChannel(values, length, label, bounded = false) {
+ if (!(values instanceof Float32Array) || values.length !== length) {
+ throw new TypeError(`${label} requires a Float32Array matching the vertex count.`);
+ }
+ for (const value of values) {
+ if (!Number.isFinite(value) || (bounded && (value < 0 || value > 1))) {
+ throw new RangeError(`${label} requires finite values${bounded ? ' within [0,1]' : ''}.`);
+ }
+ }
+}
+
+function validateFactor(value, label, maximum = 1) {
+ if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value)) || value < 0 || value > maximum) {
+ throw new RangeError(`${label} requires a finite nonnegative Float32 value${maximum === 1 ? ' within [0,1]' : ''}.`);
+ }
+}
+
+function validateColor(values, label) {
+ if (!values || values.length !== 3) throw new TypeError(`${label} requires three linear RGB components.`);
+ for (const value of values) validateFactor(value, label);
+}
+
+function validateGeometry(geometry) {
+ const count = geometry?.positions?.length;
+ if (!Number.isSafeInteger(count) || count < 3 || count % 3 !== 0) {
+ throw new TypeError('GLB positions require a nonempty array of XYZ vertices.');
+ }
+ validateFloatChannel(geometry.positions, count, 'GLB positions');
+ validateFloatChannel(geometry.normals, count, 'GLB normals');
+ for (let offset = 0; offset < count; offset += 3) {
+ const length = Math.hypot(geometry.normals[offset], geometry.normals[offset + 1], geometry.normals[offset + 2]);
+ if (Math.abs(length - 1) > 0.001) throw new RangeError('GLB normals require unit vectors.');
+ }
+ if (geometry.colors !== undefined) validateFloatChannel(geometry.colors, count, 'GLB colors', true);
+ if (geometry.uvs !== undefined) validateFloatChannel(geometry.uvs, count / 3 * 2, 'GLB UVs');
+ if (!(geometry.indices instanceof Uint32Array) || geometry.indices.length === 0 || geometry.indices.length % 3 !== 0) {
+ throw new TypeError('GLB indices require a nonempty Uint32Array of triangles.');
+ }
+ for (const index of geometry.indices) {
+ if (index >= count / 3) throw new RangeError('GLB index exceeds the vertex count.');
+ }
+}
+
+function validatePart(part) {
+ if (!part.matrix || part.matrix.length !== 16 || Array.from(part.matrix).some(value => !Number.isFinite(value) || !Number.isFinite(Math.fround(value)))) {
+ throw new RangeError('GLB matrix requires 16 finite components.');
+ }
+ if (part.matrix[3] !== 0 || part.matrix[7] !== 0 || part.matrix[11] !== 0 || part.matrix[15] !== 1) {
+ throw new RangeError('GLB matrix requires an affine transform.');
+ }
+ validateTransformColumns(part.matrix);
+ const material = part.material;
+ if (!material || typeof material !== 'object') throw new TypeError('GLB parts require a material.');
+ validateColor(material.color, 'GLB base color');
+ validateColor(material.emissiveColor ?? material.color, 'GLB emissive color');
+ validateFactor(material.metallic, 'GLB metallic factor');
+ validateFactor(material.roughness, 'GLB roughness factor');
+ validateFactor(material.emission ?? 0, 'GLB emission', Infinity);
+}
+
+function validateTransformColumns(matrix) {
+ const columns = [0, 4, 8].map(offset => {
+ const values = [Math.fround(matrix[offset]), Math.fround(matrix[offset + 1]), Math.fround(matrix[offset + 2])];
+ const length = Math.hypot(...values);
+ // Three's matrix decomposition divides by scale, so zero scales cannot roundtrip.
+ if (length === 0) throw new RangeError('GLB matrix requires nonzero scales.');
+ return values.map(value => value / length);
+ });
+ // Normalized column products remove scale dependence and allow Float32 TRS roundoff.
+ const tolerance = 8 * 2 ** -23;
+ for (let first = 0; first < 3; first++) {
+ for (let second = first + 1; second < 3; second++) {
+ let dot = 0;
+ for (let axis = 0; axis < 3; axis++) dot += columns[first][axis] * columns[second][axis];
+ if (Math.abs(dot) > tolerance) throw new RangeError('GLB matrix cannot preserve shear. Use a transform with orthogonal rotation and scale columns.');
+ }
+ }
+}
function paddedLength(length) {
return Math.ceil(length / 4) * 4;
}
export function exportGlb(parts) {
+ if (!Array.isArray(parts) || parts.length === 0) throw new TypeError('GLB export requires a nonempty parts array.');
+ const validatedGeometries = new Set();
+ const morphMetadata = new Map();
for (const part of parts) {
- validateMorphGeometry(part.geometry, part.morph);
+ if (!validatedGeometries.has(part?.geometry)) {
+ validateGeometry(part?.geometry);
+ validatedGeometries.add(part.geometry);
+ }
+ validatePart(part);
+ const metadata = morphMetadata.get(part.geometry);
+ if (metadata) {
+ validateMorphPose(part.morph, metadata);
+ } else {
+ morphMetadata.set(part.geometry, validateMorphGeometry(part.geometry, part.morph));
+ }
if (part.skin || part.geometry.skinIndices || part.geometry.skinWeights) {
throw new RangeError('GLB export cannot preserve skinning yet. Bake the pose or export through a tool that preserves the skeleton.');
}
@@ -37,7 +132,7 @@ export function exportGlb(parts) {
document.bufferViews.push({ buffer: 0, byteOffset: byteLength, byteLength: data.byteLength, target });
chunks.push({ offset: byteLength, data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength) });
byteLength += paddedLength(data.byteLength);
- const entry = { bufferView: viewIndex, componentType: data instanceof Float32Array ? 5126 : 5125, count: type === 'VEC3' ? data.length / 3 : data.length, type };
+ const entry = { bufferView: viewIndex, componentType: data instanceof Float32Array ? 5126 : 5125, count: data.length / COMPONENT_COUNTS[type], type };
if (type === 'VEC3') {
entry.min = [Infinity, Infinity, Infinity];
entry.max = [-Infinity, -Infinity, -Infinity];
@@ -56,6 +151,8 @@ export function exportGlb(parts) {
attributes: { POSITION: accessor(part.geometry.positions, 'VEC3', 34962), NORMAL: accessor(part.geometry.normals, 'VEC3', 34962) },
indices: accessor(part.geometry.indices, 'SCALAR', 34963),
};
+ if (part.geometry.colors) geometry.attributes.COLOR_0 = accessor(part.geometry.colors, 'VEC3', 34962);
+ if (part.geometry.uvs) geometry.attributes.TEXCOORD_0 = accessor(part.geometry.uvs, 'VEC2', 34962);
if (part.geometry.morphTargets) {
geometry.targets = part.geometry.morphTargets.map(target => {
const channels = {};
@@ -69,10 +166,17 @@ export function exportGlb(parts) {
const materialKey = JSON.stringify(part.material);
if (!materials.has(materialKey)) {
materials.set(materialKey, document.materials.length);
- document.materials.push({
+ const material = {
pbrMetallicRoughness: { baseColorFactor: [...part.material.color, 1], metallicFactor: part.material.metallic, roughnessFactor: part.material.roughness },
- emissiveFactor: part.material.color.map((component) => Math.min(1, component * (part.material.emission ?? 0))),
- });
+ emissiveFactor: (part.material.emission ?? 0) === 0 ? [0, 0, 0] : Array.from(part.material.emissiveColor ?? part.material.color),
+ };
+ const strength = part.material.emission ?? 0;
+ if (strength !== 0 && strength !== 1) {
+ material.extensions = { [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
+ document.extensionsUsed = [EMISSIVE_STRENGTH];
+ document.extensionsRequired = [EMISSIVE_STRENGTH];
+ }
+ document.materials.push(material);
}
const geometry = geometries.get(part.geometry);
const material = materials.get(materialKey);
diff --git a/tests/export.test.js b/tests/export.test.js
index fbbff8e8..2b14e8d2 100644
--- a/tests/export.test.js
+++ b/tests/export.test.js
@@ -83,3 +83,199 @@ test('GLB morph snapshots retain relative channels, shared meshes and independen
first.weights[0] = NaN;
assert.throws(() => exportGlb(parts), /finite Float32/);
});
+
+function glbDocument(binary) {
+ const view = new DataView(binary);
+ const jsonLength = view.getUint32(12, true);
+ const document = JSON.parse(new TextDecoder().decode(new Uint8Array(binary, 20, jsonLength)));
+ function values(index) {
+ const accessor = document.accessors[index];
+ const bufferView = document.bufferViews[accessor.bufferView];
+ const components = { SCALAR: 1, VEC2: 2, VEC3: 3 }[accessor.type];
+ return Array.from(new Float32Array(binary, 28 + jsonLength + bufferView.byteOffset, accessor.count * components));
+ }
+ return { document, values };
+}
+
+function coloredPart() {
+ const geometry = box();
+ const colorStorage = new Float32Array(geometry.positions.length + 6).fill(99);
+ geometry.colors = colorStorage.subarray(3, colorStorage.length - 3);
+ for (let offset = 0; offset < geometry.colors.length; offset += 3) geometry.colors.set([0.125, 0.5, 0.875], offset);
+ const uvStorage = new Float32Array(geometry.positions.length / 3 * 2 + 4).fill(99);
+ geometry.uvs = uvStorage.subarray(2, uvStorage.length - 2);
+ for (let offset = 0; offset < geometry.uvs.length; offset += 2) geometry.uvs.set([-0.25, 2.5], offset);
+ return { name: 'editable channels', geometry, matrix: mat4.create(), material: {
+ color: [0.25, 0.5, 0.75], metallic: 0.25, roughness: 0.625,
+ emissiveColor: new Float32Array([0.875, 0.125, 0.25]), emission: 12.5,
+ } };
+}
+
+test('GLB keeps editable offset RGB/UV accessors and separate HDR emission with shared meshes', async () => {
+ const part = coloredPart();
+ const binary = exportGlb([part, { ...part, name: 'shared instance' }]);
+ const { document, values } = glbDocument(binary);
+ assert.equal(document.meshes.length, 1);
+ const attributes = document.meshes[0].primitives[0].attributes;
+ assert.equal(document.accessors[attributes.COLOR_0].type, 'VEC3');
+ assert.equal(document.accessors[attributes.TEXCOORD_0].type, 'VEC2');
+ assert.equal(document.accessors[attributes.TEXCOORD_0].count, part.geometry.positions.length / 3);
+ assert.deepEqual(values(attributes.COLOR_0), Array.from(part.geometry.colors));
+ assert.deepEqual(values(attributes.TEXCOORD_0), Array.from(part.geometry.uvs));
+ assert.deepEqual(document.materials[0].pbrMetallicRoughness.baseColorFactor, [0.25, 0.5, 0.75, 1]);
+ assert.deepEqual(document.materials[0].emissiveFactor, [0.875, 0.125, 0.25]);
+ assert.equal(document.materials[0].extensions.KHR_materials_emissive_strength.emissiveStrength, 12.5);
+ assert.deepEqual(document.extensionsRequired, ['KHR_materials_emissive_strength']);
+ const loaded = await new GLTFLoader().parseAsync(binary, '');
+ const meshes = [];
+ loaded.scene.traverse(node => { if (node.isMesh) meshes.push(node); });
+ assert.equal(meshes[0].geometry, meshes[1].geometry);
+ assert.deepEqual(Array.from(meshes[0].geometry.attributes.color.array), Array.from(part.geometry.colors));
+ assert.deepEqual(Array.from(meshes[0].geometry.attributes.uv.array), Array.from(part.geometry.uvs));
+ assert.deepEqual(meshes[0].material.emissive.toArray(), [0.875, 0.125, 0.25]);
+ assert.equal(meshes[0].material.emissiveIntensity, 12.5);
+ const { parseGltf } = await import('../src/gltf.js');
+ const imported = await parseGltf(binary);
+ try {
+ assert.equal(imported.parts[0].geometry, imported.parts[1].geometry);
+ assert.deepEqual(Array.from(imported.parts[0].geometry.colors), Array.from(part.geometry.colors));
+ assert.deepEqual(Array.from(imported.parts[0].geometry.uvs), Array.from(part.geometry.uvs));
+ assert.deepEqual(imported.parts[0].material.emissiveColor, [0.875, 0.125, 0.25]);
+ assert.equal(imported.parts[0].material.emission, 12.5);
+ } finally {
+ imported.dispose();
+ }
+});
+
+test('GLB defaults remain dark without extensions and active emission preserves color and scalar', async () => {
+ for (const emission of [undefined, 0, 1, 0.25, 1000]) {
+ const part = coloredPart();
+ delete part.material.emissiveColor;
+ part.material.emission = emission;
+ const binary = exportGlb([part]);
+ const { document } = glbDocument(binary);
+ assert.deepEqual(document.materials[0].emissiveFactor, emission ? part.material.color : [0, 0, 0]);
+ assert.equal(Boolean(document.extensionsUsed), Boolean(emission && emission !== 1));
+ const loaded = await new GLTFLoader().parseAsync(binary, '');
+ const material = loaded.scene.children[0].material;
+ assert.equal(material.emissive.r * material.emissiveIntensity, part.material.color[0] * (emission ?? 0));
+ }
+});
+
+test('GLB validates every channel and material before binary allocation without clamping', () => {
+ for (const [field, value] of [
+ ['colors', new Float32Array(3)], ['colors', new Float64Array(72)],
+ ['uvs', new Float32Array(3)], ['uvs', new Float64Array(48)],
+ ['positions', new Float64Array(72)], ['normals', new Float32Array(72)],
+ ['indices', new Uint16Array([0, 1, 2])], ['indices', new Uint32Array([0, 1, 4294967295])],
+ ]) {
+ const part = coloredPart();
+ part.geometry[field] = value;
+ assert.throws(() => exportGlb([part]), /GLB/);
+ }
+ for (const [field, invalid] of [['colors', NaN], ['colors', -0.01], ['colors', 1.001], ['uvs', Infinity]]) {
+ const part = coloredPart();
+ part.geometry[field][0] = invalid;
+ assert.throws(() => exportGlb([part]), /finite values/);
+ }
+ for (const [field, invalid] of [
+ ['color', [1.001, 0, 0]], ['color', [0, 0]], ['emissiveColor', [0, NaN, 0]],
+ ['emissiveColor', [-1, 0, 0]], ['metallic', 1.01], ['roughness', -0.01],
+ ['emission', -1], ['emission', Infinity], ['emission', 1e40],
+ ]) {
+ const part = coloredPart();
+ part.material[field] = invalid;
+ assert.throws(() => exportGlb([part]), /GLB/);
+ }
+ const part = coloredPart();
+ part.matrix[3] = 1;
+ assert.throws(() => exportGlb([part]), /affine/);
+ assert.throws(() => exportGlb([]), /nonempty/);
+});
+
+
+test('GLB rejects an invalid later part before allocating its output buffer', () => {
+ const valid = coloredPart();
+ const invalid = coloredPart();
+ invalid.material.emission = Infinity;
+ const NativeArrayBuffer = globalThis.ArrayBuffer;
+ let allocations = 0;
+ globalThis.ArrayBuffer = class extends NativeArrayBuffer {
+ constructor(...argumentsList) {
+ super(...argumentsList);
+ allocations++;
+ }
+ };
+ try {
+ assert.throws(() => exportGlb([valid, invalid]), /GLB emission/);
+ assert.equal(allocations, 0);
+ } finally {
+ globalThis.ArrayBuffer = NativeArrayBuffer;
+ }
+});
+
+test('GLB scans shared static geometry once while preserving different instance materials', () => {
+ const part = coloredPart();
+ const positions = part.geometry.positions;
+ let reads = 0;
+ Object.defineProperty(part.geometry, 'positions', { get() { reads++; return positions; } });
+ exportGlb([part]);
+ const singleReads = reads;
+ reads = 0;
+ const second = { ...part, material: { ...part.material, emissiveColor: [0.125, 0.875, 0.25] } };
+ const { document } = glbDocument(exportGlb([part, second]));
+ assert.equal(reads, singleReads);
+ assert.equal(document.meshes.length, 2);
+ assert.equal(document.meshes[0].primitives[0].attributes.COLOR_0, document.meshes[1].primitives[0].attributes.COLOR_0);
+ assert.deepEqual(document.materials.map(material => material.emissiveFactor), [[0.875, 0.125, 0.25], [0.125, 0.875, 0.25]]);
+});
+
+test('GLB rejects shear and zero scales before output allocation', () => {
+ for (const [offset, value, message] of [[4, 0.5, /shear/], [0, 0, /nonzero scales/], [0, 1e-50, /nonzero scales/]]) {
+ const part = coloredPart();
+ part.matrix = Array.from(part.matrix);
+ part.matrix[offset] = value;
+ const NativeArrayBuffer = globalThis.ArrayBuffer;
+ let allocations = 0;
+ globalThis.ArrayBuffer = class extends NativeArrayBuffer {
+ constructor(...argumentsList) {
+ super(...argumentsList);
+ allocations++;
+ }
+ };
+ try {
+ assert.throws(() => exportGlb([part]), message);
+ assert.equal(allocations, 0);
+ } finally {
+ globalThis.ArrayBuffer = NativeArrayBuffer;
+ }
+ }
+ const scaledShear = coloredPart();
+ mat4.scale(scaledShear.matrix, scaledShear.matrix, [1e-25, 2e-25, 3e-25]);
+ scaledShear.matrix[4] = 1e-25;
+ assert.throws(() => exportGlb([scaledShear]), /shear/);
+});
+
+test('GLB Float32 rotated nonuniform, reflected and tiny TRS transforms roundtrip through Three', async () => {
+ for (const scale of [[0.125, 7, 2.5], [-0.125, 7, 2.5], [0.125, -7, -2.5], [1e-30, 2e-25, -3e-20]]) {
+ const part = coloredPart();
+ mat4.translate(part.matrix, part.matrix, [0.25, -1.5, 3]);
+ mat4.rotateX(part.matrix, part.matrix, 0.47);
+ mat4.rotateY(part.matrix, part.matrix, -0.71);
+ mat4.rotateZ(part.matrix, part.matrix, 1.13);
+ mat4.scale(part.matrix, part.matrix, scale);
+ const binary = exportGlb([part]);
+ assert.deepEqual(glbDocument(binary).document.nodes[0].matrix, Array.from(part.matrix, value => value === 0 ? 0 : value));
+ const loaded = await new GLTFLoader().parseAsync(binary, '');
+ loaded.scene.updateMatrixWorld(true);
+ const actual = loaded.scene.children[0].matrix.elements;
+ for (let column = 0; column < 4; column++) {
+ const magnitude = Math.max(...Array.from(part.matrix.slice(column * 4, column * 4 + 4), Math.abs));
+ for (let row = 0; row < 4; row++) {
+ const offset = column * 4 + row;
+ assert.ok(Number.isFinite(actual[offset]));
+ assert.ok(Math.abs(actual[offset] - part.matrix[offset]) <= magnitude * 1e-6, `scale ${scale}, component ${offset}`);
+ }
+ }
+ }
+});