Skip to content

3D engine that AI agents drive

Add a gradient sky with a horizon glow band (#2038)

Nguyen Xuan Anc5f66e923a07
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.yml
index 5f31dc44..9f979c3b 100644
--- a/.github/workflows/cook-addon.yml
+++ b/.github/workflows/cook-addon.yml
@@ -284,6 +284,7 @@ on:
- 'src/path-tracer-webgpu-medium.js'
- 'src/path-tracer-webgpu.js'
- 'src/path-tracer.js'
+ - 'src/gradient-sky.js'
- 'src/physical-sky.js'
- 'src/physics-boat.js'
- 'src/physics-buoyancy.js'
diff --git a/changes/2038.md b/changes/2038.md
new file mode 100644
index 00000000..ff1b29ec
--- /dev/null
+++ b/changes/2038.md
@@ -0,0 +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)
diff --git a/changes/2038.size.md b/changes/2038.size.md
new file mode 100644
index 00000000..eb908933
--- /dev/null
+++ b/changes/2038.size.md
@@ -0,0 +1,3 @@
+- 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.
diff --git a/docs/agent-look.md b/docs/agent-look.md
index 0f961d04..84a71f22 100644
--- a/docs/agent-look.md
+++ b/docs/agent-look.md
@@ -124,6 +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). 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/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 753e222a..e675602b 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -315,7 +315,7 @@ const environment = z.strictObject({
resolveCoplanar: z.union([z.literal('offset'), z.literal(false)]).optional().describe("Flush faces are ranked at draw time by default ('offset'); false opts out."),
viewTransform: z.enum(VIEW_TRANSFORM_NAMES).optional().describe('Display transform, for example agx to compare with Blender.'),
look: z.union([z.enum([...LOOK_NAMES, ...BUNDLED_CUBE_LOOK_NAMES]), z.string().regex(CATALOG_FILE_ID)]).nullable().optional().describe('Look preset or .cube; scene_capabilities catalogLooks. null clears.'),
- sky: z.record(z.string(), z.unknown()).nullable().optional().describe('Physical sky: {type:"physical", sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective}; sets key light, sky and fog. Fields in scene_capabilities physicalSky.'),
+ sky: z.record(z.string(), z.unknown()).nullable().optional().describe('Physical sky: {type:"physical", sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective}; sets key light, sky and fog. Or {type:"gradient", stops:[{at,color}], horizonGlow:{color,width,intensity}}. Fields in scene_capabilities physicalSky, gradientSky.'),
wind: z.strictObject({ strength: bounded(0, 4).optional(), direction: bounded(-360, 360).optional().describe('Degrees: 0 toward +x, 90 toward +z.') }).optional().describe('Sway of foliage and grass materials; strength defaults to 0.3.'),
});
// Every tool lists the same short environment; the full schema is served by scene_capabilities topic environment.
diff --git a/skills/build-crucible-scene/references/look.md b/skills/build-crucible-scene/references/look.md
index 5075ea6e..e7e5ea5d 100644
--- a/skills/build-crucible-scene/references/look.md
+++ b/skills/build-crucible-scene/references/look.md
@@ -35,6 +35,8 @@ 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": "#7ff4ff", "width": 2.5, "intensity": 1.3 } }` 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.
+
## HDRI from the catalog
Call `scene_asset_catalog` (no arguments). It lists two shipped HDRIs, `sky-clouds` and `studio-softbox`, two shipped
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 3835587d..d69f4bf0 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -301,7 +301,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
gltfImport: 'Optional extensions and line primitives load with a warning; unlit and punctual lights are read.',
authoredLook: true, maxPointLights: MAX_POINT_LIGHTS,
catalogLooks: Object.freeze({ hdri: 'environment.hdri', hdris: BUNDLED_ENVIRONMENT_NAMES, cubeLooks: BUNDLED_CUBE_LOOK_NAMES, look: 'environment.look', catalogId: '64-hex ID of a .hdr or .cube in scene_asset_catalog', note: 'environmentIntensity and environmentRotation apply; keyIntensity 0 if the HDRI has a sun' }),
- physicalSky: 'environment.sky {type:physical, preset: golden-hour|sunset|blue-hour, sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective} drives key, sky, fog; a low sun warms them',
+ physicalSky: 'environment.sky {type:physical, preset: golden-hour|sunset|blue-hour, sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective} drives key, sky, fog; a low sun warms them; type:gradient {stops:[{at,color}], horizonGlow:{color,width,intensity}} only picks colours',
lightingSetups: LIGHTING_SETUP_NAMES,defaultLightingSetup: DEFAULT_LIGHTING_SETUP,
ambientOcclusion: Object.freeze({ default: DEFAULT_AMBIENT_OCCLUSION, defaultRadius: 0.5, off: 0 }),
// Local lights: spot and rectangular area lights. Shadows share one 2048 x 3072 depth atlas of 24 tiles; a shadowed
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index b09e8e65..089d6697 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -103,7 +103,7 @@ const MODULE_MARKERS = {
coplanar: ['"resolveCoplanar"', '"asset":{'],
// A closed room a sun lights gets the floor sky trace by default. The recipe text can not say whether a room is closed, so a recipe that names its sun loads it and the module skips an open scene.
floorSky: ['"keyColor"', '"keyIntensity"'],
- physicalSky: ['"type":"physical"'],
+ physicalSky: ['"type":"physical"', '"type":"gradient"'],
userPass: ['"postPasses"'],
game: ['"game":{', '"set-game"'],
materialSnippet: ['"snippet":{'],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 70258db9..61ac5478 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -2178,7 +2178,11 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
merged[nestedField] = { ...candidate[lookField][nestedField], ...patch[nestedField] };
}
// A preset starts the sky again from its own sun, so fields kept from the earlier sky never hide it.
- if (patch.sky) merged.sky = { ...!patch.sky.preset && candidate[lookField].sky, type: 'physical', ...patch.sky };
+ if (patch.sky) {
+ const kept = candidate[lookField].sky;
+ const type = patch.sky.type ?? kept?.type ?? 'physical';
+ merged.sky = { ...!patch.sky.preset && kept?.type === type && kept, type, ...patch.sky };
+ }
candidate[lookField] = merged;
continue;
}
diff --git a/src/gradient-sky.js b/src/gradient-sky.js
new file mode 100644
index 00000000..453db676
--- /dev/null
+++ b/src/gradient-sky.js
@@ -0,0 +1,151 @@
+import { createEnvironmentMap } from './environment.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
+// environment map that lights the scene and the water reflection, so the three always agree. The sun, the key light and the
+// haze stay as the lighting setup or the recipe set them.
+
+export const GRADIENT_SKY_FIELDS = Object.freeze(['type', 'stops', 'horizonGlow']);
+export const HORIZON_GLOW_FIELDS = Object.freeze(['color', 'width', 'intensity']);
+export const MAXIMUM_GRADIENT_STOPS = 8;
+
+const GLOW_DEFAULTS = Object.freeze({ width: 6, intensity: 1 });
+const GLOW_LIMITS = Object.freeze({
+ width: [0.5, 45, 'the glow half width in degrees of elevation, such as 6'],
+ intensity: [0, 20, 'a brightness multiplier from 0 to 20, such as 2'],
+});
+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;
+
+function checkedColor(value, field, fail) {
+ if (typeof value !== 'string' || !HEX_COLOR.test(value)) {
+ throw fail(field, value, COLOR_EXAMPLE);
+ }
+ return value.toLowerCase();
+}
+
+function resolveStops(stops, fail) {
+ if (!Array.isArray(stops) || stops.length < 1 || stops.length > MAXIMUM_GRADIENT_STOPS) {
+ throw fail('environment.sky.stops', stops, `a list of 1 to ${MAXIMUM_GRADIENT_STOPS} stops, such as [{ "at": 0, "color": "#1a8a9c" }, { "at": 1, "color": "#0e5d73" }]`);
+ }
+ let previousAt = -Infinity;
+ return stops.map((stop, index) => {
+ const field = `environment.sky.stops[${index}]`;
+ const unknown = stop && typeof stop === 'object' ? Object.keys(stop).find(key => key !== 'at' && key !== 'color') : 'stop';
+ if (unknown !== undefined) {
+ throw fail(field, unknown === 'stop' ? stop : unknown, 'an object with at (0 at the horizon to 1 at the zenith) and color');
+ }
+ if (!Number.isFinite(stop.at) || stop.at < 0 || stop.at > 1 || stop.at <= previousAt) {
+ throw fail(`${field}.at`, stop.at, 'a number from 0 (horizon) to 1 (zenith), larger than the stop before it');
+ }
+ previousAt = stop.at;
+ return { at: stop.at, color: checkedColor(stop.color, `${field}.color`, fail) };
+ });
+}
+
+function resolveHorizonGlow(glow, fail) {
+ if (!glow || typeof glow !== 'object' || Array.isArray(glow)) {
+ throw fail('environment.sky.horizonGlow', glow, `an object with color (${COLOR_EXAMPLE}), width and intensity`);
+ }
+ const unknown = Object.keys(glow).find(key => !HORIZON_GLOW_FIELDS.includes(key));
+ if (unknown !== undefined) {
+ throw fail('environment.sky.horizonGlow', unknown, `the fields ${HORIZON_GLOW_FIELDS.join(', ')}`);
+ }
+ const resolved = { color: checkedColor(glow.color, 'environment.sky.horizonGlow.color', fail) };
+ for (const [field, [minimum, maximum, example]] of Object.entries(GLOW_LIMITS)) {
+ const value = glow[field] ?? GLOW_DEFAULTS[field];
+ if (!Number.isFinite(value) || value < minimum || value > maximum) {
+ throw fail(`environment.sky.horizonGlow.${field}`, value, `a number from ${minimum} to ${maximum}, ${example}`);
+ }
+ resolved[field] = value;
+ }
+ return resolved;
+}
+
+/** Checks and normalizes a gradient sky; `fail` builds the error for a field, a value and what is accepted. */
+export function resolveGradientSky(input, fail) {
+ const unknown = Object.keys(input).find(key => !GRADIENT_SKY_FIELDS.includes(key));
+ if (unknown !== undefined) {
+ throw fail('environment.sky', unknown, `type 'gradient' with fields ${GRADIENT_SKY_FIELDS.slice(1).join(', ')}`);
+ }
+ const resolved = { type: 'gradient', stops: resolveStops(input.stops, fail) };
+ if (input.horizonGlow !== undefined && input.horizonGlow !== null) {
+ resolved.horizonGlow = resolveHorizonGlow(input.horizonGlow, fail);
+ }
+ return resolved;
+}
+
+function srgbChannelToLinear(channel) {
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
+}
+
+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);
+ 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 });
+}
+
+function stopColorsInLinear(sky) {
+ return sky.stops.map(stop => ({ at: stop.at, color: linearColorFromHex(stop.color) }));
+}
+
+function colorAtHeight(stops, height) {
+ if (height <= stops[0].at) {
+ return stops[0].color;
+ }
+ 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 stops[stops.length - 1].color;
+}
+
+function buildMapData(sky) {
+ const stops = stopColorsInLinear(sky);
+ const glow = sky.horizonGlow;
+ const glowColor = glow ? linearColorFromHex(glow.color) : null;
+ 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.
+ const elevation = 90 - ((row + 0.5) / MAP_HEIGHT) * 180;
+ const base = colorAtHeight(stops, Math.max(0, elevation) / 90);
+ const glowShare = glow ? glow.intensity * Math.exp(-((elevation / glow.width) ** 2)) : 0;
+ for (let column = 0; column < MAP_WIDTH; column++) {
+ const offset = (row * MAP_WIDTH + column) * 3;
+ for (let channel = 0; channel < 3; channel++) {
+ data[offset + channel] = base[channel] + (glowColor ? glowColor[channel] * glowShare : 0);
+ }
+ }
+ }
+ return data;
+}
+
+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]);
+ 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 }));
+ }
+ return mapsByKey.get(key);
+}
diff --git a/src/physical-sky.js b/src/physical-sky.js
index a8d428e1..484c0c96 100644
--- a/src/physical-sky.js
+++ b/src/physical-sky.js
@@ -1,4 +1,5 @@
import { createEnvironmentMap } from './environment.js';
+import { applyGradientSky, createGradientSkyMap } from './gradient-sky.js';
// environment.sky { type: 'physical' }: a clear-sky model driven by the sun alone. It is an analytic single-scattering
// approximation (Rayleigh and Henyey-Greenstein aerosol, Kasten-Young air mass), not the Nishita integration Blender uses.
@@ -50,7 +51,7 @@ const LOW_SUN_KEY_BOOST = 1.2;
export function resolvePhysicalSky(input, fail) {
const unknown = Object.keys(input).filter(key => key !== 'preset' && !PHYSICAL_SKY_FIELDS.includes(key));
if (unknown.length > 0 || input.type !== 'physical') {
- throw fail('environment.sky', input.type !== 'physical' ? input.type : unknown[0], `type 'physical' with fields ${[...PHYSICAL_SKY_FIELDS.slice(1), 'preset'].join(', ')}`);
+ throw fail('environment.sky', input.type !== 'physical' ? input.type : unknown[0], `type 'physical' or 'gradient'; physical takes fields ${[...PHYSICAL_SKY_FIELDS.slice(1), 'preset'].join(', ')}`);
}
if (input.preset !== undefined && !Object.hasOwn(PHYSICAL_SKY_PRESETS, input.preset)) {
throw fail('environment.sky.preset', input.preset, `one of ${PHYSICAL_SKY_PRESET_NAMES.join(', ')}`);
@@ -173,8 +174,15 @@ export function physicalSkyFields(sky) {
return fields;
}
-/** A physical sky owns the sun and the haze: its key light, background gradient and aerial perspective replace those fields. */
+/**
+ * A physical sky owns the sun and the haze: its key light, background gradient and aerial perspective replace those fields.
+ * A `type: 'gradient'` sky takes the same entry point and only supplies the sky colours.
+ */
export function applyPhysicalSky(input, environment, fail) {
+ if (input.type === 'gradient') {
+ applyGradientSky(input, environment, fail);
+ return;
+ }
const sky = resolvePhysicalSky(input, fail);
const { aerialDensity, ...fields } = physicalSkyFields(sky);
Object.assign(environment, fields, { sky, fogDensity: aerialDensity });
@@ -228,7 +236,11 @@ function buildMapData(sky) {
}
/** The environment map of a physical sky; the same object returns while sky, strength, rotation and background hold. */
-export function createPhysicalSkyMap({ sky, environmentIntensity: intensity, environmentRotation: rotation, world: showBackground }) {
+export function createPhysicalSkyMap(environment) {
+ if (environment.sky.type === 'gradient') {
+ return createGradientSkyMap(environment);
+ }
+ const { sky, environmentIntensity: intensity, environmentRotation: rotation, world: showBackground } = environment;
const key = [...PHYSICAL_SKY_FIELDS.slice(1).map(field => sky[field]), intensity, rotation, showBackground].join('|');
if (!mapsByKey.has(key)) {
if (mapsByKey.size >= MAXIMUM_CACHED_MAPS) {
diff --git a/tests/gradient-sky.test.js b/tests/gradient-sky.test.js
new file mode 100644
index 00000000..8fd2d17a
--- /dev/null
+++ b/tests/gradient-sky.test.js
@@ -0,0 +1,73 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+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';
+
+const TEAL_STOPS = [{ at: 0, color: '#1a8a9c' }, { at: 1, color: '#0e5d73' }];
+const GLOW = { color: '#7ff4ff', width: 3, intensity: 2 };
+
+function gradientEnvironment(sky, extra = {}) {
+ return normalizeAgentLook({ environment: { sky: { type: 'gradient', stops: TEAL_STOPS, ...sky }, ...extra } }).environment;
+}
+
+function mapPixel(map, elevationDegrees) {
+ const row = Math.min(map.height - 1, Math.floor((90 - elevationDegrees) / 180 * map.height));
+ const offset = row * map.width * 3;
+ return [...map.data.slice(offset, offset + 3)];
+}
+
+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'));
+});
+
+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');
+ 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);
+});
+
+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)];
+ assert.ok(atHorizon[0] > mapPixel(plain, 0.2)[0] + glowColor[0] * 1.5);
+ assert.ok(atHorizon[2] > glowColor[2] * 1.5);
+ assert.ok(Math.abs(high[1] - mapPixel(plain, 30)[1]) < 1e-4);
+ assert.ok(map.data.every(Number.isFinite));
+});
+
+test('stops and glow are checked with messages that say what to pass', () => {
+ assert.throws(() => gradientEnvironment({ stops: [] }), /environment\.sky\.stops.*1 to 8/s);
+ const nine = Array.from({ length: 9 }, (_, index) => ({ at: index / 8, color: '#102030' }));
+ assert.throws(() => gradientEnvironment({ stops: nine }), /environment\.sky\.stops/);
+ assert.throws(() => gradientEnvironment({ stops: [{ at: 0.5, color: '#102030' }, { at: 0.5, color: '#102030' }] }), /stops\[1\]\.at.*larger than the stop before/s);
+ assert.throws(() => gradientEnvironment({ stops: [{ at: 1.5, color: '#102030' }] }), /stops\[0\]\.at/);
+ assert.throws(() => gradientEnvironment({ stops: [{ at: 0, color: 'teal' }] }), /stops\[0\]\.color.*hex colour/s);
+ assert.throws(() => gradientEnvironment({ horizonGlow: { color: '#7ff4ff', width: 0 } }), /horizonGlow\.width.*0\.5 to 45/s);
+ assert.throws(() => gradientEnvironment({ horizonGlow: { width: 3 } }), /horizonGlow\.color/);
+ assert.throws(() => gradientEnvironment({ horizonGlow: { color: '#7ff4ff', spread: 3 } }), /horizonGlow.*spread/s);
+ assert.throws(() => gradientEnvironment({ sunElevation: 10 }), /environment\.sky.*sunElevation/s);
+});
+
+test('set-environment switches between a physical and a gradient sky and edits one gradient field', () => {
+ const session = createAgentScene({ format: 'crucible.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [],
+ environment: { sky: { type: 'physical', sunElevation: 60 } } });
+ session.apply([{ type: 'set-environment', environment: { sky: { type: 'gradient', stops: TEAL_STOPS } } }], { expectedRevision: 0 });
+ assert.equal(session.environment.sky.type, 'gradient');
+ assert.equal(session.environment.sky.sunElevation, undefined);
+ session.apply([{ type: 'set-environment', environment: { sky: { horizonGlow: GLOW } } }], { expectedRevision: 1 });
+ assert.equal(session.environment.sky.horizonGlow.color, '#7ff4ff');
+ assert.equal(session.environment.sky.stops.length, 2);
+});