Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Read glTF layer textures and accept TEXCOORD_1 on occlusion, emissive and metallic-roughness

Nguyen Xuan An6f79e893d233
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 933f04b5..1ea0b2e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Read the textures inside glTF layer extensions and accept TEXCOORD_1 (part of issue #51). `clearcoatTexture`, `clearcoatRoughnessTexture`, `clearcoatNormalTexture`, `anisotropyTexture`, `sheenColorTexture` and `sheenRoughnessTexture` load into `material.layerMaps` and draw through shader features in `material-layer-shaders`, and `exportGlb` writes them back. Occlusion, emissive and metallic-roughness textures may read TEXCOORD_1. Against Cycles, `AnisotropyBarnLamp` goes from 0.4758 to 0.3584, `AnisotropyDiscTest` from 0.3481 to 0.2808 and `ClearCoatTest` from 0.2344 to 0.2306; `TransmissionTest` is unchanged and `SheenChair` still waits on per-map texture transforms. The core entry grows by about 345 bytes gzip.
- Score material scenes and Khronos sample assets against their baseline (parts of issues #50 and #51). `brick-flat` is the control for `brick-graph`: the same wall in the graph's average colour with no maps. `npm run reference -- --khronos` draws Khronos sample assets downloaded into gitignored `artifacts/khronos/` and scores them against Cycles reading the same GLB, on the pixels the asset covers (`khronos.json`, `images/khronos-*.jpg`; `baseline.json` is unchanged). The brick bump is not weaker than Blender's: its bright edge is stronger and bump 0 would score better (0.2065 against 0.2269), so no engine change. The assets found two importer faults, fixed in `src/gltf.js`: `KHR_xmp` and `KHR_xmp_json_ld` metadata refused the whole file, and `KHR_materials_variants` is now accepted with a warning. Still open: texture slots in layer extensions (the anisotropy textures matter, both anisotropy assets score worse with the factor than with none) and occlusion on TEXCOORD_1 (`SheenChair`).
- Measure what an equal feature set costs against three.js (part of issue #74; no engine change, no speed-up). `bench/runtime` gets the engines `67js-ldr`, `67js-one-sample`, `67js-ldr-one-sample` and `three-one-sample` (run with `--engine`) and a `--cpu-only` flag. Measured: with no MSAA and no HDR target 67js is still 5.2 to 5.7 times three.js on SwiftShader in `large-mesh`, `many-materials` and `instanced-objects` (7.8, 5.3 and 7.8 with the defaults), so the gap is the lit shader and not those two features. On the RTX 3060 `large-mesh` costs 3.6 ms against 0.6 ms and is not explained by HDR, MSAA, the vertex shader or the vertex attributes; on ANGLE Vulkan the ratio is 2.3 instead of 5.8. Skipping zero-intensity fill lights was tried and reverted (inside the noise). The profile is in `bench/runtime/PROFILE.md`.
- Add cascaded sun shadows and light linking (part of issue #52; recipes do not reach either, and `lit-interior` was already improved by the light bake, not by this work). `addons/cascaded-shadows`: `new Renderer67(canvas, parts, { shadowCascades: createCascadedShadows({ count: 3 }) })` fits up to four depth maps to slices of the camera's view, with sphere fitting and texel snapping so edges do not crawl; on the new `long-street` reference scene the score against Cycles goes from 0.1555 to 0.1398 for about 0.2 ms more a frame on an RTX 3060 (+25 percent on SwiftShader) when the camera moves. `addons/light-linking`: `applyLightLinks(parts, environment)` limits a light to the parts named in its `affects` list (`environment.keyAffects` for the sun) through a per-part mask in `material.lightMask`; the new `light-linking` reference scene scores 0.0998 against Cycles with the same lists as Blender receiver collections. Both keep their GLSL out of the core bundle (`registerShaderFeatureCode`, new slots `sunVisibility`, `linkSun`, `linkPoint`, `linkSpot` and `linkArea`), and `npm run reference -- --cascades <n>` and `frame-time.mjs <scene> <backend> --cascades` measure them. No earlier reference scene moved.
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 66d7b22e..4f6fe81e 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -59,12 +59,12 @@ Khronos sample assets (issue #51): `npm run reference -- --khronos` draws files
| Asset | Pixels covered | 67js against Cycles (asset only) | 67js against EEVEE | EEVEE against Cycles | What differs |
| --- | --- | --- | --- | --- | --- |
-| `ClearCoatTest` | 0.1353 | 0.2344 | 0.1859 | 0.1336 | Only factors are read, and the asset's coat and normal textures sit in layer slots |
+| `ClearCoatTest` | 0.1353 | 0.2306 (was 0.2344) | 0.1808 | 0.1335 | The coat, coat roughness and coat normal textures are read; most of the gap is outside the coat |
| `TransmissionTest` | 0.1356 | 0.2708 | 0.2371 | 0.1656 | Refraction through the front surface only, no roughness-blurred background |
-| `AnisotropyDiscTest` | 0.1073 | 0.3481 | 0.3174 | 0.1535 | The anisotropy and rotation textures are ignored: 0.2773 with anisotropy switched off |
-| `AnisotropyBarnLamp` | 0.0734 | 0.4758 | 0.4199 | 0.3761 | The copper shade is lighter and less saturated; 0.3945 with anisotropy switched off |
+| `AnisotropyDiscTest` | 0.1074 | 0.2808 (was 0.3481) | 0.2772 | 0.1534 | `anisotropyTexture` is read: the disc pattern now draws, but the tiles are darker than Cycles; 0.2773 with anisotropy switched off |
+| `AnisotropyBarnLamp` | 0.0733 | 0.3584 (was 0.4758) | 0.4318 | 0.3765 | `anisotropyTexture` and the coat normal texture are read, and it now scores better than anisotropy switched off (0.3945) |
-Switching anisotropy off scores better than our anisotropy on both anisotropy assets, so the missing `anisotropyTexture` (strength and direction per texel) is what matters there, and it is ours; the layer factor alone spreads a highlight over the whole shade. Not added in this change. `SheenChair` was refused: its occlusion texture uses TEXCOORD_1, which `parseGltf` rejects. Both Blender's engines disagree on the lamp by 0.3761, so part of that gap is Blender's own anisotropy and clear coat. Two importer bugs the assets found are fixed: `KHR_xmp` and `KHR_xmp_json_ld` (metadata) stopped the whole import, and `KHR_materials_variants` is now accepted with a warning and draws the default material.
+Reading `anisotropyTexture` (strength in blue, direction in red and green) fixed the shade: the factor alone spread a highlight over everything, and it scored worse than no anisotropy. The disc test is still level with anisotropy switched off, so the remaining gap there is not the texture. `TransmissionTest` is unchanged at 0.2708: its `transmissionTexture` is not read, because transmission draws in the liquid pass, which has no feature code, and the scores do not show that the other slots (iridescence, specular) matter. `SheenChair` still cannot be scored: its occlusion texture on TEXCOORD_1 now loads, but its fabric gives the base color and normal textures different `KHR_texture_transform` values, and one UV transform is baked per material. Both Blender's engines disagree on the lamp by 0.3761, so part of that gap is Blender's own anisotropy and clear coat. Two importer bugs the assets found are fixed: `KHR_xmp` and `KHR_xmp_json_ld` (metadata) stopped the whole import, and `KHR_materials_variants` is now accepted with a warning and draws the default material.
`brick-flat` is the control for `brick-graph` (issue #50): the same wall and light in the average colour of the graph, with no maps. Measured 2026-11-01 it scores 0.1999 against Cycles (0.1119 against EEVEE, EEVEE against Cycles 0.1351), and `brick-graph` 0.2269 (0.1480), so by this baseline the graph does not score above it: the picture is more like Cycles in kind but FLIP punishes the misplaced bevel highlights and the tone differences of noise more than it rewards the brick pattern. The bump of `brick-graph` is not weaker than Blender's. In a profile across one brick edge (columns 365 to 420, rows 150 to 215 of the render) the dark side of the bevel is the same in both (about 0.25 below the wall), and the bright side is about 0.3 above the wall in 67js against 0.17 in Cycles; the luminance spread over the brick area is 0.132 against 0.109 (EEVEE 0.109), and the edges fall on the same rows. Turning the bump down only lowers the score: 0.2065 with a bump of 0.01, 0.2209 at 0.5, 0.2247 at 0.75 and 0.2269 at 1 against Cycles. So the earlier note, that bump is weaker, was wrong. The rim of 67js is brighter because it keeps the full slope of the steep joint edge; the flat wall brightness is also 0.07 lower than Cycles, which has indirect light from the floor (EEVEE matches 67js there).
diff --git a/bench/reference/images/khronos-AnisotropyBarnLamp.jpg b/bench/reference/images/khronos-AnisotropyBarnLamp.jpg
index 01a49dec..f561759e 100644
Binary files a/bench/reference/images/khronos-AnisotropyBarnLamp.jpg and b/bench/reference/images/khronos-AnisotropyBarnLamp.jpg differ
diff --git a/bench/reference/images/khronos-AnisotropyDiscTest.jpg b/bench/reference/images/khronos-AnisotropyDiscTest.jpg
index b0c2bab8..e9fd8d03 100644
Binary files a/bench/reference/images/khronos-AnisotropyDiscTest.jpg and b/bench/reference/images/khronos-AnisotropyDiscTest.jpg differ
diff --git a/bench/reference/images/khronos-ClearCoatTest.jpg b/bench/reference/images/khronos-ClearCoatTest.jpg
index 514e2cbb..828b506b 100644
Binary files a/bench/reference/images/khronos-ClearCoatTest.jpg and b/bench/reference/images/khronos-ClearCoatTest.jpg differ
diff --git a/bench/reference/khronos.json b/bench/reference/khronos.json
index d8dd0d36..3c00b3cb 100644
--- a/bench/reference/khronos.json
+++ b/bench/reference/khronos.json
@@ -25,40 +25,40 @@
},
"scores": {
"AnisotropyBarnLamp": {
- "gpu-vs-cycles": 0.0449,
- "gpu-vs-eevee": 0.0289,
- "cpu-vs-cycles": 0.0447,
- "cpu-vs-eevee": 0.0286,
+ "gpu-vs-cycles": 0.041,
+ "gpu-vs-eevee": 0.0462,
+ "cpu-vs-cycles": 0.0408,
+ "cpu-vs-eevee": 0.0458,
"eevee-vs-cycles": 0.0398,
- "gpu-vs-cpu": 0.0063,
- "asset-pixels": 0.0731,
- "asset-gpu-vs-cycles": 0.3945,
- "asset-gpu-vs-eevee": 0.2401,
- "asset-eevee-vs-cycles": 0.3767
+ "gpu-vs-cpu": 0.0065,
+ "asset-pixels": 0.0733,
+ "asset-gpu-vs-cycles": 0.3584,
+ "asset-gpu-vs-eevee": 0.4318,
+ "asset-eevee-vs-cycles": 0.3765
},
"AnisotropyDiscTest": {
- "gpu-vs-cycles": 0.0447,
- "gpu-vs-eevee": 0.038,
- "cpu-vs-cycles": 0.0444,
- "cpu-vs-eevee": 0.0377,
+ "gpu-vs-cycles": 0.0445,
+ "gpu-vs-eevee": 0.0419,
+ "cpu-vs-cycles": 0.0443,
+ "cpu-vs-eevee": 0.0417,
"eevee-vs-cycles": 0.024,
- "gpu-vs-cpu": 0.0058,
+ "gpu-vs-cpu": 0.0062,
"asset-pixels": 0.1074,
- "asset-gpu-vs-cycles": 0.2773,
- "asset-gpu-vs-eevee": 0.2416,
+ "asset-gpu-vs-cycles": 0.2808,
+ "asset-gpu-vs-eevee": 0.2772,
"asset-eevee-vs-cycles": 0.1534
},
"ClearCoatTest": {
- "gpu-vs-cycles": 0.0454,
- "gpu-vs-eevee": 0.034,
- "cpu-vs-cycles": 0.0451,
- "cpu-vs-eevee": 0.0337,
+ "gpu-vs-cycles": 0.0448,
+ "gpu-vs-eevee": 0.0333,
+ "cpu-vs-cycles": 0.0445,
+ "cpu-vs-eevee": 0.0329,
"eevee-vs-cycles": 0.0271,
- "gpu-vs-cpu": 0.0075,
+ "gpu-vs-cpu": 0.0076,
"asset-pixels": 0.1353,
- "asset-gpu-vs-cycles": 0.2344,
- "asset-gpu-vs-eevee": 0.1859,
- "asset-eevee-vs-cycles": 0.1336
+ "asset-gpu-vs-cycles": 0.2306,
+ "asset-gpu-vs-eevee": 0.1808,
+ "asset-eevee-vs-cycles": 0.1335
},
"TransmissionTest": {
"gpu-vs-cycles": 0.0485,
diff --git a/bench/reference/scenes.js b/bench/reference/scenes.js
index 3d85dfc9..2e9dcf4b 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -112,7 +112,8 @@ async function brickWallScene({ withGraph }) {
// Khronos glTF sample assets (issue #51), downloaded by hand into artifacts/khronos/<name>/<name>.glb. Blender imports
// the same file with its own importer, so the reference is Cycles reading the asset, not our reading of it.
-// SheenChair is left out: its occlusion texture uses TEXCOORD_1, which parseGltf refuses (README, Khronos table).
+// SheenChair is still left out: its occlusion texture on TEXCOORD_1 now loads, but its fabric gives the base color and normal
+// textures different KHR_texture_transform values, which parseGltf refuses (one UV transform is baked per material).
const KHRONOS_ASSET_NAMES = ['ClearCoatTest', 'TransmissionTest', 'AnisotropyBarnLamp', 'AnisotropyDiscTest'];
const KHRONOS_VIEW_DIRECTION = [0.35, 0.25, 1];
const KHRONOS_FIELD_OF_VIEW = 35;
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index cddc58f4..107bedd8 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 288009,
- "gzip": 82348,
- "brotli": 70217
+ "min": 289074,
+ "gzip": 82693,
+ "brotli": 70523
},
"entry:model": {
"min": 40093,
@@ -39,14 +39,14 @@
"brotli": 7331
},
"entry:gltf": {
- "min": 156410,
- "gzip": 48011,
- "brotli": 41568
+ "min": 158507,
+ "gzip": 48585,
+ "brotli": 42083
},
"entry:gltf+lazy": {
- "min": 162843,
- "gzip": 50001,
- "brotli": 43377
+ "min": 169452,
+ "gzip": 51780,
+ "brotli": 45001
},
"entry:modeling": {
"min": 21149,
@@ -144,24 +144,24 @@
"brotli": 762
},
"entry:agent-scene": {
- "min": 211577,
- "gzip": 65756,
- "brotli": 57523
+ "min": 211709,
+ "gzip": 65808,
+ "brotli": 57572
},
"entry:agent-scene+lazy": {
- "min": 659276,
- "gzip": 227206,
- "brotli": 200480
+ "min": 663920,
+ "gzip": 228461,
+ "brotli": 201694
},
"entry:agent-asset": {
- "min": 306884,
- "gzip": 97436,
- "brotli": 85596
+ "min": 307016,
+ "gzip": 97483,
+ "brotli": 85682
},
"entry:agent-asset+lazy": {
- "min": 696350,
- "gzip": 238925,
- "brotli": 210566
+ "min": 700994,
+ "gzip": 240176,
+ "brotli": 211765
},
"entry:hdri": {
"min": 8075,
@@ -179,44 +179,44 @@
"brotli": 1425
},
"entry:material-layer-shaders": {
- "min": 71897,
- "gzip": 18688,
- "brotli": 16369
+ "min": 76528,
+ "gzip": 19676,
+ "brotli": 17263
},
"entry:light-linking": {
- "min": 67458,
- "gzip": 17938,
- "brotli": 15753
+ "min": 67578,
+ "gzip": 17981,
+ "brotli": 15804
},
"entry:cascaded-shadows": {
- "min": 95474,
- "gzip": 26574,
- "brotli": 22646
+ "min": 95594,
+ "gzip": 26620,
+ "brotli": 22668
},
"scene:lit-box": {
- "min": 218221,
- "gzip": 59990,
- "brotli": 51264
+ "min": 218625,
+ "gzip": 60169,
+ "brotli": 51383
},
"scene:gltf-box": {
- "min": 277847,
- "gzip": 80037,
- "brotli": 69616
+ "min": 280207,
+ "gzip": 80800,
+ "brotli": 70220
},
"scene:gltf-box+lazy": {
- "min": 284280,
- "gzip": 82027,
- "brotli": 71422
+ "min": 291152,
+ "gzip": 83995,
+ "brotli": 73136
},
"scene:agent-scene": {
- "min": 323127,
- "gzip": 96652,
- "brotli": 84272
+ "min": 323543,
+ "gzip": 96819,
+ "brotli": 84320
},
"scene:agent-scene+lazy": {
- "min": 770826,
- "gzip": 258108,
- "brotli": 227330
+ "min": 775754,
+ "gzip": 259481,
+ "brotli": 228479
}
}
}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index eb061dbe..46fd96f0 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -6,13 +6,13 @@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 84000,
+ "entry:core": 84400,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 13600,
"entry:canvas2d": 9400,
- "entry:gltf": 49000,
- "entry:gltf+lazy": 51100,
+ "entry:gltf": 49600,
+ "entry:gltf+lazy": 52900,
"entry:modeling": 8700,
"entry:sculpt": 2500,
"entry:surface": 10100,
@@ -32,20 +32,20 @@
"entry:light-bake": 27100,
"entry:path-tracer": 13800,
"entry:texture-set": 900,
- "entry:agent-scene": 67100,
- "entry:agent-scene+lazy": 231800,
- "entry:agent-asset": 99400,
- "entry:agent-asset+lazy": 243800,
+ "entry:agent-scene": 67200,
+ "entry:agent-scene+lazy": 233100,
+ "entry:agent-asset": 99500,
+ "entry:agent-asset+lazy": 245000,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
- "entry:material-layer-shaders": 19100,
- "entry:light-linking": 18300,
+ "entry:material-layer-shaders": 20100,
+ "entry:light-linking": 18400,
"entry:cascaded-shadows": 27200,
- "scene:lit-box": 61200,
- "scene:gltf-box": 81700,
- "scene:gltf-box+lazy": 83700,
- "scene:agent-scene": 98600,
- "scene:agent-scene+lazy": 263300
+ "scene:lit-box": 61400,
+ "scene:gltf-box": 82500,
+ "scene:gltf-box+lazy": 85700,
+ "scene:agent-scene": 98800,
+ "scene:agent-scene+lazy": 264700
}
}
diff --git a/docs/gltf.md b/docs/gltf.md
index ca43b839..6f77d6f5 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -140,7 +140,7 @@ Line and point primitives are unsupported.
| `KHR_draco_mesh_compression` | Needs `options.decoders.draco`. |
| `EXT_meshopt_compression` | Needs `options.decoders.meshopt`. |
| `KHR_texture_basisu` | Needs `options.decoders.ktx2`. |
-| `KHR_materials_clearcoat`, `_transmission`, `_ior`, `_specular`, `_sheen`, `_volume`, `_anisotropy`, `_iridescence` | Read as factors and rendered as material layers, see `docs/material-maps.md`. Their textures are ignored, and an iridescent film takes the thickness maximum. Export writes them back. |
+| `KHR_materials_clearcoat`, `_transmission`, `_ior`, `_specular`, `_sheen`, `_volume`, `_anisotropy`, `_iridescence` | Read as factors and rendered as material layers, see `docs/material-maps.md`. The textures `clearcoatTexture`, `clearcoatRoughnessTexture`, `clearcoatNormalTexture`, `anisotropyTexture`, `sheenColorTexture` and `sheenRoughnessTexture` are read too, into `material.layerMaps` (their GLSL loads with `material-layer-shaders`); a renderer draws at most three different ones, and none beside splat layers. The transmission, iridescence and specular textures are not read: their factors are used. `occlusionTexture`, `emissiveTexture` and `metallicRoughnessTexture` may use TEXCOORD_1 (the mesh's `lightUvs`, which a light bake also uses); base color and normal textures must use TEXCOORD_0, and a texture on TEXCOORD_1 cannot carry `KHR_texture_transform`. Their textures are ignored, and an iridescent film takes the thickness maximum. Export writes them back. |
`KHR_materials_transmission` with a factor above zero sets `material.transmission` to that factor.
It is a hint only: the renderer does not draw transmission yet.
diff --git a/docs/parity.md b/docs/parity.md
index 5c05cf76..3364fb3a 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -201,7 +201,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Materials > Legacy Textures | out of scope | Blender keeps these for old files. | | |
| Rendering > Shader Nodes > Input | partial | `uv` coordinates only. There is no object, geometry, camera or light-path input. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Output | partial | A graph makes base colour, roughness, metallic, emission and height. It is baked to textures on the CPU, so it can not react to light, view or position. The `brick-graph` reference scene scores 0.2269 against Cycles; its `brick-flat` control (the graph's average colour, no maps) is the baseline it is compared with, and a bump of 0 would score 0.2065, so the bump is stronger than Blender's, not weaker. | [material-graph](../tests/material-graph.test.js), [brick-graph scene](../bench/reference/scenes.js) | #50 |
-| Rendering > Shader Nodes > Shader | partial | A metallic-roughness surface with clear coat, transmission, sheen and specular layers, and unlit, liquid and foam tags. Anisotropy (key, fill and local lights, and a bent environment lookup) and thin-film iridescence follow the glTF extensions rather than Blender's tangent and thin-film inputs, scored in the `brushed-film` reference scene. Khronos sample assets (`npm run reference -- --khronos`, files downloaded by hand) score 0.23 to 0.48 against Cycles on the pixels the asset covers (0.13 to 0.38 for EEVEE): the glTF anisotropy textures and the other texture slots inside layer extensions are not read, and on both anisotropy assets the factor alone scores worse than no anisotropy. There is no subsurface. | [material-layers](../tests/material-layers.test.js) | #51 |
+| Rendering > Shader Nodes > Shader | partial | A metallic-roughness surface with clear coat, transmission, sheen and specular layers, and unlit, liquid and foam tags. Anisotropy (key, fill and local lights, and a bent environment lookup) and thin-film iridescence follow the glTF extensions rather than Blender's tangent and thin-film inputs, scored in the `brushed-film` reference scene. Khronos sample assets (`npm run reference -- --khronos`, files downloaded by hand) score 0.23 to 0.48 against Cycles on the pixels the asset covers (0.13 to 0.38 for EEVEE): the glTF clear coat (strength, roughness, normal), anisotropy and sheen textures are read (`layerMaps`, shader code in `material-layer-shaders`), which took the barn lamp from 0.4758 to 0.3584 and the anisotropy disc from 0.3481 to 0.2808; the transmission, iridescence and specular textures are not read, and `SheenChair` waits on per-map texture transforms. There is no subsurface. | [material-layers](../tests/material-layers.test.js) | #51 |
| Rendering > Shader Nodes > Displacement | partial | Bump: a graph's height becomes a normal map. There is no displacement of the surface. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Texture | partial | Image maps, 11 pattern presets, and graph nodes for noise, voronoi, wave, checker and gradient. Noise is not Blender's noise function, and there is no brick, musgrave, magic or environment node. Patterns follow UVs or box projection. | [material-patterns](../tests/material-patterns.test.js), [material-graph](../tests/material-graph.test.js), [brick-graph scene](../bench/reference/scenes.js) | #50 |
| Rendering > Shader Nodes > Color | partial | Color ramp, mix and invert. There is no hue, curves, gamma or blend modes. | [material-graph](../tests/material-graph.test.js) | #50 |
diff --git a/src/export-textures.js b/src/export-textures.js
index 62f21b93..265f4fdb 100644
--- a/src/export-textures.js
+++ b/src/export-textures.js
@@ -72,7 +72,7 @@ export function createTextureWriter(writer, maxTextureSize = DEFAULT_MAX_TEXTURE
return {
/** Index of the glTF texture for a renderer texture descriptor `{ image, wrapS, ... }`. */
textureIndex(descriptor, channel) {
- if ((descriptor.uvChannel ?? 0) !== 0) throw new RangeError(`GLB ${channel} uses UV channel ${descriptor.uvChannel}; only channel 0 is supported.`);
+ if (![0, 1].includes(descriptor.uvChannel ?? 0)) throw new RangeError(`GLB ${channel} uses UV channel ${descriptor.uvChannel}; only channels 0 and 1 are supported.`);
const source = imageIndex(descriptor, channel);
const sampler = samplerIndex(descriptor);
const key = `${source}:${sampler}`;
diff --git a/src/export.js b/src/export.js
index 6719bb3c..5c93625f 100644
--- a/src/export.js
+++ b/src/export.js
@@ -1,5 +1,5 @@
import { validateMorphGeometry, validateMorphPose } from './morph.js';
-import { gltfExtensionsFromLayers } from './gltf-layers.js';
+import { gltfExtensionsFromLayers, LAYER_TEXTURE_SLOTS } from './gltf-layers.js';
import { validateSkinGeometry } from './skinning.js';
import { boxProjectedGeometry } from './export-box-uv.js';
import { createTextureWriter } from './export-textures.js';
@@ -139,9 +139,29 @@ function createIdentityTracker() {
function materialKeyOf(material, identify) {
const textures = [...TEXTURE_CHANNELS, 'lightMap'].map(channel => material[channel] ? identify(material[channel]) : null);
+ const layerTextures = Object.entries(material.layerMaps ?? {}).map(([name, descriptor]) => [name, identify(descriptor)]);
const fields = { ...material };
- for (const channel of [...TEXTURE_CHANNELS, 'lightMap', 'pattern', 'boxMapScale', 'boxMapAxis']) delete fields[channel];
- return JSON.stringify([fields, textures, material.boxMapScale ?? 0, material.boxMapAxis ?? 1]);
+ for (const channel of [...TEXTURE_CHANNELS, 'lightMap', 'layerMaps', 'pattern', 'boxMapScale', 'boxMapAxis']) delete fields[channel];
+ return JSON.stringify([fields, textures, layerTextures, material.boxMapScale ?? 0, material.boxMapAxis ?? 1]);
+}
+
+/** Adds the layer textures to the KHR_materials_* objects, creating an extension that only has textures to carry. */
+function writeLayerTextures(writer, textureWriter, material, layerExtensions) {
+ for (const [extensionName, property] of LAYER_TEXTURE_SLOTS) {
+ const descriptor = material.layerMaps?.[property];
+ if (!descriptor) continue;
+ if (!layerExtensions[extensionName]) {
+ layerExtensions[extensionName] = {};
+ writer.addExtension(extensionName);
+ }
+ layerExtensions[extensionName][property] = textureReference(textureWriter, descriptor, property);
+ }
+}
+
+function textureReference(textureWriter, descriptor, channel) {
+ const reference = { index: textureWriter.textureIndex(descriptor, channel) };
+ if (descriptor.uvChannel === 1) reference.texCoord = 1;
+ return reference;
}
/**
@@ -168,16 +188,15 @@ function writeMaterial(writer, textureWriter, material) {
};
writeAlphaFields(gltfMaterial, material);
const layerExtensions = gltfExtensionsFromLayers(material);
- if (Object.keys(layerExtensions).length > 0) {
- gltfMaterial.extensions = layerExtensions;
- for (const extensionName of Object.keys(layerExtensions)) writer.addExtension(extensionName);
- }
+ for (const extensionName of Object.keys(layerExtensions)) writer.addExtension(extensionName);
+ writeLayerTextures(writer, textureWriter, material, layerExtensions);
+ if (Object.keys(layerExtensions).length > 0) gltfMaterial.extensions = layerExtensions;
const strength = material.emission ?? 0;
if (strength !== 0 && strength !== 1) {
gltfMaterial.extensions = { ...gltfMaterial.extensions, [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
writer.addExtension(EMISSIVE_STRENGTH, { required: true });
}
- const textureOf = channel => ({ index: textureWriter.textureIndex(material[channel], channel) });
+ const textureOf = channel => textureReference(textureWriter, material[channel], channel);
if (material.map) pbr.baseColorTexture = textureOf('map');
if (material.metallicRoughnessMap) pbr.metallicRoughnessTexture = textureOf('metallicRoughnessMap');
if (material.normalMap) gltfMaterial.normalTexture = { ...textureOf('normalMap'), scale: material.normalScale?.[0] ?? 1 };
diff --git a/src/gltf-decode.js b/src/gltf-decode.js
index 9e174f43..deeca35b 100644
--- a/src/gltf-decode.js
+++ b/src/gltf-decode.js
@@ -1,6 +1,7 @@
import { mat4 } from 'gl-matrix';
import { COMPONENT_TYPES, attributeFloats, createAccessorReader } from './gltf-accessors.js';
import { createClips } from './gltf-animation.js';
+import { layerTextureReferences } from './gltf-layers.js';
import { Matrix4, SceneNode } from './gltf-nodes.js';
import { createSkinPose, validateSkinGeometry } from './skinning.js';
@@ -9,6 +10,7 @@ const GEOMETRY_ATTRIBUTE_NAMES = {
NORMAL: 'normal',
COLOR_0: 'color',
TEXCOORD_0: 'uv',
+ TEXCOORD_1: 'uv1',
JOINTS_0: 'skinIndex',
WEIGHTS_0: 'skinWeight',
};
@@ -183,6 +185,15 @@ export async function decodeGltf({ document, glbBinary, resourceBytes, decoders,
throw new Error(`${sourceField} failed to decode. Use a valid PNG or JPEG image. ${error.message}`);
}
}
+ const layerTextures = {};
+ for (const [name, reference] of layerTextureReferences(definition)) {
+ try {
+ layerTextures[name] = await loadTexture(reference.index);
+ } catch (error) {
+ throw new Error(`${name} failed to decode. Use a valid PNG or JPEG image. ${error.message}`);
+ }
+ }
+ if (Object.keys(layerTextures).length > 0) material.layerTextures = layerTextures;
materials.set(materialIndex, material);
return material;
}
diff --git a/src/gltf-layers.js b/src/gltf-layers.js
index d8b5f480..e11276b3 100644
--- a/src/gltf-layers.js
+++ b/src/gltf-layers.js
@@ -1,5 +1,4 @@
// Reads and writes the glTF material extensions that map onto the material layers of material-layers.js.
-// Texture slots inside these extensions (clearcoatTexture, transmissionTexture and so on) are not read: a factor is used.
import { MATERIAL_LAYER_DEFAULTS, validateMaterialLayers } from './material-layers.js';
export const GLTF_LAYER_EXTENSIONS = Object.freeze([
@@ -26,6 +25,28 @@ const IMPORT_RULES = Object.freeze([
['KHR_materials_iridescence', { iridescence: 'iridescenceFactor', iridescenceIor: 'iridescenceIor', iridescenceThickness: 'iridescenceThicknessMaximum' }],
]);
+// Texture slots inside the layer extensions. Each row: the extension, the glTF property and the texture's colour space.
+// The property is also the key under material.layerMaps, the GLSL sampler and the shader feature (material-layer-shaders.js).
+// Slots without shader code (transmissionTexture, the iridescence and specular textures) are not read: a factor is used.
+export const LAYER_TEXTURE_SLOTS = Object.freeze([
+ ['KHR_materials_clearcoat', 'clearcoatTexture', 'linear'],
+ ['KHR_materials_clearcoat', 'clearcoatRoughnessTexture', 'linear'],
+ ['KHR_materials_clearcoat', 'clearcoatNormalTexture', 'linear'],
+ ['KHR_materials_anisotropy', 'anisotropyTexture', 'linear'],
+ ['KHR_materials_sheen', 'sheenColorTexture', 'srgb'],
+ ['KHR_materials_sheen', 'sheenRoughnessTexture', 'linear'],
+]);
+
+/** The texture references a material definition makes inside its layer extensions: [glTF property, reference, colour space]. */
+export function layerTextureReferences(definition) {
+ const references = [];
+ for (const [extensionName, property, colorSpace] of LAYER_TEXTURE_SLOTS) {
+ const reference = definition?.extensions?.[extensionName]?.[property];
+ if (reference) references.push([property, reference, colorSpace]);
+ }
+ return references;
+}
+
/** Layer fields of one glTF material definition, validated, as a plain object to spread onto a material. */
export function materialLayersFromGltf(definition) {
const layers = {};
diff --git a/src/gltf.js b/src/gltf.js
index 6483196d..ab199b9e 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -1,5 +1,5 @@
import { applyClip } from './gltf-animation.js';
-import { GLTF_LAYER_EXTENSIONS, materialLayersFromGltf } from './gltf-layers.js';
+import { GLTF_LAYER_EXTENSIONS, layerTextureReferences, materialLayersFromGltf } from './gltf-layers.js';
import { attributeFloats } from './gltf-accessors.js';
import { decodeGltf, textureSourceIndex } from './gltf-decode.js';
import { Matrix4 } from './gltf-nodes.js';
@@ -9,17 +9,17 @@ import { MAX_MORPH_TARGETS, createMorphPose, validateMorphGeometry, validateMorp
export const GLTF_CAPABILITIES = Object.freeze({
formats: ['glb', 'gltf'],
- supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_materials_clearcoat, transmission, volume, ior, specular, sheen, anisotropy and iridescence factors', 'KHR_texture_transform baked into UVs', 'EXT_mesh_gpu_instancing expanded into parts', 'KHR_draco_mesh_compression with options.decoders.draco', 'EXT_meshopt_compression with options.decoders.meshopt', 'KHR_texture_basisu with options.decoders.ktx2'],
+ supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'TEXCOORD_1 for occlusion, emissive and metallic-roughness textures', 'clearcoat, clearcoat roughness, clearcoat normal, anisotropy, sheen color and sheen roughness textures', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_materials_clearcoat, transmission, volume, ior, specular, sheen, anisotropy and iridescence factors', 'KHR_texture_transform baked into UVs', 'EXT_mesh_gpu_instancing expanded into parts', 'KHR_draco_mesh_compression with options.decoders.draco', 'EXT_meshopt_compression with options.decoders.meshopt', 'KHR_texture_basisu with options.decoders.ktx2'],
// The primitive's own material is drawn; the other variants are not selectable.
ignoredExtensions: ['KHR_materials_variants'],
- unsupported: ['more than four skin influences', 'singular weighted skin transforms', 'reflected skin transforms', 'TANGENT morph targets', 'morph targets without authored base normals', 'vertex alpha below one', 'different texture transforms on one material', 'skinned or morphed GPU instancing', 'textures inside material layer extensions (factors only)'],
+ unsupported: ['more than four skin influences', 'singular weighted skin transforms', 'reflected skin transforms', 'TANGENT morph targets', 'morph targets without authored base normals', 'vertex alpha below one', 'different texture transforms on one material', 'skinned or morphed GPU instancing', 'transmission, iridescence and specular textures (their factors are used)', 'texture transforms on TEXCOORD_1'],
});
const LAYER_SHADER_EXTENSIONS = Object.freeze(['KHR_materials_anisotropy', 'KHR_materials_iridescence']);
// The shader code for anisotropy and iridescence is not in the core bundle; a file that uses either brings it in.
async function loadLayerShadersFor(document) {
- const usesLayerShaders = (document.materials ?? []).some(material => LAYER_SHADER_EXTENSIONS.some(extension => material?.extensions?.[extension]));
+ const usesLayerShaders = (document.materials ?? []).some(material => LAYER_SHADER_EXTENSIONS.some(extension => material?.extensions?.[extension]) || layerTextureReferences(material).length > 0);
if (usesLayerShaders) await import('./material-layer-shaders.js');
}
@@ -43,10 +43,33 @@ const MATERIAL_TEXTURES = [
['emissiveMap', 'emissiveTexture', 'srgb'],
];
+// Only these textures may read the second UV set, because the shader samples them with lightmapUV. The base color map is
+// sampled in the depth pass and by box mapping, and the normal map builds its tangent frame from the first set.
+const SECOND_UV_TEXTURES = ['metallicRoughnessTexture', 'occlusionTexture', 'emissiveTexture'];
+
function materialTexture(material, field) {
return ['baseColorTexture', 'metallicRoughnessTexture'].includes(field) ? material.pbrMetallicRoughness?.[field] : material[field];
}
+function uvChannelOf(reference) {
+ return reference.texCoord ?? 0;
+}
+
+/** Every texture a material definition references, as [name, reference]: the five material maps, then the layer maps. */
+function materialTextureReferences(material) {
+ const references = [];
+ for (const [, property] of MATERIAL_TEXTURES) {
+ const reference = materialTexture(material, property);
+ if (reference) references.push([property, reference]);
+ }
+ for (const [name, reference] of layerTextureReferences(material)) references.push([name, reference]);
+ return references;
+}
+
+function usesSecondUvSet(material) {
+ return materialTextureReferences(material ?? {}).some(([, reference]) => uvChannelOf(reference) === 1);
+}
+
function limitsFor(options) {
const limits = {
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
@@ -185,13 +208,15 @@ function uvTransformKey(transform) {
return transform === IDENTITY_UV_TRANSFORM ? '' : JSON.stringify([transform.offset, transform.rotation, transform.scale]);
}
-/** All maps of a material read one UV set, so one shared transform can be baked into it. */
+/** All maps on TEXCOORD_0 of a material share one UV set, so one shared transform can be baked into it. */
function materialUvTransform(material) {
let found = null;
- for (const [, field] of MATERIAL_TEXTURES) {
- const texture = materialTexture(material, field);
- if (!texture) continue;
+ for (const [name, texture] of materialTextureReferences(material)) {
const transform = textureUvTransform(texture);
+ if (uvChannelOf(texture) !== 0) {
+ if (uvTransformKey(transform) !== '') throw new Error(`${name} reads TEXCOORD_1, where KHR_texture_transform is unsupported. Bake the transform into the UVs.`);
+ continue;
+ }
if (found && uvTransformKey(found) !== uvTransformKey(transform)) {
throw new Error('Maps of one material must share the same KHR_texture_transform. Different transforms per map are unsupported.');
}
@@ -361,10 +386,9 @@ function validateDocument(document, limits, allowedExtensions) {
const alphaCutoff = material.alphaCutoff ?? 0.5;
if (!Number.isFinite(alphaCutoff) || alphaCutoff < 0 || alphaCutoff > 1) throw new Error('Invalid glTF alphaCutoff.');
if (material.doubleSided !== undefined && typeof material.doubleSided !== 'boolean') throw new Error('glTF doubleSided must be a boolean.');
- for (const [, field] of MATERIAL_TEXTURES) {
- const texture = materialTexture(material, field);
- if (!texture) continue;
- if ((texture.texCoord ?? 0) !== 0 || Object.keys(texture.extensions ?? {}).some(name => name !== 'KHR_texture_transform')) throw new Error(`${field} requires TEXCOORD_0 and no texture extensions besides KHR_texture_transform.`);
+ for (const [field, texture] of materialTextureReferences(material)) {
+ const allowedChannels = SECOND_UV_TEXTURES.includes(field) ? [0, 1] : [0];
+ if (!allowedChannels.includes(uvChannelOf(texture)) || Object.keys(texture.extensions ?? {}).some(name => name !== 'KHR_texture_transform')) throw new Error(`${field} requires ${SECOND_UV_TEXTURES.includes(field) ? 'TEXCOORD_0 or TEXCOORD_1' : 'TEXCOORD_0'} and no texture extensions besides KHR_texture_transform.`);
if (!Number.isInteger(texture.index) || !document.textures?.[texture.index]) throw new Error(`Invalid ${field} texture index.`);
if (field === 'normalTexture' && (!Number.isFinite(texture.scale ?? 1) || !Number.isFinite(Math.fround(texture.scale ?? 1)))) throw new Error('Normal texture scale must be a finite float.');
if (field === 'occlusionTexture' && (!Number.isFinite(texture.strength ?? 1) || (texture.strength ?? 1) < 0 || (texture.strength ?? 1) > 1)) throw new Error('Occlusion texture strength must be within zero and one.');
@@ -381,7 +405,10 @@ function validateDocument(document, limits, allowedExtensions) {
for (const mesh of document.meshes ?? []) {
for (const primitive of mesh.primitives ?? []) {
const material = document.materials?.[primitive.material];
- if (material && MATERIAL_TEXTURES.some(([, field]) => materialTexture(material, field)) && primitive.attributes?.TEXCOORD_0 === undefined) throw new Error('Material textures require TEXCOORD_0.');
+ for (const [, reference] of materialTextureReferences(material ?? {})) {
+ const attribute = `TEXCOORD_${uvChannelOf(reference)}`;
+ if (primitive.attributes?.[attribute] === undefined) throw new Error(`Material textures require ${attribute}.`);
+ }
}
}
let decodedBytes = morphBytes;
@@ -577,8 +604,8 @@ function computeVertexNormals(positions, indices) {
return normals;
}
-function convertGeometry(source, mirrored, primitive) {
- const { position, normal, uv, color, skinIndex, skinWeight } = source.attributes;
+function convertGeometry(source, mirrored, primitive, secondUvSet) {
+ const { position, normal, uv, uv1, color, skinIndex, skinWeight } = source.attributes;
const positions = copyAttribute(position, 3);
const indices = new Uint32Array(source.index?.count ?? position.count);
for (let index = 0; index < indices.length; index++) {
@@ -603,6 +630,11 @@ function convertGeometry(source, mirrored, primitive) {
}
if (uv && uv.count !== position.count) throw new Error('TEXCOORD_0 and POSITION counts must match.');
if (uv) geometry.uvs = copyAttribute(uv, 2);
+ // The renderer's second UV set is geometry.lightUvs, the one light maps use.
+ if (secondUvSet) {
+ if (!uv1 || uv1.count !== position.count) throw new Error('TEXCOORD_1 and POSITION counts must match.');
+ geometry.lightUvs = copyAttribute(uv1, 2);
+ }
if (color) geometry.colors = convertVertexColors(color, position.count);
if (skinIndex) geometry.skinIndices = new Uint16Array(copyAttribute(skinIndex, 4));
if (skinWeight) geometry.skinWeights = copyAttribute(skinWeight, 4);
@@ -720,6 +752,29 @@ function decodedTextureImage(texture, field) {
return typeof ImageData === 'function' ? new ImageData(pixels, width, height) : { width, height, data: pixels };
}
+function textureDescriptorFor(texture, field, { colorSpace, uvChannel }, limits, maps) {
+ if (!maps.has(texture)) maps.set(texture, new Map());
+ const descriptors = maps.get(texture);
+ const key = `${colorSpace}:${uvChannel}`;
+ if (!descriptors.has(key)) {
+ const image = decodedTextureImage(texture, field);
+ if (!image || image.width * image.height > limits.maxTexturePixels) throw new Error(`${field} image is missing or exceeds maxTexturePixels.`);
+ const descriptor = {
+ image,
+ uvChannel,
+ wrapS: texture.wrapS,
+ wrapT: texture.wrapT,
+ minFilter: texture.minFilter,
+ magFilter: texture.magFilter,
+ flipY: false,
+ colorSpace,
+ };
+ textureDescriptorInfo(descriptor);
+ descriptors.set(key, descriptor);
+ }
+ return descriptors.get(key);
+}
+
function convertMaterial(source, limits, maps, definition = {}) {
const material = {
tag: 'gltf',
@@ -738,28 +793,17 @@ function convertMaterial(source, limits, maps, definition = {}) {
Object.assign(material, materialLayersFromGltf(definition));
if (!material.emissiveColor.some(value => value > 0)) material.emission = 0;
if (!Number.isFinite(Math.fround(material.emission)) || material.emission < 0) throw new Error('Emissive intensity must be a finite nonnegative float.');
- for (const [field, , colorSpace] of MATERIAL_TEXTURES) {
+ for (const [field, property, colorSpace] of MATERIAL_TEXTURES) {
const texture = source[field === 'metallicRoughnessMap' ? 'metalnessMap' : field === 'occlusionMap' ? 'aoMap' : field];
if (!texture) continue;
- if (!maps.has(texture)) maps.set(texture, new Map());
- const descriptors = maps.get(texture);
- if (!descriptors.has(colorSpace)) {
- const image = decodedTextureImage(texture, field);
- if (!image || image.width * image.height > limits.maxTexturePixels) throw new Error(`${field} image is missing or exceeds maxTexturePixels.`);
- const descriptor = {
- image,
- uvChannel: 0,
- wrapS: texture.wrapS,
- wrapT: texture.wrapT,
- minFilter: texture.minFilter,
- magFilter: texture.magFilter,
- flipY: false,
- colorSpace,
- };
- textureDescriptorInfo(descriptor);
- descriptors.set(colorSpace, descriptor);
- }
- material[field] = descriptors.get(colorSpace);
+ const uvChannel = uvChannelOf(materialTexture(definition, property));
+ material[field] = textureDescriptorFor(texture, field, { colorSpace, uvChannel }, limits, maps);
+ }
+ for (const [name, reference, colorSpace] of layerTextureReferences(definition)) {
+ const texture = source.layerTextures?.[name];
+ if (!texture) continue;
+ material.layerMaps ??= {};
+ material.layerMaps[name] = textureDescriptorFor(texture, name, { colorSpace, uvChannel: uvChannelOf(reference) }, limits, maps);
}
return material;
}
@@ -799,6 +843,7 @@ export async function parseGltf(data, options = {}) {
const materialIndex = node.material.materialIndex;
const uvTransform = materialUvTransform(document.materials?.[materialIndex] ?? {});
const uvKey = uvTransformKey(uvTransform);
+ const secondUvSet = usesSecondUvSet(document.materials?.[materialIndex]);
if (!materials.has(node.material)) materials.set(node.material, convertMaterial(node.material, limits, maps, document.materials?.[materialIndex]));
const material = materials.get(node.material);
for (const instanceMatrix of instanceMatricesOf(node, limits.maxInstances)) {
@@ -806,16 +851,17 @@ export async function parseGltf(data, options = {}) {
if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-12) throw new Error('Mesh world transform is singular or non-finite.');
const mirrored = determinant < 0;
const geometryMirrored = node.isSkinnedMesh ? false : mirrored;
- const geometryKey = `${node.geometry.uuid}:${geometryMirrored}:${uvKey}`;
+ const geometryKey = `${node.geometry.uuid}:${geometryMirrored}:${uvKey}:${secondUvSet}`;
if (!geometries.has(geometryKey)) {
actualVertices += node.geometry.attributes.position.count * (1 + (primitive.targets?.length ?? 0));
if (actualVertices > limits.maxVertices) throw new Error('Decoded geometry exceeds maxVertices.');
- const converted = convertGeometry(node.geometry, geometryMirrored, primitive);
+ const converted = convertGeometry(node.geometry, geometryMirrored, primitive, secondUvSet);
if (converted.uvs) bakeUvTransform(converted.uvs, uvTransform);
geometries.set(geometryKey, converted);
}
const geometry = geometries.get(geometryKey);
- if (MATERIAL_TEXTURES.some(([field]) => material[field]) && !geometry.uvs) throw new Error('Material textures require TEXCOORD_0.');
+ const firstSetMaps = [...MATERIAL_TEXTURES.map(([field]) => material[field]), ...Object.values(material.layerMaps ?? {})];
+ if (firstSetMaps.some(map => map && map.uvChannel === 0) && !geometry.uvs) throw new Error('Material textures require TEXCOORD_0.');
const part = { name: node.name || `glTF mesh ${parts.length + 1}`, geometry, matrix: new Float32Array(worldMatrixOf(node, instanceMatrix, pendingTransform).elements), material };
const transformBinding = { node, instanceMatrix, part, mirrored, matrix: part.matrix, pendingMatrix: new Float32Array(16) };
let pendingSkin;
diff --git a/src/material-layer-shaders.js b/src/material-layer-shaders.js
index 3f51edf1..5ace82f6 100644
--- a/src/material-layer-shaders.js
+++ b/src/material-layer-shaders.js
@@ -1,4 +1,4 @@
-import { registerShaderFeatureCode } from './shaders.js';
+import { layerTextureSupport, registerShaderFeatureCode } from './shaders.js';
// Shader code for the anisotropy and iridescence material layers. It lives outside shaders.js so that a scene that
// uses neither layer never downloads it: the renderer asks for it only when a part uses a layer, and importing this
@@ -14,10 +14,14 @@ import { registerShaderFeatureCode } from './shaders.js';
// KHR_materials_iridescence; filmReflectanceAtNormal turns the film's Fresnel at this view angle back into the
// reflectance at normal incidence that a Schlick curve needs.
-const ANISOTROPY_DECLARATIONS = `uniform vec2 materialAnisotropy;
+const ANISOTROPY_DECLARATIONS = `#ifndef ANISOTROPY_DECLARED
+#define ANISOTROPY_DECLARED
+uniform vec2 materialAnisotropy;
float anisotropyStrength = 0.0;
vec3 anisotropyTangent = vec3(1.0, 0.0, 0.0);
vec3 anisotropyBitangent = vec3(0.0, 0.0, 1.0);
+vec3 anisotropyFrameTangent = vec3(1.0, 0.0, 0.0);
+vec3 anisotropyFrameBitangent = vec3(0.0, 0.0, 1.0);
float anisotropicSpecular(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 halfway, float alpha) {
float alphaTangent = mix(alpha, 1.0, anisotropyStrength * anisotropyStrength);
float alphaBitangent = alpha;
@@ -54,9 +58,12 @@ void setAnisotropyFrame(vec3 normal) {
}
tangent = normalize(tangent / tangentScale);
vec3 bitangent = cross(normal, tangent);
+ anisotropyFrameTangent = tangent;
+ anisotropyFrameBitangent = bitangent;
anisotropyTangent = tangent * cos(materialAnisotropy.y) + bitangent * sin(materialAnisotropy.y);
anisotropyBitangent = cross(normal, anisotropyTangent);
}
+#endif
`;
@@ -69,6 +76,9 @@ const ANISOTROPY_COAT_RESET = ` anisotropyStrength = 0.0;
const ANISOTROPY_MAIN_SETUP = ` if (materialAnisotropy.x > 0.0) {
anisotropyStrength = materialAnisotropy.x;
setAnisotropyFrame(normal);
+#ifdef ANISOTROPY_TEXTURE
+ if (anisotropyTextureOn > 0.5) applyAnisotropyTexture(normal);
+#endif
vec3 grainSide = cross(anisotropyBitangent, viewDirection);
vec3 grainNormal = cross(grainSide, anisotropyBitangent);
specularNormal = normalize(mix(normal, grainNormal, anisotropyStrength * clamp(5.0 * roughness, 0.0, 1.0)));
@@ -155,3 +165,156 @@ registerShaderFeatureCode('iridescence', Object.freeze({
coatReset: IRIDESCENCE_COAT_RESET,
mainSetup: IRIDESCENCE_MAIN_SETUP,
}));
+
+// Layer textures. The renderer adds the feature named as the glTF property (clearcoatTexture and so on) when a material
+// has that texture in material.layerMaps, binds the sampler, and sets the NameOn flag to 1 for batches that own it.
+// A feature may be spliced beside another that shares state, so shared GLSL sits in blocks guarded with #ifndef.
+// - The clear coat and sheen read their strength from the uniforms materialCoat and materialSheen. Their state blocks
+// rename those to coatState and sheenState, which main sets per pixel from the uniform times the texture, so the core
+// shader needs no texture code. coatUniform and sheenUniform are declared first, while the name still means the uniform.
+// - A coat normal texture replaces the coat's normal, built from the geometric normal as the base normal map is.
+// - An anisotropy texture holds the grain direction in red and green and a strength factor in blue (KHR_materials_anisotropy).
+// Only the anisotropy feature reads it, from its own main setup, so the order the features are spliced in does not matter.
+
+const COAT_STATE_DECLARATIONS = `#ifndef COAT_STATE
+#define COAT_STATE
+vec2 coatState = vec2(0.0);
+vec2 coatUniform() {
+ return materialCoat;
+}
+#define materialCoat coatState
+#endif
+`;
+
+const COAT_STATE_SETUP = `#ifndef COAT_STATE_SET
+#define COAT_STATE_SET
+ coatState = coatUniform();
+#endif
+`;
+
+const SHEEN_STATE_DECLARATIONS = `#ifndef SHEEN_STATE
+#define SHEEN_STATE
+vec4 sheenState = vec4(0.0);
+vec4 sheenUniform() {
+ return materialSheen;
+}
+#define materialSheen sheenState
+#endif
+`;
+
+const SHEEN_STATE_SETUP = `#ifndef SHEEN_STATE_SET
+#define SHEEN_STATE_SET
+ sheenState = sheenUniform();
+#endif
+`;
+
+function textureUniforms(name) {
+ return `uniform sampler2D ${name};
+uniform float ${name}On;
+`;
+}
+
+registerShaderFeatureCode('clearcoatTexture', Object.freeze({
+ declarations: textureUniforms('clearcoatTexture') + COAT_STATE_DECLARATIONS,
+ mainSetup: COAT_STATE_SETUP + ` if (clearcoatTextureOn > 0.5) coatState.x *= texture(clearcoatTexture, textureUV).r;
+`,
+}));
+
+registerShaderFeatureCode('clearcoatRoughnessTexture', Object.freeze({
+ declarations: textureUniforms('clearcoatRoughnessTexture') + COAT_STATE_DECLARATIONS,
+ mainSetup: COAT_STATE_SETUP + ` if (clearcoatRoughnessTextureOn > 0.5) coatState.y *= texture(clearcoatRoughnessTexture, textureUV).g;
+`,
+}));
+
+registerShaderFeatureCode('clearcoatNormalTexture', Object.freeze({
+ declarations: textureUniforms('clearcoatNormalTexture') + `vec3 coatMappedNormal() {
+ vec3 normal = normalize(worldNormal);
+ if (doubleSided > 0.5 && !gl_FrontFacing) normal = -normal;
+ vec3 positionX = dFdx(worldPosition);
+ vec3 positionY = dFdy(worldPosition);
+ vec2 uvX = dFdx(textureUV);
+ vec2 uvY = dFdy(textureUV);
+ float uvScale = max(max(abs(uvX.x), abs(uvX.y)), max(abs(uvY.x), abs(uvY.y)));
+ if (uvScale == 0.0) return normal;
+ uvX /= uvScale;
+ uvY /= uvScale;
+ float determinant = uvX.x * uvY.y - uvX.y * uvY.x;
+ if (abs(determinant) < 1e-7) return normal;
+ vec3 tangent = (positionX * uvY.y - positionY * uvX.y) / determinant;
+ vec3 bitangent = (positionY * uvX.x - positionX * uvY.x) / determinant;
+ tangent -= normal * dot(normal, tangent);
+ float tangentScale = max(max(abs(tangent.x), abs(tangent.y)), abs(tangent.z));
+ if (tangentScale == 0.0) return normal;
+ tangent = normalize(tangent / tangentScale);
+ float handedness = dot(cross(normal, tangent), bitangent) < 0.0 ? -1.0 : 1.0;
+ bitangent = normalize(cross(normal, tangent)) * handedness;
+ vec3 mapped = mat3(tangent, bitangent, normal) * (texture(clearcoatNormalTexture, textureUV).xyz * 2.0 - 1.0);
+ return dot(mapped, mapped) > 1e-12 ? normalize(mapped) : normal;
+}
+`,
+ coatReset: ` if (clearcoatNormalTextureOn > 0.5) normal = coatMappedNormal();
+`,
+}));
+
+registerShaderFeatureCode('sheenColorTexture', Object.freeze({
+ declarations: textureUniforms('sheenColorTexture') + SHEEN_STATE_DECLARATIONS,
+ mainSetup: SHEEN_STATE_SETUP + ` if (sheenColorTextureOn > 0.5) sheenState.rgb *= texture(sheenColorTexture, textureUV).rgb;
+`,
+}));
+
+registerShaderFeatureCode('sheenRoughnessTexture', Object.freeze({
+ declarations: textureUniforms('sheenRoughnessTexture') + SHEEN_STATE_DECLARATIONS,
+ mainSetup: SHEEN_STATE_SETUP + ` if (sheenRoughnessTextureOn > 0.5) sheenState.w *= texture(sheenRoughnessTexture, textureUV).a;
+`,
+}));
+
+registerShaderFeatureCode('anisotropyTexture', Object.freeze({
+ declarations: ANISOTROPY_DECLARATIONS + textureUniforms('anisotropyTexture') + `#define ANISOTROPY_TEXTURE
+void applyAnisotropyTexture(vec3 normal) {
+ vec3 sampled = texture(anisotropyTexture, textureUV).rgb;
+ vec2 direction = sampled.rg * 2.0 - 1.0;
+ float cosine = cos(materialAnisotropy.y);
+ float sine = sin(materialAnisotropy.y);
+ vec2 rotated = vec2(cosine * direction.x - sine * direction.y, sine * direction.x + cosine * direction.y);
+ anisotropyStrength = materialAnisotropy.x * sampled.b;
+ if (dot(rotated, rotated) > 1e-8) {
+ anisotropyTangent = normalize(anisotropyFrameTangent * rotated.x + anisotropyFrameBitangent * rotated.y);
+ anisotropyBitangent = cross(normal, anisotropyTangent);
+ }
+}
+`,
+}));
+
+// Layer textures share the units 11 to 13 with the splat arrays, so one renderer draws at most three different ones and
+// none beside splat layers. A batch without a texture gets the white texture and a NameOn flag of 0.
+const LAYER_TEXTURE_UNIT = 11;
+const MAX_LAYER_TEXTURES = 3;
+
+function layerTextureNamesOf(renderer) {
+ if (renderer.layerTextureNamesFor?.size !== renderer.shaderFeatures.size) {
+ const names = [...renderer.shaderFeatures].filter(feature => feature.endsWith('Texture'));
+ if (names.length > MAX_LAYER_TEXTURES || renderer.shaderFeatures.has('splat')) {
+ throw new Error(`A renderer draws at most ${MAX_LAYER_TEXTURES} layer textures and none beside splat layers, got ${names.join(', ')}.`);
+ }
+ renderer.layerTextureNames = names;
+ renderer.layerTextureNamesFor = { size: renderer.shaderFeatures.size };
+ }
+ return renderer.layerTextureNames;
+}
+
+function uniformOf(renderer, name) {
+ renderer.uniforms[name] ??= renderer.context.getUniformLocation(renderer.program, name);
+ return renderer.uniforms[name];
+}
+
+layerTextureSupport.bind = (renderer, layerMaps) => {
+ if (!renderer.shaderFeatures) return;
+ const context = renderer.context;
+ layerTextureNamesOf(renderer).forEach((name, index) => {
+ const descriptor = layerMaps?.[name];
+ context.activeTexture(context.TEXTURE0 + LAYER_TEXTURE_UNIT + index);
+ context.bindTexture(context.TEXTURE_2D, descriptor ? renderer.createTexture(descriptor) : renderer.whiteTexture);
+ context.uniform1i(uniformOf(renderer, name), LAYER_TEXTURE_UNIT + index);
+ context.uniform1f(uniformOf(renderer, `${name}On`), descriptor ? 1 : 0);
+ });
+};
diff --git a/src/renderer.js b/src/renderer.js
index 5006de7f..48f868e8 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1,5 +1,5 @@
import { mat4, mat3 } from 'gl-matrix';
-import { vertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';
+import { layerTextureSupport, vertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';
import { postFragment, skyFragment, bloomFragment } from './post.js';
import { fullscreenVertex, startProgram, finishProgram, compileProgram } from './gl-program.js';
import { ambientOcclusionFragment } from './ambient-occlusion.js';
@@ -55,6 +55,7 @@ function shaderFeaturesOfParts(parts) {
if (material[field]) features.add(MAP_SHADER_FEATURES[index]);
});
if (material.lightMap) features.add('lightMap');
+ Object.keys(material.layerMaps ?? {}).forEach(name => features.add(name));
if (material.layers) features.add('splat');
if (material.moss > 0) features.add('moss');
if (material.anisotropy > 0) features.add('anisotropy');
@@ -147,7 +148,7 @@ function materialMapState(material) {
const occlusionStrength = material.occlusionStrength ?? 1;
validateSplatMaterial(material);
if (material.layers && PROCEDURAL_MATERIAL_TAGS.has(material.tag)) throw new Error('Splat layers require a standard PBR material tag.');
- return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), ...splatBatchState(material)];
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), ...splatBatchState(material), material.layerMaps ?? null];
}
// A baked light map reads the second UV set, so it is only drawn for parts that cannot be skinned or morphed.
@@ -292,7 +293,7 @@ export function textureDescriptorInfo(map, maximumSize = Infinity) {
const width = map.image?.naturalWidth ?? map.image?.width;
const height = map.image?.naturalHeight ?? map.image?.height;
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0 || width > maximumSize || height > maximumSize) throw new Error('Texture image dimensions are invalid or exceed MAX_TEXTURE_SIZE.');
- if ((map.uvChannel ?? 0) !== 0) throw new Error('Only texture UV channel 0 is supported.');
+ if (![0, 1].includes(map.uvChannel ?? 0)) throw new Error('Only texture UV channels 0 and 1 are supported.');
if (map.transform || map.offset || map.repeat || map.rotation !== undefined || map.extensions && Object.keys(map.extensions).length) throw new Error('Texture transforms and extensions are unsupported. Bake them into UV channel 0.');
if (map.colorSpace && !['srgb', 'linear'].includes(map.colorSpace)) throw new Error('Texture color space must be srgb or linear.');
const wrapS = map.wrapS ?? 10497;
@@ -444,8 +445,8 @@ export class Renderer67 {
}
const maps = new Set();
for (const group of groups) {
- for (const field of [...MATERIAL_MAPS, 'lightMap']) {
- const map = group[0].material[field];
+ const material = group[0].material;
+ for (const [field, map] of [...MATERIAL_MAPS, 'lightMap'].map(name => [name, material[name]]).concat(Object.entries(material.layerMaps ?? {}))) {
if (!map) continue;
const info = textureDescriptorInfo(map, textureLimit);
if (['normalMap', 'metallicRoughnessMap', 'occlusionMap'].includes(field) && map.colorSpace !== 'linear') throw new Error(`${field} requires a linear texture descriptor.`);
@@ -471,7 +472,7 @@ export class Renderer67 {
for (const group of groups) {
const geometry = group[0].geometry;
if (geometry.uvs && geometry.uvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry UV count must match the vertex count.');
- if (hasMaterialMap(group[0].material) && !geometry.uvs && !group[0].material.boxMapScale) throw new Error('Textured geometry requires UV channel 0.');
+ if (hasMaterialMap(group[0].material) && !geometry.uvs && !geometry.lightUvs && !group[0].material.boxMapScale) throw new Error('Textured geometry requires UV channel 0.');
for (const coordinate of geometry.uvs ?? []) {
if (!Number.isFinite(coordinate)) throw new Error('Geometry UVs must be finite.');
}
@@ -1095,7 +1096,7 @@ export class Renderer67 {
if ((part.material[MATERIAL_MAPS[index]] ?? null) !== mapState[index]) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
}
const [lightMapDescriptor, lightMapScale] = lightMapState(part.material);
- if (lightMapDescriptor !== (mapState[14] ?? null) || lightMapScale !== (mapState[15] ?? 0)) throw new Error(`Light map changes require a new renderer: ${part.name}`);
+ if (lightMapDescriptor !== (mapState[14] ?? null) || lightMapScale !== (mapState[15] ?? 0) || (part.material.layerMaps ?? null) !== (mapState[18] ?? null)) throw new Error(`Light map and layer texture changes require a new renderer: ${part.name}`);
if (normalScale[0] !== mapState[5] || normalScale[1] !== mapState[6] || (part.material.occlusionStrength ?? 1) !== mapState[7] || mossState(part.material).some((value, index) => value !== mapState[8 + index]) || materialLayerState(part.material).some((value, index) => value !== location.layerState[index])) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
validateTransform(part, location.normalMatrix);
}
@@ -1790,7 +1791,7 @@ export class Renderer67 {
this.context.activeTexture(this.context.TEXTURE0 + index + 1);
this.context.bindTexture(this.context.TEXTURE_2D, batch.textures[index]);
this.context.uniform1i(this.uniforms[MAP_UNIFORMS[index]], index + 1);
- this.context.uniform1f(this.uniforms[MAP_FLAGS[index]], batch.mapState[index] ? 1 : 0);
+ this.context.uniform1f(this.uniforms[MAP_FLAGS[index]], batch.mapState[index] ? 1 + (batch.mapState[index].uvChannel ?? 0) : 0);
}
this.context.uniform2f(this.uniforms.normalScale, batch.mapState[5], batch.mapState[6]);
this.context.uniform1f(this.uniforms.occlusionStrength, batch.mapState[7]);
@@ -1805,6 +1806,7 @@ export class Renderer67 {
this.context.uniform1f(this.uniforms.boxMapScale, batch.mapState[12]);
this.context.uniform1i(this.uniforms.boxMapAxis, batch.mapState[13]);
this.bindSplat(batch.splat);
+ layerTextureSupport.bind?.(this, batch.mapState[18]);
this.context.uniform1f(this.uniforms.hasLightMap, batch.lightMapTexture ? 1 : 0);
if (batch.lightMapTexture) {
this.context.activeTexture(this.context.TEXTURE0 + LIGHT_MAP_UNIT);
diff --git a/src/shaders.js b/src/shaders.js
index 12d13083..f4749137 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -599,6 +599,10 @@ vec3 boxMappedNormal(vec3 normal) {
return dot(world, normal) < 0.0 ? -world : world;
}
+vec2 mapUV(float flag) {
+ return flag > 1.5 ? lightmapUV : textureUV;
+}
+
vec3 mappedNormal(vec3 normal) {
vec3 positionX = dFdx(worldPosition);
vec3 positionY = dFdy(worldPosition);
@@ -724,7 +728,7 @@ void main() {
}
float alpha = surfaceAlpha(textureAlpha);
vec3 emission = emissionColor * surface.z;
- if (USES_EMISSIVE_MAP) emission *= (boxMapScale > 0.0 ? sampleBox(emissiveMap) : texture(emissiveMap, textureUV)).rgb;
+ if (USES_EMISSIVE_MAP) emission *= (boxMapScale > 0.0 ? sampleBox(emissiveMap) : texture(emissiveMap, mapUV(hasEmissiveMap))).rgb;
if (USES_RENDER_PASS) {
outputColor = vec4(renderPassValue(color, normal, emission), 1.0);
return;
@@ -741,7 +745,7 @@ void main() {
roughness = armorSurface.y;
}
if (USES_METALLIC_ROUGHNESS_MAP) {
- vec4 sampled = boxMapScale > 0.0 ? sampleBox(metallicRoughnessMap) : texture(metallicRoughnessMap, textureUV);
+ vec4 sampled = boxMapScale > 0.0 ? sampleBox(metallicRoughnessMap) : texture(metallicRoughnessMap, mapUV(hasMetallicRoughnessMap));
metallic *= sampled.b;
roughness *= sampled.g;
}
@@ -859,7 +863,7 @@ ${featureCode("linkArea")} vec3 lightNormal = areaLightNormals[index].xyz;
}
vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), baseReflectance);
float occlusion = 1.0;
- if (USES_OCCLUSION_MAP) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);
+ if (USES_OCCLUSION_MAP) occlusion = mix(1.0, texture(occlusionMap, mapUV(hasOcclusionMap)).r, occlusionStrength);
occlusion *= splatCavity;
// Leaf and grass cards keep a faint sheen; full sky reflection washed grazing cards grey-blue.
float skyReflection = canopyShaded ? 0.3 : 1.0;
@@ -960,6 +964,9 @@ const SHADER_FEATURE_CONDITIONS = {
// A feature that replaces the sun shadow defines shadowVisibility as a macro in its declarations.
const registeredFeatureCode = new Map();
+// material-layer-shaders.js sets bind(renderer, layerMaps): it binds the textures of material.layerMaps for one batch.
+export const layerTextureSupport = {};
+
/** Register the GLSL of an optional feature. Called by the module that holds it, on import. */
export function registerShaderFeatureCode(feature, slots) {
registeredFeatureCode.set(feature, slots);
diff --git a/tests/layer-textures.test.js b/tests/layer-textures.test.js
new file mode 100644
index 00000000..f0e07e94
--- /dev/null
+++ b/tests/layer-textures.test.js
@@ -0,0 +1,137 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { inflateSync } from 'node:zlib';
+import { mat4 } from 'gl-matrix';
+import { exportGlb } from '../src/export.js';
+import { parseGltf } from '../src/gltf.js';
+import { LAYER_TEXTURE_SLOTS } from '../src/gltf-layers.js';
+import { box } from '../src/geometry.js';
+import { createFragmentShader } from '../src/shaders.js';
+import '../src/material-layer-shaders.js';
+
+// Node has no image decoder: decode the exporter's PNGs (unfiltered rows) so parseGltf sees real pixels.
+globalThis.self = globalThis;
+globalThis.createImageBitmap = async blob => {
+ const bytes = Buffer.from(await blob.arrayBuffer());
+ const width = bytes.readUInt32BE(16);
+ const height = bytes.readUInt32BE(20);
+ const channels = bytes[25] === 6 ? 4 : 3;
+ const compressed = [];
+ for (let offset = 8; offset < bytes.length;) {
+ const length = bytes.readUInt32BE(offset);
+ if (bytes.toString('latin1', offset + 4, offset + 8) === 'IDAT') compressed.push(bytes.subarray(offset + 8, offset + 8 + length));
+ offset += 12 + length;
+ }
+ const raw = inflateSync(Buffer.concat(compressed));
+ const data = new Uint8Array(width * height * 4).fill(255);
+ for (let row = 0; row < height; row++) {
+ for (let column = 0; column < width; column++) {
+ for (let channel = 0; channel < channels; channel++) {
+ data[(row * width + column) * 4 + channel] = raw[row * (width * channels + 1) + 1 + column * channels + channel];
+ }
+ }
+ }
+ return { width, height, data, close() {} };
+};
+
+const IMAGE_SIZE = 4;
+
+function gradientImage(seed) {
+ const data = new Uint8ClampedArray(IMAGE_SIZE * IMAGE_SIZE * 4);
+ for (let texel = 0; texel < IMAGE_SIZE * IMAGE_SIZE; texel++) {
+ data.set([(texel * 16 + seed) % 256, (texel * 7 + seed * 3) % 256, (seed * 29) % 256, 255], texel * 4);
+ }
+ return { width: IMAGE_SIZE, height: IMAGE_SIZE, data };
+}
+
+function descriptorFor(seed, colorSpace, uvChannel = 0) {
+ return { image: gradientImage(seed), wrapS: 10497, wrapT: 10497, magFilter: 9729, minFilter: 9729, colorSpace, uvChannel };
+}
+
+function boxPart(material, { secondUvSet = false } = {}) {
+ const geometry = box();
+ const vertexCount = geometry.positions.length / 3;
+ geometry.uvs = new Float32Array(vertexCount * 2).map((unused, index) => (index % 5) / 5);
+ if (secondUvSet) geometry.lightUvs = new Float32Array(vertexCount * 2).map((unused, index) => (index % 3) / 3);
+ return { name: 'Box', geometry, matrix: mat4.create(), material };
+}
+
+function layeredMaterial() {
+ const layerMaps = {};
+ LAYER_TEXTURE_SLOTS.forEach(([, property, colorSpace], index) => {
+ layerMaps[property] = descriptorFor(index + 1, colorSpace);
+ });
+ return {
+ color: [0.8, 0.7, 0.6],
+ metallic: 0.5,
+ roughness: 0.4,
+ clearcoat: 1,
+ clearcoatRoughness: 0.2,
+ anisotropy: 0.8,
+ sheenColor: [0.5, 0.5, 0.5],
+ sheenRoughness: 0.5,
+ layerMaps,
+ };
+}
+
+test('every layer texture slot round trips through GLB with its pixels and colour space', async () => {
+ const source = boxPart(layeredMaterial());
+ const imported = await parseGltf(exportGlb([source]));
+ const material = imported.parts[0].material;
+ assert.deepEqual(Object.keys(material.layerMaps).sort(), LAYER_TEXTURE_SLOTS.map(([, property]) => property).sort());
+ for (const [, property, colorSpace] of LAYER_TEXTURE_SLOTS) {
+ const expected = source.material.layerMaps[property];
+ const actual = material.layerMaps[property];
+ assert.equal(actual.colorSpace, colorSpace, property);
+ assert.equal(actual.uvChannel, 0, property);
+ assert.deepEqual(Array.from(actual.image.data), Array.from(expected.image.data), property);
+ }
+});
+
+test('textures that share an image in the file share one descriptor', async () => {
+ const material = layeredMaterial();
+ material.layerMaps.clearcoatRoughnessTexture = material.layerMaps.clearcoatTexture;
+ const imported = await parseGltf(exportGlb([boxPart(material)]));
+ const { layerMaps } = imported.parts[0].material;
+ assert.equal(layerMaps.clearcoatRoughnessTexture, layerMaps.clearcoatTexture);
+});
+
+test('an occlusion texture on TEXCOORD_1 round trips with the second UV set', async () => {
+ const material = { color: [1, 1, 1], metallic: 0, roughness: 0.5, occlusionMap: descriptorFor(9, 'linear', 1) };
+ const glb = exportGlb([boxPart(material, { secondUvSet: true })]);
+ const imported = await parseGltf(glb);
+ const part = imported.parts[0];
+ assert.equal(part.material.occlusionMap.uvChannel, 1);
+ assert.equal(part.geometry.lightUvs.length, part.geometry.positions.length / 3 * 2);
+ assert.equal(part.material.map, undefined);
+});
+
+test('a texture that needs a second UV set the mesh lacks is refused', async () => {
+ const material = { color: [1, 1, 1], metallic: 0, roughness: 0.5, occlusionMap: descriptorFor(9, 'linear', 1) };
+ const glb = exportGlb([boxPart(material)]);
+ await assert.rejects(parseGltf(glb), /TEXCOORD_1/);
+});
+
+test('the base color and normal maps stay on the first UV set', async () => {
+ const material = { color: [1, 1, 1], metallic: 0, roughness: 0.5, normalMap: descriptorFor(4, 'linear', 1) };
+ const glb = exportGlb([boxPart(material, { secondUvSet: true })]);
+ await assert.rejects(parseGltf(glb), /normalTexture requires TEXCOORD_0/);
+});
+
+test('layer texture features splice their sampler once and guard shared code, whatever order they come in', () => {
+ const features = ['clearcoatTexture', 'clearcoatRoughnessTexture', 'clearcoatNormalTexture', 'anisotropy', 'anisotropyTexture', 'sheenColorTexture'];
+ for (const ordered of [features, [...features].reverse()]) {
+ const source = createFragmentShader(ordered);
+ for (const name of ['clearcoatTexture', 'clearcoatRoughnessTexture', 'clearcoatNormalTexture', 'anisotropyTexture', 'sheenColorTexture']) {
+ assert.equal(source.split(`uniform sampler2D ${name};`).length - 1, 1, name);
+ }
+ assert.ok(source.includes('#ifndef ANISOTROPY_DECLARED\n#define ANISOTROPY_DECLARED\n'));
+ assert.match(source, /#define materialCoat coatState/);
+ assert.match(source, /#define materialSheen sheenState/);
+ }
+});
+
+test('a scene without layer textures gets no layer texture code', () => {
+ const source = createFragmentShader(['anisotropy']);
+ assert.doesNotMatch(source, /coatState|sheenState|uniform sampler2D anisotropyTexture/);
+});
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index ea8610bf..f6c944c5 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -210,7 +210,8 @@ test('texture descriptor preflight validates dimensions, channel, samplers and m
assert.equal(info.mipmaps, true);
assert.equal(textureDescriptorInfo({ image: { width: 4, height: 4 }, minFilter: 9729 }, 16).bytes, 64);
assert.throws(() => textureDescriptorInfo({ image: { width: 32, height: 32 } }, 16), /MAX_TEXTURE_SIZE/);
- assert.throws(() => textureDescriptorInfo({ image: { width: 4, height: 4 }, uvChannel: 1 }), /channel 0/);
+ assert.equal(textureDescriptorInfo({ image: { width: 4, height: 4 }, uvChannel: 1 }).bytes, 84);
+ assert.throws(() => textureDescriptorInfo({ image: { width: 4, height: 4 }, uvChannel: 2 }), /channels 0 and 1/);
assert.throws(() => textureDescriptorInfo({ image: { width: 4, height: 4 }, minFilter: 4 }), /filtering/);
});