scene: terrain haze is aerial perspective from a baked Hillaire camera volume
Replaces the exp(-(k d)^1.6) haze with the camera volume of Hillaire, EGSR 2020 section 5.4 (and sebh/UnrealEngineSkyAtmosphere RenderCameraVolumePS): slices on the squared distribution, in-scatter integrated with each step's extinction analytic, alpha the grey opacity 1 - mean(T). Baked into baked.scatter.aerial_perspective by src/sky/scatter.js (RGBA16F 7 x 96 x 12, 86 KB), looked up in the terrain fragment shader (two fetches). Night: the moon lights the haze through the same volume, plus a deep blue starlight floor. Shortcuts, with units and constants, in src/sky/README.md: sun-relative indexing, 12 x 8 x 7 texels, path = scene metres x 8, ground ignored, single scattering, no multi-scattering LUT. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
685abbb19b
commit
c35ac7e5cd
12 changed files with 521 additions and 67 deletions
|
|
@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|||
import { createTerrainScene } from './Terrain';
|
||||
import { GRID, triangleCount } from './terrainWorld';
|
||||
import { groundLight, SKY, skyAtSun } from './terrainSky';
|
||||
import { SKY_VIEW, skyViewWords } from './terrainScatter';
|
||||
import { AP_VOLUME, apVolumeWords, SKY_VIEW, skyViewWords } from './terrainScatter';
|
||||
import { SKY_FRAG } from './terrainShaders';
|
||||
import { startBackgroundScene } from '../index';
|
||||
|
||||
|
|
@ -176,14 +176,17 @@ describe('createTerrainScene', () => {
|
|||
expect(has(ambients({}), groundLight(SKY.midnight).ambient)).toBe(true);
|
||||
});
|
||||
|
||||
it('uploads the baked scattering table once, as half floats, to a 3D texture', () => {
|
||||
it('uploads the baked sky table and the aerial perspective volume once each, as half floats, to 3D textures', () => {
|
||||
const { gl, calls } = fakeGl();
|
||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose();
|
||||
expect(calls.texImage3D).toHaveLength(1);
|
||||
expect(calls.texImage3D).toHaveLength(2);
|
||||
const a = calls.texImage3D[0];
|
||||
expect([a[3], a[4], a[5]]).toEqual([SKY_VIEW.width, SKY_VIEW.height, SKY_VIEW.depth]);
|
||||
expect(a[9]).toEqual(skyViewWords());
|
||||
expect(calls.deleteTexture).toHaveLength(2);
|
||||
const ap = calls.texImage3D[1];
|
||||
expect([ap[3], ap[4], ap[5]]).toEqual([AP_VOLUME.width, AP_VOLUME.height, AP_VOLUME.depth]);
|
||||
expect(ap[9]).toEqual(apVolumeWords());
|
||||
expect(calls.deleteTexture).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('dithers the sky output by half an 8-bit step either way, and the terrain not at all', () => {
|
||||
|
|
@ -243,7 +246,7 @@ describe('createTerrainScene', () => {
|
|||
createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose();
|
||||
expect(calls.deleteProgram).toHaveLength(3);
|
||||
expect(calls.deleteBuffer).toHaveLength(2);
|
||||
expect(calls.deleteTexture).toHaveLength(2);
|
||||
expect(calls.deleteTexture).toHaveLength(3);
|
||||
expect(rafQueue).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@ import type { Scene, SceneOptions } from '../Scene';
|
|||
import { FrameSampler, FrameStats } from '../ridge/probe';
|
||||
import { albedoPalette } from './terrainAlbedo';
|
||||
import { sunIndex } from '../../../../sky/scatter.js';
|
||||
import { SKY_VIEW, skyViewWords } from './terrainScatter';
|
||||
import { AP_VOLUME, apVolumeWords, SKY_VIEW, skyViewWords } from './terrainScatter';
|
||||
import {
|
||||
nightness,
|
||||
glowColour,
|
||||
groundLight,
|
||||
HAZE_K,
|
||||
chooseSky,
|
||||
SkyName,
|
||||
START_TURNS,
|
||||
|
|
@ -138,6 +138,26 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
|
|||
[gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) =>
|
||||
gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE)
|
||||
);
|
||||
// The aerial perspective volume, RGBA16F, half floats as stored (src/sky/scatter.js).
|
||||
const apTex = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_3D, apTex);
|
||||
gl.texImage3D(
|
||||
gl.TEXTURE_3D,
|
||||
0,
|
||||
gl.RGBA16F,
|
||||
AP_VOLUME.width,
|
||||
AP_VOLUME.height,
|
||||
AP_VOLUME.depth,
|
||||
0,
|
||||
gl.RGBA,
|
||||
gl.HALF_FLOAT,
|
||||
apVolumeWords()
|
||||
);
|
||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
||||
[gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) =>
|
||||
gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE)
|
||||
);
|
||||
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
|
||||
gl.bindTexture(gl.TEXTURE_2D, heightTex);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
|
||||
|
|
@ -148,6 +168,7 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
|
|||
free.forEach((f) => f());
|
||||
gl.deleteTexture(heightTex);
|
||||
gl.deleteTexture(skyTex);
|
||||
gl.deleteTexture(apTex);
|
||||
gl.deleteFramebuffer(fbo);
|
||||
gl.deleteProgram(bakeProg);
|
||||
gl.deleteProgram(skyProg);
|
||||
|
|
@ -192,6 +213,8 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
|
|||
const heading = START_TURNS;
|
||||
const glow = [...glowColour(sky)];
|
||||
const sunTexel = sunIndex(sky.elevation);
|
||||
const night = nightness(sky.elevation);
|
||||
const moonTexel = sunIndex(Math.abs(sky.elevation));
|
||||
const palette = albedoPalette(sky);
|
||||
const triangles = triangleCount(spec.grid);
|
||||
|
||||
|
|
@ -252,7 +275,11 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
|
|||
gl.activeTexture(gl.TEXTURE1);
|
||||
gl.bindTexture(gl.TEXTURE_3D, skyTex);
|
||||
gl.uniform1i(u('uSky'), 1);
|
||||
gl.uniform1f(u('uHazeK'), HAZE_K);
|
||||
gl.uniform1f(u('uNight'), night);
|
||||
gl.uniform1f(u('uMoonIndex'), moonTexel);
|
||||
gl.activeTexture(gl.TEXTURE2);
|
||||
gl.bindTexture(gl.TEXTURE_3D, apTex);
|
||||
gl.uniform1i(u('uAP'), 2);
|
||||
gl.uniform3fv(u('uSoil'), palette.soil);
|
||||
gl.uniform3fv(u('uScree'), palette.scree);
|
||||
gl.uniform3fv(u('uRock'), palette.rock);
|
||||
|
|
|
|||
|
|
@ -111,7 +111,7 @@ describe('shader agrees with the pure function on its numbers', () => {
|
|||
expect(GRID_FRAG).toContain(`#define ALB_GRAIN_COARSE ${ALBEDO.grainCoarse}`);
|
||||
expect(GRID_FRAG).toContain(`#define ALB_STRATA ${ALBEDO.strata}`);
|
||||
// the only fetch for colour-by-material would be a texture; the height map's texelFetch is the only other read, and the sky lookup is the baked scattering table's
|
||||
expect(GRID_FRAG.match(/texelFetch|texture\((?!uSky)/g)).toHaveLength(1);
|
||||
expect(GRID_FRAG.match(/texelFetch|texture\((?!uSky|uAP)/g)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,21 @@
|
|||
/* eslint-disable no-restricted-syntax -- tests walk table texels */
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { baked } from '../../../../sky/baked';
|
||||
import { decode, viewElevation } from '../../../../sky/scatter.js';
|
||||
import {
|
||||
aerialRay,
|
||||
AP_ELEVATIONS,
|
||||
AP_SLICES,
|
||||
apElevation,
|
||||
apSliceKm,
|
||||
decode,
|
||||
SUN_ELEVATIONS_DEG,
|
||||
viewElevation,
|
||||
} from '../../../../sky/scatter.js';
|
||||
import {
|
||||
AERIAL_GLSL,
|
||||
aerialAt,
|
||||
AP_VOLUME,
|
||||
apVolumeWords,
|
||||
SCATTER_GLSL,
|
||||
scatterRadiance,
|
||||
skyViewWords,
|
||||
|
|
@ -86,3 +99,43 @@ describe('the GLSL sampler', () => {
|
|||
expect(SCATTER_GLSL).toContain('* 6.0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the aerial perspective volume as the terrain reads it', () => {
|
||||
it('uploads RGBA half floats in the baked layout', () => {
|
||||
const a = baked.scatter.aerial_perspective;
|
||||
expect(apVolumeWords()).toHaveLength(a.width * a.height * a.depth * 4);
|
||||
expect(AP_VOLUME).toEqual({ width: a.width, height: a.height, depth: a.depth });
|
||||
});
|
||||
|
||||
it('on a texel centre the CPU twin returns the baked ray exactly (to half-float precision)', () => {
|
||||
const sunI = 8;
|
||||
const ei = 5;
|
||||
const slice = 6;
|
||||
const want = aerialRay(SUN_ELEVATIONS_DEG[sunI], apElevation(ei), 90)[slice];
|
||||
const got = aerialAt(SUN_ELEVATIONS_DEG[sunI], apElevation(ei), 90, apSliceKm(slice));
|
||||
for (let c = 0; c < 3; c += 1) expect(got.L[c]).toBeCloseTo(want[c], 3);
|
||||
expect(got.alpha).toBeCloseTo(want[3], 3);
|
||||
});
|
||||
|
||||
it('between texels it is near the model: the filtering error is small against the signal', () => {
|
||||
const want = aerialRay(10, -1.3, 75)[AP_SLICES - 2];
|
||||
const got = aerialAt(10, -1.3, 75, apSliceKm(AP_SLICES - 2));
|
||||
expect(Math.abs(got.alpha - want[3])).toBeLessThan(0.03);
|
||||
expect(got.L[0] / want[0]).toBeGreaterThan(0.6);
|
||||
expect(got.L[0] / want[0]).toBeLessThan(1.6);
|
||||
});
|
||||
|
||||
it('fades to nothing at the observer, and clamps past the last slice', () => {
|
||||
expect(aerialAt(45, -2, 90, 0)).toEqual({ L: [0, 0, 0], alpha: 0 });
|
||||
const last = aerialAt(45, -2, 90, apSliceKm(AP_SLICES - 1));
|
||||
const beyond = aerialAt(45, -2, 90, 1e6);
|
||||
expect(beyond.alpha).toBeCloseTo(last.alpha, 9);
|
||||
});
|
||||
|
||||
it('the shader lookup carries the same constants as the table', () => {
|
||||
const a = baked.scatter.aerial_perspective;
|
||||
expect(AERIAL_GLSL).toContain(`/ ${a.height}.0`);
|
||||
expect(AERIAL_GLSL).toContain(`${a.max_km.toFixed(1)}`);
|
||||
expect(AERIAL_GLSL).toContain(`${AP_ELEVATIONS}.0 +`);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,10 +2,20 @@
|
|||
// uses them: decoded to half-float words for the GPU, a CPU twin of the shader's sky lookup for tests and
|
||||
// for the sun's colour at an arbitrary elevation, and the GLSL both shaders share. No DOM, no GL.
|
||||
import { baked } from '../../../../sky/baked';
|
||||
import { decode, sunIndex, viewIndex } from '../../../../sky/scatter.js';
|
||||
import {
|
||||
AP_DISTANCE_SCALE,
|
||||
AP_ELEVATIONS,
|
||||
AP_SLICES,
|
||||
apElevationIndex,
|
||||
apSliceIndex,
|
||||
decode,
|
||||
sunIndex,
|
||||
viewIndex,
|
||||
} from '../../../../sky/scatter.js';
|
||||
import type { Vec3 } from './terrainSky';
|
||||
|
||||
const S = baked.scatter;
|
||||
const AP = S.aerial_perspective;
|
||||
const SKY = S.sky_view;
|
||||
const VIEW = S.view_elevation_deg;
|
||||
|
||||
|
|
@ -22,6 +32,11 @@ export const SKY_VIEW = { width: SKY.width, height: SKY.height, depth: SKY.depth
|
|||
export const STORE_SCALE = S.store_scale;
|
||||
export const skyViewWords = (): Uint16Array => tableWords(SKY.data);
|
||||
|
||||
/** The aerial perspective volume (layout in src/sky/scatter.js): RGBA16F, x azimuth from the light, y slice-major block of elevations, z light elevation. */
|
||||
export const AP_VOLUME = { width: AP.width, height: AP.height, depth: AP.depth } as const;
|
||||
export const apVolumeWords = (): Uint16Array => tableWords(AP.data);
|
||||
export { AP_DISTANCE_SCALE };
|
||||
|
||||
/** Decode a stored table to values, once. */
|
||||
const decoded = (data: string) => {
|
||||
let values: Float32Array | undefined;
|
||||
|
|
@ -32,6 +47,7 @@ const decoded = (data: string) => {
|
|||
};
|
||||
const transmittanceTable = decoded(S.transmittance.data);
|
||||
const skyTable = decoded(SKY.data);
|
||||
const apTable = decoded(AP.data);
|
||||
|
||||
/** Sun colour at normal incidence for a sun at `elevationDeg`: the baked transmittance, per channel. Zero under the horizon. */
|
||||
export function transmittanceAt(elevationDeg: number): Vec3 {
|
||||
|
|
@ -67,6 +83,52 @@ export function scatterRadiance(sunElDeg: number, viewElDeg: number, azFromSunDe
|
|||
return [out[0], out[1], out[2]];
|
||||
}
|
||||
|
||||
/**
|
||||
* Aerial perspective along a view ray: in-scatter luminance per channel (for a light of unit irradiance) and opacity
|
||||
* (1 - mean transmittance), for a light at `lightElDeg`, a ray `viewElDeg` (0 and below) and `azDeg` from the light,
|
||||
* `km` of baked path along it. Trilinear in (azimuth, elevation, light elevation) and linear between slices, the arithmetic the
|
||||
* shader's `aerial()` does on the GPU; below the first slice it fades to nothing at the observer (Hillaire's near-slice fade).
|
||||
*/
|
||||
export function aerialAt(
|
||||
lightElDeg: number,
|
||||
viewElDeg: number,
|
||||
azDeg: number,
|
||||
km: number
|
||||
): { L: Vec3; alpha: number } {
|
||||
const t = apTable();
|
||||
const x = Math.min(Math.abs(azDeg) / 180, 1) * (AP.width - 1);
|
||||
const e = apElevationIndex(viewElDeg);
|
||||
const z = sunIndex(lightElDeg);
|
||||
const texel = (slice: number): number[] => {
|
||||
const lo = [
|
||||
Math.min(Math.floor(x), AP.width - 2),
|
||||
Math.min(Math.floor(e), AP_ELEVATIONS - 2),
|
||||
Math.min(Math.floor(z), AP.depth - 2),
|
||||
];
|
||||
const f = [x - lo[0], e - lo[1], z - lo[2]];
|
||||
const out = [0, 0, 0, 0];
|
||||
for (let corner = 0; corner < 8; corner += 1) {
|
||||
const dx = corner % 2;
|
||||
const dy = Math.floor(corner / 2) % 2;
|
||||
const dz = Math.floor(corner / 4);
|
||||
const w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]);
|
||||
const base =
|
||||
(((lo[2] + dz) * AP.height + slice * AP_ELEVATIONS + lo[1] + dy) * AP.width + lo[0] + dx) *
|
||||
4;
|
||||
for (let c = 0; c < 4; c += 1) out[c] += w * t[base + c];
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const f = apSliceIndex(km);
|
||||
const fs = Math.min(Math.max(f, 0), AP_SLICES - 1);
|
||||
const k = Math.min(Math.floor(fs), AP_SLICES - 2);
|
||||
const a = texel(k);
|
||||
const b = texel(k + 1);
|
||||
const fade = Math.min(Math.max(f + 1, 0), 1);
|
||||
const v = [0, 1, 2, 3].map((c) => (a[c] + (b[c] - a[c]) * (fs - k)) * fade);
|
||||
return { L: [v[0], v[1], v[2]], alpha: v[3] };
|
||||
}
|
||||
|
||||
/**
|
||||
* The lowest view elevation the sky is sampled at, degrees. The table dips toward the ground over its last degree
|
||||
* (its rows below the horizon are for an observer who would hit the ground), so at and below this the sky and the
|
||||
|
|
@ -92,3 +154,26 @@ vec3 skyScatter(vec3 d) {
|
|||
SKY.height
|
||||
}.0, (uSunIndex + 0.5) / ${SKY.depth}.0)).rgb / ${S.store_scale.toFixed(1)};
|
||||
}`;
|
||||
|
||||
/**
|
||||
* The aerial perspective lookup, in GLSL: `aerial(lightIndex, viewElDeg, azDeg, km)` is `aerialAt` on the GPU. Needs uAP.
|
||||
* Each slice is one hardware-filtered fetch, kept inside its block of elevation rows so the filter never reads a
|
||||
* neighbouring slice; two fetches and a lerp per call.
|
||||
*/
|
||||
export const AERIAL_GLSL = `
|
||||
uniform highp sampler3D uAP;
|
||||
vec4 apSlice(float k, float e, float x, float z) {
|
||||
return texture(uAP, vec3((x + 0.5) / ${AP.width}.0, (k * ${AP.elevations}.0 + e + 0.5) / ${
|
||||
AP.height
|
||||
}.0, (z + 0.5) / ${AP.depth}.0)) / ${S.store_scale.toFixed(1)};
|
||||
}
|
||||
vec4 aerial(float lightIndex, float viewElDeg, float azDeg, float km) {
|
||||
float e = ${(AP.elevations - 1).toFixed(
|
||||
1
|
||||
)} * (1.0 - sqrt(clamp(-viewElDeg / ${(-AP.elevation_min_deg).toFixed(1)}, 0.0, 1.0)));
|
||||
float x = clamp(abs(azDeg) / 180.0, 0.0, 1.0) * ${(AP.width - 1).toFixed(1)};
|
||||
float f = ${AP.slices}.0 * sqrt(max(km, 0.0) / ${AP.max_km.toFixed(1)}) - 1.0;
|
||||
float fs = clamp(f, 0.0, ${(AP.slices - 1).toFixed(1)});
|
||||
float k = min(floor(fs), ${(AP.slices - 2).toFixed(1)});
|
||||
return mix(apSlice(k, e, x, lightIndex), apSlice(k + 1.0, e, x, lightIndex), fs - k) * clamp(f + 1.0, 0.0, 1.0);
|
||||
}`;
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ import cultmath from '../shaders/CultMath.glsl?raw';
|
|||
import phacelle from '../shaders/CultMath.Phacelle.glsl?raw';
|
||||
import { trimGlsl } from '../cultmathTrim';
|
||||
import { ALBEDO } from './terrainAlbedo';
|
||||
import { SCATTER_GLSL } from './terrainScatter';
|
||||
import { GLOW_ZENITH, HAZE_POWER, SKY_EXPOSURE } from './terrainSky';
|
||||
import { AERIAL_GLSL, AP_DISTANCE_SCALE, SCATTER_GLSL } from './terrainScatter';
|
||||
import { GLOW_ZENITH, MOON_HAZE, SKY_EXPOSURE, STAR_FLOOR } from './terrainSky';
|
||||
import { TERRAIN } from './terrainWorld';
|
||||
|
||||
const HEADER =
|
||||
|
|
@ -146,11 +146,11 @@ vec3 skyColour(vec3 d) {
|
|||
)}, sqrt(clamp(d.y, 0.0, 1.0)));
|
||||
}`;
|
||||
|
||||
export const GRID_FRAG = `${HEADER}${ALBEDO_DEFINES}${SKY_COLOUR_GLSL}
|
||||
export const GRID_FRAG = `${HEADER}${ALBEDO_DEFINES}${SKY_COLOUR_GLSL}${AERIAL_GLSL}
|
||||
in vec2 v_uv;
|
||||
in vec3 v_world;
|
||||
uniform vec3 uCamera, uLightDir, uLight, uAmbient, uSoil, uScree, uRock, uSnow;
|
||||
uniform float uSpan, uHazeK, uSnowLine;
|
||||
uniform float uSpan, uSnowLine, uNight, uMoonIndex;
|
||||
out vec4 o;
|
||||
${FETCH}
|
||||
// Triplanar patterns: each projection plane's value, blended by the weights of the face's normal (terrainAlbedo.triWeights).
|
||||
|
|
@ -187,9 +187,23 @@ void main() {
|
|||
float cavity = 1.0 - 0.55 * clamp(curv / 12.0, 0.0, 1.0) + 0.3 * clamp(-curv / 12.0, 0.0, 1.0);
|
||||
vec3 lit = albedo * cavity * (uLight * max(dot(n, uLightDir), 0.0) + uAmbient * (0.5 + 0.5 * n.y));
|
||||
vec3 toSurface = v_world - uCamera;
|
||||
float T = exp(-pow(uHazeK * length(toSurface), ${lit(HAZE_POWER)}));
|
||||
vec3 haze = skyColour(normalize(vec3(toSurface.x, 0.0, toSurface.z)));
|
||||
o = vec4(pow(mix(haze, lit, T), vec3(1.0 / 2.2)), 1.0);
|
||||
float dist = length(toSurface);
|
||||
// Aerial perspective (terrainSky.aerialPerspective): the baked volume by this ray's elevation, azimuth from the light and path.
|
||||
vec3 ray = toSurface / dist;
|
||||
float el = min(degrees(asin(clamp(ray.y, -1.0, 1.0))), 0.0);
|
||||
vec2 hz = ray.xz, sz = uSun.xz;
|
||||
float az = (length(hz) < 1e-4 || length(sz) < 1e-4) ? 0.0 : degrees(acos(clamp(dot(normalize(hz), normalize(sz)), -1.0, 1.0)));
|
||||
float km = dist * ${lit(AP_DISTANCE_SCALE / 1000)};
|
||||
vec4 ap = aerial(uSunIndex, el, az, km);
|
||||
vec3 L = ap.rgb;
|
||||
// The moon lights the haze from where the sun is mirrored above the horizon, sharing its azimuth; a starlight floor stays.
|
||||
if (uNight > 0.0) L += uNight * vec3(${MOON_HAZE.map(lit).join(
|
||||
', '
|
||||
)}) * aerial(uMoonIndex, el, az, km).rgb;
|
||||
vec3 haze = 1.0 - exp(-${lit(SKY_EXPOSURE)} * L) + uNight * ap.a * vec3(${STAR_FLOOR.map(
|
||||
lit
|
||||
).join(', ')});
|
||||
o = vec4(pow(lit * (1.0 - ap.a) + haze, vec3(1.0 / 2.2)), 1.0);
|
||||
}`;
|
||||
|
||||
// The sky behind: the baked scattering tables by the view ray's elevation and azimuth from the sun, a sun disc, and a
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
/* eslint-disable no-restricted-syntax -- tests loop over skies, normals and distances */
|
||||
import { AP_DISTANCE_SCALE } from './terrainScatter';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { baked } from '../../../../sky/baked';
|
||||
import {
|
||||
|
|
@ -13,7 +14,8 @@ import {
|
|||
skyColour,
|
||||
skyNameFor,
|
||||
sunDirection,
|
||||
transmittance,
|
||||
aerialPerspective,
|
||||
metresToKm,
|
||||
groundLight,
|
||||
HAZE_K,
|
||||
HAZE_POWER,
|
||||
|
|
@ -185,47 +187,72 @@ describe('the scattered sky', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('haze', () => {
|
||||
it('transmittance falls monotonically from 1 toward 0', () => {
|
||||
let prev = transmittance(0);
|
||||
expect(prev).toBe(1);
|
||||
for (const d of [10, 100, 400, 1000, 3000, 8000]) {
|
||||
const t = transmittance(d);
|
||||
expect(t).toBeLessThan(prev);
|
||||
expect(t).toBeGreaterThan(0);
|
||||
prev = t;
|
||||
describe('aerial perspective', () => {
|
||||
const ray = (el: number, az: number): Vec3 => look(el, az);
|
||||
const along = (d: typeof SKY.midnight, el: number, az: number, m: number) =>
|
||||
aerialPerspective(d, ray(el, az), m);
|
||||
|
||||
it('opacity grows with distance from nothing at the eye toward the far value, never past 1', () => {
|
||||
let prev = along(SKY.noonday, -2, 200, 0).alpha;
|
||||
expect(prev).toBe(0);
|
||||
for (const m of [10, 100, 400, 1000, 2000, 2500]) {
|
||||
const a = along(SKY.noonday, -2, 200, m).alpha;
|
||||
expect(a).toBeGreaterThan(prev);
|
||||
expect(a).toBeLessThanOrEqual(1);
|
||||
prev = a;
|
||||
}
|
||||
});
|
||||
|
||||
it('far surfaces take the scattered sky at the horizon in their azimuth, at both skies', () => {
|
||||
for (const d of [...Object.values(SKY), skyAtSun(2, 270)]) {
|
||||
const far = shade(d, [0.9, 0.2, 0.1], UP, 100000, look(-3, 200));
|
||||
const sky = skyColour(d, look(0, 200));
|
||||
for (let i = 0; i < 3; i += 1) expect(far[i]).toBeCloseTo(sky[i], 6);
|
||||
}
|
||||
it('leaves the near ground its own colour and takes the far ridges', () => {
|
||||
expect(along(SKY.noonday, -2, 200, 100).alpha).toBeLessThan(0.15);
|
||||
expect(along(SKY.noonday, -2, 200, 2000).alpha).toBeGreaterThan(0.3);
|
||||
});
|
||||
|
||||
it('haze toward the dusk sun is warmer and brighter than haze away from it', () => {
|
||||
const dusk = skyAtSun(-1, 270);
|
||||
const toward = shade(dusk, [0, 0, 0], UP, 100000, look(-3, 270));
|
||||
const away = shade(dusk, [0, 0, 0], UP, 100000, look(-3, 90));
|
||||
const blueShare = (c: Vec3) => c[2] / (c[0] + c[1] + c[2]);
|
||||
it('the in-scatter is a function of the baked volume: its colour is bluer than the sun far by day', () => {
|
||||
const far = along(SKY.noonday, -2, 90, 2400).colour;
|
||||
expect(far[2]).toBeGreaterThan(far[0]);
|
||||
});
|
||||
|
||||
it('haze toward a setting sun is brighter than away from it, and red, not blue (the sun is reddened on its way)', () => {
|
||||
const dusk = skyAtSun(2, 270);
|
||||
const toward = along(dusk, -1, 270, 2000).colour;
|
||||
const away = along(dusk, -1, 90, 2000).colour;
|
||||
expect(luma(toward)).toBeGreaterThan(3 * luma(away));
|
||||
expect(blueShare(toward)).toBeLessThan(blueShare(away));
|
||||
expect(toward[0]).toBeGreaterThan(toward[2]);
|
||||
});
|
||||
|
||||
it('haze colour differs between the two skies: pale day horizon, dim night one', () => {
|
||||
const far = (d: typeof SKY.midnight) => luma(shade(d, [0, 0, 0], UP, 1e6, look(-3, 180)));
|
||||
expect(far(SKY.noonday)).toBeGreaterThan(5 * far(SKY.midnight));
|
||||
it('night haze is a deep blue floor, not grey: dark, blue over red by a wide margin, brighter than black', () => {
|
||||
const c = along(SKY.midnight, -2, 0, 2400).colour;
|
||||
expect(luma(c)).toBeGreaterThan(0.001);
|
||||
expect(luma(c)).toBeLessThan(0.08);
|
||||
expect(c[2]).toBeGreaterThan(2.5 * c[0]);
|
||||
expect(luma(along(SKY.noonday, -2, 0, 2400).colour)).toBeGreaterThan(5 * luma(c));
|
||||
});
|
||||
|
||||
it('with distance a dark surface rises toward the haze and a bright one falls toward it', () => {
|
||||
it('moonlight lights the night haze toward the moon more than away from it', () => {
|
||||
const moon = groundLight(SKY.midnight).dir;
|
||||
const toward = aerialPerspective(SKY.midnight, [moon[0], -0.02, moon[2]], 2400).colour;
|
||||
const away = aerialPerspective(SKY.midnight, [-moon[0], -0.02, -moon[2]], 2400).colour;
|
||||
expect(luma(toward)).toBeGreaterThan(luma(away));
|
||||
});
|
||||
|
||||
it('with distance a dark surface rises toward the haze and its own colour is lost', () => {
|
||||
const d = SKY.noonday;
|
||||
const view = look(-4, 200);
|
||||
const h = luma(skyColour(d, look(0, 200)));
|
||||
const view = ray(-4, 200);
|
||||
const dark = (x: number) => luma(shade(d, [0.02, 0.02, 0.02], UP, x, view));
|
||||
expect(dark(2000)).toBeGreaterThan(dark(200));
|
||||
expect(dark(2000)).toBeLessThan(h);
|
||||
expect(dark(2000)).toBeGreaterThan(dark(100));
|
||||
const own = (x: number) => 1 - aerialPerspective(d, view, x).alpha;
|
||||
expect(own(2000)).toBeLessThan(0.7 * own(100));
|
||||
});
|
||||
|
||||
it('is continuous in the sun elevation through dusk: no step between neighbours', () => {
|
||||
const at = (e: number) => luma(along(skyAtSun(e, 270), -1, 270, 2000).colour);
|
||||
for (let e = -12; e < 12; e += 0.5) expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.45);
|
||||
});
|
||||
|
||||
it('the metres-to-km law is the scene metres times the baked distance scale', () => {
|
||||
expect(metresToKm(1000)).toBeCloseTo(AP_DISTANCE_SCALE, 9);
|
||||
expect(metresToKm(-5)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -246,13 +273,6 @@ describe('ground light and haze', () => {
|
|||
for (let e = -10; e < 10; e += 0.5) expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.35);
|
||||
});
|
||||
|
||||
it('haze leaves the near ground nearly clear and takes the far ridges: a power law, not plain exp(-k d)', () => {
|
||||
expect(transmittance(300)).toBeGreaterThan(0.85);
|
||||
expect(transmittance(300)).toBeGreaterThan(Math.exp(-HAZE_K * 300));
|
||||
expect(transmittance(2500)).toBeLessThan(0.15);
|
||||
expect(HAZE_POWER).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it('the camera starts with the noon sun off its axis, so the light rakes the relief', () => {
|
||||
const yaw = 2 * Math.PI * START_TURNS;
|
||||
const forward = [Math.sin(yaw), 0, -Math.cos(yaw)];
|
||||
|
|
|
|||
|
|
@ -4,7 +4,13 @@ import { baked } from '../../../../sky/baked';
|
|||
import { isNight } from '../ridge/stars';
|
||||
import { skyColours } from '../ridge/skyColour';
|
||||
import type { SkyColours } from '../ridge/skyColour';
|
||||
import { HORIZON_FLOOR, scatterRadiance, transmittanceAt } from './terrainScatter';
|
||||
import {
|
||||
AP_DISTANCE_SCALE,
|
||||
aerialAt,
|
||||
HORIZON_FLOOR,
|
||||
scatterRadiance,
|
||||
transmittanceAt,
|
||||
} from './terrainScatter';
|
||||
|
||||
export type SkyName = 'midnight' | 'noonday';
|
||||
export type Vec3 = readonly [number, number, number];
|
||||
|
|
@ -129,13 +135,48 @@ export function skyColour(d: SkyData, dir: Vec3): Vec3 {
|
|||
}
|
||||
|
||||
/**
|
||||
* Haze: transmittance T = exp(-(k d)^HAZE_POWER) at distance d metres. The power above 1 keeps the near and middle
|
||||
* ground at its own colour and lets only the far ridges melt toward the sky; a plain exp(-k d) greyed everything.
|
||||
* Aerial perspective: the baked volume of src/sky/scatter.js (after Hillaire 2020, see there for what follows the paper
|
||||
* and what does not), looked up by the view ray relative to the light and the metres to the surface. The surface keeps
|
||||
* (1 - alpha) of its own colour (alpha = 1 - mean transmittance, a grey transmittance as the paper) and gains the in-scatter L,
|
||||
* lifted by the sky's exposure and tone-mapped the way the sky is, so far ground meets the sky's colour. SHORTCUT: the path is
|
||||
* the scene's metres times AP_DISTANCE_SCALE (a real atmosphere is nearly clear over 3 km).
|
||||
*/
|
||||
export const HAZE_K = 0.0007;
|
||||
export const HAZE_POWER = 1.6;
|
||||
export const transmittance = (distance: number): number =>
|
||||
Math.exp(-((HAZE_K * Math.max(0, distance)) ** HAZE_POWER));
|
||||
export const metresToKm = (metres: number): number =>
|
||||
(Math.max(0, metres) / 1000) * AP_DISTANCE_SCALE;
|
||||
|
||||
/** Moonlight's irradiance on the haze, relative to the sun's 1, at full night. EYEBALLED, far above a real moon (about 3e-6) as the sky exposure is. */
|
||||
export const MOON_HAZE: Vec3 = [0.0004, 0.0007, 0.0018];
|
||||
/** Starlight and airglow scattered by the air, added to the in-scatter in proportion to alpha, at full night: a deep blue floor, not grey. EYEBALLED. */
|
||||
export const STAR_FLOOR: Vec3 = [0.0006, 0.0012, 0.0045];
|
||||
|
||||
/** Haze in front of a surface seen along `dir` (unit, eye to surface) `distance` metres away: the colour it adds and the surface's loss. */
|
||||
export function aerialPerspective(
|
||||
d: SkyData,
|
||||
dir: Vec3,
|
||||
distance: number
|
||||
): { colour: Vec3; alpha: number } {
|
||||
const el = Math.min(0, Math.asin(Math.min(1, Math.max(-1, dir[1]))) / RAD);
|
||||
const sun = sunDirection(d);
|
||||
const h = Math.hypot(dir[0], dir[2]);
|
||||
const s = Math.hypot(sun[0], sun[2]);
|
||||
const az =
|
||||
h < 1e-4 || s < 1e-4
|
||||
? 0
|
||||
: Math.acos(Math.min(1, Math.max(-1, (dir[0] * sun[0] + dir[2] * sun[2]) / (h * s)))) / RAD;
|
||||
const km = metresToKm(distance);
|
||||
const night = nightness(d.elevation);
|
||||
const day = aerialAt(d.elevation, el, az, km);
|
||||
const L = [...day.L];
|
||||
if (night > 0) {
|
||||
// The moon stands where the sun is mirrored above the horizon (groundLight), so it shares the sun's azimuth.
|
||||
const moon = aerialAt(Math.abs(d.elevation), el, az, km);
|
||||
for (let i = 0; i < 3; i += 1) L[i] += MOON_HAZE[i] * night * moon.L[i];
|
||||
}
|
||||
const colour = [0, 1, 2].map(
|
||||
(i) => 1 - Math.exp(-SKY_EXPOSURE * L[i]) + STAR_FLOOR[i] * night * day.alpha
|
||||
) as unknown as Vec3;
|
||||
return { colour, alpha: day.alpha };
|
||||
}
|
||||
|
||||
/** Added to the ambient on a dark sky, scaled by `nightness`: the baked night floor is too dark to show any form on a phone. */
|
||||
export const NIGHT_AMBIENT_LIFT = 3;
|
||||
|
|
@ -162,19 +203,17 @@ export const START_TURNS = ((SKY.noonday.azimuth - 100) / 360 + 1) % 1;
|
|||
/**
|
||||
* Linear colour of a surface seen along the unit direction `view` (from the eye to the surface): lambert from
|
||||
* the ground light plus ambient (full on an upward face, half on a vertical one, none on a downward one: `0.5 + 0.5 n.y`),
|
||||
* then hazed by distance toward the sky at the horizon in that direction. `normal` is a unit vector. Never negative.
|
||||
* then aerial perspective (`aerialPerspective`). `normal` is a unit vector. Never negative.
|
||||
*/
|
||||
export function shade(d: SkyData, albedo: Vec3, normal: Vec3, distance: number, view: Vec3): Vec3 {
|
||||
const light = groundLight(d);
|
||||
const sun = light.dir;
|
||||
const lambert = Math.max(0, normal[0] * sun[0] + normal[1] * sun[1] + normal[2] * sun[2]);
|
||||
const hemi = 0.5 + 0.5 * normal[1];
|
||||
const flat = Math.hypot(view[0], view[2]) || 1;
|
||||
const haze = skyColour(d, [view[0] / flat, 0, view[2] / flat]);
|
||||
const t = transmittance(distance);
|
||||
const haze = aerialPerspective(d, view, distance);
|
||||
return [0, 1, 2].map((i) => {
|
||||
const lit = albedo[i] * (light.colour[i] * lambert + light.ambient[i] * Math.max(0, hemi));
|
||||
return lit * t + haze[i] * (1 - t);
|
||||
return lit * (1 - haze.alpha) + haze.colour[i];
|
||||
}) as unknown as Vec3;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -81,3 +81,25 @@ Size: 16,128 bytes for `sky_view` (21.5 KB as base64) and 192 bytes for `transmi
|
|||
twice the "few KB" of an 8-bit table, the price of not quantising the glow. `scatter.test.ts` pins the
|
||||
layout, the encoding, the checksums and a set of physical anchors (blue noon sky, red sunset toward the sun,
|
||||
black below the planet's shadow limit).
|
||||
|
||||
### `aerial_perspective`: the camera volume for ground seen through the air
|
||||
|
||||
After Hillaire, "A Scalable and Production Ready Sky and Atmosphere Rendering Technique", EGSR 2020, section 5.4, and its
|
||||
reference code (sebh/UnrealEngineSkyAtmosphere, `RenderCameraVolumePS` in `RenderSkyRayMarching.hlsl`). RGBA half floats
|
||||
(same encoding, `store_scale` 64), `width` 7, `height` 96, `depth` 12, 4 channels; one 3D texture, `x` fastest:
|
||||
|
||||
- `x`: azimuth of the view ray from the light, 0, 30, ... 180 degrees (as `sky_view`).
|
||||
- `y`: `slice * 8 + elevation`: 12 slices, each a block of 8 view elevations, `-50 * (1 - i / 7)^2` degrees (finest at 0,
|
||||
rays at or above the horizon are clamped to 0). Keep the filter inside a block: sample at `(slice * 8 + e + 0.5) / 96`, `e` in 0..7.
|
||||
- `z`: light elevation, `sun_elevations_deg`, as `sky_view`. The same volume serves the moon: look up at the moon's elevation.
|
||||
- Slice `k` is the far side of `max_km * ((k + 1) / 12)^2` km (the paper's squared distribution; `max_km` 20). Between slices interpolate
|
||||
linearly; below slice 0 fade to zero at the observer, as the reference does for `Slice < 0.5`.
|
||||
- RGB: in-scatter luminance per steradian for a light of unit irradiance. A: opacity `1 - mean(rgb transmittance)`, the paper's grey
|
||||
transmittance. Apply as `surface * (1 - A) + L * exposure`.
|
||||
|
||||
Follows the paper: the squared slice distribution, the in-scatter integral with each step's extinction integrated analytically
|
||||
(`S (1 - exp(-e dt)) / e`), single scattering with Rayleigh and Mie (g 0.8) phase, and the grey opacity in alpha.
|
||||
Shortcuts: sun-relative azimuth and elevation instead of screen position; 12 x 8 x 7 texels, not 32 x 32 x 32; path lengths are the
|
||||
scene's metres times `distance_scale` (8), because a real atmosphere is nearly clear across a 3 km patch; the ray ignores the ground
|
||||
(density held at its ground value, sun visibility tested from the ground sphere); no multi-scattering LUT (the paper's dusk fix);
|
||||
observer at 100 m. Units: distances in km, radiance per unit sun irradiance, as `sky_view`. 86 KB as base64.
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -193,6 +193,87 @@ export function skyRadiance(sunElevationDeg, viewElevationDeg, azimuthDeg) {
|
|||
return radiance;
|
||||
}
|
||||
|
||||
// ---- Aerial perspective ------------------------------------------------------------------------------------------
|
||||
// After Hillaire, "A Scalable and Production Ready Sky and Atmosphere Rendering Technique", EGSR 2020 (section 5.4, the
|
||||
// aerial perspective "camera volume"), and its reference implementation, sebh/UnrealEngineSkyAtmosphere
|
||||
// Resources/RenderSkyRayMarching.hlsl `RenderCameraVolumePS`: a volume of AP_SLICES slices whose depth grows with the
|
||||
// square of the slice index (`Slice *= Slice`), each texel holding the single-scattered luminance L accumulated along
|
||||
// the view ray to that depth, and in alpha the opacity 1 - mean(rgb transmittance) (a grey transmittance, as the paper).
|
||||
// Applied to a surface as out = surface * (1 - alpha) + L, with L the in-scatter along that ray.
|
||||
//
|
||||
// What differs from the paper, and why:
|
||||
// - the volume is indexed by the view ray relative to the sun (azimuth from the sun, elevation) and sun elevation, not by
|
||||
// screen position, because the terrain camera turns and the sky tables here are sun-relative too;
|
||||
// - the path lengths are the scene's length times AP_DISTANCE_SCALE: a real atmosphere is nearly clear over the 3 km patch,
|
||||
// so the baked path is that many times longer (EYEBALLED); it sets how fast far ridges go to the sky;
|
||||
// - the ray ignores the ground: below the observer's altitude the density is held at its ground value, and the sun's
|
||||
// visibility is tested from the ground sphere; the terrain is the ground;
|
||||
// - single scattering with the sky tables' own air (no multi-scattering LUT, which the paper adds for dusk);
|
||||
// - AP_SLICES = 12 slices, 8 view elevations and 7 azimuths, not 32 x 32 x 32 screen froxels, to stay phone-sized.
|
||||
export const AP_SLICES = 12;
|
||||
export const AP_ELEVATIONS = 8;
|
||||
/** The view elevations the volume holds run from this down to 0 degrees, finest at 0: -AP_ELEVATION_MIN_DEG * (1 - i / 7)^2. */
|
||||
export const AP_ELEVATION_MIN_DEG = 50;
|
||||
/** Scene metres a slice volume covers: the patch's far corner (about 2.1 km) with margin. */
|
||||
export const AP_SCENE_MAX_M = 2500;
|
||||
export const AP_DISTANCE_SCALE = 8;
|
||||
/** Physical kilometres the last slice stands for. */
|
||||
export const AP_MAX_KM = (AP_SCENE_MAX_M * AP_DISTANCE_SCALE) / 1000;
|
||||
const AP_SUBSTEPS = 4;
|
||||
|
||||
export const apElevation = (i) => -AP_ELEVATION_MIN_DEG * (1 - i / (AP_ELEVATIONS - 1)) ** 2;
|
||||
/** Fractional elevation index of a view elevation in degrees (clamped to 0 degrees and below). */
|
||||
export const apElevationIndex = (deg) =>
|
||||
(AP_ELEVATIONS - 1) * (1 - Math.sqrt(clamp(-deg / AP_ELEVATION_MIN_DEG, 0, 1)));
|
||||
/** Distance in km at the far side of slice k (k = 0 .. AP_SLICES - 1): the squared distribution. */
|
||||
export const apSliceKm = (k) => AP_MAX_KM * ((k + 1) / AP_SLICES) ** 2;
|
||||
/** Fractional slice index of a distance in km: below 0 the volume fades to nothing at the observer. */
|
||||
export const apSliceIndex = (km) => AP_SLICES * Math.sqrt(Math.max(km, 0) / AP_MAX_KM) - 1;
|
||||
|
||||
/**
|
||||
* In-scatter luminance per channel (for a sun of unit irradiance) and opacity along a view ray from the observer,
|
||||
* at the far side of each of AP_SLICES slices: [[r, g, b, alpha] x AP_SLICES].
|
||||
*/
|
||||
export function aerialRay(sunElevationDeg, viewElevationDeg, azimuthDeg) {
|
||||
const v = viewDirection(viewElevationDeg, azimuthDeg);
|
||||
const s = sunDirection(sunElevationDeg);
|
||||
const cosTheta = v[0] * s[0] + v[1] * s[1] + v[2] * s[2];
|
||||
const pr = rayleighPhase(cosTheta);
|
||||
const pm = miePhase(cosTheta);
|
||||
const out = [];
|
||||
const along = [0, 0, 0];
|
||||
const radiance = [0, 0, 0];
|
||||
let from = 0;
|
||||
for (let k = 0; k < AP_SLICES; k += 1) {
|
||||
const to = apSliceKm(k);
|
||||
const dt = (to - from) / AP_SUBSTEPS;
|
||||
for (let j = 0; j < AP_SUBSTEPS; j += 1) {
|
||||
const t = from + (j + 0.5) * dt;
|
||||
let q = [observer[0] + v[0] * t, observer[1] + v[1] * t, observer[2] + v[2] * t];
|
||||
const r = Math.hypot(...q);
|
||||
if (r < PLANET_RADIUS_KM) q = q.map((x) => (x * PLANET_RADIUS_KM) / r);
|
||||
const h = Math.max(r - PLANET_RADIUS_KM, 0);
|
||||
const e = extinction(h);
|
||||
const toSun = opticalDepthToSpace(q, s, 12);
|
||||
const rm = Math.exp(-h / H_RAYLEIGH);
|
||||
const mm = Math.exp(-h / H_MIE);
|
||||
for (let c = 0; c < 3; c += 1) {
|
||||
// The step's own extinction is integrated analytically (Hillaire eq. 6): S (1 - exp(-e dt)) / e.
|
||||
const step = Math.exp(-e[c] * dt);
|
||||
if (toSun) {
|
||||
const scatter = BETA_RAYLEIGH[c] * rm * pr + BETA_MIE_SCA * mm * pm;
|
||||
radiance[c] += Math.exp(-along[c] - toSun[c]) * ((scatter * (1 - step)) / e[c]);
|
||||
}
|
||||
along[c] += e[c] * dt;
|
||||
}
|
||||
}
|
||||
from = to;
|
||||
const mean = along.reduce((a, x) => a + Math.exp(-x), 0) / 3;
|
||||
out.push([...radiance, 1 - mean]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const base64 = (halves) => {
|
||||
const bytes = new Uint8Array(halves.length * 2);
|
||||
halves.forEach((h, i) => {
|
||||
|
|
@ -226,6 +307,26 @@ export function bakeScatter() {
|
|||
})
|
||||
);
|
||||
|
||||
// x = azimuth from the sun, y = elevation block k * AP_ELEVATIONS + i (slice-major), z = sun elevation: four half floats per texel (L rgb, alpha).
|
||||
const aerial = new Uint16Array(
|
||||
SUN_ELEVATIONS_DEG.length * AP_SLICES * AP_ELEVATIONS * AZIMUTH_SAMPLES * 4
|
||||
);
|
||||
let ap = 0;
|
||||
SUN_ELEVATIONS_DEG.forEach((sun) => {
|
||||
const rays = Array.from({ length: AP_ELEVATIONS }, (_, i) =>
|
||||
Array.from({ length: AZIMUTH_SAMPLES }, (_, a) =>
|
||||
aerialRay(sun, apElevation(i), a * AZIMUTH_STEP_DEG)
|
||||
)
|
||||
);
|
||||
for (let k = 0; k < AP_SLICES; k += 1)
|
||||
for (let i = 0; i < AP_ELEVATIONS; i += 1)
|
||||
for (let a = 0; a < AZIMUTH_SAMPLES; a += 1)
|
||||
rays[i][a][k].forEach((x) => {
|
||||
aerial[ap] = encode(x);
|
||||
ap += 1;
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
planet_radius_km: PLANET_RADIUS_KM,
|
||||
atmosphere_height_km: ATMOSPHERE_HEIGHT_KM,
|
||||
|
|
@ -245,5 +346,17 @@ export function bakeScatter() {
|
|||
channels: 3,
|
||||
data: base64(sky),
|
||||
},
|
||||
aerial_perspective: {
|
||||
slices: AP_SLICES,
|
||||
elevations: AP_ELEVATIONS,
|
||||
elevation_min_deg: -AP_ELEVATION_MIN_DEG,
|
||||
max_km: AP_MAX_KM,
|
||||
distance_scale: AP_DISTANCE_SCALE,
|
||||
width: AZIMUTH_SAMPLES,
|
||||
height: AP_SLICES * AP_ELEVATIONS,
|
||||
depth: SUN_ELEVATIONS_DEG.length,
|
||||
channels: 4,
|
||||
data: base64(aerial),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
AP_ELEVATIONS,
|
||||
AP_MAX_KM,
|
||||
AP_SLICES,
|
||||
apElevation,
|
||||
apElevationIndex,
|
||||
apSliceIndex,
|
||||
apSliceKm,
|
||||
aerialRay,
|
||||
AZIMUTH_SAMPLES,
|
||||
AZIMUTH_STEP_DEG,
|
||||
STORE_SCALE,
|
||||
|
|
@ -158,3 +166,61 @@ describe('scattering tables', () => {
|
|||
expect([sum(sky), sum(trans)]).toEqual([SKY_CHECKSUM, TRANS_CHECKSUM]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('aerial perspective volume', () => {
|
||||
const ap = scatter.aerial_perspective;
|
||||
|
||||
it('has the documented layout and size: RGBA half floats, x azimuth, y slice-major elevations, z sun elevation', () => {
|
||||
expect([ap.width, ap.height, ap.depth, ap.channels]).toEqual([
|
||||
AZIMUTH_SAMPLES,
|
||||
AP_SLICES * AP_ELEVATIONS,
|
||||
SUN_ELEVATIONS_DEG.length,
|
||||
4,
|
||||
]);
|
||||
expect(table(ap.data)).toHaveLength(ap.width * ap.height * ap.depth * 4);
|
||||
});
|
||||
|
||||
it("slices follow the paper's squared distribution, ending at the covered distance", () => {
|
||||
expect(apSliceKm(AP_SLICES - 1)).toBeCloseTo(AP_MAX_KM, 9);
|
||||
expect(apSliceKm(0)).toBeCloseTo(AP_MAX_KM / AP_SLICES ** 2, 9);
|
||||
for (let k = 0; k < AP_SLICES; k += 1) expect(apSliceIndex(apSliceKm(k))).toBeCloseTo(k, 9);
|
||||
expect(apSliceIndex(0)).toBeCloseTo(-1, 9);
|
||||
});
|
||||
|
||||
it('elevations are finest at the horizon and the index inverts them', () => {
|
||||
expect(apElevation(AP_ELEVATIONS - 1)).toBeCloseTo(0, 12);
|
||||
for (let i = 0; i < AP_ELEVATIONS; i += 1)
|
||||
expect(apElevationIndex(apElevation(i))).toBeCloseTo(i, 9);
|
||||
expect(apElevation(AP_ELEVATIONS - 1) - apElevation(AP_ELEVATIONS - 2)).toBeLessThan(
|
||||
apElevation(1) - apElevation(0)
|
||||
);
|
||||
});
|
||||
|
||||
it("opacity grows with path, in-scatter grows with path, and a sun under the planet's shadow scatters nothing", () => {
|
||||
const r = aerialRay(45, -2, 90);
|
||||
for (let k = 1; k < AP_SLICES; k += 1) {
|
||||
expect(r[k][3]).toBeGreaterThan(r[k - 1][3]);
|
||||
expect(r[k][0]).toBeGreaterThan(r[k - 1][0]);
|
||||
}
|
||||
for (const slice of aerialRay(-18, -2, 0)) expect(slice.slice(0, 3)).toEqual([0, 0, 0]);
|
||||
});
|
||||
|
||||
it('is brighter toward a low sun than away, and redder toward it (Rayleigh and Mie phase)', () => {
|
||||
const toward = aerialRay(2, -2, 0)[AP_SLICES - 1];
|
||||
const away = aerialRay(2, -2, 180)[AP_SLICES - 1];
|
||||
expect(toward[0]).toBeGreaterThan(20 * away[0]);
|
||||
expect(toward[0] / toward[2]).toBeGreaterThan(away[0] / away[2]);
|
||||
});
|
||||
|
||||
it('opacity does not depend on the sun, only on the path', () => {
|
||||
expect(aerialRay(45, -2, 0)[5][3]).toBeCloseTo(aerialRay(-18, -2, 90)[5][3], 12);
|
||||
});
|
||||
|
||||
it("the baked table is the model's output: spot texels equal aerialRay, to half-float precision", () => {
|
||||
const t = table(ap.data);
|
||||
const at = (sun: number, slice: number, el: number, az: number, c: number) =>
|
||||
decode(t[((sun * ap.height + slice * AP_ELEVATIONS + el) * ap.width + az) * 4 + c]);
|
||||
const r = aerialRay(SUN_ELEVATIONS_DEG[8], apElevation(6), 60)[7];
|
||||
for (let c = 0; c < 4; c += 1) expect(at(8, 7, 6, 2, c)).toBeCloseTo(r[c], 3);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue