Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Import SheenChair: a normal map may carry its own texture scale and offset

Nguyen Xuan An9fba3199d36b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 35074dd7..a14bdafc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Import `SheenChair` and score it (part of issue #51). A glTF normal map may now carry its own `KHR_texture_transform` offset and positive scale (same rotation) on top of the transform the other maps share: the importer bakes the shared one into the UVs and stores the remainder as `uvTransform` on the normal map descriptor, and the `normalMapTransform` shader feature in `addons/material-layer-shaders` applies it (a scene without such a normal map compiles the same shader as before). Any other difference between the maps of one material still fails the import, and an extension `texCoord` equal to the texture's own is no longer refused. Core grew by 25 bytes gzip (`lit-box` 60,179 to 60,204): a hook in the normal map lookup, one feature line and the `bind` argument; the glTF importer grew by about 370.
+
- Let the path tracer stop converged pixels, draw normal and roughness maps on box-projected materials, and finish a 1080p still (part of issue #129, which stays open). `noiseThreshold` (0 to 1, default 0.03, 0 draws every sample) stops a pixel once the standard error of its mean luminance is under that share of the mean plus 0.05, checked from 16 samples on and after every 8 more; the decision reads only the pixel's own samples, so bands and thread counts still give the same bytes, and `report.averageSamples` says what was used. Shadow rays no longer interpolate the surface they hit unless it is a cutout (pixels unchanged, 1.23 to 1.36 times faster per thread on the demo room). Box-projected parts are traced with the UVs of their projection (`boxProjectedGeometry`, with `columnLengths` now exported from `src/export-box-uv.js`), so their colour, normal and metallic-roughness maps are all read (before, a box-projected colour map read one texel); `report.ignored` no longer lists them. Render jobs may set `maxSeconds` up to 600 (was 240; the deadline is `maxSeconds` plus 60 s): the 1920 by 1080, 64 sample still of `tests/fixtures/demo-room.recipe.json` took 246.4 s in the tracer (30.7 samples per pixel on average, 8 threads, 257 s per job), 6 s past the old limit. Measured, and not all good: at 24 fixed samples with the filter `brick-graph` is 0.0024 and `character` 0.0048 worse than at 64; adaptive sampling costs `spot-area` 0.0658 to 0.0900 against Cycles at the default threshold; drawing one light at the first hit was tried and dropped (twice as fast, 66 percent more error). `brick-graph` did not improve against the same tracer at 64 samples (0.1370 to 0.1373); the darker floor of `character` and `outdoor-hdri` was narrowed but not found. `bench/reference/run.mjs` takes `--noise-threshold` and records `averageSamples`. Core did not change.
- 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.
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 055edffa..f70fc0f2 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -55,7 +55,7 @@ EEVEE against Cycles is a yardstick: it shows what a good rasterizer scores. In
- **Display:** Blender writes linear pixels, and `score.py` applies the tone curve and gamma from `src/post.js`. Both sides then use one display transform.
- **Lighting tricks:** the 67js fill lights are off. All light comes from the sun, the environment and point lights.
-Khronos sample assets (issue #51): `npm run reference -- --khronos` draws files from [KhronosGroup/glTF-Sample-Assets](https://github.com/KhronosGroup/glTF-Sample-Assets) that you download by hand into `artifacts/khronos/<name>/<name>.glb` (gitignored; nothing is committed). Blender imports the same GLB with its own importer, so Cycles is the reference for the file and not for our reading of it. The run uses its own work directory and writes `khronos.json` and `images/khronos-<name>.jpg`; `baseline.json` stays as it is. The sky fills most of each frame and both sides draw it alike, so the whole-frame FLIP score is about 0.05 for every asset and says little. The `asset-` columns score only the pixels the asset changes (a second render of the empty sky decides which, threshold 0.03). Licences, checked in each model's `LICENSE.md`: ClearCoatTest and AnisotropyBarnLamp are CC BY 4.0 (Analytical Graphics, Inc. and Wayfair, LLC), TransmissionTest and AnisotropyDiscTest are CC0 1.0. Measured 2026-11-01 on the RTX 3060 (SwiftShader within 0.0004 on the whole frame):
+Khronos sample assets (issue #51): `npm run reference -- --khronos` draws files from [KhronosGroup/glTF-Sample-Assets](https://github.com/KhronosGroup/glTF-Sample-Assets) that you download by hand into `artifacts/khronos/<name>/<name>.glb` (gitignored; nothing is committed). Blender imports the same GLB with its own importer, so Cycles is the reference for the file and not for our reading of it. The run uses its own work directory and writes `khronos.json` and `images/khronos-<name>.jpg`; `baseline.json` stays as it is. The sky fills most of each frame and both sides draw it alike, so the whole-frame FLIP score is about 0.05 for every asset and says little. The `asset-` columns score only the pixels the asset changes (a second render of the empty sky decides which, threshold 0.03). Licences, checked in each model's `LICENSE.md`: ClearCoatTest and AnisotropyBarnLamp are CC BY 4.0 (Analytical Graphics, Inc. and Wayfair, LLC), TransmissionTest, AnisotropyDiscTest and SheenChair are CC0 1.0 (SheenChair's model files are CC0; only its metadata files are CC BY 4.0). Measured 2026-11-01 on the RTX 3060 (SwiftShader within 0.0004 on the whole frame):
| Asset | Pixels covered | 67js against Cycles (asset only) | 67js against EEVEE | EEVEE against Cycles | What differs |
| --- | --- | --- | --- | --- | --- |
@@ -63,8 +63,9 @@ Khronos sample assets (issue #51): `npm run reference -- --khronos` draws files
| `TransmissionTest` | 0.1356 | 0.2708 | 0.2371 | 0.1656 | Refraction through the front surface only, no roughness-blurred background |
| `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) |
+| `SheenChair` | 0.1007 | 0.3745 | 0.3374 | 0.2384 | New. Cycles shows a bright red velvet rim along the top of the backrest and a more saturated orange; 67js draws the same shape and tufting but flatter, paler and with only a faint rim, so the error is a band along that edge and the seat front |
-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.
+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` is scored since the importer accepts a normal map with its own `KHR_texture_transform` scale and offset: the fabric tiles its base color 7 times and its normal map 2 times, so the importer bakes the base color transform into the UVs and the shader applies the normal map's remainder (`normalMapTransform`, outside core; core grew by 25 bytes gzip). The score does not say that the transform is right: the visible gap is the sheen rim, and why it is weaker was not investigated. 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-SheenChair.jpg b/bench/reference/images/khronos-SheenChair.jpg
new file mode 100644
index 00000000..033d302e
Binary files /dev/null and b/bench/reference/images/khronos-SheenChair.jpg differ
diff --git a/bench/reference/khronos.json b/bench/reference/khronos.json
index 3c00b3cb..34ec6d0e 100644
--- a/bench/reference/khronos.json
+++ b/bench/reference/khronos.json
@@ -3,20 +3,24 @@
"blenderVersion": "5.2.2 LTS",
"seconds": {
"AnisotropyBarnLamp": {
- "cycles": 7.7,
- "eevee": 3.9
+ "cycles": 23.4,
+ "eevee": 29.1
},
"AnisotropyDiscTest": {
- "cycles": 4.7,
- "eevee": 1.3
+ "cycles": 24.1,
+ "eevee": 3.7
},
"ClearCoatTest": {
- "cycles": 6.9,
- "eevee": 9.9
+ "cycles": 13.7,
+ "eevee": 10.2
+ },
+ "SheenChair": {
+ "cycles": 13.4,
+ "eevee": 36.2
},
"TransmissionTest": {
- "cycles": 7.2,
- "eevee": 6.5
+ "cycles": 22.2,
+ "eevee": 10.0
}
},
"graphics": {
@@ -60,6 +64,18 @@
"asset-gpu-vs-eevee": 0.1808,
"asset-eevee-vs-cycles": 0.1335
},
+ "SheenChair": {
+ "gpu-vs-cycles": 0.051,
+ "gpu-vs-eevee": 0.0438,
+ "cpu-vs-cycles": 0.0507,
+ "cpu-vs-eevee": 0.0435,
+ "eevee-vs-cycles": 0.0309,
+ "gpu-vs-cpu": 0.0065,
+ "asset-pixels": 0.1007,
+ "asset-gpu-vs-cycles": 0.3745,
+ "asset-gpu-vs-eevee": 0.3374,
+ "asset-eevee-vs-cycles": 0.2384
+ },
"TransmissionTest": {
"gpu-vs-cycles": 0.0485,
"gpu-vs-eevee": 0.042,
diff --git a/bench/reference/scenes.js b/bench/reference/scenes.js
index 2e9dcf4b..4fc83d81 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -112,9 +112,9 @@ 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 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'];
+// SheenChair's fabric gives the base color and normal textures different KHR_texture_transform values: the importer bakes
+// the shared one into the UVs and the shader applies the normal map's remainder.
+const KHRONOS_ASSET_NAMES = ['ClearCoatTest', 'TransmissionTest', 'AnisotropyBarnLamp', 'AnisotropyDiscTest', 'SheenChair'];
const KHRONOS_VIEW_DIRECTION = [0.35, 0.25, 1];
const KHRONOS_FIELD_OF_VIEW = 35;
diff --git a/docs/gltf.md b/docs/gltf.md
index 6f77d6f5..c3c72f39 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -135,7 +135,7 @@ Line and point primitives are unsupported.
| Extension | Behavior |
| --- | --- |
| `KHR_mesh_quantization`, `KHR_materials_emissive_strength` | Supported. |
-| `KHR_texture_transform` | Offset, rotation and scale are baked into `geometry.uvs`. All maps of one material must share one transform, otherwise the import fails. `texCoord` overrides are rejected. |
+| `KHR_texture_transform` | Offset, rotation and scale are baked into `geometry.uvs`. All maps of one material must share one transform, except the normal map: it may differ by an offset and a positive scale (same rotation), which the shader applies on top of the baked UVs (`normalMapTransform` in `material-layer-shaders`). Any other difference fails the import. `texCoord` overrides are rejected. |
| `EXT_mesh_gpu_instancing` | The node expands into one part per instance and primitive. Parts of one primitive share one geometry object, so the renderer batches them. Skinned or morphed instancing is rejected. |
| `KHR_draco_mesh_compression` | Needs `options.decoders.draco`. |
| `EXT_meshopt_compression` | Needs `options.decoders.meshopt`. |
diff --git a/docs/parity.md b/docs/parity.md
index 553dc7a2..27d23d5e 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 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 > 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` imports since a normal map may carry its own scale and offset. 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/gltf.js b/src/gltf.js
index ab199b9e..79599cb5 100644
--- a/src/gltf.js
+++ b/src/gltf.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', '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'],
+ 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, with a normal map that differs by scale and offset applied in the shader', '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', 'transmission, iridescence and specular textures (their factors are used)', 'texture transforms on TEXCOORD_1'],
+ 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, except a normal map that differs by scale and offset', '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]) || layerTextureReferences(material).length > 0);
+ const usesLayerShaders = (document.materials ?? []).some(material => LAYER_SHADER_EXTENSIONS.some(extension => material?.extensions?.[extension]) || layerTextureReferences(material).length > 0 || materialUvTransforms(material ?? {}).normalRelative);
if (usesLayerShaders) await import('./material-layer-shaders.js');
}
@@ -35,6 +35,7 @@ const DECODER_BY_EXTENSION = { KHR_draco_mesh_compression: 'draco', EXT_meshopt_
// Accepted when optional, because 67js does not render them. Rejected when listed in extensionsRequired.
const IGNORED_EXTENSIONS = new Set(GLTF_CAPABILITIES.ignoredExtensions);
const IDENTITY_UV_TRANSFORM = Object.freeze({ offset: [0, 0], rotation: 0, scale: [1, 1] });
+const IDENTITY_UV_TRANSFORM_KEY = JSON.stringify([IDENTITY_UV_TRANSFORM.offset, IDENTITY_UV_TRANSFORM.rotation, IDENTITY_UV_TRANSFORM.scale]);
const MATERIAL_TEXTURES = [
['map', 'baseColorTexture', 'srgb'],
['normalMap', 'normalTexture', 'linear'],
@@ -200,29 +201,56 @@ function textureUvTransform(texture) {
const rotation = extension.rotation ?? 0;
const vectorsAreFinite = [offset, scale].every(vector => Array.isArray(vector) && vector.length === 2 && vector.every(Number.isFinite));
if (!vectorsAreFinite || !Number.isFinite(rotation)) throw new Error('KHR_texture_transform requires finite offset, rotation and scale.');
- if ((extension.texCoord ?? 0) !== 0) throw new Error('KHR_texture_transform texCoord overrides are unsupported.');
+ if ((extension.texCoord ?? uvChannelOf(texture)) !== uvChannelOf(texture)) throw new Error('KHR_texture_transform texCoord overrides are unsupported.');
return { offset, rotation, scale };
}
function uvTransformKey(transform) {
- return transform === IDENTITY_UV_TRANSFORM ? '' : JSON.stringify([transform.offset, transform.rotation, transform.scale]);
+ const key = JSON.stringify([transform.offset, transform.rotation, transform.scale]);
+ return key === IDENTITY_UV_TRANSFORM_KEY ? '' : key;
}
-/** 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;
+/**
+ * The scale and offset that turn UVs already baked with `shared` into the UVs of `own`: [scaleU, scaleV, offsetU, offsetV].
+ * The normal map's tangent frame comes from the baked UVs, so the two must have the same rotation and a positive scale
+ * ratio, equal on both axes unless there is no rotation.
+ */
+function relativeUvTransform(shared, own) {
+ const ratios = own.scale.map((scale, axis) => scale / shared.scale[axis]);
+ const sameRotation = own.rotation === shared.rotation;
+ const keepsAxes = shared.rotation === 0 || ratios[0] === ratios[1];
+ if (!sameRotation || !keepsAxes || !ratios.every(ratio => ratio > 0 && Number.isFinite(ratio))) {
+ throw new Error('The normal texture transform may differ from the other maps only by an offset and a positive scale, with the same rotation.');
+ }
+ return [...ratios, own.offset[0] - ratios[0] * shared.offset[0], own.offset[1] - ratios[1] * shared.offset[1]];
+}
+
+/**
+ * The maps on TEXCOORD_0 of a material share one UV set, so one transform is baked into it: the one every map but the
+ * normal map has. A normal map with another transform keeps it as `normalRelative`, which the shader applies on top.
+ */
+function materialUvTransforms(material) {
+ let shared = null;
+ let normalTransform = null;
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.');
+ if (name === 'normalTexture') {
+ normalTransform = transform;
+ continue;
+ }
+ if (shared && uvTransformKey(shared) !== uvTransformKey(transform)) {
+ throw new Error('Maps of one material must share the same KHR_texture_transform, except the normal map. Different transforms per map are unsupported.');
}
- found = transform;
+ shared = transform;
}
- return found ?? IDENTITY_UV_TRANSFORM;
+ if (!normalTransform) return { shared: shared ?? IDENTITY_UV_TRANSFORM, normalRelative: null };
+ if (!shared) return { shared: normalTransform, normalRelative: null };
+ if (uvTransformKey(shared) === uvTransformKey(normalTransform)) return { shared, normalRelative: null };
+ return { shared, normalRelative: relativeUvTransform(shared, normalTransform) };
}
function bakeUvTransform(uvs, transform) {
@@ -239,7 +267,7 @@ function bakeUvTransform(uvs, transform) {
}
function validateMaterialExtensions(material) {
- materialUvTransform(material);
+ materialUvTransforms(material);
materialLayersFromGltf(material);
}
@@ -752,10 +780,10 @@ 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) {
+function textureDescriptorFor(texture, field, { colorSpace, uvChannel, uvTransform = null }, limits, maps) {
if (!maps.has(texture)) maps.set(texture, new Map());
const descriptors = maps.get(texture);
- const key = `${colorSpace}:${uvChannel}`;
+ const key = `${colorSpace}:${uvChannel}:${uvTransform ?? ''}`;
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.`);
@@ -769,6 +797,7 @@ function textureDescriptorFor(texture, field, { colorSpace, uvChannel }, limits,
flipY: false,
colorSpace,
};
+ if (uvTransform) descriptor.uvTransform = uvTransform;
textureDescriptorInfo(descriptor);
descriptors.set(key, descriptor);
}
@@ -797,7 +826,8 @@ function convertMaterial(source, limits, maps, definition = {}) {
const texture = source[field === 'metallicRoughnessMap' ? 'metalnessMap' : field === 'occlusionMap' ? 'aoMap' : field];
if (!texture) continue;
const uvChannel = uvChannelOf(materialTexture(definition, property));
- material[field] = textureDescriptorFor(texture, field, { colorSpace, uvChannel }, limits, maps);
+ const uvTransform = field === 'normalMap' ? materialUvTransforms(definition).normalRelative : null;
+ material[field] = textureDescriptorFor(texture, field, { colorSpace, uvChannel, uvTransform }, limits, maps);
}
for (const [name, reference, colorSpace] of layerTextureReferences(definition)) {
const texture = source.layerTextures?.[name];
@@ -841,7 +871,7 @@ export async function parseGltf(data, options = {}) {
if (!primitive) throw new Error('Decoded mesh requires a valid original primitive association.');
if (Array.isArray(node.material)) throw new Error('Multiple materials on one decoded primitive are unsupported.');
const materialIndex = node.material.materialIndex;
- const uvTransform = materialUvTransform(document.materials?.[materialIndex] ?? {});
+ const uvTransform = materialUvTransforms(document.materials?.[materialIndex] ?? {}).shared;
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]));
diff --git a/src/material-layer-shaders.js b/src/material-layer-shaders.js
index 5ace82f6..6be7d88e 100644
--- a/src/material-layer-shaders.js
+++ b/src/material-layer-shaders.js
@@ -307,9 +307,26 @@ function uniformOf(renderer, name) {
return renderer.uniforms[name];
}
-layerTextureSupport.bind = (renderer, layerMaps) => {
+// A normal map whose KHR_texture_transform differs from the other maps of its material: the importer bakes the shared
+// transform into the UVs and leaves the normal map's remainder (scale and offset) in descriptor.uvTransform.
+registerShaderFeatureCode('normalMapTransform', Object.freeze({
+ declarations: `uniform vec4 normalMapTransform;
+`,
+ normalUv: ' * normalMapTransform.xy + normalMapTransform.zw',
+}));
+
+const IDENTITY_NORMAL_MAP_TRANSFORM = [1, 1, 0, 0];
+const MAP_STATE_NORMAL_MAP = 1;
+const MAP_STATE_LAYER_MAPS = 18;
+
+layerTextureSupport.bind = (renderer, mapState) => {
if (!renderer.shaderFeatures) return;
const context = renderer.context;
+ const layerMaps = mapState[MAP_STATE_LAYER_MAPS];
+ if (renderer.shaderFeatures.has('normalMapTransform')) {
+ const transform = mapState[MAP_STATE_NORMAL_MAP]?.uvTransform ?? IDENTITY_NORMAL_MAP_TRANSFORM;
+ context.uniform4f(uniformOf(renderer, 'normalMapTransform'), ...transform);
+ }
layerTextureNamesOf(renderer).forEach((name, index) => {
const descriptor = layerMaps?.[name];
context.activeTexture(context.TEXTURE0 + LAYER_TEXTURE_UNIT + index);
diff --git a/src/renderer.js b/src/renderer.js
index 6671cb12..f3111020 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -55,6 +55,7 @@ function shaderFeaturesOfParts(parts) {
if (material[field]) features.add(MAP_SHADER_FEATURES[index]);
});
if (material.lightMap) features.add('lightMap');
+ if (material.normalMap?.uvTransform) features.add('normalMapTransform');
Object.keys(material.layerMaps ?? {}).forEach(name => features.add(name));
if (material.layers) features.add('splat');
if (material.moss > 0) features.add('moss');
@@ -1806,7 +1807,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]);
+ layerTextureSupport.bind?.(this, batch.mapState);
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 f4749137..e777ebd8 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -624,7 +624,7 @@ vec3 mappedNormal(vec3 normal) {
tangent = normalize(tangent);
float handedness = dot(cross(normal, tangent), bitangent) < 0.0 ? -1.0 : 1.0;
bitangent = normalize(cross(normal, tangent)) * handedness;
- vec3 sampled = texture(normalMap, textureUV).xyz * 2.0 - 1.0;
+ vec3 sampled = texture(normalMap, textureUV${featureCode("normalUv")}).xyz * 2.0 - 1.0;
sampled.xy *= normalScale;
vec3 mapped = mat3(tangent, bitangent, normal) * sampled;
return dot(mapped, mapped) > 1e-12 ? normalize(mapped) : normal;
@@ -959,7 +959,8 @@ const SHADER_FEATURE_CONDITIONS = {
// A feature that is not in the list above has its GLSL in another module, so a scene that never uses it does not carry
// it. That module calls registerShaderFeatureCode on import, with blocks of GLSL that createFragmentShader splices in:
-// declarations, illuminateReflectance, illuminateSpecular, coatReset and mainSetup, each ending in a newline, and the
+// declarations, illuminateReflectance, illuminateSpecular, coatReset and mainSetup, each ending in a newline, normalUv
+// (a suffix on the normal map's UV, as in `textureUV * scale + offset`), and the
// one-line linkSun (a factor on the sun) with linkPoint, linkSpot and linkArea (statements that skip a light for a part).
// A feature that replaces the sun shadow defines shadowVisibility as a macro in its declarations.
const registeredFeatureCode = new Map();
diff --git a/tests/gltf-extensions.test.js b/tests/gltf-extensions.test.js
index 9753dbc4..4e96baea 100644
--- a/tests/gltf-extensions.test.js
+++ b/tests/gltf-extensions.test.js
@@ -116,11 +116,57 @@ test('KHR_texture_transform bakes one shared offset, rotation and scale into the
test('KHR_texture_transform rejects different transforms and texCoord overrides on one material', async context => {
mockImageBitmap(context);
const moved = { offset: [0.5, 0] };
- await assert.rejects(parseGltf(triangleDocument({ edit: document => addTexturedMaterial(document, [moved, undefined]) })), /same KHR_texture_transform/);
- await assert.rejects(parseGltf(triangleDocument({ edit: document => addTexturedMaterial(document, [moved, { offset: [0, 0.5] }]) })), /same KHR_texture_transform/);
+ const metallicRoughnessMoved = document => {
+ addTexturedMaterial(document, [moved, moved]);
+ document.materials[0].pbrMetallicRoughness.metallicRoughnessTexture = { index: 0, extensions: { KHR_texture_transform: { offset: [0, 0.5] } } };
+ };
+ await assert.rejects(parseGltf(triangleDocument({ edit: metallicRoughnessMoved })), /same KHR_texture_transform/);
await assert.rejects(parseGltf(triangleDocument({ edit: document => addTexturedMaterial(document, [{ texCoord: 1 }, { texCoord: 1 }]) })), /texCoord/);
});
+test('a normal map may differ from the other maps by scale and offset, which the shader applies', async context => {
+ mockImageBitmap(context);
+ const base = { offset: [-3, 3], scale: [7, 7] };
+ const normal = { offset: [-0.5, 0.5], scale: [2, 2] };
+ const asset = await parseGltf(triangleDocument({ edit: document => addTexturedMaterial(document, [base, normal]) }));
+ assertClose(asset.parts[0].geometry.uvs, [-3, 3, 4, 3, -3, 10]);
+ const [scaleU, scaleV, offsetU, offsetV] = asset.parts[0].material.normalMap.uvTransform;
+ assertClose([scaleU, scaleV, offsetU, offsetV], [2 / 7, 2 / 7, -0.5 + 6 / 7, 0.5 - 6 / 7]);
+ assert.notEqual(asset.parts[0].material.normalMap, asset.parts[0].material.baseColorMap);
+ const firstVertexNormalUv = [-3 * scaleU + offsetU, 3 * scaleV + offsetV];
+ assertClose(firstVertexNormalUv, [-0.5, 0.5]);
+});
+
+test('a texture transform that only repeats the texture own texCoord changes nothing', async context => {
+ mockImageBitmap(context);
+ const edit = document => {
+ addTexturedMaterial(document, [undefined, undefined]);
+ document.meshes[0].primitives[0].attributes.TEXCOORD_1 = 1;
+ document.materials[0].occlusionTexture = { index: 0, texCoord: 1, extensions: { KHR_texture_transform: { texCoord: 1 } } };
+ };
+ const asset = await parseGltf(triangleDocument({ edit }));
+ assert.equal(asset.parts[0].material.occlusionMap.uvChannel, 1);
+ assertClose(asset.parts[0].geometry.uvs, TRIANGLE_UVS);
+});
+
+test('a normal map with the same transform as its material keeps no extra transform', async context => {
+ mockImageBitmap(context);
+ const shared = { offset: [0.25, 0.5], scale: [2, 4] };
+ const asset = await parseGltf(triangleDocument({ edit: document => addTexturedMaterial(document, [shared, shared]) }));
+ assert.equal(asset.parts[0].material.normalMap.uvTransform, undefined);
+ assertClose(asset.parts[0].geometry.uvs, [0.25, 0.5, 2.25, 0.5, 0.25, 4.5]);
+ const plainBase = await parseGltf(triangleDocument({ edit: document => addTexturedMaterial(document, [undefined, undefined]) }));
+ assert.equal(plainBase.parts[0].material.normalMap.uvTransform, undefined);
+ assertClose(plainBase.parts[0].geometry.uvs, TRIANGLE_UVS);
+});
+
+test('a normal map transform that needs a different rotation is rejected', async context => {
+ mockImageBitmap(context);
+ const base = { scale: [2, 2] };
+ const rotated = { scale: [2, 2], rotation: 0.5 };
+ await assert.rejects(parseGltf(triangleDocument({ edit: document => addTexturedMaterial(document, [base, rotated]) })), /offset and a positive scale/);
+});
+
function instancingDocument(translations, edit = () => {}) {
return triangleDocument({
extraChunks: [bytesOf(new Float32Array(translations))],
diff --git a/tests/material-layer-shaders.test.js b/tests/material-layer-shaders.test.js
index fa76d99b..93ac51c0 100644
--- a/tests/material-layer-shaders.test.js
+++ b/tests/material-layer-shaders.test.js
@@ -35,3 +35,13 @@ test('importing the layer shader module registers the code for the shader that a
assert.doesNotMatch(createFragmentShader(['anisotropy']), /filmReflectance/);
assert.doesNotMatch(createFragmentShader(['iridescence']), /anisotropicSpecular/);
});
+
+test('the normal map transform is applied only when its feature is on', async () => {
+ await import('../src/material-layer-shaders.js');
+ const { createFragmentShader } = await import('../src/shaders.js');
+ const plain = createFragmentShader(['normalMap']);
+ const transformed = createFragmentShader(['normalMap', 'normalMapTransform']);
+ assert.match(transformed, /texture\(normalMap, textureUV \* normalMapTransform\.xy \+ normalMapTransform\.zw\)/);
+ assert.match(plain, /texture\(normalMap, textureUV\)/);
+ assert.doesNotMatch(plain, /normalMapTransform/);
+});