3D engine that AI agents drive
Make the graph noise node Blender's Noise Texture, value for value (part of #50)
Nguyen Xuan Anbd6e448c76a1
diff --git a/bench/reference/README.md b/bench/reference/README.mdindex 4df221b3..b77d34ec 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -1481,6 +1481,31 @@ After the change: `brick-graph` 0.0933 (GPU) and 0.0930 (CPU) against Cycles, 0.What is left is not in the bake. On the bump-only wall across the dark side of a joint, luminance (display space) is 0.25 at the darkest pixel in Cycles, 0.34 in EEVEE and 0.37 in 67js, against 0.62 on the flat wall: EEVEE and 67js agree with each other and Cycles is darker. That is a shading difference on a normal tilted about 70 degrees from the surface, in the lighting of `src/shaders.js`, which this change does not touch; it needs the engine session.+## The graph noise node is Blender's Noise Texture (2026-11-04, part of issue #50, RTX 3060 960 x 540)++The brick-tone error of `brick-graph` was a pattern error: the `noise` node was a periodic gradient noise with its own hash, so its blotches sat in other places than Cycles' and EEVEE's. Blender 5.2.2 headless baked its Noise Texture (2D, Fac) over the unit square to float arrays (Cycles on the CPU, 1 sample, filter 0.01, `Geometry > Position` as the vector), and the 67js node was evaluated at the same pixel centres, 256 x 256.++| Property | Before | Blender 5.2 | Now |+| --- | --- | --- | --- |+| Lattice hash | `hashCell` (xxHash-style mix of the cell and the seed) | Jenkins lookup3 `hash_uint2` of the corner | the same as Blender |+| Corner gradient | one angle per corner, unit vector | 8 gradients picked by the low 3 hash bits, `(x, y)` mixed with `2 * (y, x)` | the same |+| Output scale | `1.5 * gradient`, range about -1 to 1 | `0.6616 * perlin` | the same |+| Octaves | cells doubled per octave inside a wrapped period, gain 0.5, own seed per octave | Detail `n - 1`: `n` octaves, Roughness 0.5, Lacunarity 2, same lattice shifted by the frequency | the same |+| Normalize and offset | `value * 0.5 + 0.5` of the amplitude-normalised sum | `0.5 * sum / amplitude sum + 0.5` | the same |+| Tiling | wrapped over the unit square | none | none by default, `"tile": true` wraps it |+| Seed | per-octave seed in the hash | none | moves the lattice by whole cells; Blender's side adds the same shift |++Node output against the Cycles bake: scale 10, detail 2: max 0.000048, mean 0.000011 over 65,536 pixels (both ranges 0.120 to 0.831); scale 7, detail 5 (6 octaves): max 0.000052, mean 0.000010. That is float precision, so the match is per pixel; `tests/material-graph.test.js` keeps six Cycles values. The colour ramp (LINEAR in RGB, stops in linear colour) and the Map Range smoothstep were read and need no change. Not touched: `voronoi`, which no reference scene uses and which Blender computes with its own jittered-point hash; it still differs from Blender's Voronoi Texture.++Suite on the GPU through `raster-only.mjs` (26 scenes, before on main, after on this branch), scored by FLIP against the stored Cycles arrays: 24 scenes are byte-identical PNGs (no other scene reads a graph), so the worst delta there is 0.0000. The two that changed:++| Scene | Before | After |+| --- | --- | --- |+| `brick-graph` | 0.0871 | 0.0734 |+| `brick-flat` (its colour is the average of the graph map, which moved) | 0.0547 | 0.0556 |++The excess of the graph wall over the flat wall is 0.0178 (was 0.0324), against EEVEE's 0.0120, so the first Done-when box of #50 stays open, by 0.0058. The wall luminance mean is 0.5455 (Cycles 0.5495) and the darkest pixel 0.210 (Cycles 0.218). In the error map of the wall the brick tones now agree; what is left is a thin line along the lit and dark edges of every brick (the bump at the joint), not the tone. The scene's noise seed of 2 became the default 0 because Cycles never had it (the stored Cycles and EEVEE arrays stay valid).+## The sky share of a tilted normal, squared (2026-11-04, part of issue #50, SwiftShader 960 x 540)Rendered on SwiftShader (`run.mjs --no-gpu --skip-blender --skip-cpu --scene brick-graph,brick-flat`, no GPU) and scored by FLIP against the stored Cycles and EEVEE arrays (`brick-graph` and `brick-flat` rows reproduce the committed 0.0933 and 0.0547 to within 0.0004). Only `brick-graph` has a normal map in the suite, so the change cannot move any other scene (the line is behind `USES_NORMAL_MAP`); `brick-flat` was rendered again and stayed 0.0543. Wall pixels are rows 110 to 430, columns 230 to 730, display luminance.diff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.pyindex 2f2b70a2..8ca3056a 100644--- a/bench/reference/render-blender.py+++ b/bench/reference/render-blender.py@@ -233,8 +233,8 @@ GRAPH_MATH_OPERATIONS = {"add": "ADD", "sub": "SUBTRACT", "mul": "MULTIPLY", "div": "DIVIDE", "min": "MINIMUM", "max": "MAXIMUM","pow": "POWER", "abs": "ABSOLUTE", "floor": "FLOOR", "fract": "FRACT", "sqrt": "SQRT",}-# 67js noise has no seed in Blender, and Blender's noise function differs from the one in src/material-texture-kit.js,-# so a graph with noise only matches in how it looks, not pixel for pixel.+# The graph noise node of 67js is Blender's Noise Texture (2D, fBm, Roughness 0.5, Lacunarity 2, Normalize), value for+# value (bench/reference/README.md, 2026-11-04). A graph noise with "tile": true wraps its lattice and is not translated.GRAPH_BUMP_DISTANCE = 0.15@@ -319,14 +319,20 @@ class GraphTranslator:return node.outputs["Result"]def noise(self, settings):+ if settings.get("tile"):+ raise NotImplementedError("Blender's noise lattice does not wrap, so a tiled noise has no Blender node.")node = self.nodes.new("ShaderNodeTexNoise")node.noise_dimensions = "2D"node.inputs["Scale"].default_value = settings.get("scale", 4)node.inputs["Detail"].default_value = settings.get("octaves", 4) - 1node.inputs["Roughness"].default_value = 0.5+ seed = settings.get("seed", 0)+ scale = settings.get("scale", 4)+ # 67js moves the lattice by whole cells per seed (NOISE seed shifts in src/material-graph.js), in scaled units.+ shifts = ((seed * 7919) % 1024 / scale, (seed * 104729) % 1024 / scale)combine = self.nodes.new("ShaderNodeCombineXYZ")for index, part in enumerate(self.position(settings)):- self.connect(combine.inputs[index], part)+ self.connect(combine.inputs[index], self.math("ADD", part, shifts[index]) if index < 2 and shifts[index] else part)self.links.new(combine.outputs[0], node.inputs["Vector"])return node.outputs["Fac"]diff --git a/bench/reference/scenes.js b/bench/reference/scenes.jsindex 656b6332..8c6afc5a 100644--- a/bench/reference/scenes.js+++ b/bench/reference/scenes.js@@ -78,7 +78,7 @@ function brickGraph() {const jointAcross = { smoothstep: [0.12, 0.3, { wave: { frequency: BRICK_COLUMNS, direction: 'u', shape: 'triangle', at: shifted } }] };const jointAlong = { smoothstep: [0.08, 0.2, { wave: { frequency: BRICK_ROWS, direction: 'v', shape: 'triangle' } }] };const body = { min: [jointAcross, jointAlong] };- const tone = { ramp: { value: { noise: { scale: 10, seed: 2, octaves: 3 } }, stops: [[0, [0.3, 0.09, 0.05]], [1, [0.58, 0.24, 0.14]]] } };+ const tone = { ramp: { value: { noise: { scale: 10, octaves: 3 } }, stops: [[0, [0.3, 0.09, 0.05]], [1, [0.58, 0.24, 0.14]]] } };return { color: { mix: [[0.45, 0.42, 0.38], tone, body] }, height: body };}diff --git a/changes/50-noise.md b/changes/50-noise.mdnew file mode 100644index 00000000..70d73b5d--- /dev/null+++ b/changes/50-noise.md@@ -0,0 +1 @@+- Make the graph `noise` node Blender's Noise Texture node, value for value (issue #50). It was a periodic gradient noise with its own hash; it is now Blender's 2D Perlin (Jenkins hash, 8 gradients, quintic fade) summed as fractal Brownian motion with detail `octaves - 1`, roughness 0.5, lacunarity 2 and Normalize on, and matches a Cycles bake of the node to 5e-5 at every pixel. The seed shifts the lattice by whole cells, and `"tile": true` wraps the lattice for a texture that must repeat.diff --git a/changes/50-noise.size.md b/changes/50-noise.size.mdnew file mode 100644index 00000000..ac7b6662--- /dev/null+++ b/changes/50-noise.size.md@@ -0,0 +1 @@+- scene:agent-scene+lazy: Blender's hash and Perlin gradients take the place of the gradient noise in the graph bake, which brings the brick-tone noise of `brick-graph` to the pixels Cycles drawsdiff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 4f90c6d1..a752dcc1 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -175,7 +175,10 @@ Nodes: `uv` (`"u"`, `"v"` or `"both"`), `noise`, `voronoi` (`output`: `distance`(2 to 8 stops of numbers or colours), `vec`, and the maths nodes `add`, `sub`, `mul`, `div`, `min`, `max`, `pow`, `abs`, `floor`,`fract`, `sqrt`, `invert`, `clamp`, `smoothstep` and `mix`. Maths nodes work on each component of a vector. Every texturenode takes `at`, a vector expression such as `{ "add": [{ "uv": "both" }, { "mul": [{ "vec": [0.1, 0, 0] }, 1] }] }`, to warp-it. Scales and counts are whole numbers (1 to 64, even for `checker`), so every texture node tiles.+it. Scales and counts are whole numbers (1 to 64, even for `checker`), so every texture node tiles, except `noise`: it is+Blender's Noise Texture node value for value (2D, detail `octaves - 1`, roughness 0.5, lacunarity 2, normalized; `seed` moves the+lattice by whole cells), whose lattice does not wrap. Add `"tile": true` to a `noise` that must repeat, at the cost of a different+last cell row and column.Limits, checked while the recipe is read: at most 64 nodes in all outputs, depth 12 (the field expression limits), at most 8 rampstops, `resolution` of 256, 512 or 1024, and a work budget of 30 million units, where a plain node costs 1, a `noise` octave 3diff --git a/src/material-graph.js b/src/material-graph.jsindex a53d63d1..9daaa3cb 100644--- a/src/material-graph.js+++ b/src/material-graph.js@@ -1,5 +1,5 @@import { MATERIAL_GRAPH_LIMITS, MATERIAL_GRAPH_OUTPUTS, MATERIAL_GRAPH_OPERATORS } from './agent-scene-capabilities.js';-import { clampUnit, smoothStep, fractalNoise, cellularNoise, linearToSrgbByte, createImage, normalMapFromHeightFunction } from './material-texture-kit.js';+import { clampUnit, smoothStep, wrapCell, cellularNoise, linearToSrgbByte, createImage, normalMapFromHeightFunction } from './material-texture-kit.js';// A bounded material node graph. Like a field expression (src/mesh-fields.js), a graph is data and never code: it is// walked as plain objects against a fixed table of operators, checked against its limits before any pixel is@@ -121,14 +121,100 @@ function textureSettings(node, name, allowed) {return settings;}+// Blender's Noise Texture node (2D, Perlin, fractal Brownian motion, Normalize on): Jenkins lookup3 hash of the lattice+// corner, the 8 gradients of its 2D Perlin, 6t^5 - 15t^4 + 10t^3 fade, and the octave sum divided by the amplitude sum.+// Detail is octaves - 1, Roughness 0.5 and Lacunarity 2, the node's defaults.+const HASH_START = (0xdeadbeef + (2 << 2) + 13) >>> 0;+const rotateLeft = (value, bits) => (value << bits) | (value >>> (32 - bits));+const PERLIN_OUTPUT_SCALE = 0.6616;+const NOISE_ROUGHNESS = 0.5;+const NOISE_LACUNARITY = 2;++function hashLatticeCorner(cellX, cellY) {+ let a = (HASH_START + cellX) >>> 0;+ let b = (HASH_START + cellY) >>> 0;+ let c = HASH_START;+ c = (c ^ b) - rotateLeft(b, 14);+ a = ((a ^ c) >>> 0) - rotateLeft(c, 11);+ b = ((b ^ a) >>> 0) - rotateLeft(a, 25);+ c = ((c ^ b) >>> 0) - rotateLeft(b, 16);+ a = ((a ^ c) >>> 0) - rotateLeft(c, 4);+ b = ((b ^ a) >>> 0) - rotateLeft(a, 14);+ c = ((c ^ b) >>> 0) - rotateLeft(b, 24);+ return c >>> 0;+}++function cornerGradient(hash, offsetX, offsetY) {+ const choice = hash & 7;+ const major = choice < 4 ? offsetX : offsetY;+ const minor = 2 * (choice < 4 ? offsetY : offsetX);+ return ((choice & 1) ? -major : major) + ((choice & 2) ? -minor : minor);+}++const fade = value => value * value * value * (value * (value * 6 - 15) + 10);++// A period of 0 leaves the lattice unwrapped, which is Blender's. A period in cells wraps the corner indices so the+// noise repeats every period cells (only the cells at the far edge of the unit square then differ from Blender).+function latticeHash(cellX, cellY, period) {+ if (period === 0) return hashLatticeCorner(cellX, cellY);+ return hashLatticeCorner(wrapCell(cellX, period), wrapCell(cellY, period));+}++function perlinNoise(x, y, period) {+ const cellX = Math.floor(x);+ const cellY = Math.floor(y);+ const fractionX = x - cellX;+ const fractionY = y - cellY;+ const blendX = fade(fractionX);+ const blendY = fade(fractionY);+ const bottom = mixNumbers(+ cornerGradient(latticeHash(cellX, cellY, period), fractionX, fractionY),+ cornerGradient(latticeHash(cellX + 1, cellY, period), fractionX - 1, fractionY),+ blendX,+ );+ const top = mixNumbers(+ cornerGradient(latticeHash(cellX, cellY + 1, period), fractionX, fractionY - 1),+ cornerGradient(latticeHash(cellX + 1, cellY + 1, period), fractionX - 1, fractionY - 1),+ blendX,+ );+ return PERLIN_OUTPUT_SCALE * mixNumbers(bottom, top, blendY);+}++/**+ * Blender's Noise Texture Fac at (x, y), already scaled by the node's Scale. `tileCells` is the first octave's number of+ * cells across the unit square when the noise must repeat, or 0 for Blender's endless lattice.+ */+export function blenderNoise(x, y, octaves, tileCells = 0) {+ let total = 0;+ let amplitude = 1;+ let amplitudeSum = 0;+ let frequency = 1;+ for (let octave = 0; octave < octaves; octave++) {+ total += perlinNoise(x * frequency, y * frequency, tileCells * frequency) * amplitude;+ amplitudeSum += amplitude;+ amplitude *= NOISE_ROUGHNESS;+ frequency *= NOISE_LACUNARITY;+ }+ return 0.5 * total / amplitudeSum + 0.5;+}++// The seed moves the lattice by whole cells, the same for Blender's side (bench/reference/render-blender.py).+const SEED_SHIFT_X = 7919;+const SEED_SHIFT_Y = 104729;+const SEED_SHIFT_RANGE = 1024;+function compileNoise(node, state, depth) {- const settings = textureSettings(node, 'noise', ['scale', 'seed', 'octaves', 'at']);+ const settings = textureSettings(node, 'noise', ['scale', 'seed', 'octaves', 'tile', 'at']);const scale = integerInRange(settings.scale ?? 4, 1, NOISE_SCALE_LIMIT, 'noise scale');const seed = integerInRange(settings.seed ?? 0, 0, MAX_SEED, 'noise seed');const octaves = integerInRange(settings.octaves ?? 4, 1, NOISE_OCTAVE_LIMIT, 'noise octaves');+ if (settings.tile !== undefined && typeof settings.tile !== 'boolean') throw graphError('noise tile must be true or false.');+ const tileCells = settings.tile ? scale : 0;+ const shiftX = (seed * SEED_SHIFT_X) % SEED_SHIFT_RANGE;+ const shiftY = (seed * SEED_SHIFT_Y) % SEED_SHIFT_RANGE;state.cost += octaves * NOISE_COST_PER_OCTAVE;const [positionU, positionV] = compilePosition(settings, state, depth);- return scalarValue((u, v) => fractalNoise(positionU(u, v), positionV(u, v), scale, scale, seed, octaves) * 0.5 + 0.5);+ return scalarValue((u, v) => blenderNoise(positionU(u, v) * scale + shiftX, positionV(u, v) * scale + shiftY, octaves, tileCells));}const VORONOI_OUTPUTS = ['distance', 'edge', 'cell'];diff --git a/tests/material-graph.test.js b/tests/material-graph.test.jsindex 77b731ca..ca9ad8ab 100644--- a/tests/material-graph.test.js+++ b/tests/material-graph.test.js@@ -94,7 +94,7 @@ test('the slope of a sharp joint edge stays within one texel of the edge instead});test('every graph texture node tiles across the seam', () => {- const nodes = [{ noise: { scale: 6 } }, { voronoi: { scale: 5, output: 'edge' } }, { wave: { frequency: 3, direction: 'diagonal' } }, { checker: { count: 8 } }];+ const nodes = [{ noise: { scale: 6, tile: true } }, { voronoi: { scale: 5, output: 'edge' } }, { wave: { frequency: 3, direction: 'diagonal' } }, { checker: { count: 8 } }];for (const node of nodes) {const { outputs } = compileMaterialGraph({ height: node });const evaluate = outputs.height.evaluate;@@ -107,6 +107,30 @@ test('every graph texture node tiles across the seam', () => {}});+test('the noise node returns the values of Blender 5.2 Noise Texture (2D, scale 10, detail 2, roughness 0.5, normalized)', () => {+ // Fac read back from a Cycles bake at these positions (bench/reference/README.md, 2026-11-04).+ const golden = [+ [0.080078125, 0.041015625, 0.439068],+ [0.783203125, 0.236328125, 0.398615],+ [0.501953125, 0.501953125, 0.495776],+ [0.130859375, 0.783203125, 0.461263],+ [0.998046875, 0.998046875, 0.511450],+ [0.978515625, 0.013671875, 0.487824],+ ];+ const { outputs } = compileMaterialGraph({ height: { noise: { scale: 10, octaves: 3 } } });+ for (const [u, v, expected] of golden) {+ assert.ok(Math.abs(outputs.height.evaluate(u, v) - expected) < 1e-4, `noise at ${u}, ${v}`);+ }+});++test('a tiled noise repeats over the unit square and differs from the endless one only near the far edges', () => {+ const endless = compileMaterialGraph({ height: { noise: { scale: 10, octaves: 3 } } }).outputs.height.evaluate;+ const tiled = compileMaterialGraph({ height: { noise: { scale: 10, octaves: 3, tile: true } } }).outputs.height.evaluate;+ assert.ok(Math.abs(tiled(0.4, 0.3) - endless(0.4, 0.3)) < 1e-12);+ assert.ok(Math.abs(tiled(0.4, 0.3) - tiled(1.4, 2.3)) < 1e-9);+ assert.throws(() => compileMaterialGraph({ height: { noise: { tile: 'yes' } } }), /tile/);+});+test('patterns with mapping uv use the geometry UVs from uv_unwrap instead of box projection', () => {const recipe = {format: '67js.scene', schemaVersion: 1,