diff --git a/src/app/features/scene/ridge/lightCards.test.ts b/src/app/features/scene/ridge/lightCards.test.ts index f9144a2c..adf3030a 100644 --- a/src/app/features/scene/ridge/lightCards.test.ts +++ b/src/app/features/scene/ridge/lightCards.test.ts @@ -103,18 +103,18 @@ describe('the lighting inputs', () => { it("takes the display of the sky's own fit, so terrain and sky share one exposure", () => { const l = lightingOf(manifest, sky(30)); expect([l.exposure, l.curve]).toEqual([12, LIFT_ONLY]); - expect(l.ambient).toEqual([0.1, 0.2, 0.3]); + [0.1, 0.2, 0.3].forEach((a, i) => expect(l.key.ambient[i]).toBeCloseTo(a, 6)); // plus the airglow's expect(l.logDMin).toBe(4.6); expect(l.logDSpan).toBeCloseTo(11.5 - 4.6, 12); }); it("gives the ground the sun's transmittance at its elevation, and none with the sun below the atmosphere's cut-off", () => { const l = lightingOf(manifest, sky(30)); - expect(l.sunTransmittance[0]).toBeCloseTo(0.9 * Math.sin(30 * RAD), 12); - expect(l.sunTransmittance[2]).toBeCloseTo(0.7 * Math.sin(30 * RAD), 12); - expect(lightingOf(manifest, sky(DEFAULT_LOOK.sunCutoffDeg - 1)).sunTransmittance).toEqual([0, 0, 0]); + expect(l.key.direct[0]).toBeCloseTo(0.9 * Math.sin(30 * RAD), 12); + expect(l.key.direct[2]).toBeCloseTo(0.7 * Math.sin(30 * RAD), 12); + expect(lightingOf(manifest, sky(DEFAULT_LOOK.sunCutoffDeg - 1)).key.direct).toEqual([0, 0, 0]); expect( - lightingOf(manifest, sky(DEFAULT_LOOK.sunCutoffDeg + 0.5)).sunTransmittance[0] + lightingOf(manifest, sky(DEFAULT_LOOK.sunCutoffDeg + 0.5)).key.direct[0] ).toBeGreaterThanOrEqual(0); }); @@ -137,9 +137,9 @@ describe('the lighting inputs', () => { const above = Math.floor((horizonRow / planeH) * SKY_LUT.h) - 6; expect(texel(0, above)[0]).toBeCloseTo( Math.sin(((horizonRow - rowAt(above)) / pxPerDegV) * RAD), - 9 + 7 // the airglow floor adds a few 1e-9 ); - expect(texel(0, SKY_LUT.h - 1)[0]).toBe(0); + expect(texel(0, SKY_LUT.h - 1)[0]).toBeCloseTo(0, 7); // The sun lies at 214 degrees, the middle of the window: the cosine from the sun is 1 there and falls to the sides. const mid = texel(SKY_LUT.w / 2, above)[1]; expect(mid).toBeGreaterThan(0.999); @@ -245,9 +245,9 @@ describe('the look reaches the shader', () => { const base = run(); const look = run({ hazeScale: 2 * DEFAULT_LOOK.hazeScale, ambientScale: 0.5 }); look.uExt.forEach((e, k) => expect(e).toBeCloseTo(2 * base.uExt[k], 12)); - expect(look.uAmbient[2]).toBeCloseTo(0.15, 12); + expect(look.uAmbient[2]).toBeCloseTo(0.15, 6); // plus the airglow's ambient expect( - lightingOf(manifest, sky30(), { ...DEFAULT_LOOK, sunCutoffDeg: 45 }).sunTransmittance + lightingOf(manifest, sky30(), { ...DEFAULT_LOOK, sunCutoffDeg: 45 }).key.direct ).toEqual([0, 0, 0]); }); }); @@ -265,33 +265,48 @@ function sky30(): PhysicalSky { } as unknown as PhysicalSky; } -describe('night ambient', () => { - const nightAtm = { +describe('night key light', () => { + const atmOf = (ambient: [number, number, number]) => ({ observerKm: 0.183, mieScale: 1, transmittanceToSpace: (_m: number, o: number[]) => o.fill(1), - irradiance: { direct: [0, 0, 0], ambient: [0.001, 0.001, 0.002] }, + irradiance: { direct: [0, 0, 0], ambient }, radiance: (_a: number, _b: number, o: number[]) => o.fill(0), - }; - const night = (state: string, nightAmbient?: [number, number, number]) => - lightingOf( - manifest, - { - state, - sun: { azimuth: 0, elevation: -30 }, - atm: nightAtm, - fit: { display: { exposure: 1, curve: LIFT_ONLY } }, - view: manifest.view, - } as unknown as PhysicalSky, - nightAmbient ? { ...DEFAULT_LOOK, nightAmbient } : DEFAULT_LOOK - ); - it('lights the ground at night, cool, and only at night', () => { - const n = night('night'); - const base = nightAtm.irradiance.ambient; - n.ambient.forEach((a, i) => expect(a).toBeGreaterThan(base[i])); - expect(n.ambient[2] - base[2]).toBeGreaterThan(n.ambient[0] - base[0]); - expect(night('dusk').ambient).toEqual(base); - expect(DEFAULT_LOOK.nightAmbient.every((c) => c > 0)).toBe(true); + }); + const night = (moonEl: number | undefined, state = 'night') => + lightingOf(manifest, { + state, + sun: { azimuth: 0, elevation: -30 }, + moon: { azimuth: 150, elevation: moonEl ?? -20 }, + night: + moonEl === undefined + ? {} + : { moon: { azimuth: 150, elevation: moonEl, ratio: 2.5e-6, atm: atmOf([0.4, 0.5, 0.8]) } }, + atm: atmOf([0.001, 0.001, 0.002]), + fit: { display: { exposure: 1, curve: LIFT_ONLY } }, + view: manifest.view, + } as unknown as PhysicalSky); + + it('is the moon at night: its direction, its irradiance ratio times the transmittance, its ambient scaled by the ratio', () => { + const l = night(40); + expect([l.key.azimuth, l.key.elevation]).toEqual([150, 40]); + expect(l.key.direct[0]).toBeCloseTo(2.5e-6, 12); + expect(l.key.ambient[2]).toBeGreaterThan(0.002); + expect(l.key.ambient[2]).toBeCloseTo(0.002 + 0.8 * 2.5e-6, 4); + }); + it('has no direct light with the moon down, and keeps the ambient (twilight and airglow)', () => { + const l = night(undefined); + expect(l.key.direct).toEqual([0, 0, 0]); + expect(l.key.ambient.every((a) => a > 0)).toBe(true); + }); + it('fades the moon out over the horizon', () => { + expect(night(-0.5).key.direct[0]).toBe(0); + expect(night(0.5).key.direct[0]).toBeGreaterThan(0); + expect(night(0.5).key.direct[0]).toBeLessThan(night(5).key.direct[0]); + }); + it('the sun lights the other states', () => { + const l = lightingOf(manifest, sky30()); + expect(l.key.elevation).toBe(30); }); }); diff --git a/src/app/features/scene/ridge/lightCards.ts b/src/app/features/scene/ridge/lightCards.ts index 29745834..5ffbd6fc 100644 --- a/src/app/features/scene/ridge/lightCards.ts +++ b/src/app/features/scene/ridge/lightCards.ts @@ -12,7 +12,8 @@ import { extinctionAt } from './earthAtmosphere'; import type { Vec3 } from './earthAtmosphere'; import type { RidgeManifest } from './manifest'; import type { PhysicalSky } from './physicalSky'; -import { ACES_FIT, ACES_IN, ACES_OUT, KNOTS } from './toneMap'; +import { addNightRadiance, airglow } from './nightSky'; +import { ACES_FIT, ACES_IN, ACES_OUT, KNOTS, SCOTOPIC } from './toneMap'; import type { Curve } from './toneMap'; import type { View } from './view'; @@ -71,8 +72,6 @@ export interface RidgeLook { groundNoise: number; /** Low-frequency noise darkening of the direct sun (static). 0 = none. */ cloudShadows: number; - /** Night's moonlight on the ground: the radiance of a white card in it (rgb, at the night exposure, before the curve); added only in the night state, where the atmosphere gives the ground none. A dim cool value. */ - nightAmbient: readonly [number, number, number]; /** Cel shading: the lit side of the relief (n.s) in this many flat bands instead of Lambert's ramp (0 = Lambert; at most `CEL_MAX`). */ celBands: number; /** Width of each band edge in n.s units (0 = hard). */ @@ -102,7 +101,6 @@ export const PHYSICAL_LOOK: RidgeLook = { inkScale: 1, groundNoise: 0, cloudShadows: 0, - nightAmbient: [0.5, 0.66, 1.1], celBands: 0, celSoftness: 0, celAmbientAway: 1, @@ -192,12 +190,54 @@ export interface Lighting { logDSpan: number; /** Per km of horizontal path, per channel. */ extinction: Vec3; - /** The sun's transmittance to the ground, per channel; zero with the sun below the atmosphere's cut-off. */ - sunTransmittance: Vec3; - ambient: Vec3; + /** Where the key light is (the sun by day and dusk, the moon at night) and what of it reaches the ground. */ + key: KeyLight; exposure: number; /** The sky's fitted curve (`toneMap.ts`), applied per channel after ACES. */ curve: Curve; + /** Weight of the scotopic grade (`toneMap.ts`), applied to the radiance before exposure. */ + grade: number; +} + +/** + * The key light of the ground and what it brings. Day and dusk: the sun, by its transmittance to the ground, cut off below `look.sunCutoffDeg`. + * Night: the moon, by its transmittance times its irradiance relative to the sun's (phase and distance, `nightSky.ts`), faded out over the + * horizon; it is the direction the cel bands are cut by, and what is left of it, the sun's twilight and the airglow, is the ambient. + * `direct` is per unit of sun irradiance, `ambient` the irradiance the sky and the airglow give a horizontal surface. + */ +export interface KeyLight { + azimuth: number; + elevation: number; + direct: Vec3; + ambient: Vec3; +} + +export function keyLight(sky: PhysicalSky, look: RidgeLook = DEFAULT_LOOK): KeyLight { + const ambient = scale3(sky.atm.irradiance.ambient, look.ambientScale); + const glow = [0, 0, 0]; + airglow(0.6, glow); + const base = add3(ambient, scale3([glow[0], glow[1], glow[2]], Math.PI)); + const trans = [0, 0, 0]; + if (sky.state === 'night') { + const m = sky.night.moon; + if (!m) return { azimuth: sky.moon.azimuth, elevation: sky.moon.elevation, direct: [0, 0, 0], ambient: base }; + m.atm.transmittanceToSpace(Math.max(Math.sin(m.elevation * RAD), 0), trans); + const fade = smooth(-0.5, 1.5, m.elevation) * m.ratio; + return { + azimuth: m.azimuth, + elevation: m.elevation, + direct: [trans[0] * fade, trans[1] * fade, trans[2] * fade], + ambient: add3(base, scale3(scale3(m.atm.irradiance.ambient, look.ambientScale), m.ratio)), + }; + } + sky.atm.transmittanceToSpace(Math.max(Math.sin(sky.sun.elevation * RAD), 0), trans); + const lit = sky.sun.elevation > look.sunCutoffDeg; + return { + azimuth: sky.sun.azimuth, + elevation: sky.sun.elevation, + direct: lit ? [trans[0], trans[1], trans[2]] : [0, 0, 0], + ambient: base, + }; } const scale3 = (v: Vec3, k: number): Vec3 => [v[0] * k, v[1] * k, v[2] * k]; @@ -208,23 +248,16 @@ export function lightingOf( sky: PhysicalSky, look: RidgeLook = DEFAULT_LOOK ): Lighting { - const trans = [0, 0, 0]; - const sinEl = Math.sin(sky.sun.elevation * RAD); - sky.atm.transmittanceToSpace(Math.max(sinEl, 0), trans); - const lit = sky.sun.elevation > look.sunCutoffDeg; return { planeW: manifest.view.planeW, planeH: manifest.view.planeH, logDMin: manifest.encoding.logDMin, logDSpan: manifest.encoding.logDMax - manifest.encoding.logDMin, extinction: scale3(extinctionAt(sky.atm.observerKm, sky.atm.mieScale), look.hazeScale), - sunTransmittance: lit ? [trans[0], trans[1], trans[2]] : [0, 0, 0], - ambient: add3( - scale3(sky.atm.irradiance.ambient, look.ambientScale), - sky.state === 'night' ? scale3(look.nightAmbient as Vec3, Math.PI) : [0, 0, 0] - ), + key: keyLight(sky, look), exposure: sky.fit.display.exposure, curve: sky.fit.display.curve, + grade: sky.fit.display.grade ?? 0, }; } @@ -250,6 +283,7 @@ export function skyLut(sky: PhysicalSky, view: View, w: number, h: number): Floa for (let i = 0; i < w; i += 1) { const az = columnAzimuth(view, ((i + 0.5) / w) * view.planeW - 0.5, view.planeW); sky.atm.radiance(Math.sin(elDeg * RAD), Math.cos((az - sky.sun.azimuth) * RAD), rgb); + addNightRadiance(sky.night, Math.sin(elDeg * RAD), az * RAD, rgb); out.set([rgb[0], rgb[1], rgb[2], 0], (j * w + i) * 4); } } @@ -276,6 +310,8 @@ uniform vec3 uExt; uniform vec3 uTSun; uniform vec3 uAmbient; uniform float uExposure; +uniform float uGrade; +uniform vec3 uScotTint; uniform float uCx[${KNOTS}]; uniform float uCy[${KNOTS}]; uniform float uCm[${KNOTS}]; @@ -306,6 +342,19 @@ ${[0, 1, 2] const vec3 FIT_AB = vec3(${glsl(ACES_FIT[0])}, ${glsl(ACES_FIT[1])}, 0.0); const vec3 FIT_CDE = vec3(${glsl(ACES_FIT[2])}, ${glsl(ACES_FIT[3])}, ${glsl(ACES_FIT[4])}); +// toneMap.ts scotopic: toward the rods' luminance (Jensen et al. 2001) in a blue-shifted grey, at weight w. +float scotLum(vec3 c) { + float X = dot(vec3(0.4124, 0.3576, 0.1805), c); + float Y = dot(vec3(0.2126, 0.7152, 0.0722), c); + float Z = dot(vec3(0.0193, 0.1192, 0.9505), c); + return max(0.0, Y * (1.33 * (1.0 + (Y + Z) / max(X, 1e-30)) - 1.68)); +} +vec3 scotopic(vec3 c, float w) { + if (w <= 0.0) return c; + float k = scotLum(c) / scotLum(vec3(1.0)); + return mix(c, k * uScotTint, w); +} + vec3 toLinear(vec3 c) { return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c)); } @@ -432,7 +481,7 @@ void main() { } radiance *= 1.0 - (1.0 - keep) * uInkScale; - vec3 rgb = toSrgb(curve(aces(radiance * uExposure))); + vec3 rgb = toSrgb(curve(aces(scotopic(radiance, uGrade) * uExposure))); outColor = vec4(rgb * c.a, c.a); } `; @@ -526,8 +575,10 @@ export function lightCards( gl.uniform2f(u('uPlane'), lit.planeW, lit.planeH); gl.uniform2f(u('uLogD'), lit.logDMin, lit.logDSpan); gl.uniform3f(u('uExt'), ...lit.extinction); - gl.uniform3f(u('uTSun'), ...lit.sunTransmittance); - gl.uniform3f(u('uAmbient'), ...lit.ambient); + gl.uniform3f(u('uTSun'), ...lit.key.direct); + gl.uniform3f(u('uAmbient'), ...lit.key.ambient); + gl.uniform1f(u('uGrade'), lit.grade); + gl.uniform3f(u('uScotTint'), ...SCOTOPIC.tint); gl.uniform1f(u('uExposure'), lit.exposure); gl.uniform1fv(u('uCx'), lit.curve.x); gl.uniform1fv(u('uCy'), lit.curve.y); @@ -550,7 +601,7 @@ export function lightCards( gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands, look.celBandLevels)); gl.uniform1f(u('uRadPerPx'), (manifest.view.windowDeg * RAD) / lit.planeW); gl.uniform2i(u('uSkySize'), SKY_LUT.w, SKY_LUT.h); - const sunTex = floatTexture(gl, 2, lit.planeW, 1, sunColumns(manifest.view, sky.sun)); + const sunTex = floatTexture(gl, 2, lit.planeW, 1, sunColumns(manifest.view, lit.key)); const skyTex = floatTexture( gl, 3, diff --git a/src/app/features/scene/ridge/nightSky.ts b/src/app/features/scene/ridge/nightSky.ts new file mode 100644 index 00000000..4bc63293 --- /dev/null +++ b/src/app/features/scene/ridge/nightSky.ts @@ -0,0 +1,190 @@ +// The night's light and bodies, in the units of the day sky: radiance per unit of the sun's irradiance (`skyDome.ts`). The sun is 1; the moon +// is its brightness by phase (Krisciunas & Schaefer 1991) times the atmosphere's response to a light at the moon's elevation +// (`earthAtmosphere.ts`, the same sky-view LUT, baked for the moon instead of the sun); the airglow is a floor; a star is its illuminance +// over the point spread it is drawn with. Everything marked EYEBALLED is a knob of the look, tuned by eye, not a measurement. +import { moonPhase, moonPosition } from '../../../../sky/moon.js'; +import type { Atmosphere, Vec3 } from './earthAtmosphere'; +import type { Place } from './view'; + +const RAD = Math.PI / 180; +const clamp = (x: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, x)); + +/** Illuminance in lux of a source of apparent visual magnitude `m` above the atmosphere (V = 0 is 2.13e-6 lux; the sun, V = -26.74, 1.06e5). */ +export const luxOfMagnitude = (m: number): number => 10 ** (-0.4 * (m + 14.18)); +export const SUN_V = -26.74; +/** The sun's illuminance, the unit of every radiance of the ridge sky. */ +export const SUN_LUX = luxOfMagnitude(SUN_V); + +/** The look of the night's bodies. EYEBALLED knobs: the operator tunes these by eye. */ +export const NIGHT_LOOK = { + /** Radius of the point spread a star's light is spread over, arcminutes: smaller is brighter and more of them saturate. */ + starPsfArcmin: 4, + /** Atmospheric extinction in magnitudes per air mass (V band, a clean low site is 0.2). */ + extinctionPerAirmass: 0.2, + /** + * Display contrast of a star over its sky is the physical contrast to this power (1 = physical): the eye and a camera cannot show a + * mag 0 star at the 1e4:1 it has over a dark sky. Brightest stars still saturate; the faintest keep a little. + */ + starContrastExp: 0.5, + /** The same for the moon's disc (physical contrast is 1e7 and more). */ + moonContrastExp: 0.3, + /** Visible radius of a star, CSS px: `base` for the faintest, plus `perMag` for each magnitude brighter than 5.5. */ + starRadius: { base: 0.45, perMag: 0.17 }, + /** The moon's disc, as a multiple of its true angular size (1 is true; a viewer's eye sees it larger than a lens does). */ + moonScale: 1, + /** Earthshine on the unlit part of the disc, as a fraction of the lit surface's radiance. */ + earthshine: 4e-5, + /** Constellation lines: opacity of the stroke (a pale blue-white) and its width in CSS px. */ + lines: { alpha: 0.22, widthPx: 0.9, rgb: [160, 185, 235] as const }, +}; + +// ---- Airglow ---------------------------------------------------------------------------------- + +/** Natural night-sky radiance at the zenith without moon or town, cd/m^2 (about 22 V mag/arcsec^2: 2.5e-4). */ +export const AIRGLOW_CD = 2.5e-4; +/** Its colour, linear, luminance 1 (a faint cool green-blue). EYEBALLED. */ +const AIRGLOW_TINT: Vec3 = [0.8, 1, 1.35]; +const AIRGLOW_NORM = 0.2126 * 0.8 + 0.7152 + 0.0722 * 1.35; + +/** The airglow floor, per unit of sun irradiance, at view elevation sine `vz` (brighter toward the horizon, van Rhijn). */ +export function airglow(vz: number, out: number[]): void { + const k = ((AIRGLOW_CD / SUN_LUX) * (0.6 + 1.4 * (1 - clamp(vz, 0, 1)))) / AIRGLOW_NORM; + out[0] += AIRGLOW_TINT[0] * k; + out[1] += AIRGLOW_TINT[1] * k; + out[2] += AIRGLOW_TINT[2] * k; +} + +// ---- Moon -------------------------------------------------------------------------------------- + +/** The moon over a place at a moment, with its light. */ +export interface MoonSample { + /** Degrees clockwise from north, and above the horizon (topocentric, no refraction). */ + azimuth: number; + elevation: number; + time: Date; + /** Lit fraction of the disc, and the sun-moon-earth angle in degrees (0 full, 180 new). */ + illuminated: number; + phaseAngleDeg: number; + waxing: boolean; + distanceKm: number; + /** Angular radius in radians. */ + radius: number; + /** The moon's illuminance relative to the sun's: its light on the ground per unit of the sun's. */ + ratio: number; +} + +/** The moon's visual magnitude at phase angle `alphaDeg`: Krisciunas & Schaefer 1991 (the Allen / Lane & Irvine fit) plus the distance. */ +export const moonMagnitude = (alphaDeg: number, distanceKm: number): number => { + const a = Math.abs(alphaDeg); + return -12.73 + 0.026 * a + 4e-9 * a ** 4 + 5 * Math.log10(distanceKm / 384400); +}; + +/** The moon's illuminance over the sun's. At full moon about 2.5e-6. */ +export const moonIrradianceRatio = (alphaDeg: number, distanceKm: number): number => + 10 ** (-0.4 * (moonMagnitude(alphaDeg, distanceKm) - SUN_V)); + +export function moonAt(place: Place, time: Date): MoonSample { + const p = moonPosition(time, place.lat, place.lon) as { elevation: number; azimuth: number }; + const ph = moonPhase(time) as { + illuminated: number; + phaseAngleDeg: number; + waxing: boolean; + distanceKm: number; + }; + return { + ...p, + time, + illuminated: ph.illuminated, + phaseAngleDeg: ph.phaseAngleDeg, + waxing: ph.waxing, + distanceKm: ph.distanceKm, + radius: Math.asin(1737.4 / ph.distanceKm), + ratio: moonIrradianceRatio(ph.phaseAngleDeg, ph.distanceKm), + }; +} + +/** + * The radiance of the moon's lit surface per unit of sun irradiance: its flux over the lit area of the disc. About 4000 cd/m^2 at full moon. + * `lit` is the lit fraction (at least a sliver, so a thin crescent's surface brightness stays finite). + */ +export const moonSurface = (m: MoonSample): number => + m.ratio / (Math.max(m.illuminated, 0.02) * Math.PI * m.radius * m.radius); + +// ---- The night's light, as the dome and the cards read it ------------------------------------ + +/** What lights the sky besides the sun: the moon (its own atmosphere bake, scaled by `ratio`) and the airglow. */ +export interface NightLight { + moon?: { azimuth: number; elevation: number; atm: Atmosphere; ratio: number }; +} + +/** + * Add the night's radiance (the moon's scattered light and the airglow, per unit of sun irradiance) for a view ray: `vz` the sine of its + * elevation, `azRad` its azimuth in radians, written onto `out`. + */ +export function addNightRadiance( + n: NightLight | undefined, + vz: number, + azRad: number, + out: number[] +): void { + airglow(vz, out); + if (!n?.moon) return; + const m = n.moon; + const tmp = [0, 0, 0]; + m.atm.radiance(vz, Math.cos(azRad - m.azimuth * RAD), tmp); + out[0] += tmp[0] * m.ratio; + out[1] += tmp[1] * m.ratio; + out[2] += tmp[2] * m.ratio; +} + +// ---- Stars ------------------------------------------------------------------------------------- + +/** Relative air mass, Kasten & Young 1989. Elevation in degrees. */ +export const airMass = (elDeg: number): number => + 1 / (Math.sin(Math.max(elDeg, 0) * RAD) + 0.50572 * Math.pow(Math.max(elDeg, 0) + 6.07995, -1.6364)); + +/** A star's magnitude after the air: extinction per air mass along its elevation. */ +export const extinguished = (mag: number, elDeg: number): number => + mag + NIGHT_LOOK.extinctionPerAirmass * airMass(elDeg); + +/** Linear sRGB colour of a black body of temperature `t` kelvin at luminance 1 (Kim et al. 2002 Planckian locus, sRGB primaries). */ +export function blackbodyRgb(t: number): Vec3 { + const T = clamp(t, 1700, 24000); + const x = + T <= 4000 + ? -0.2661239e9 / T ** 3 - 0.2343589e6 / T ** 2 + 0.8776956e3 / T + 0.17991 + : -3.0258469e9 / T ** 3 + 2.1070379e6 / T ** 2 + 0.2226347e3 / T + 0.24039; + const y = + T <= 2222 + ? -1.1063814 * x ** 3 - 1.3481102 * x ** 2 + 2.18555832 * x - 0.20219683 + : T <= 4000 + ? -0.9549476 * x ** 3 - 1.37418593 * x ** 2 + 2.09137015 * x - 0.16748867 + : 3.081758 * x ** 3 - 5.8733867 * x ** 2 + 3.75112997 * x - 0.37001483; + const X = x / y; + const Z = (1 - x - y) / y; + const rgb = [ + 3.2406 * X - 1.5372 - 0.4986 * Z, + -0.9689 * X + 1.8758 + 0.0415 * Z, + 0.0557 * X - 0.204 + 1.057 * Z, + ].map((c) => Math.max(0, c)); + const lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]; + return [rgb[0] / lum, rgb[1] / lum, rgb[2] / lum]; +} + +/** Effective temperature of a star from its B-V colour index (Ballesteros 2012). */ +export const temperatureOfBV = (bv: number): number => { + const c = clamp(bv, -0.4, 2); + return 4600 * (1 / (0.92 * c + 1.7) + 1 / (0.92 * c + 0.62)); +}; + +/** A star's radiance when seen through the point spread, per unit of sun irradiance: its illuminance over the spread's solid angle. */ +export const starRadiance = (mag: number): number => { + const r = (NIGHT_LOOK.starPsfArcmin / 60) * RAD; + return luxOfMagnitude(mag) / (Math.PI * r * r) / SUN_LUX; +}; + +/** Perceptual compression of a body's contrast over the sky behind it: `bg` the sky's radiance, `add` the body's on top; the exponent 1 is physical. */ +export const compressed = (bg: number, add: number, exp: number): number => { + const b = Math.max(bg, 1e-30); + return b * ((b + add) / b) ** exp; +}; diff --git a/src/app/features/scene/ridge/physicalSky.ts b/src/app/features/scene/ridge/physicalSky.ts index f65497dd..6cc28fe2 100644 --- a/src/app/features/scene/ridge/physicalSky.ts +++ b/src/app/features/scene/ridge/physicalSky.ts @@ -9,6 +9,8 @@ import type { Dome } from './skyDome'; import type { Srgb } from './skyColour'; import { display8, fitDisplay, MARGIN } from './toneMap'; import type { Display, Fit } from './toneMap'; +import { moonAt } from './nightSky'; +import type { MoonSample, NightLight } from './nightSky'; import { sunForState } from './sunAt'; import type { SunSample } from './sunAt'; import { windowFor } from './view'; @@ -21,6 +23,10 @@ export interface PhysicalSky { /** Where the observer stands and where the planes look: the camera of any viewport is `windowFor(view, w, h).camera`. */ view: View; sun: SunSample; + /** The moon over the place at the sun's moment (`sun.time`): the night's key light, and a body in any sky it is above the horizon of. */ + moon: MoonSample; + /** What lights the sky besides the sun: at night, the moon above the horizon with its own atmosphere bake. */ + night: NightLight; weather: Weather; atm: Atmosphere; /** The display fitted to this sky's budget. */ @@ -67,13 +73,33 @@ export function makePhysicalSky( }); // A 16:9 viewport: the camera's fov and horizon fraction do not depend on its size, only on its shape. const { camera } = windowFor(view, CANON.w, CANON.h); - const dome = renderDome(atm, sun, camera, CANON.w, CANON.h, weather.cover); + // The moon is the night's light: its own bake of the same atmosphere, for a light at its elevation (the transmittance and the + // multiple-scattering tables do not depend on it, but the bake is one function). Only in the night state, and only above -2 degrees. + const moon = moonAt(view.place, sun.time); + const night: NightLight = + state === 'night' && moon.elevation > -2 + ? { + moon: { + azimuth: moon.azimuth, + elevation: moon.elevation, + ratio: moon.ratio, + atm: bakeAtmosphere({ + sunElevationDeg: moon.elevation, + mieScale: weather.mieScale, + observerKm: view.place.altitudeKm, + }), + }, + } + : {}; + const dome = renderDome(atm, sun, camera, CANON.w, CANON.h, weather.cover, night); const fit = fitDisplay(state, dome.hdr, dome.meanLuma); const at = (f: number) => rowMean(dome, fit.display, Math.round(f * CANON.h)); return { state, view, sun, + moon, + night, weather, atm, fit, @@ -96,7 +122,7 @@ export interface SkyPixels { /** The sky for a viewport seen through `camera` (`windowFor(p.view, cssW, cssH).camera`), as a small RGBA grid the host canvas upscales smoothly. */ export function paintSky(p: PhysicalSky, cssW: number, cssH: number, camera: Camera): SkyPixels { const { w, h } = domeSize(cssW, cssH); - const dome = renderDome(p.atm, p.sun, camera, w, h, p.weather.cover); + const dome = renderDome(p.atm, p.sun, camera, w, h, p.weather.cover, p.night); const data = new Uint8ClampedArray(w * h * 4); const out = [0, 0, 0]; const display = p.fit.display; diff --git a/src/app/features/scene/ridge/skyDome.ts b/src/app/features/scene/ridge/skyDome.ts index 0edb3e5f..913ae298 100644 --- a/src/app/features/scene/ridge/skyDome.ts +++ b/src/app/features/scene/ridge/skyDome.ts @@ -5,6 +5,8 @@ import type { Atmosphere } from './earthAtmosphere'; import type { SunSample } from './sunAt'; import type { Camera } from './view'; import { cloudAmount, cloudRadiance } from './clouds'; +import { addNightRadiance } from './nightSky'; +import type { NightLight } from './nightSky'; const RAD = Math.PI / 180; /** The sun's angular radius in radians (Hillaire's/Bruneton's `sun_angular_radius`). */ @@ -25,7 +27,7 @@ export const domeSize = (cssW: number, cssH: number): { w: number; h: number } = }); /** - * Render the HDR sky. Rays below the horizon take the horizon's radiance (the ridges cover them). The sun's disc is not here: it is smaller than a texel, so the host draws it on the upscaled canvas (`sunOnScreen`). `cover` (0..1, `weather.ts`) lays the cloud deck (`clouds.ts`) over it. + * Render the HDR sky: the sun's atmosphere, plus at night the moon's (`night`, scaled by its irradiance ratio) and the airglow. Rays below the horizon take the horizon's radiance (the ridges cover them). The sun's disc is not here: it is smaller than a texel, so the host draws it on the upscaled canvas (`sunOnScreen`). `cover` (0..1, `weather.ts`) lays the cloud deck (`clouds.ts`) over it. */ export function renderDome( atm: Atmosphere, @@ -33,7 +35,8 @@ export function renderDome( camera: Camera, w: number, h: number, - cover = 0 + cover = 0, + night?: NightLight ): Dome { const hdr = new Float32Array(w * h * 3); const sunAz = sun.azimuth * RAD; @@ -47,6 +50,19 @@ export function renderDome( const zenith = [0, 0, 0]; atm.radiance(1, 1, zenith); cloudRadiance(sz, trans, zenith, cover, cloud); + if (night?.moon) { + // The deck is moonlit as it is sunlit: the moon's own light through the air, scaled by its irradiance. + const m = night.moon; + const moonCloud = [0, 0, 0]; + const moonTrans = [0, 0, 0]; + const moonZenith = [0, 0, 0]; + m.atm.transmittanceToSpace(Math.max(Math.sin(m.elevation * RAD), 0), moonTrans); + m.atm.radiance(1, 1, moonZenith); + cloudRadiance(Math.sin(m.elevation * RAD), moonTrans, moonZenith, cover, moonCloud); + for (let i = 0; i < 3; i += 1) cloud[i] += moonCloud[i] * m.ratio; + } + // The airglow lights the deck too, at the zenith's strength. + addNightRadiance(undefined, 1, 0, cloud); } let logSum = 0; for (let j = 0; j < h; j += 1) { @@ -57,6 +73,7 @@ export function renderDome( const az = (camera.azimuthDeg + ((i + 0.5) / w - 0.5) * camera.hfovDeg) * RAD; const cosFromSun = Math.cos(az - sunAz); atm.radiance(vz, cosFromSun, rgb); + addNightRadiance(night, vz, az, rgb); let r = rgb[0]; let g = rgb[1]; let b = rgb[2]; diff --git a/src/app/features/scene/ridge/toneMap.test.ts b/src/app/features/scene/ridge/toneMap.test.ts index b6f0101a..536c0b1c 100644 --- a/src/app/features/scene/ridge/toneMap.test.ts +++ b/src/app/features/scene/ridge/toneMap.test.ts @@ -3,7 +3,8 @@ import { FALLBACK_VIEW } from './view'; import { makePhysicalSky } from './physicalSky'; import { renderDome } from './skyDome'; import { windowFor } from './view'; -import { applyCurve, BLACK_LIFT, BUDGET, NIGHT_LIFT, displayLumaOf, fitDisplay, makeCurve } from './toneMap'; +import { applyCurve, BLACK_LIFT, BUDGET, NIGHT_CEILING, NIGHT_LIFT, SCOTOPIC, displayLumaOf, fitDisplay, makeCurve, scotopic, scotopicWeight } from './toneMap'; +import { sunAt } from './sunAt'; import type { FixedSkyState } from '../skyState'; const sweep = (c: ReturnType) => @@ -29,7 +30,7 @@ describe('the tone curve', () => { describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted to a sky', (state) => { const sky = makePhysicalSky(state, new Date('2026-06-21T10:40:00Z'), 0, FALLBACK_VIEW); const { camera } = windowFor(sky.view, 64, 36); - const dome = renderDome(sky.atm, sky.sun, camera, 64, 36, sky.weather.cover); + const dome = renderDome(sky.atm, sky.sun, camera, 64, 36, sky.weather.cover, sky.night); const b = BUDGET[state]; it('has the black lift constant at black and every texel inside the state budget', () => { @@ -42,12 +43,7 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted for (let i = 1; i < v.length; i += 1) expect(v[i]).toBeGreaterThanOrEqual(v[i - 1] - 1e-12); }); - it('puts the curve through the targets at the fixed knots (a night sky carries nothing to fit)', () => { - if (!b.knots) return; - b.knots.forEach((k, i) => expect(applyCurve(sky.fit.display.curve, k)).toBeCloseTo(b.targets[i], 9)); - }); - - it.skipIf(b.knots !== undefined)('puts the sky percentiles on the targets (as far as the gain limit allows)', () => { + it('puts the sky percentiles on the targets (as far as the gain limit allows)', () => { const n = dome.hdr.length / 3; const ls: number[] = []; for (let i = 0; i < n; i += 1) @@ -57,9 +53,64 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted const flat = fitDisplay(state, dome.hdr, dome.meanLuma); expect(flat.display).toEqual(sky.fit.display); // The curve is fitted on luminance and applied per channel, so the byte luminance is near its targets, not on them. The median is never limited; the outer two are at or below their targets by the gain limit only. - expect(at(0.5)).toBeGreaterThan(b.targets[1] * 0.75); - expect(at(0.5)).toBeLessThan(b.targets[1] * 1.25); - expect(at(0.95)).toBeLessThanOrEqual(b.targets[2] * 1.25 + 0.004); + const p = b.partial; + const level = p ? Math.min(p.levelMax, Math.max(p.levelMin, (dome.meanLuma / p.ref) ** (1 - p.exponent))) : 1; + expect(at(0.5)).toBeGreaterThan(b.targets[1] * level * 0.75); + // The scotopic grade lifts the blue channel, which the per-channel curve takes up faster than the luminance it was fitted on: night reads up to twice its target. + const slack = p ? 2.5 : 1.25; + expect(at(0.5)).toBeLessThan(b.targets[1] * level * slack); + expect(at(0.95)).toBeLessThanOrEqual(b.targets[2] * level * slack + 0.004); expect(at(0.05)).toBeLessThan(at(0.5)); }); }); + +describe('the night display', () => { + const night = (iso: string) => { + const t = new Date(iso); + return makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t)); + }; + const fullMoon = night('2026-11-24T22:00:00Z'); + const newMoon = night('2026-12-09T20:00:00Z'); + + it('adapts the exposure to the sky: a moonless night is exposed far brighter than a moonlit one', () => { + expect(fullMoon.moon.illuminated).toBeGreaterThan(0.99); + expect(newMoon.moon.illuminated).toBeLessThan(0.1); + expect(newMoon.fit.display.exposure).toBeGreaterThan(10 * fullMoon.fit.display.exposure); + }); + + it('reads the new-moon night darker than the full-moon night (partial adaptation), by the level of the budget', () => { + const med = (p: ReturnType) => applyCurve(p.fit.display.curve, 0.5); + expect(med(newMoon)).toBeLessThan(0.6 * med(fullMoon)); + }); + + it('grades toward the rods at night and not by day', () => { + expect(fullMoon.fit.display.grade).toBeGreaterThan(0.8); + expect(newMoon.fit.display.grade).toBeGreaterThan(0.99); + expect(makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), 0, FALLBACK_VIEW).fit.display.grade ?? 0).toBe(0); + }); + + it('has no fixed night ceiling: the curve tops out at NIGHT_CEILING', () => { + expect(applyCurve(newMoon.fit.display.curve, 1)).toBe(NIGHT_CEILING); + expect(BUDGET.night.ceiling).toBe(NIGHT_CEILING); + }); +}); + +describe('the scotopic grade', () => { + it('leaves a neutral grey alone in hue, moves colour toward blue and darkens red against blue', () => { + const o = [0, 0, 0]; + scotopic(0.2, 0.2, 0.2, 1, o); + expect(o[0] / o[1]).toBeCloseTo(SCOTOPIC.tint[0] / SCOTOPIC.tint[1], 6); + scotopic(0.5, 0.1, 0.1, 1, o); + const red = [...o]; + scotopic(0.1, 0.1, 0.5, 1, o); + expect(o[2]).toBeGreaterThan(red[2]); + expect(red[0]).toBeLessThan(0.5); // red is nearly black to the rods + scotopic(0.3, 0.2, 0.1, 0, o); + expect(o).toEqual([0.3, 0.2, 0.1]); + }); + it('weighs 1 in the dark and 0 in daylight, falling through the mesopic range', () => { + expect(scotopicWeight(2e-9)).toBeCloseTo(1, 6); + expect(scotopicWeight(0.3)).toBe(0); + expect(scotopicWeight(1e-6)).toBeGreaterThan(scotopicWeight(1e-4)); + }); +}); diff --git a/src/app/features/scene/ridge/toneMap.ts b/src/app/features/scene/ridge/toneMap.ts index 1746b595..a33b7c92 100644 --- a/src/app/features/scene/ridge/toneMap.ts +++ b/src/app/features/scene/ridge/toneMap.ts @@ -3,13 +3,15 @@ // matrix), then the sRGB encode. A per-pixel function with no state, applied once to the baked sky (CPU: the scene is a 2D // canvas, there is no float render target to fall back from). // -// Exposure is chosen per sky state: the sky is physical radiance, so brightness is the camera's. Day and dusk expose to the -// sky's own luminance (adaptation); night is the physical dark. After ACES comes one more curve, per channel in display-linear: -// a monotone cubic through five knots, fitted per sky from the luminance distribution of the sky grid so that its 5th, 50th and -// 95th percentiles land on the state's target display luminances. The curve starts at a small black lift (BLACK_LIFT, the only -// absolute lift) and ends at white (day, dusk) or at the night ceiling (light ink needs a dark ground). It is fitted on the sky -// grid alone: the cards are not sampled, they ride the same curve. +// Exposure adapts to the sky's own luminance in every state (the sky is physical radiance, so brightness is the camera's); night +// adapts only in part (`Budget.partial`), so a new-moon night reads darker than a full-moon one. Before exposure a scotopic grade +// (`scotopic`: desaturation and a blue shift as the adapted luminance falls through the mesopic range) carries the night read. After +// ACES comes one more curve, per channel in display-linear: a monotone cubic through five knots, fitted per sky from the luminance +// distribution of the sky grid so that its 5th, 50th and 95th percentiles land on the state's target display luminances. The curve +// starts at a small black lift and ends at white, or at the state's ceiling when it has one. It is fitted on the sky grid alone: the +// cards are not sampled, they ride the same curve. import type { FixedSkyState } from '../skyState'; +import { SUN_LUX } from './nightSky'; type Rgb = readonly [number, number, number]; @@ -47,6 +49,43 @@ export function acesLinear(r: number, g: number, b: number, exposure: number, ou ); } +/** Scotopic luminance of linear sRGB (Jensen et al. 2001, from CIE XYZ): the response of the rods, which see red as nearly black. */ +export const scotopicLuminance = (r: number, g: number, b: number): number => { + const X = 0.4124 * r + 0.3576 * g + 0.1805 * b; + const Y = 0.2126 * r + 0.7152 * g + 0.0722 * b; + const Z = 0.0193 * r + 0.1192 * g + 0.9505 * b; + return Math.max(0, Y * (1.33 * (1 + (Y + Z) / Math.max(X, 1e-30)) - 1.68)); +}; + +/** + * The scotopic grade of linear radiance `r, g, b` at weight `w` (0 photopic .. 1 scotopic): toward the rods' luminance in a blue-shifted grey. A neutral grey keeps its luminance, so the grade moves colour more than brightness. Written into `out`. + * `lightCards.ts` writes the same into its shader. + */ +export function scotopic(r: number, g: number, b: number, w: number, out: number[]): void { + if (w <= 0) { + out[0] = r; + out[1] = g; + out[2] = b; + return; + } + const v = scotopicLuminance(r, g, b); + // Scale the rods' grey to the cones' luminance for a neutral, so only the colour is graded. + const grey = scotopicLuminance(1, 1, 1); + const k = v / grey; + for (let i = 0; i < 3; i += 1) { + const target = k * SCOTOPIC.tint[i]; + out[i] = [r, g, b][i] + (target - [r, g, b][i]) * w; + } +} + +/** How scotopic a sky is, 0..1, from its log-mean luminance per unit of sun irradiance: through the mesopic range (`SCOTOPIC`). */ +export function scotopicWeight(meanLuma: number): number { + const lg = Math.log10(Math.max(meanLuma * SUN_LUX, 1e-12)); + const [lo, hi] = SCOTOPIC.mesopic; + const t = Math.min(1, Math.max(0, (lg - lo) / (hi - lo))); + return SCOTOPIC.strength * (1 - t * t * (3 - 2 * t)); +} + /** The 8-bit sRGB of linear radiance, exposed and tone-mapped. */ export function toneMap8(r: number, g: number, b: number, exposure: number, out: number[]): void { acesLinear(r, g, b, exposure, out); @@ -74,8 +113,11 @@ export interface Budget { max: number; /** Display luminance the 5th, 50th and 95th percentile of the sky's luminance are mapped to. */ targets: readonly [number, number, number]; - /** Fixed knot positions (ACES output) for the three targets instead of the sky's percentiles: for a state whose sky carries no signal to fit (night: the sky is black, the cards are what the curve is for). */ - knots?: readonly [number, number, number]; + /** + * Partial adaptation: the targets are scaled by `(meanLuma / ref) ^ (1 - exponent)` (clamped to `levelMin`..`levelMax`) where `meanLuma` is the sky's + * log-mean luminance per unit of sun irradiance and `ref` the one the targets were set at. Exponent 1 is full adaptation (day, dusk). + */ + partial?: { ref: number; exponent: number; levelMin: number; levelMax: number }; /** The most the curve may steepen the sky's own spread about its median (display luminance per unit of ACES output): a nearly flat overcast sky is not blown up into a gradient. */ maxGain: number; } @@ -85,22 +127,37 @@ export const MARGIN = 0.004; /** The one absolute lift of day and dusk: what black is drawn as, display-linear. The rest of the range is made by the curve. */ export const BLACK_LIFT = 0.02; -/** Night's black lift: the whole night range is under its ceiling (0.043), so its black is lifted less. */ +/** Night's black lift: a little lower than day's, the darks stay soft rather than crushed. */ export const NIGHT_LIFT = 0.004; +/** The night's ceiling, display-linear: the top of its curve (1 is white). EYEBALLED: the operator tunes it by eye; the moon and the stars are drawn through the same display and need the room. */ +export const NIGHT_CEILING = 1; + +/** + * The scotopic grade (Thompson, Shirley & Ferwerda 2002; Kirk & O'Brien 2011; Jensen et al. 2001): `strength` scales it (EYEBALLED, 0 off), + * the mesopic range is log10 of the adapted luminance in cd/m^2 from `mesopic[0]` (fully scotopic) to `mesopic[1]` (fully photopic), + * and `tint` is the blue shift of the scotopic luminance (Jensen et al.). + */ +export const SCOTOPIC = { + strength: 1, + mesopic: [-2, 0.5] as const, + tint: [1.05, 0.97, 1.27] as const, +}; -/** Night wears light ink, whose dimmer foldout headers (L 0.386 on screen, rat-crest-a7c95ce-20261111) need a backdrop of at most 0.047. */ export const BUDGET: Record = { day: { floor: BLACK_LIFT - 0.001, lift: BLACK_LIFT, ceiling: 1, key: 0.45, min: 4, max: 60, targets: [0.22, 0.58, 0.9], maxGain: 4 }, dusk: { floor: BLACK_LIFT - 0.001, lift: BLACK_LIFT, ceiling: 1, key: 0.5, min: 4, max: 400, targets: [0.12, 0.45, 0.85], maxGain: 4 }, night: { floor: NIGHT_LIFT - 0.001, lift: NIGHT_LIFT, - ceiling: 0.047 - MARGIN, - min: 1, - max: 1, - knots: [0.002, 0.02, 0.15], - targets: [0.008, 0.018, 0.032], - maxGain: 1e6, + ceiling: NIGHT_CEILING, + key: 0.45, + min: 4, + max: 1e13, + targets: [0.012, 0.03, 0.07], + maxGain: 4, + // A full-moon sky is about 2e-7 of the sun's irradiance in radiance; a moonless one about 2e-9. Partial adaptation of 0.7 puts + // the second at about a quarter of the first. + partial: { ref: 2e-7, exponent: 0.7, levelMin: 0.2, levelMax: 1.3 }, }, }; @@ -158,11 +215,16 @@ export const LIFT_ONLY: Curve = makeCurve( export interface Display { exposure: number; curve: Curve; + /** Weight of the scotopic grade before exposure, 0 (photopic, the default) .. 1 (`scotopicWeight`). */ + grade?: number; } /** The 8-bit sRGB of linear radiance through a display. */ export function display8(r: number, g: number, b: number, d: Display, out: number[]): void { - acesLinear(r, g, b, d.exposure, out); + if (d.grade) { + scotopic(r, g, b, d.grade, out); + acesLinear(out[0], out[1], out[2], d.exposure, out); + } else acesLinear(r, g, b, d.exposure, out); for (let i = 0; i < 3; i += 1) out[i] = Math.round(encode(applyCurve(d.curve, out[i]))); } @@ -193,7 +255,7 @@ export interface Fit { /** * Choose the display of a sky, the one place brightness is decided. `hdr` is the grid's radiance (3 floats a texel) and `meanLuma` its - * log-mean luminance. Exposure is the state's key (adaptation). The curve is then fitted: the 5th, 50th and 95th percentile of the + * log-mean luminance. Exposure is the state's key (adaptation); the targets of a state with partial adaptation are scaled by the sky's level. The scotopic grade's weight comes from the sky's luminance. The curve is then fitted: the 5th, 50th and 95th percentile of the * grid's luminance after ACES go to the state's targets (the outer two held to the budget's `maxGain` times the sky's own spread about the median), * between a black lift below and white (or the night ceiling) above. Monotone by construction, so the ceiling holds for every texel * of every grid and card, and no pass over another viewport's grid is needed. @@ -207,13 +269,15 @@ export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: nu const n = hdr.length / 3; const tmp = [0, 0, 0]; const xs: number[] = []; + const grade = scotopicWeight(meanLuma); for (let i = 0; i < n; i += 1) { - acesLinear(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], keyExposure, tmp); + scotopic(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], grade, tmp); + acesLinear(tmp[0], tmp[1], tmp[2], keyExposure, tmp); xs.push(displayLuma(tmp)); } xs.sort((p, q) => p - q); const pct = (q: number) => xs[Math.min(n - 1, Math.floor(q * n))]; - const x = [0, ...(b.knots ?? [pct(0.05), pct(0.5), pct(0.95)]), 1]; + const x = [0, pct(0.05), pct(0.5), pct(0.95), 1]; x[1] = Math.max(x[1], 1e-7); x[2] = Math.max(x[2], x[1] * 1.001 + 1e-7); x[3] = Math.max(x[3], x[2] * 1.001 + 1e-7); @@ -222,7 +286,11 @@ export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: nu x[2] = Math.min(x[2], 0.965); x[1] = Math.min(x[1], 0.96); } - const [t0, t1, t2] = b.targets; + const p = b.partial; + const level = p + ? Math.min(p.levelMax, Math.max(p.levelMin, (Math.max(meanLuma, 1e-30) / p.ref) ** (1 - p.exponent))) + : 1; + const [t0, t1, t2] = b.targets.map((t) => t * level); const y = [ b.lift, Math.max(b.lift + 1e-4, t0, t1 - b.maxGain * (x[2] - x[1])), @@ -232,7 +300,7 @@ export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: nu ]; y[1] = Math.min(y[1], y[2] - 1e-4); y[3] = Math.max(y[3], y[2] + 1e-4); - const display: Display = { exposure: keyExposure, curve: makeCurve(x, y) }; + const display: Display = { exposure: keyExposure, curve: makeCurve(x, y), grade }; let lo = 2; let hi = -1; const stride = Math.max(1, Math.floor(n / 4000)); diff --git a/src/app/features/scene/skyForState.test.ts b/src/app/features/scene/skyForState.test.ts index 237c1f5a..f5fab324 100644 --- a/src/app/features/scene/skyForState.test.ts +++ b/src/app/features/scene/skyForState.test.ts @@ -92,11 +92,12 @@ describe('ridgeSkyFor', () => { expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('night', FALLBACK_VIEW, 0.3)); }); - it.each(STATES)('%s: the display is the curve of its budget: black lift at the floor, the ceiling the light ink needs', (state) => { - const { ceiling } = needs(state); + // Night has no ink ceiling: its display top is a tunable (NIGHT_CEILING, ruling ridge-night-real-sky: the operator tunes it by eye), + // because the moon and the stars are drawn through the same display. + it.each(STATES)('%s: the display is the curve of its budget: black lift at the floor, and its ceiling', (state) => { const r = ridgeDrawn(state); expect(r.darkest).toBe(BUDGET[state].floor); - expect(r.lightest).toBeLessThanOrEqual(ceiling); + if (state !== 'night') expect(r.lightest).toBeLessThanOrEqual(needs(state).ceiling); const fit = ridgeSkyFor(state, FALLBACK_VIEW, 0.3).physical?.fit; expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9); expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9); @@ -104,7 +105,7 @@ describe('ridgeSkyFor', () => { }); describe('skyBackdrop holds the ridge sky', () => { - it.each(STATES)('%s: the backdrop bound contains the ridge display ceiling', (state) => { + it.each(['day', 'dusk'] as const)('%s: the backdrop bound contains the ridge display ceiling', (state) => { expect(skyBackdrop(state).lightest).toBeGreaterThanOrEqual(ridgeDrawn(state).lightest); }); });