Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Decode an 8-bit sRGB map after filtering it, as Cycles does (#1030)

Nguyen Xuan An2f1c1cfa4cfb
diff --git a/bench/cycles-parity/render-cycles.py b/bench/cycles-parity/render-cycles.py
index 9e38ee60..c6338296 100644
--- a/bench/cycles-parity/render-cycles.py
+++ b/bench/cycles-parity/render-cycles.py
@@ -124,14 +124,17 @@ def build_blender_mesh(mesh_name, geometry_entry):
def unpack_shared_image(image_name, texture_descriptor, image_entries, built_images):
- image_identifier = texture_descriptor["image"]["imageId"]
+ image_identifier = (texture_descriptor["image"]["imageId"], texture_descriptor.get("colorSpace", "srgb"))
if image_identifier in built_images:
return built_images[image_identifier]
- source_entry = image_entries[image_identifier]
+ source_entry = image_entries[image_identifier[0]]
raw_pixels = decode_typed_array(source_entry["data"])
width = source_entry["width"]
height = source_entry["height"]
blender_image = bpy.data.images.new(image_name, width, height, alpha=True)
+ if image_identifier[1] == "linear":
+ # Set before the pixels: changing the colour space of an image that holds pixels reloads it and drops them.
+ blender_image.colorspace_settings.name = "Non-Color"
flipped_pixels = raw_pixels.reshape(height, width, 4)[::-1].astype(numpy.float32) / 255.0
blender_image.pixels.foreach_set(flipped_pixels.reshape(-1))
blender_image.pack()
diff --git a/bench/cycles-parity/texture-scenes.mjs b/bench/cycles-parity/texture-scenes.mjs
index 60ddb2b2..fed86e77 100644
--- a/bench/cycles-parity/texture-scenes.mjs
+++ b/bench/cycles-parity/texture-scenes.mjs
@@ -115,6 +115,28 @@ function textureSplitScene(include) {
return sceneWithParts(parts);
}
+// An emissive quad seen head on with no light in the room, so a pixel is the texture itself and the mean of the picture is
+// known in closed form from the texels (`texture-mean-expectation.py`). Cook and Cycles differ here only in how they read a
+// texture. One frame covers 10 degrees of a 3 x 3 repeat of the quad.
+function emissiveProbeScene(colorSpace) {
+ const emissiveMap = { image: gradientChecker(false), colorSpace };
+ return {
+ parts: [part('emitter', quadGeometry(3), [0, 0, 0], [1, 1, 1], { color: [0, 0, 0], emission: 1, emissiveColor: [1, 1, 1], emissiveMap })],
+ blenderWorld: { type: 'constant', value: 0 },
+ environment: { ...environment(), pointLights: [] },
+ camera: { eye: [0, 0, 8], target: [0, 0, 0], up: [0, 1, 0], fov: 10, near: 0.1, far: 50 },
+ };
+}
+
+// The mask quad of tex-repeat without the backdrop that receives its shadow, and with an opaque map under the same mask material.
+// Cook over Cycles on these two says whether a gap on the mask quad sits on the quad, in its shadow or in the cutout itself.
+function maskDiagnosticScene(variant) {
+ const mapImage = variant === 'opaque' ? gradientChecker(false) : gradientChecker(true);
+ const maskMap = { image: mapImage, colorSpace: 'srgb' };
+ const maskQuad = part('mask', quadGeometry(3), [2.2, 0, 0], [1.9, 1.9, 1], { color: [0.9, 0.95, 0.9], alphaMode: 'mask', alphaCutoff: 0.5, map: maskMap });
+ return sceneWithParts(variant === 'alone' ? [maskQuad] : [backdrop(), maskQuad]);
+}
+
function textureWrapsScene() {
const wrapped = (extra) => ({ image: gradientChecker(false), colorSpace: 'srgb', uvScale: [2.5, 2.5], uvOffset: [0.15, -0.1], ...extra });
const alpha = (extra) => ({ image: gradientChecker(true), colorSpace: 'srgb', uvScale: [2.5, 2.5], ...extra });
@@ -142,6 +164,10 @@ export const TEXTURE_SCENES = {
'tex-repeat': () => textureRepeatScene('srgb'),
'tex-repeat-linear': () => textureRepeatScene('linear'),
'tex-wraps': textureWrapsScene,
+ 'tex-emit-srgb': () => emissiveProbeScene('srgb'),
+ 'tex-emit-linear': () => emissiveProbeScene('linear'),
+ 'tex-mask-alone': () => maskDiagnosticScene('alone'),
+ 'tex-mask-opaque-map': () => maskDiagnosticScene('opaque'),
'tex-split-room': () => textureSplitScene('none'),
'tex-split-colour': () => textureSplitScene('colour'),
'tex-split-mask': () => textureSplitScene('mask'),
diff --git a/changes/1030.md b/changes/1030.md
new file mode 100644
index 00000000..f6ea464b
--- /dev/null
+++ b/changes/1030.md
@@ -0,0 +1 @@
+- The Cycles kernel decodes an 8-bit sRGB colour map after filtering it, as Blender Cycles does, so textured surfaces no longer render 2 to 3.5 percent brighter than Cycles (#1030)
diff --git a/docs/cycles-parity.md b/docs/cycles-parity.md
index 94838828..f15ae5b0 100644
--- a/docs/cycles-parity.md
+++ b/docs/cycles-parity.md
@@ -1032,3 +1032,33 @@ Texture cost on the same A10G, one scene per process `[measured]`:
The number of textures is not limited by either build (2000 descriptors of 16x16 packed and rendered the same); the limit is the 1 GiB pool. Bindings, bind groups and struct sizes are unchanged.
Commands: `node bench/cycles-parity/texture-scenes.mjs <dir>` writes `tex-repeat` (Cycles can render it), `tex-repeat-linear` and `tex-wraps` (clamp, mirror, nearest, blend and normal map; Cook only), `node bench/cycles-parity/texture-pool-bench.mjs --textures 256 --size 512` prints pack, setup, compile and upload seconds and peak memory.
+
+## Why textured surfaces rendered bright (#1030)
+
+The `cycles` kernel decoded every texel of an 8-bit sRGB map to linear and then filtered the decoded values. Blender Cycles filters the stored 8-bit values and decodes the blend. The decode curve is convex, so a blended texel decoded first is always brighter than one decoded last, and the gap is largest where neighbouring texels differ, at the edges of a checker. The kernel now fetches stored values and decodes the filtered result (`texture_decode_filtered` in `closure.wgsl`). Opaque and nearest-filtered reads, linear maps and every untextured scene take the same arithmetic as before. Textured scenes change: this is a look change toward Cycles.
+
+Proof on the smallest scene, `tex-emit-srgb` (an emissive quad seen head on with nothing else in the room, 128 x 128, 256 spp, RTX 4090, Blender 5.3). The mean of the picture in closed form from the texels, for each order of decode and filter, against what each renderer drew (R, G, B):
+
+| | Mean linear value |
+| --- | --- |
+| closed form, decode then filter | 0.47000, 0.36315, 0.19351 |
+| closed form, filter then decode | 0.44136, 0.34604, 0.17975 |
+| Cook before | 0.47000, 0.36314, 0.19350 |
+| Cycles | 0.44144, 0.34608, 0.17978 |
+| Cook after | 0.44144, 0.34608, 0.17979 |
+
+`tex-emit-linear` (the same map as a linear map) is 0.64706, 0.58824, 0.42157 in closed form, in Cook and in Cycles, so the sampler's geometry (texel centres, wrap, flip) was right and the colour curve order was the whole gap on opaque maps. `render-cycles.py` now builds a `colorSpace: 'linear'` map as a Non-Color image; before, it always used sRGB, so a linear map could not be compared.
+
+Cook over Cycles, 2048 spp, 960 x 540, seed 1, mean ratio R, G, B and relMSE (eps 0.01); Cycles seed against seed is 7.9e-7 to 1.7e-6:
+
+| Scene | Before | After |
+| --- | --- | --- |
+| `tex-split-colour` (opaque colour map) | 1.0207, 1.0275, 1.0357; 2.2e-3 | 1.0001, 1.0002, 1.0002; 7.6e-7 |
+| `tex-split-mask` (colour map with an alpha ramp, cutout) | 1.0182, 1.0246, 1.0234; 1.6e-3 | 1.0131, 1.0110, 1.0145; 1.3e-3 |
+| `tex-repeat` (both quads) | 1.0396, 1.0388, 1.0512; 3.9e-3 | 1.0131, 1.0065, 1.0099; 1.3e-3 |
+| `tex-split-room`, `tex-split-flat` (no texture) | 1.000 | 1.000 |
+| `brick-graph` (graph material with a map) | 0.9817, 0.9880, 0.9925; 1.61e-2 | 0.9817, 0.9879, 0.9923; 1.61e-2 |
+
+Still open: the mask quad is 1.1 to 1.5 percent bright. Two renders of the diagnostic scenes (`tex-mask-alone`: the mask quad without the backdrop; `tex-mask-opaque-map`: the backdrop plus the same mask material over an opaque map) put it off the texture read: with the backdrop removed the quad is 1.0021, 1.0022, 1.0012 (measured in a build that also blended colour weighted by alpha, which did not move the full scene beyond 0.2 percent, so it was dropped), and with an opaque map under the mask material the whole scene is 1.0001. The ratio map of `tex-split-mask` puts the excess in the columns of the cutout holes and in the strip of backdrop below the quad, where Cook is up to 40 percent brighter: the light that reaches the backdrop past a cutout, not the colour of the quad. The cause there is not known.
+
+Commands: `node bench/cycles-parity/texture-scenes.mjs <dir>` also writes `tex-emit-srgb`, `tex-emit-linear`, `tex-split-*`, `tex-mask-alone` and `tex-mask-opaque-map`; `native-texture-sampler.test.js` holds a GPU-gated test of the seam between a black and a white texel (0.214 linear when blended before decoding, 0.5 when decoded first).
diff --git a/packages/render-native/src/cycles/closure.wgsl b/packages/render-native/src/cycles/closure.wgsl
index 96c13206..eaf903b8 100644
--- a/packages/render-native/src/cycles/closure.wgsl
+++ b/packages/render-native/src/cycles/closure.wgsl
@@ -94,11 +94,17 @@ fn texture_fetch_texel(desc: TextureDescriptor, ix: i32, iy: i32, format: u32) -
let rg = unpack2x16float(texture_texels[desc.data_offset + texel_idx]);
return vec4<f32>(rg.x, rg.y, 0.0, 1.0);
}
- let rgba = unpack4x8unorm(texture_texels[desc.data_offset + texel_idx]);
+ return unpack4x8unorm(texture_texels[desc.data_offset + texel_idx]);
+}
+
+// An 8-bit sRGB map is filtered on its stored values and decoded after, the way Blender Cycles reads a byte image. Decoding
+// each texel first and filtering after makes every blended texel brighter (the decode curve is convex): 2 to 7 percent of the
+// mean of a checker map at texel scale (#1030).
+fn texture_decode_filtered(color: vec4<f32>, format: u32) -> vec4<f32> {
if (format == 1u) {
- return vec4<f32>(closure_srgb_to_linear(rgba.rgb), rgba.a);
+ return vec4<f32>(closure_srgb_to_linear(color.rgb), color.a);
}
- return rgba;
+ return color;
}
// The one texture sampler of the kernel: shading (closure_sample_texture), bump, and the alpha tests of the integrator all
@@ -133,7 +139,7 @@ fn texture_sample(tex_index: i32, raw_uv0: vec2<f32>, raw_uv1: vec2<f32>) -> vec
if (is_nearest) {
let ix = clamp(i32(floor(u_wrapped * f32(w_i))), 0, w_i - 1);
let iy = clamp(i32(floor(v_wrapped * f32(h_i))), 0, h_i - 1);
- return texture_fetch_texel(desc, ix, iy, format);
+ return texture_decode_filtered(texture_fetch_texel(desc, ix, iy, format), format);
}
let fx = u_wrapped * f32(w_i) - 0.5;
@@ -151,7 +157,7 @@ fn texture_sample(tex_index: i32, raw_uv0: vec2<f32>, raw_uv1: vec2<f32>) -> vec
let c10 = texture_fetch_texel(desc, ix1, iy0, format);
let c01 = texture_fetch_texel(desc, ix0, iy1, format);
let c11 = texture_fetch_texel(desc, ix1, iy1, format);
- return mix(mix(c00, c10, tx), mix(c01, c11, tx), ty);
+ return texture_decode_filtered(mix(mix(c00, c10, tx), mix(c01, c11, tx), ty), format);
}
fn closure_sample_texture(tex_index: i32, point: ptr<function, ShadingPoint>) -> vec4<f32> {
diff --git a/packages/render-native/src/cycles/mod.rs b/packages/render-native/src/cycles/mod.rs
index 08366267..7fd588fa 100644
--- a/packages/render-native/src/cycles/mod.rs
+++ b/packages/render-native/src/cycles/mod.rs
@@ -1082,6 +1082,18 @@ mod tests {
assert!(kernel.contains("texture_sample(material.alpha_tex, uv0, uv1).r"));
}
+ /// Blender Cycles filters the stored values of an 8-bit sRGB image and decodes the blend. Decoding each texel before the
+ /// blend reads 2 to 7 percent too bright on a checker map (#1030).
+ #[test]
+ fn an_srgb_map_is_decoded_after_the_filter_and_not_per_texel() {
+ let kernel = assemble_cycles_kernel().expect("the kernel assembles");
+ let fetch_start = kernel.find("fn texture_fetch_texel(").expect("the shared texel fetch exists");
+ let fetch_end = fetch_start + kernel[fetch_start..].find("\n}").expect("the fetch function ends");
+ assert!(!kernel[fetch_start..fetch_end].contains("closure_srgb_to_linear"));
+ assert!(kernel.contains("texture_decode_filtered(mix(mix(c00, c10, tx), mix(c01, c11, tx), ty), format)"));
+ assert!(kernel.contains("texture_decode_filtered(texture_fetch_texel(desc, ix, iy, format), format)"));
+ }
+
#[test]
fn the_bootstrap_entry_samples_alpha_through_the_shared_sampler() {
let bootstrap = include_str!("bootstrap_main.wgsl");
diff --git a/tests/native-texture-sampler.test.js b/tests/native-texture-sampler.test.js
index 1996b6c7..1a5123f1 100644
--- a/tests/native-texture-sampler.test.js
+++ b/tests/native-texture-sampler.test.js
@@ -161,3 +161,24 @@ test('a masked material reads its base map alpha through base_color_tex, not thr
assert.equal(readMaterialWord(input, 0, ALPHA_TEX_WORD), -1);
assert.equal(readMaterialWord(input, 1, ALPHA_TEX_WORD), 1, 'an explicit alpha map is still bound');
});
+
+// Two texels, black and white, on a quad seen head on and lit by nothing: the pixel on the seam between them is the blend of the
+// two. Blender Cycles blends the stored 8-bit values (0.5) and decodes the blend (0.214); decoding each texel first gives 0.5 (#1030).
+test('an sRGB colour map is blended on its stored values and decoded after, as Cycles does', { skip: !findNativeAddon() }, () => {
+ const size = 9;
+ const camera = createCamera({ eye: [0, 0, 2.2], target: [0, 0, 0], fov: 30 }, size, size);
+ const blackThenWhite = { width: 2, height: 1, data: new Uint8Array([0, 0, 0, 255, 255, 255, 255, 255]) };
+ const input = buildNativeInputV2(
+ {
+ materials: [{ color: [0, 0, 0], emission: 1, emissiveColor: [1, 1, 1], emissiveMap: { image: blackThenWhite, colorSpace: 'srgb' } }],
+ instances: [{ geometry: quadGeometry(0), materialIndex: 0 }],
+ lights: {},
+ },
+ camera,
+ { width: size, height: size, samples: 16 },
+ );
+ const result = traceNative(input, { width: size, height: size, samples: 16, kernel: 'cycles' });
+ const centrePixel = Math.floor(size / 2) * size + Math.floor(size / 2);
+ const decodedBlend = ((0.5 + 0.055) / 1.055) ** 2.4;
+ assert.ok(Math.abs(result.rgba[centrePixel * 4] - decodedBlend) < 0.02, `centre red ${result.rgba[centrePixel * 4]}, expected ${decodedBlend}`);
+});