Skip to content

3D engine that AI agents drive

Show the gradient sky's stops and glow as the hex the user gave (#2038)

Nguyen Xuan An464ccd9228b8
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.yml
index 9f979c3b..c6d59603 100644
--- a/.github/workflows/cook-addon.yml
+++ b/.github/workflows/cook-addon.yml
@@ -344,6 +344,7 @@ on:
- 'src/view-transform-names.js'
- 'src/view-transform-shader.js'
- 'src/view-transform.js'
+ - 'src/view-transform-inverse.js'
- 'src/volume-grid-sequence.js'
- 'src/volume-grid.js'
- 'src/volume-step-integral.js'
diff --git a/changes/2038.md b/changes/2038.md
index ff1b29ec..cca14bce 100644
--- a/changes/2038.md
+++ b/changes/2038.md
@@ -1 +1 @@
-- `environment.sky { type: "gradient", stops, horizonGlow }` paints a picked-colour sky with an optional horizon glow band that also lights the scene and shows in water reflections; the physical sky render is unchanged (#2038)
+- `environment.sky { type: "gradient", stops, horizonGlow }` paints a picked-colour sky with an optional horizon glow band that also lights the scene and shows in water reflections, compensated for the view transform so stops and glow display as their hex and blended in OKLab; the physical sky render is unchanged (#2038)
diff --git a/changes/2038.size.md b/changes/2038.size.md
index eb908933..32174c4e 100644
--- a/changes/2038.size.md
+++ b/changes/2038.size.md
@@ -1,3 +1,4 @@
- scene:agent-scene: the sky patch merge now keeps the sky type and the capabilities line names the gradient sky (68 bytes gzip), the only core cost of an agent-facing sky an art director can colour.
- scene:agent-scene+lazy: the gradient sky is a 1.3 KB gzip addition that loads only for a recipe with "type":"gradient", which gives anime-style sky colour that the physical sky cannot reach.
- goal:agent-scene: 68 bytes in the core for the gradient sky entry point; the sky code itself loads on demand.
+- scene:agent-scene+lazy: the sky now inverts the view transform and blends in OKLab (view-transform-inverse.js plus colour code in the lazy gradient chunk), so a stop displays as its hex instead of being shifted by 6 to 15 levels; it loads only for "type":"gradient".
diff --git a/docs/agent-look.md b/docs/agent-look.md
index d6818374..e19ce632 100644
--- a/docs/agent-look.md
+++ b/docs/agent-look.md
@@ -124,7 +124,7 @@ Sky colors use display RGB, matching the renderer's existing environment contrac
| `resolveCoplanar` | `'offset'` | Flush and near-flush faces, inside one mesh or across parts, are ranked per triangle and drawn with a small depth-only bias, so the face in front wins at every distance and nothing flickers. Geometry never moves. `false` opts out, and `scene_inspect` then lists each pair as a `coplanar-overlap` warning. Parts that set `decal` or `depthLayer` keep their own layer. Where an opaque face covers another on the same plane, or in front of it by at most a thousandth of the shared face (between a millimetre and a centimetre), the covered part is cut out of the drawn copy of the hidden face (the part and its geometry stay as you made them), so a stack of any depth is settled and the path tracer sees one face. What cannot be settled comes back as a `coplanar-overlap` warning with a `reason`: `rank-overflow` (more than 16 faces a wider gap apart), `double-sided-gap`, `unchecked` (past the triangle or pair budget, the part the search stopped at is named) or `collapsed-node` (an axis a millionth of the longest one; a 2 cm slab 400 m wide is a ground, not a collapse) |
| `objectReflections` | on | Absent unless set. Each smooth metal part (`metallic` 0.5 or more, `roughness` 0.6 or less; at most 8 such parts, in a scene with at most 1,024 other parts) gets a reflection probe of the scene around it, so a chrome sphere shows the floor and its neighbours. `false` turns it off. Probes are traced at rest, so a part that moves reflects the scene as it started. `scene_inspect` names them in `reflections` |
| `sky` | absent | Absent unless set. `{ type: 'physical', preset, sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective, ozone, sunDisc }`: one time-of-day control. `sunElevation` -90 to 90 degrees (default 45), `sunRotation` degrees clockwise from -Z seen from above (0), `turbidity` 1 to 10 haze (3), `groundAlbedo` 0 to 1 (0.3), `aerialPerspective` 0 to 4 scales the distance haze (1; 0 for none), `ozone` 0 to 10 Chappuis-band absorption (1), `sunDisc` boolean (true). `preset` is `golden-hour` (sun 4 degrees up), `sunset` (1 degree) or `blue-hour` (4 degrees below the horizon), each with the sun turned to rotation 250: it supplies the sun only, fields beside it win, and a preset in a `set-environment` patch starts the sky again from its own sun with the other fields at their defaults. A sun below 14 degrees is fitted to Blender's sky (checked at 2, 6 and 15 degrees, comparison in `docs/golden-hour-comparison.jpg`): a narrow saturated orange band forms along the horizon, the zenith dims and the key warms and strengthens; at 14 degrees and above the sky is unchanged. The sky sets `lightDirection`, `keyColor` (the sun reddens and dims with air mass and sets below the horizon), `skyTop`, `skyBottom`, `fogColor` and `fogDensity`, and replaces the setup's environment map with the sky, so those fields no longer take your values while a sky is set. `environment` motion tracks can animate `sunElevation`, `sunRotation`, `turbidity`, `groundAlbedo`, `aerialPerspective` and `ozone` for time-of-day arcs. A `set-environment` patch changes the fields it names and keeps the rest; `sky: null` in a patch keeps the last derived values as plain fields. It is an analytic single-scattering approximation (Rayleigh, aerosol and ozone, Kasten-Young air mass), not Blender's Nishita integration: no clouds. Raster first: the path tracer backends read the same environment map and key light, but are not yet checked against it. |
-| `sky` (gradient) | absent | `{ type: 'gradient', stops: [{ at, color }], horizonGlow: { color, width, intensity } }`: a sky whose colours you pick, for a mood that physics would not give (a teal anime sky with a bright cyan band at the horizon). `stops` holds 1 to 8 entries with `at` rising from 0 (horizon) to 1 (zenith, by elevation angle) and `color` as a `#rrggbb` hex in sRGB; below the horizon the first stop continues. `horizonGlow` is optional: `color` as hex, `width` 0.5 to 45 degrees of elevation (the half width of the band, default 6) and `intensity` 0 to 20 (default 1) multiplies the glow colour at the horizon, so 1 shows the colour as given; the band blends toward the glow colour, so it keeps its hue and does not wash to white until the colour itself is bright. The background goes through the scene's view transform like any sky (the default `aces` lifts mid tones: a flat `#0e5d73` shows as about `#0c6988`); set `viewTransform: 'neutral'` to see stop colours close to their hex. The same colours are the background (with `world: true`), the light and reflections of the scene, and the water reflection. It sets `skyTop`, `skyBottom` and `fogColor` from the first and last stop and leaves the sun, the key light and the fog density to the setup and the recipe. A `set-environment` patch with `type: 'gradient'` replaces a physical sky; a patch without `type` edits the gradient in place. Raster first; the path tracer backends read the same map but are not checked against it. |
+| `sky` (gradient) | absent | `{ type: 'gradient', stops: [{ at, color }], horizonGlow: { color, width, intensity } }`: a sky whose colours you pick, for a mood that physics would not give (a teal anime sky with a bright cyan band at the horizon). `stops` holds 1 to 8 entries with `at` rising from 0 (horizon) to 1 (zenith, by elevation angle) and `color` as a `#rrggbb` hex in sRGB; below the horizon the first stop continues. `horizonGlow` is optional: `color` as hex, `width` 0.5 to 45 degrees of elevation (the half width of the band, default 6) and `intensity` 0 to 20 (default 1) multiplies the glow colour at the horizon, so 1 shows the colour as given; the band blends toward the glow colour, so it keeps its hue and does not wash to white until the colour itself is bright. The stop and glow colours are compensated for the scene's view transform and the display power, so the frame shows the hex you gave at the horizon, the stops, the zenith and the glow peak (measured within 1 level under `aces` and `neutral`); between stops the colours blend in OKLab, which keeps the lightness and hue steady and bands less than a blend of encoded values. The inverse assumes exposure 1, no look and no post effect, divides by `environmentIntensity`, and is exact for `aces`; `agx` and `neutral` are solved numerically, and a colour they cannot show (a saturated red under `neutral`, pure white under `agx`) lands on the nearest one they can. The scene light and the water reflection read the same compensated radiance, so a gradient lights the scene more strongly than the same hex taken as plain radiance would. The same colours are the background (with `world: true`), the light and reflections of the scene, and the water reflection. It sets `skyTop`, `skyBottom` and `fogColor` from the first and last stop and leaves the sun, the key light and the fog density to the setup and the recipe. A `set-environment` patch with `type: 'gradient'` replaces a physical sky; a patch without `type` edits the gradient in place. Raster first; the path tracer backends read the same map but are not checked against it. |
| `floorSkyTrace` | on | Absent unless set. A closed room a sun lights gets the sky each floor texel sees traced into its floor (`applyFloorSkyVisibility`, strength 0.2), so shadowed floors under a roof or between walls get less world and sky light; it makes the dark end of halls closer to Cycles. Open scenes and rooms lit by lamps alone are left as they are. `false` turns it off; a value that is not a boolean is refused. It loads lazily with a recipe that names its sun (`keyColor` or `keyIntensity`), costs about 1 s of trace when the scene is built and adds triangles to the floor (0.1 to 0.4 ms per frame in the reference halls). |
| `specularAntiAliasing` | `1` | Absent unless set. `0` to `4`. Widens highlights where the shading normal or normal map detail changes within a pixel (geometric specular anti-aliasing plus a Toksvig term read from the filtered normal map length), so grainy or scanned metal stops sparkling from frame to frame at grazing angles. `0` gives a highlight that follows every texel; above `1` is softer. |
| `sunBounce` | `1` | Absent unless set. A number of 0 or more. A closed room a sun lights gets a few point lights at its sunlit patches (`withSunBounce`, found when the scene is prepared), so the floor, walls and pillars around a patch are lit by the light it bounces and the far end of the room less. `0` turns it off and gives the look without it; `1` is fitted to Cycles; above `1` is stronger. A value that is not a number of 0 or more is refused. Open scenes and rooms with no sun are left as they are. It loads lazily with the sun, and the lights take up to 6 of the 16 point light slots. |
diff --git a/skills/build-crucible-scene/references/look.md b/skills/build-crucible-scene/references/look.md
index a95eedd3..d6dbd12a 100644
--- a/skills/build-crucible-scene/references/look.md
+++ b/skills/build-crucible-scene/references/look.md
@@ -35,7 +35,7 @@ target hex and scale `emission`.
Time of day comes from the sun alone: `"sky": { "type": "physical", "preset": "golden-hour" }` (also `sunset`, `blue-hour`) sets sun elevation and azimuth, and the key, sky and haze follow from one atmosphere, so a low sun reads warm with no grading. Put `sunElevation` or `sunRotation` beside a preset to move the sun; a preset starts the sky again, so earlier sky fields are dropped.
-For a mood that physics does not give, pick the colours: `"sky": { "type": "gradient", "stops": [{ "at": 0, "color": "#1a8a9c" }, { "at": 1, "color": "#0e5d73" }], "horizonGlow": { "color": "#19d0e8", "width": 1, "intensity": 1 } }` runs from the horizon (`at` 0) to the zenith (1), adds a bright band at the horizon, and lights the scene and shows in water like any sky. It leaves the sun to the setup. Add `"viewTransform": "neutral"` to the environment to see the stop colours close to their hex; the default curve lifts mid tones.
+For a mood that physics does not give, pick the colours: `"sky": { "type": "gradient", "stops": [{ "at": 0, "color": "#1a8a9c" }, { "at": 1, "color": "#0e5d73" }], "horizonGlow": { "color": "#19d0e8", "width": 1, "intensity": 1 } }` runs from the horizon (`at` 0) to the zenith (1), adds a bright band at the horizon, and lights the scene and shows in water like any sky. It leaves the sun to the setup. The stop and glow colours show as the hex you give, under any view transform (the sky compensates for it; it assumes exposure 1 and no look or post effect).
## HDRI from the catalog
diff --git a/src/gradient-sky.js b/src/gradient-sky.js
index f7bc241c..49456558 100644
--- a/src/gradient-sky.js
+++ b/src/gradient-sky.js
@@ -1,4 +1,5 @@
import { createEnvironmentMap } from './environment.js';
+import { radianceForDisplayColor } from './view-transform-inverse.js';
// environment.sky { type: 'gradient' }: a sky whose colours are picked, not computed. Stops run from the horizon (at 0) to the
// zenith (at 1) by elevation angle, and an optional glow band hugs the horizon. The same colours feed the background, the
@@ -18,7 +19,7 @@ const GLOW_LIMITS = Object.freeze({
const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
const COLOR_EXAMPLE = 'a hex colour such as "#0e5d73"';
const MAP_WIDTH = 1024;
-const MAP_HEIGHT = 512;
+const MAP_HEIGHT = 513;
function checkedColor(value, field, fail) {
if (typeof value !== 'string' || !HEX_COLOR.test(value)) {
@@ -82,56 +83,110 @@ function srgbChannelToLinear(channel) {
return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
}
+function linearChannelToSrgb(channel) {
+ const clamped = Math.min(1, Math.max(0, channel));
+ return clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * clamped ** (1 / 2.4) - 0.055;
+}
+
export function linearColorFromHex(hex) {
return [1, 3, 5].map(offset => srgbChannelToLinear(parseInt(hex.slice(offset, offset + 2), 16) / 255));
}
-/** The recipe fields a gradient implies: the legacy sky colours that fog and the probe trace read. */
-export function gradientSkyFields(sky) {
- const horizon = linearColorFromHex(sky.stops[0].color);
- const zenith = linearColorFromHex(sky.stops[sky.stops.length - 1].color);
+// OKLab (Ottosson): blending in it keeps lightness and hue steady between two stops, where a blend of linear radiance
+// goes grey and dark in the middle and a blend of encoded values bands where the hue turns.
+function oklabFromLinear([red, green, blue]) {
+ const long = Math.cbrt(0.4122214708 * red + 0.5363325363 * green + 0.0514459929 * blue);
+ const medium = Math.cbrt(0.2119034982 * red + 0.6806995451 * green + 0.1073969566 * blue);
+ const short = Math.cbrt(0.0883024619 * red + 0.2817188376 * green + 0.6299787005 * blue);
+ return [
+ 0.2104542553 * long + 0.793617785 * medium - 0.0040720468 * short,
+ 1.9779984951 * long - 2.428592205 * medium + 0.4505937099 * short,
+ 0.0259040371 * long + 0.7827717662 * medium - 0.808675766 * short,
+ ];
+}
+
+function linearFromOklab([lightness, greenRed, blueYellow]) {
+ const long = (lightness + 0.3963377774 * greenRed + 0.2158037573 * blueYellow) ** 3;
+ const medium = (lightness - 0.1055613458 * greenRed - 0.0638541728 * blueYellow) ** 3;
+ const short = (lightness - 0.0894841775 * greenRed - 1.291485548 * blueYellow) ** 3;
+ return [
+ 4.0767416621 * long - 3.3077115913 * medium + 0.2309699292 * short,
+ -1.2684380046 * long + 2.6097574011 * medium - 0.3413193965 * short,
+ -0.0041960863 * long - 0.7034186147 * medium + 1.707614701 * short,
+ ];
+}
+
+function mixOklab(from, to, share) {
+ return from.map((component, index) => component + (to[index] - component) * share);
+}
+
+const oklabFromHex = hex => oklabFromLinear(linearColorFromHex(hex));
+const encodedFromOklab = lab => linearFromOklab(lab).map(linearChannelToSrgb);
+
+/**
+ * The radiance that shows as the hex you asked for: the view transform and the display power turn it back into the hex,
+ * so a stop reads as its colour in the frame instead of being lifted by the transform (a flat #0e5d73 under aces used to
+ * show as #0c6988). The inverse assumes exposure 1 and no look or post effect on the frame, and divides by the
+ * environment strength, which the background and the light both multiply back in. Under aces every hex is reachable.
+ * Under agx and neutral a colour the transform cannot produce lands on the nearest one it can.
+ */
+export function radianceFromHex(hex, viewTransform) {
+ const encoded = [1, 3, 5].map(offset => parseInt(hex.slice(offset, offset + 2), 16) / 255);
+ return radianceForDisplayColor(encoded, viewTransform).radiance;
+}
+
+/** The recipe fields a gradient implies: the legacy sky colours that fog and the probe trace read, as radiance. */
+export function gradientSkyFields(sky, viewTransform) {
+ const horizon = radianceFromHex(sky.stops[0].color, viewTransform);
+ const zenith = radianceFromHex(sky.stops[sky.stops.length - 1].color, viewTransform);
return { skyTop: zenith, skyBottom: horizon, fogColor: horizon };
}
/** A gradient sky leaves the sun alone and only supplies the sky colours. */
export function applyGradientSky(input, environment, fail) {
const sky = resolveGradientSky(input, fail);
- Object.assign(environment, gradientSkyFields(sky), { sky });
+ Object.assign(environment, gradientSkyFields(sky, environment.viewTransform), { sky });
}
-function stopColorsInLinear(sky) {
- return sky.stops.map(stop => ({ at: stop.at, color: linearColorFromHex(stop.color) }));
+function stopLabs(sky) {
+ return sky.stops.map(stop => ({ at: stop.at, lab: oklabFromHex(stop.color) }));
}
-function colorAtHeight(stops, height) {
+function labAtHeight(stops, height) {
if (height <= stops[0].at) {
- return stops[0].color;
+ return stops[0].lab;
}
for (let index = 1; index < stops.length; index++) {
if (height <= stops[index].at) {
- const share = (height - stops[index - 1].at) / (stops[index].at - stops[index - 1].at);
- return stops[index - 1].color.map((component, channel) => component + (stops[index].color[channel] - component) * share);
+ return mixOklab(stops[index - 1].lab, stops[index].lab, (height - stops[index - 1].at) / (stops[index].at - stops[index - 1].at));
}
}
- return stops[stops.length - 1].color;
+ return stops[stops.length - 1].lab;
+}
+
+// The glow colour blends in over the gradient by its share, so the band keeps its hue as it brightens and never washes
+// to white; `intensity` then scales the radiance of the band (1 shows the colour as given).
+function radianceAtElevation(stops, glow, glowLab, elevation, viewTransform, strengthScale) {
+ const base = labAtHeight(stops, Math.max(0, elevation) / 90);
+ const glowShare = glow ? Math.exp(-((elevation / glow.width) ** 2)) : 0;
+ const displayed = encodedFromOklab(glow ? mixOklab(base, glowLab, glowShare) : base);
+ const brightness = glow ? 1 + (glow.intensity - 1) * glowShare : 1;
+ return radianceForDisplayColor(displayed, viewTransform).radiance.map(channel => channel * brightness * strengthScale);
}
-function buildMapData(sky) {
- const stops = stopColorsInLinear(sky);
+function buildMapData(sky, viewTransform, environmentIntensity) {
+ const stops = stopLabs(sky);
const glow = sky.horizonGlow;
- const glowColor = glow ? linearColorFromHex(glow.color) : null;
+ const glowLab = glow ? oklabFromHex(glow.color) : null;
+ const strengthScale = environmentIntensity > 0 ? 1 / environmentIntensity : 1;
const data = new Float32Array(MAP_WIDTH * MAP_HEIGHT * 3);
for (let row = 0; row < MAP_HEIGHT; row++) {
- // Each row is one elevation: the gradient and the glow depend on the angle above the horizon only.
+ // Each row is one elevation: the gradient and the glow depend on the angle above the horizon only. The odd row count
+ // puts the middle row exactly on the horizon, so the glow peak is the glow colour itself.
const elevation = 90 - ((row + 0.5) / MAP_HEIGHT) * 180;
- const base = colorAtHeight(stops, Math.max(0, elevation) / 90);
- const glowShare = glow ? Math.exp(-((elevation / glow.width) ** 2)) : 0;
+ const radiance = radianceAtElevation(stops, glow, glowLab, elevation, viewTransform, strengthScale);
for (let column = 0; column < MAP_WIDTH; column++) {
- const offset = (row * MAP_WIDTH + column) * 3;
- for (let channel = 0; channel < 3; channel++) {
- // The band blends toward the glow colour instead of adding it, so it keeps its hue as it brightens and never washes to white.
- data[offset + channel] = glowColor ? base[channel] + (glowColor[channel] * glow.intensity - base[channel]) * glowShare : base[channel];
- }
+ data.set(radiance, (row * MAP_WIDTH + column) * 3);
}
}
return data;
@@ -140,14 +195,14 @@ function buildMapData(sky) {
const mapsByKey = new Map();
const MAXIMUM_CACHED_MAPS = 8;
-/** The environment map of a gradient sky; the same object returns while sky, strength, rotation and background hold. */
-export function createGradientSkyMap({ sky, environmentIntensity: intensity, environmentRotation: rotation, world: showBackground }) {
- const key = JSON.stringify([sky, intensity, rotation, showBackground]);
+/** The environment map of a gradient sky; the same object returns while sky, strength, rotation, background and view transform hold. */
+export function createGradientSkyMap({ sky, environmentIntensity: intensity, environmentRotation: rotation, world: showBackground, viewTransform = 'aces' }) {
+ const key = JSON.stringify([sky, intensity, rotation, showBackground, viewTransform]);
if (!mapsByKey.has(key)) {
if (mapsByKey.size >= MAXIMUM_CACHED_MAPS) {
mapsByKey.clear();
}
- mapsByKey.set(key, createEnvironmentMap({ width: MAP_WIDTH, height: MAP_HEIGHT, data: buildMapData(sky), intensity, rotation, showBackground }));
+ mapsByKey.set(key, createEnvironmentMap({ width: MAP_WIDTH, height: MAP_HEIGHT, data: buildMapData(sky, viewTransform, intensity), intensity, rotation, showBackground }));
}
return mapsByKey.get(key);
}
diff --git a/src/view-transform-inverse.js b/src/view-transform-inverse.js
new file mode 100644
index 00000000..9be99926
--- /dev/null
+++ b/src/view-transform-inverse.js
@@ -0,0 +1,77 @@
+import { applyViewTransform } from './view-transform.js';
+
+// The inverse of the display path for a picked colour: radiance that the view transform and the 1 / 2.2 display power
+// return as the colour asked for. aces is inverted in closed form per channel; agx and neutral mix the channels, so they
+// are solved with a few Newton steps. A display value that no radiance reaches (a channel the transform never produces,
+// such as pure white under agx) lands on the nearest value the solver found, and `error` says how far off it is.
+
+const DISPLAY_POWER = 2.2;
+const NEWTON_STEPS = 24;
+const DIFFERENCE_STEP = 1e-4;
+const ACCEPTED_ERROR = 1e-4;
+const LARGEST_RADIANCE = 1e4;
+
+/** Radiance for one ACES channel (the rasterizer's Narkowicz fit) that maps to `target` in 0 to 1. */
+export function inverseAcesChannel(target) {
+ const level = Math.min(1, Math.max(0, target));
+ const quadratic = 2.51 - 2.43 * level;
+ const linear = 0.03 - 0.59 * level;
+ const constant = -0.14 * level;
+ return (-linear + Math.sqrt(linear * linear - 4 * quadratic * constant)) / (2 * quadratic);
+}
+
+function solveThreeByThree(matrix, vector) {
+ const rows = matrix.map((row, index) => [...row, vector[index]]);
+ for (let pivot = 0; pivot < 3; pivot++) {
+ let best = pivot;
+ for (let row = pivot + 1; row < 3; row++) {
+ if (Math.abs(rows[row][pivot]) > Math.abs(rows[best][pivot])) best = row;
+ }
+ if (Math.abs(rows[best][pivot]) < 1e-12) return null;
+ [rows[pivot], rows[best]] = [rows[best], rows[pivot]];
+ for (let row = 0; row < 3; row++) {
+ if (row === pivot) continue;
+ const factor = rows[row][pivot] / rows[pivot][pivot];
+ for (let column = pivot; column < 4; column++) rows[row][column] -= factor * rows[pivot][column];
+ }
+ }
+ return rows.map((row, index) => row[3] / row[index]);
+}
+
+function largestDifference(first, second) {
+ return Math.max(...first.map((value, channel) => Math.abs(value - second[channel])));
+}
+
+function solveMixedChannels(name, target) {
+ const forward = radiance => applyViewTransform(name, radiance);
+ let radiance = target.map(channel => Math.max(channel, 1e-4));
+ let best = { radiance, error: largestDifference(forward(radiance), target) };
+ for (let step = 0; step < NEWTON_STEPS && best.error > ACCEPTED_ERROR; step++) {
+ const current = forward(radiance);
+ const columns = radiance.map((value, channel) => {
+ const nudged = [...radiance];
+ nudged[channel] = value + DIFFERENCE_STEP;
+ return forward(nudged).map((result, row) => (result - current[row]) / DIFFERENCE_STEP);
+ });
+ const jacobian = [0, 1, 2].map(row => columns.map(column => column[row]));
+ const move = solveThreeByThree(jacobian, current.map((value, channel) => value - target[channel]));
+ if (move === null) break;
+ radiance = radiance.map((value, channel) => Math.min(LARGEST_RADIANCE, Math.max(0, value - move[channel])));
+ const error = largestDifference(forward(radiance), target);
+ if (error < best.error) best = { radiance, error };
+ }
+ return best;
+}
+
+/**
+ * Radiance that displays as `displayEncoded` (RGB in 0 to 1, the pixel as shown) under `viewTransform`.
+ * Returns { radiance, error }: error is the largest channel gap, in display-linear units, between the round trip and the
+ * request; it is 0 for aces and below 1e-4 where agx and neutral can reach the colour.
+ */
+export function radianceForDisplayColor(displayEncoded, viewTransform = 'aces') {
+ const target = displayEncoded.map(channel => Math.min(1, Math.max(0, channel)) ** DISPLAY_POWER);
+ if (viewTransform === 'aces') {
+ return { radiance: target.map(inverseAcesChannel), error: 0 };
+ }
+ return solveMixedChannels(viewTransform, target);
+}
diff --git a/tests/gradient-sky-compensation.test.js b/tests/gradient-sky-compensation.test.js
new file mode 100644
index 00000000..36421793
--- /dev/null
+++ b/tests/gradient-sky-compensation.test.js
@@ -0,0 +1,83 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { agentEnvironmentMap, normalizeAgentLook } from '../src/agent-look.js';
+import { radianceFromHex } from '../src/gradient-sky.js';
+import { inverseAcesChannel, radianceForDisplayColor } from '../src/view-transform-inverse.js';
+import { acesChannel, displayColor } from '../src/view-transform.js';
+
+const STOPS = [{ at: 0, color: '#1a8a9c' }, { at: 0.45, color: '#127285' }, { at: 1, color: '#0e5d73' }];
+const GLOW = { color: '#19d0e8', width: 1, intensity: 1 };
+
+const hexOf = encoded => `#${encoded.map(channel => Math.round(channel * 255).toString(16).padStart(2, '0')).join('')}`;
+const channelsOf = hex => [1, 3, 5].map(offset => parseInt(hex.slice(offset, offset + 2), 16));
+const largestLevelGap = (first, second) => Math.max(...channelsOf(first).map((level, channel) => Math.abs(level - channelsOf(second)[channel])));
+
+function environmentFor(sky, extra = {}) {
+ return normalizeAgentLook({ environment: { world: true, sky: { type: 'gradient', stops: STOPS, ...sky }, ...extra } }).environment;
+}
+
+// What the frame shows for one map row: the radiance the map holds, times its strength, through the view transform and the display power.
+function shownHex(map, elevation, viewTransform = 'aces') {
+ const row = Math.min(map.height - 1, Math.floor((90 - elevation) / 180 * map.height));
+ const offset = row * map.width * 3;
+ const radiance = [...map.data.slice(offset, offset + 3)].map(channel => channel * map.intensity);
+ return hexOf(displayColor(radiance, { viewTransform }));
+}
+
+test('the aces inverse returns the channel it was given for the whole 0 to 1 range', () => {
+ for (let level = 0; level <= 255; level++) {
+ assert.ok(Math.abs(acesChannel(inverseAcesChannel(level / 255)) - level / 255) < 1e-9, `level ${level}`);
+ }
+ assert.ok(Number.isFinite(inverseAcesChannel(1)));
+ assert.equal(inverseAcesChannel(-3), 0);
+});
+
+test('a hex goes through the inverse and the display path and comes back as the same hex', () => {
+ const hexes = ['#0e5d73', '#127285', '#1a8a9c', '#19d0e8', '#000000', '#ffffff', '#808080', '#ff3a10', '#fefefe'];
+ for (const hex of hexes) {
+ assert.equal(hexOf(displayColor(radianceFromHex(hex, 'aces'), { viewTransform: 'aces' })), hex);
+ }
+ for (const hex of ['#0e5d73', '#127285', '#1a8a9c', '#19d0e8', '#808080']) {
+ assert.ok(largestLevelGap(hexOf(displayColor(radianceFromHex(hex, 'neutral'), { viewTransform: 'neutral' })), hex) <= 1, `neutral ${hex}`);
+ }
+});
+
+test('colours the transform cannot show land on the nearest one and report the gap', () => {
+ const saturatedRed = [1, 0.23, 0.06];
+ const unreachable = radianceForDisplayColor(saturatedRed, 'neutral');
+ assert.ok(unreachable.radiance.every(Number.isFinite));
+ assert.ok(unreachable.error > 0.01, 'neutral desaturates a saturated red, so no radiance shows it');
+ assert.equal(radianceForDisplayColor([0.2, 0.4, 0.5], 'aces').error, 0);
+});
+
+test('the gradient shows the requested hex at the horizon, the middle stop, the zenith and the glow peak', () => {
+ const map = agentEnvironmentMap(environmentFor({ horizonGlow: GLOW }));
+ assert.equal(shownHex(map, 0), GLOW.color);
+ assert.equal(shownHex(map, 89.9), '#0e5d73');
+ assert.ok(largestLevelGap(shownHex(map, 40.5), '#127285') <= 2);
+ assert.ok(largestLevelGap(shownHex(map, 20), '#1a8a9c') > 2, 'the band fades into the gradient above the glow');
+ const plain = agentEnvironmentMap(environmentFor({}));
+ assert.equal(shownHex(plain, 0), '#1a8a9c');
+ assert.equal(shownHex(plain, -30), '#1a8a9c');
+});
+
+test('the hex holds under the neutral view transform and a different environment strength', () => {
+ const map = agentEnvironmentMap(environmentFor({ horizonGlow: GLOW }, { viewTransform: 'neutral', environmentIntensity: 2 }));
+ assert.equal(map.intensity, 2);
+ assert.ok(largestLevelGap(shownHex(map, 0, 'neutral'), GLOW.color) <= 2);
+ assert.ok(largestLevelGap(shownHex(map, 89.9, 'neutral'), '#0e5d73') <= 2);
+});
+
+test('glow intensity above 1 brightens the band and the fog colour follows the compensated horizon', () => {
+ const bright = agentEnvironmentMap(environmentFor({ horizonGlow: { ...GLOW, intensity: 2 } }));
+ const normal = agentEnvironmentMap(environmentFor({ horizonGlow: GLOW }));
+ assert.ok(bright.data[256 * bright.width * 3 + 1] > normal.data[256 * normal.width * 3 + 1] * 1.9);
+ const environment = environmentFor({});
+ assert.deepEqual(environment.fogColor, radianceFromHex('#1a8a9c', 'aces'));
+});
+
+test('stops blend in OKLab, so black to white passes through the perceptual middle grey', () => {
+ const map = agentEnvironmentMap(environmentFor({ stops: [{ at: 0, color: '#000000' }, { at: 1, color: '#ffffff' }] }));
+ assert.ok(largestLevelGap(shownHex(map, 45), '#636363') <= 2);
+});
diff --git a/tests/gradient-sky.test.js b/tests/gradient-sky.test.js
index ae1b1416..5cc3ca1d 100644
--- a/tests/gradient-sky.test.js
+++ b/tests/gradient-sky.test.js
@@ -4,7 +4,7 @@ import assert from 'node:assert/strict';
import { createAgentScene } from '../src/agent-scene.js';
import { agentSceneModulesNeeded } from '../src/agent-scene-modules.js';
import { agentEnvironmentMap, normalizeAgentLook } from '../src/agent-look.js';
-import { linearColorFromHex } from '../src/gradient-sky.js';
+import { radianceFromHex } from '../src/gradient-sky.js';
const TEAL_STOPS = [{ at: 0, color: '#1a8a9c' }, { at: 1, color: '#0e5d73' }];
const GLOW = { color: '#19d0e8', width: 3, intensity: 1 };
@@ -23,15 +23,15 @@ test('a gradient sky loads the sky code, keeps the sun and sets the sky colours'
assert.ok(agentSceneModulesNeeded({ environment: { sky: { type: 'gradient' } } }).includes('physicalSky'));
const environment = gradientEnvironment({});
assert.deepEqual(environment.lightDirection, [-3, 6, 4]);
- assert.deepEqual(environment.skyBottom, linearColorFromHex('#1a8a9c'));
- assert.deepEqual(environment.skyTop, linearColorFromHex('#0e5d73'));
+ assert.deepEqual(environment.skyBottom, radianceFromHex('#1a8a9c'));
+ assert.deepEqual(environment.skyTop, radianceFromHex('#0e5d73'));
});
test('the map runs from the horizon colour to the zenith colour', () => {
const map = agentEnvironmentMap(gradientEnvironment({}, { world: true }));
assert.equal(map.showBackground, true);
- const zenith = linearColorFromHex('#0e5d73');
- const nearHorizon = linearColorFromHex('#1a8a9c');
+ const zenith = radianceFromHex('#0e5d73');
+ const nearHorizon = radianceFromHex('#1a8a9c');
mapPixel(map, 89.8).forEach((value, channel) => assert.ok(Math.abs(value - zenith[channel]) < 0.01));
mapPixel(map, 0.2).forEach((value, channel) => assert.ok(Math.abs(value - nearHorizon[channel]) < 0.02));
assert.equal(agentEnvironmentMap(gradientEnvironment({}, { world: true })), map);
@@ -40,10 +40,10 @@ test('the map runs from the horizon colour to the zenith colour', () => {
test('the horizon glow is a band: bright at the horizon and gone well above it', () => {
const map = agentEnvironmentMap(gradientEnvironment({ horizonGlow: GLOW }));
const plain = agentEnvironmentMap(gradientEnvironment({}));
- const glowColor = linearColorFromHex(GLOW.color);
- const [atHorizon, high] = [mapPixel(map, 0.2), mapPixel(map, 30)];
+ const glowColor = radianceFromHex(GLOW.color);
+ const [atHorizon, high] = [mapPixel(map, 0), mapPixel(map, 30)];
atHorizon.forEach((value, channel) => assert.ok(Math.abs(value - glowColor[channel] * GLOW.intensity) < 0.02));
- assert.ok(atHorizon[1] > mapPixel(plain, 0.2)[1] + 0.2);
+ assert.ok(atHorizon[1] > mapPixel(plain, 0)[1] + 0.2);
// Hue is kept: the band is the glow colour scaled, so the red to green ratio of the peak is the glow's, not the sky's.
assert.ok(Math.abs(atHorizon[0] / atHorizon[1] - glowColor[0] / glowColor[1]) < 0.02);
assert.ok(Math.abs(high[1] - mapPixel(plain, 30)[1]) < 1e-4);