Add raster imagery to the globe contract and draw FIRMS heat and Recent Imagery through it

engine.imagery draws raster layers over the globe: Web Mercator tile
templates and single images or canvases stretched over a rectangle, with
alpha, show, a left/right split against the engine's split position and
an order. A layer's source can be replaced in place.

- Cesium puts one ImageryLayer per layer on the globe's imagery stack,
  or on the shown 3D tileset's when the globe is hidden, and moves it
  when the surface changes; the Recent Imagery request gate moved here.
- Navara draws them in one screen pass after tone mapping that samples up
  to eight layers by geodetic position from mipmapped textures and a tile
  atlas, under the other drapes and engine.ground.
- The fake engine keeps each layer's state.

The FIRMS far-zoom heat raster and Recent Imagery now draw through it, so
FIRMS' heat seam and both its backends, and Recent Imagery's Cesium and
Navara renderers and tile plan, go. Against HEAD, Cesium's pixels are
identical in all four compared scenes; Navara's orbital heat changes by a
mean of 3.8 from new mipmapping, slightly towards Cesium. The contract
suite passes on both engines (Cesium 68/68, Navara 71/71).

engine.maps.addOverlay stays a Navara-only extension for Sea Marks and
Ski Pistes until imagery has a finer tile path for oblique global views.
This commit is contained in:
German Khokhlov committed 2026-11-07 08:07:57 +04:00
1 parent 1559bd57f4
commit 406dd9122e
52 files changed
+4171 -1988

No files matched your search

+25 -1
View File
@@ -54,6 +54,15 @@ const NO_GROUND = Object.freeze({
},
list: () => [],
});
const NO_IMAGERY = Object.freeze({
createLayer() {
throw new Error("Navara imagery needs the view's three runtime (imagery/)");
},
list: () => [],
setSplitPosition() {},
splitPosition: () => 0.5,
surface: () => 'globe',
});
// Navara's drawn camera (view.camera.raw, a three PerspectiveCamera in
// Earth-fixed metres): matrixWorld columns are right, up, back, position.
@@ -73,6 +82,7 @@ function readCamera(raw) {
* @param {object} view An initialised Navara ThreeView.
* @param {{
* hooks: { tileRoots: Function, isIdle: Function, retainTileGeometry: Function, dropOrphanFeatureChanges?: Function },
* imagery?: (parts: { camera: object, size: Function, credits: object, photorealActive: () => boolean }) => { imagery: object, diagnostics: Function, destroy: Function },
* container?: HTMLElement,
* fetch?: typeof fetch,
* clock?: object,
@@ -97,7 +107,9 @@ function readCamera(raw) {
* `movers` is engine.movers on the view's three runtime (movers/index.js;
* without it createSet throws), `lines` engine.lines (lines/index.js;
* likewise), `ground` engine.ground (ground/index.js; likewise), all
* destroyed with the engine;
* destroyed with the engine; `imagery` makes engine.imagery from the
* engine's camera, size, credits and photoreal state (imagery/index.js;
* without it createLayer throws), destroyed with the engine;
* `fetch` and `clock` (the camera model's timers) are test seams.
* @returns {import('../contract.js').GlobeEngine}
*/
@@ -112,6 +124,7 @@ export function createNavaraEngine(
movers: moversPort = null,
lines: linesPort = null,
ground: groundPort = null,
imagery: imageryPort = null,
sharpen: sharpenPort = null,
styles: stylesPort = null,
bloom: bloomPort = null,
@@ -223,6 +236,13 @@ export function createNavaraEngine(
});
const credits = createNavaraCredits(view);
const maps = createNavaraMaps(view, fetch ? { fetch } : {});
const imagery =
imageryPort?.({
camera: model.camera,
size,
credits: credits.credits,
photorealActive: () => maps.maps.photorealActive(),
}) ?? null;
const { surface } = createNavaraSurface(view, hooks);
// Navara's controller zooms through the ground; keep the camera above it.
// With the camera inputs off nothing zooms, and the app places the camera
@@ -414,6 +434,7 @@ export function createNavaraEngine(
movers: moversPort?.movers ?? NO_MOVERS,
lines: linesPort?.lines ?? NO_LINES,
ground: groundPort?.ground ?? NO_GROUND,
imagery: imagery?.imagery ?? NO_IMAGERY,
destroy() {
if (destroyed) return;
destroyed = true;
@@ -424,6 +445,7 @@ export function createNavaraEngine(
input.destroy();
removeGroundPicks();
picking.destroy();
imagery?.destroy();
credits.destroy();
maps.destroy();
sharpenPort?.destroy();
@@ -450,6 +472,8 @@ export function createNavaraEngine(
},
// Navara only, not contract: what the ground pass holds (QA reads it).
groundDiagnostics: () => groundPort?.diagnostics?.() ?? null,
// Navara only, not contract: what each imagery layer holds.
imageryDiagnostics: () => imagery?.diagnostics?.() ?? null,
// Navara only, not contract: the ground the floor last sampled under
// the camera and the margin it keeps above it (QA measures against it).
groundFloor: {
+1 -1
View File
@@ -230,7 +230,7 @@ class GroundEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
'gevEarthquakeGround',
'gevObservedWeather',
'gevNepalEvent',
'gevRecentImagery',
'gevImagery',
'toneMapping',
];
static insertBefore = [
+444
View File
@@ -0,0 +1,444 @@
// engine.imagery on Navara: every shown layer in one screen pass (pass.js),
// classified on the scene depth, so rasters drape on terrain and 3D tiles
// alike. An image source is one texture (mipmapped, wrapping across 180°
// when it spans the globe); setting the same canvas again uploads its new
// pixels. A tiles source is an atlas of at most 8×8 Web Mercator tiles over
// the part of its rectangle in view, at the level the camera's height asks
// for, rebuilt when the camera moves to another plan and filled as tiles
// arrive (6 loads at a time, or the source's maxRequests). A layer's credit
// shows while it does. Every change composes the drawn layers (bottom
// first) and asks for one frame; nothing animates on its own.
import {
CanvasTexture,
ClampToEdgeWrapping,
DataTexture,
LinearFilter,
LinearMipmapLinearFilter,
RepeatWrapping,
RGBAFormat,
Texture,
UnsignedByteType,
} from 'three';
import {
WEB_MERCATOR_LIMIT,
createImageryRegistry,
createImageryTileQueue,
imageryTileLevel,
imageryTilePlan,
imageryTileUrl,
isPixelImage,
wrapsGlobe,
} from '../../imagery.js';
/** Layers one frame of the pass draws (pass.js samples one texture each). */
export const MAX_IMAGERY_SLOTS = 8;
const SIDE = { none: 0, left: -1, right: 1 };
async function loadTile(url, signal) {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error(`Imagery tile HTTP ${response.status}`);
const blob = await response.blob();
signal.throwIfAborted();
return createImageBitmap(blob);
}
const defaultCanvas = (width, height) =>
Object.assign(document.createElement('canvas'), { width, height });
// Linear between texels, mipmapped, row 0 at v = 0 (no flip).
function finish(texture, wrap) {
texture.flipY = false;
texture.magFilter = LinearFilter;
texture.minFilter = LinearMipmapLinearFilter;
texture.generateMipmaps = true;
texture.wrapS = wrap ? RepeatWrapping : ClampToEdgeWrapping;
texture.wrapT = ClampToEdgeWrapping;
texture.needsUpdate = true;
return texture;
}
// An image source's texture. RGBA bytes are read as they are (sRGB bytes,
// blended in display space), as canvases and images are.
function imageTexture(image, wrap) {
if (isPixelImage(image))
return finish(
new DataTexture(
image.data,
image.width,
image.height,
RGBAFormat,
UnsignedByteType,
),
wrap,
);
return finish(
typeof image.getContext === 'function'
? new CanvasTexture(image)
: new Texture(image),
wrap,
);
}
// Degrees, east past west (an antimeridian crossing adds 360°).
const unwrapped = ({ west, south, east, north }) => [
west,
south,
east <= west ? east + 360 : east,
north,
];
/**
* @param {object} view an initialised Navara ThreeView
* @param {{ camera: object, size: () => { width: number, height: number },
* credits: { addStatic: (html: string) => () => void },
* photorealActive: () => boolean,
* createPass: (view: object) => ReturnType<typeof import('./pass.js').createImageryPass>,
* load?: (url: string, signal: AbortSignal) => Promise<object>,
* createCanvas?: (width: number, height: number) => object }} options
* The engine's camera, size and credits; `createPass` makes the pass
* (pass.js createImageryPass; the view's three runtime, which Node tests
* replace); `load` (a tile or an image URL to a decoded image) and
* `createCanvas` are test seams.
* @returns {{ imagery: import('../../contract.js').GlobeImagery,
* diagnostics: () => object, destroy: () => void }}
*/
export function createNavaraImagery(
view,
{
camera,
size,
credits,
photorealActive,
createPass,
load = loadTile,
createCanvas = defaultCanvas,
},
) {
const pass = createPass(view);
const entries = new Map();
let warned = false;
const compose = () => {
const drawn = registry
.ordered()
.map((state) => entries.get(state))
.filter(
(entry) => entry?.state.shown && entry.state.alpha > 0 && entry.slot(),
);
if (drawn.length > MAX_IMAGERY_SLOTS && !warned) {
warned = true;
console.warn(
`[Imagery] Navara draws the top ${MAX_IMAGERY_SLOTS} of ${drawn.length} layers`,
);
}
pass.set(
drawn.slice(-MAX_IMAGERY_SLOTS).map((entry) => entry.slot()),
registry.imagery.splitPosition(),
);
view.forceUpdate();
};
// A layer's credit shows while the layer does.
function syncCredit(entry) {
const credit = entry.state.shown ? entry.state.source.credit : null;
if (credit === entry.credit) return;
entry.releaseCredit?.();
entry.credit = credit;
entry.releaseCredit = credit ? credits.addStatic(credit) : null;
}
function imageEntry(entry) {
let texture = null,
image = null,
loading = null;
const drop = () => {
texture?.dispose();
texture = null;
};
const show = (next, source) => {
const wrapS = wrapsGlobe(source.rectangle)
? RepeatWrapping
: ClampToEdgeWrapping;
if (texture && image === next && texture.wrapS === wrapS) {
// The same canvas or bytes again: their new pixels.
texture.needsUpdate = true;
} else {
drop();
texture = imageTexture(next, wrapS === RepeatWrapping);
}
image = next;
};
return {
source() {
const { source } = entry.state;
loading?.abort();
loading = null;
if (source.image) {
show(source.image, source);
return;
}
drop();
image = null;
const controller = new AbortController();
loading = controller;
Promise.resolve()
.then(() => load(source.url, controller.signal))
.then(
(decoded) => {
if (controller.signal.aborted || entry.state.destroyed) {
decoded?.close?.();
return;
}
loading = null;
show(decoded, source);
compose();
},
(error) => {
if (controller.signal.aborted) return;
loading = null;
console.warn('[Imagery] image failed to load:', error);
},
);
},
slot() {
if (!texture) return null;
const rect = unwrapped(entry.state.source.rectangle);
return {
texture,
rect,
bounds: rect,
look: [entry.state.alpha, SIDE[entry.state.split], 0, 0],
};
},
ready: () => texture !== null,
cameraChanged: () => false,
destroy() {
loading?.abort();
loading = null;
drop();
image = null;
},
diagnostics: () => ({ kind: 'image', loaded: texture !== null }),
};
}
function tilesEntry(entry) {
let atlas = null,
queue = null;
const disposeAtlas = () => {
const current = atlas;
atlas = null;
if (!current) return;
for (const controller of current.controllers) controller.abort();
current.texture.dispose();
current.canvas.width = current.canvas.height = 0;
queue?.prune();
};
// The source's rectangle within Web Mercator's latitudes; across the
// antimeridian the atlas covers every longitude.
const box = () => {
const { west, south, east, north } = entry.state.source.rectangle;
return {
west: west < east ? west : -180,
east: west < east ? east : 180,
south: Math.max(south, -WEB_MERCATOR_LIMIT),
north: Math.min(north, WEB_MERCATOR_LIMIT),
};
};
// The atlas for the view; true when it changed.
function update() {
if (!entry.state.shown) {
if (!atlas) return false;
disposeAtlas();
return true;
}
const source = entry.state.source;
let pose;
try {
pose = camera.pose();
} catch {
// Before the first frame the camera has no pose yet.
return false;
}
const level = Math.max(
source.minLevel,
Math.min(
source.maxLevel,
imageryTileLevel({
height: pose.cartographic.height,
latitude: pose.cartographic.latitude,
fovy: pose.fovy,
heightPx: size().height,
}),
),
);
const plan = imageryTilePlan(box(), camera.viewRectangle(), level);
if ((atlas?.plan.key ?? null) === (plan?.key ?? null)) return false;
disposeAtlas();
if (!plan) return true;
const tile = source.tileSize;
const canvas = createCanvas(plan.width * tile, plan.height * tile);
const texture = finish(new CanvasTexture(canvas), false);
const current = {
plan,
canvas,
texture,
controllers: new Set(),
loaded: 0,
failed: 0,
};
atlas = current;
const context = canvas.getContext('2d');
const tasks = [];
for (let y = 0; y < plan.height; y++)
for (let x = 0; x < plan.width; x++)
tasks.push({
url: imageryTileUrl(
source.url,
plan.x + x,
plan.y + y,
plan.z,
source.subdomains,
),
controllers: current.controllers,
live: () => !entry.state.destroyed && atlas === current,
draw(image) {
context.drawImage(image, x * tile, y * tile, tile, tile);
current.loaded++;
texture.needsUpdate = true;
view.forceUpdate();
},
fail() {
current.failed++;
},
});
queue.add(tasks);
return true;
}
return {
source() {
queue?.destroy();
disposeAtlas();
queue = createImageryTileQueue({
load,
limit: entry.state.source.maxRequests ?? 6,
});
update();
},
slot() {
if (!atlas) return null;
const [west, south, east, north] = unwrapped(
entry.state.source.rectangle,
);
return {
texture: atlas.texture,
rect: [
west,
Math.max(south, -WEB_MERCATOR_LIMIT),
east,
Math.min(north, WEB_MERCATOR_LIMIT),
],
bounds: atlas.plan.bounds,
look: [entry.state.alpha, SIDE[entry.state.split], 1, 0],
};
},
ready: () => true,
cameraChanged: update,
look: update,
destroy() {
queue?.destroy();
queue = null;
disposeAtlas();
},
diagnostics: () => ({
kind: 'tiles',
...(queue?.diagnostics() ?? {}),
atlas: atlas
? {
level: atlas.plan.z,
tiles: atlas.plan.width * atlas.plan.height,
loaded: atlas.loaded,
failed: atlas.failed,
}
: null,
}),
};
}
// One drawing per source kind; a new kind replaces it.
function drawingFor(entry) {
const kind = entry.state.source.kind;
if (entry.drawing?.kind === kind) return entry.drawing;
entry.drawing?.destroy();
entry.drawing = kind === 'image' ? imageEntry(entry) : tilesEntry(entry);
entry.drawing.kind = kind;
return entry.drawing;
}
const registry = createImageryRegistry(
(state) => {
const entry = {
state,
drawing: null,
credit: null,
releaseCredit: null,
slot: () => entry.drawing?.slot() ?? null,
};
entries.set(state, entry);
drawingFor(entry).source();
syncCredit(entry);
compose();
return {
source() {
drawingFor(entry).source();
syncCredit(entry);
compose();
},
look() {
entry.drawing.look?.();
syncCredit(entry);
compose();
},
ready: () => entry.drawing.ready(),
destroy() {
entries.delete(state);
entry.drawing.destroy();
entry.releaseCredit?.();
entry.releaseCredit = null;
compose();
},
};
},
{
splitPosition: () => compose(),
surface: () => (photorealActive() ? 'tiles' : 'globe'),
},
);
const offCamera = camera.changed.addEventListener(() => {
let changed = false;
for (const entry of entries.values())
changed = entry.drawing.cameraChanged() || changed;
if (changed) compose();
});
return {
imagery: registry.imagery,
/** Not contract: what each layer holds (QA reads it). */
diagnostics: () =>
Object.fromEntries(
registry
.ordered()
.map((state) => [
state.options.id,
entries.get(state)?.drawing.diagnostics(),
]),
),
destroy() {
offCamera();
registry.destroyAll();
pass.destroy();
},
};
}
+200
View File
@@ -0,0 +1,200 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createEngineEvent } from '../../contract.js';
import { MAX_IMAGERY_SLOTS, createNavaraImagery } from './index.js';
const BOX = { west: -97.77, south: 30.25, east: -97.71, north: 30.29 };
const tick = () => new Promise((resolve) => setImmediate(resolve));
function fixture() {
const canvases = [];
const draws = [];
const jobs = [];
const sets = [];
const credits = new Map();
const changed = createEngineEvent();
let photoreal = false;
let frames = 0;
const view = {
forceUpdate: () => frames++,
};
const { imagery, diagnostics, destroy } = createNavaraImagery(view, {
camera: {
changed,
pose: () => ({
cartographic: { height: 12_000, latitude: 0.53 },
fovy: 0.7,
}),
viewRectangle: () => null,
},
size: () => ({ width: 1280, height: 800 }),
credits: {
addStatic(html) {
credits.set(html, (credits.get(html) ?? 0) + 1);
return () => credits.set(html, credits.get(html) - 1);
},
},
photorealActive: () => photoreal,
createPass: () => ({
set: (slots, split) => sets.push({ slots, split }),
destroy: () => sets.push('destroyed'),
}),
load: (url, signal) =>
new Promise((resolve) => jobs.push({ url, signal, resolve })),
createCanvas(width, height) {
const canvas = {
width,
height,
getContext: () => ({ drawImage: (image) => draws.push(image) }),
};
canvases.push(canvas);
return canvas;
},
});
return {
imagery,
diagnostics,
destroy,
canvases,
draws,
jobs,
credits,
changed,
last: () => sets.filter((entry) => entry !== 'destroyed').at(-1),
sets,
frames: () => frames,
setPhotoreal: (value) => (photoreal = value),
};
}
const tiles = (extra = {}) => ({
kind: 'tiles',
url: 'https://gibs-{s}.example/{z}/{y}/{x}.png',
maxLevel: 12,
rectangle: BOX,
credit: 'NASA GIBS',
...extra,
});
test('a tiles layer mosaics the visible tiles into one atlas; a new source drops it and its loads', async () => {
const f = fixture();
const layer = f.imagery.createLayer({ id: 'a', source: tiles() });
await tick();
const first = f.diagnostics().a;
assert.equal(first.atlas.level, 12);
assert.ok(first.atlas.tiles >= 1 && first.atlas.tiles <= 64);
assert.equal(f.jobs.length, Math.min(6, first.atlas.tiles), 'six at a time');
assert.match(
f.jobs[0].url,
/^https:\/\/gibs-[abc]\.example\/12\/\d+\/\d+\.png$/,
);
const [slot] = f.last().slots;
assert.deepEqual(slot.look, [1, 0, 1, 0], 'alpha 1, no side, Web Mercator');
assert.deepEqual(slot.rect, [BOX.west, BOX.south, BOX.east, BOX.north]);
assert.equal(f.credits.get('NASA GIBS'), 1);
// A tile arriving draws into the atlas and asks for a frame.
const before = f.frames();
f.jobs[0].resolve({ close() {} });
await tick();
assert.equal(f.draws.length, 1);
assert.ok(f.frames() > before);
// A restyle keeps the atlas; the split side reaches the pass.
const texture = slot.texture;
layer.setAlpha(0.4);
layer.setSplit('left');
assert.equal(f.last().slots[0].texture, texture);
assert.deepEqual(f.last().slots[0].look, [0.4, -1, 1, 0]);
// Another day: the atlas goes, its pending loads abort, late images close.
let disposed = 0;
texture.addEventListener('dispose', () => disposed++);
const pending = f.jobs.slice(1);
layer.setSource(tiles({ url: 'https://other.example/{z}/{x}/{y}.png' }));
assert.equal(disposed, 1);
assert.ok(pending.every((job) => job.signal.aborted));
assert.equal(f.canvases[0].width, 0, 'the old atlas canvas is released');
let closed = 0;
for (const job of pending) job.resolve({ close: () => closed++ });
await tick();
assert.equal(closed, pending.length);
assert.equal(f.draws.length, 1, 'late images never draw');
assert.match(f.jobs.at(-1).url, /^https:\/\/other\.example\//);
layer.destroy();
assert.equal(f.credits.get('NASA GIBS'), 0);
assert.deepEqual(f.last().slots, []);
f.destroy();
assert.equal(f.sets.at(-1), 'destroyed');
});
test('an image layer is one texture; the same canvas again uploads its pixels', () => {
const f = fixture();
const canvas = { width: 8, height: 4, getContext: () => ({}) };
const layer = f.imagery.createLayer({
id: 'heat',
source: { kind: 'image', image: canvas },
order: 1,
});
const [slot] = f.last().slots;
assert.deepEqual(slot.rect, [-180, -90, 180, 90]);
assert.deepEqual(slot.bounds, slot.rect);
assert.deepEqual(slot.look, [1, 0, 0, 0], 'geographic');
assert.equal(slot.texture.image, canvas);
assert.equal(slot.texture.flipY, false, 'row 0 is the north edge');
const version = slot.texture.version;
layer.setSource({ kind: 'image', image: canvas });
assert.equal(f.last().slots[0].texture, slot.texture);
assert.ok(slot.texture.version > version, 'its new pixels upload');
// Across the antimeridian the east edge comes after the west one.
layer.setSource({
kind: 'image',
image: { width: 2, height: 2, data: new Uint8Array(16) },
rectangle: { west: 170, south: -10, east: -170, north: 10 },
});
assert.deepEqual(f.last().slots[0].rect, [170, -10, 190, 10]);
layer.setAlpha(0);
assert.deepEqual(f.last().slots, [], 'alpha 0 draws nothing');
layer.setAlpha(1);
layer.show(false);
assert.deepEqual(f.last().slots, []);
});
test('the pass draws the shown layers bottom first, at most its slot count', () => {
const f = fixture();
const image = { width: 1, height: 1, data: new Uint8Array(4) };
const layers = Array.from({ length: MAX_IMAGERY_SLOTS + 2 }, (_, index) =>
f.imagery.createLayer({
id: `layer-${index}`,
source: { kind: 'image', image },
order: -index,
alpha: 0.5 + index / 100,
}),
);
const drawn = f.last().slots.map((slot) => slot.look[0]);
assert.equal(drawn.length, MAX_IMAGERY_SLOTS);
// Highest order last; the lowest two are left out.
assert.deepEqual(
drawn,
layers
.slice(0, MAX_IMAGERY_SLOTS)
.map((layer) => layer.alpha())
.reverse(),
);
f.imagery.setSplitPosition(0.3);
assert.equal(f.last().split, 0.3);
assert.equal(f.imagery.surface(), 'globe');
f.setPhotoreal(true);
assert.equal(f.imagery.surface(), 'tiles');
});
test('a hidden tiles layer drops its atlas; shown again it builds one at the view', async () => {
const f = fixture();
const layer = f.imagery.createLayer({ id: 'a', source: tiles() });
layer.show(false);
assert.equal(f.diagnostics().a.atlas, null);
assert.equal(f.credits.get('NASA GIBS'), 0, 'its credit goes too');
f.changed.raiseEvent();
assert.equal(f.diagnostics().a.atlas, null);
layer.show(true);
await tick();
assert.ok(f.diagnostics().a.atlas);
assert.equal(f.last().slots.length, 1);
});
+222
View File
@@ -0,0 +1,222 @@
// engine.imagery's screen pass on Navara: one public EffectDesc right after
// tone mapping, under every other surface pass (the remaining layer drapes,
// engine.ground) and before the sharpening, anti-aliasing and gev's
// overlays. Each pixel's world position comes from Navara's packed scene
// depth (terrain, 3D tiles); where that is the ground (not a mesh in front
// of it), up to MAX_IMAGERY_SLOTS layers are sampled in draw order at its
// longitude and latitude, each in its rectangle, on its side of the split:
// an image in longitude and latitude, a tile atlas in Web Mercator. Texels
// are blended in display space by their alpha times the layer's, as
// Cesium's globe blends imagery layers. Mip levels come from the
// derivatives of the ground position, taken before any branch. Costs
// nothing while no layer is drawn (the effect is hidden).
import { EffectDesc, Effect as NavaraEffect } from '@navaramap/three';
import { Effect, EffectAttribute } from 'postprocessing';
import { DataTexture, Matrix4, RGBADepthPacking, Uniform } from 'three';
import { withFrameUpdates, withPassDisposal } from '../frameDescriptor.js';
import { MAX_IMAGERY_SLOTS } from './index.js';
export const IMAGERY_EFFECT_KEY = 'gevImagery';
const SLOTS = Array.from({ length: MAX_IMAGERY_SLOTS }, (_, index) => index);
const fragmentShader = /* glsl */ `
uniform sampler2D tAllDepth;
uniform sampler2D tSurfaceDepth;
uniform mat4 uInverseProjection;
uniform mat4 uWorld;
uniform float uLogDepthFC;
uniform float uSplit;
${SLOTS.map(
(i) => `uniform sampler2D tImage${i};
uniform vec4 uRect${i};
uniform vec4 uBounds${i};
uniform vec4 uLook${i};`,
).join('\n')}
vec3 toDisplay(vec3 c) {
return mix(12.92*c,1.055*pow(max(c,vec3(0.0)),vec3(1.0/2.4))-0.055,step(vec3(0.0031308),c));
}
vec3 toLinear(vec3 c) {
return mix(c/12.92,pow(max((c+0.055)/1.055,vec3(0.0)),vec3(2.4)),step(vec3(0.04045),c));
}
// One layer over the colour: rect is where it draws (degrees, east past
// west), bounds the image's extent (degrees) or the atlas's (Web Mercator
// x, y, width, height), look its alpha, side (-1 left, 1 right, 0 both)
// and projection (1 Web Mercator).
vec3 paint(vec3 color, sampler2D image, vec4 rect, vec4 bounds, vec4 look,
vec2 geo, vec2 geoDx, vec2 geoDy, vec2 merc, vec2 mercDx, vec2 mercDy, float x) {
if (look.x <= 0.0) return color;
if ((look.y < 0.0 && x > uSplit) || (look.y > 0.0 && x < uSplit)) return color;
float lon = geo.x < rect.x ? geo.x + 360.0 : geo.x;
if (lon > rect.z || geo.y < rect.y || geo.y > rect.w) return color;
vec2 at;
vec2 dx;
vec2 dy;
if (look.z > 0.5) {
vec2 m = vec2(merc.x + (lon - geo.x) / 360.0, merc.y);
at = (m - bounds.xy) / bounds.zw;
dx = mercDx / bounds.zw;
dy = mercDy / bounds.zw;
} else {
vec2 span = vec2(bounds.z - bounds.x, bounds.y - bounds.w);
at = vec2(lon - bounds.x, geo.y - bounds.w) / span;
dx = geoDx / span;
dy = geoDy / span;
}
if (any(lessThan(at, vec2(0.0))) || any(greaterThan(at, vec2(1.0)))) return color;
vec4 texel = textureGrad(image, at, dx, dy);
return mix(color, texel.rgb, texel.a * look.x);
}
void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
outputColor = inputColor;
float depth = unpackRGBAToDepth(texture2D(tAllDepth, uv));
float distance = exp2(2.0 * depth / uLogDepthFC) - 1.0;
vec4 ray = uInverseProjection * vec4(uv * 2.0 - 1.0, -1.0, 1.0);
vec3 point = (uWorld * vec4(ray.xyz * (distance / -ray.z), 1.0)).xyz;
// Geodetic longitude and latitude (Bowring), degrees.
float p = length(point.xy);
float theta = atan(point.z * 6378137.0, p * 6356752.314245);
float st = sin(theta);
float ct = cos(theta);
float latitude = atan(point.z + 42841.311513 * st * st * st, p - 42697.672707 * ct * ct * ct);
vec2 geo = vec2(atan(point.y, point.x), latitude) * 57.29577951308232;
float clamped = clamp(latitude, -1.4844222297, 1.4844222297);
vec2 merc = vec2((geo.x + 180.0) / 360.0,
(1.0 - log(tan(0.7853981633974483 + clamped * 0.5)) / 3.141592653589793) / 2.0);
// Derivatives before any divergent branch; across the antimeridian a
// longitude step wraps; across the sky's edge there is none.
vec2 geoDx = dFdx(geo);
vec2 geoDy = dFdy(geo);
vec2 mercDx = dFdx(merc);
vec2 mercDy = dFdy(merc);
geoDx.x -= 360.0 * floor(geoDx.x / 360.0 + 0.5);
geoDy.x -= 360.0 * floor(geoDy.x / 360.0 + 0.5);
mercDx.x -= floor(mercDx.x + 0.5);
mercDy.x -= floor(mercDy.x + 0.5);
float onSurface = 1.0 - step(1.0, depth);
float edge = 1.0 - step(0.5, abs(dFdx(onSurface)) + abs(dFdy(onSurface)));
geoDx *= edge;
geoDy *= edge;
mercDx *= edge;
mercDy *= edge;
if (depth >= 1.0) return;
// The packed depth also holds forward meshes, which are not ground.
if (depth < texture2D(tSurfaceDepth, uv).r - 2e-7) return;
vec3 color = toDisplay(inputColor.rgb);
${SLOTS.map(
(i) =>
`color = paint(color, tImage${i}, uRect${i}, uBounds${i}, uLook${i}, geo, geoDx, geoDy, merc, mercDx, mercDy, uv.x);`,
).join('\n ')}
outputColor = vec4(toLinear(color), inputColor.a);
}
`;
class ImageryEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
static key = IMAGERY_EFFECT_KEY;
// Navara takes the first anchor that exists: right after tone mapping.
static insertAfter = ['toneMapping'];
static insertBefore = [
'gevNepalEvent',
'gevObservedWeather',
'gevEarthquakeGround',
'gevAwarenessPulses',
'gevGround',
'gevPreSharpenOverlay',
'gevSharpen',
'smaa',
'fxaa',
'gevOverlay',
'final',
];
constructor(view, ctx, config) {
super(view, ctx, config);
this.owner = config[IMAGERY_EFFECT_KEY].owner;
}
createPass() {
const camera = this.view.camera.raw;
if (!camera) throw new Error('Camera not available for the imagery pass');
this.effect = new Effect('GevImagery', fragmentShader, {
// Its own pass: inputColor is the tone-mapped frame.
attributes: EffectAttribute.CONVOLUTION,
uniforms: new Map([
['tAllDepth', new Uniform(null)],
['tSurfaceDepth', new Uniform(null)],
['uInverseProjection', new Uniform(new Matrix4())],
['uWorld', new Uniform(new Matrix4())],
['uLogDepthFC', new Uniform(1)],
['uSplit', new Uniform(0.5)],
...SLOTS.flatMap((i) => [
[`tImage${i}`, new Uniform(null)],
[`uRect${i}`, new Uniform([0, 0, 0, 0])],
[`uBounds${i}`, new Uniform([0, 0, 1, 1])],
[`uLook${i}`, new Uniform([0, 0, 0, 0])],
]),
]),
});
return new NavaraEffect(camera, this.effect);
}
updateFrame() {
const camera = this.view.camera.raw;
const owner = this.owner;
if (!this.effect || !camera) return;
const mrt = this.find('mrt');
if (mrt?.depthBufferPacking !== RGBADepthPacking)
throw new Error('The imagery pass needs packed scene depth');
const u = this.effect.uniforms;
u.get('tAllDepth').value = mrt.depthBuffer;
u.get('tSurfaceDepth').value = this.ctx.getRenderTarget().depthTexture;
u.get('uInverseProjection').value.copy(camera.projectionMatrixInverse);
u.get('uWorld').value.copy(camera.matrixWorld);
u.get('uLogDepthFC').value = 2 / Math.log2(camera.far + 1);
u.get('uSplit').value = owner.split;
for (const i of SLOTS) {
const slot = owner.slots[i];
u.get(`tImage${i}`).value = slot?.texture ?? owner.empty;
u.get(`uRect${i}`).value = slot?.rect ?? [0, 0, 0, 0];
u.get(`uBounds${i}`).value = slot?.bounds ?? [0, 0, 1, 1];
u.get(`uLook${i}`).value = slot?.look ?? [0, 0, 0, 0];
}
}
}
const registered = new WeakSet();
/**
* The pass of one view: set(slots, split) draws up to MAX_IMAGERY_SLOTS
* layers ({ texture, rect, bounds, look }, bottom first; none: the effect
* hidden) with the split at `split` (a fraction of the width from the left).
*/
export function createImageryPass(view) {
if (!registered.has(view)) {
view.registerEffect(IMAGERY_EFFECT_KEY, ImageryEffectDesc);
registered.add(view);
}
const empty = new DataTexture(new Uint8Array(4), 1, 1);
empty.needsUpdate = true;
const owner = { slots: [], split: 0.5, empty };
let handle = null;
return {
owner,
set(slots, split) {
owner.slots = slots.slice(0, MAX_IMAGERY_SLOTS);
owner.split = split;
const visible = owner.slots.length > 0;
if (visible && !handle)
handle = view.addEffect({
[IMAGERY_EFFECT_KEY]: { owner },
visible: true,
});
else handle?.update({ visible });
},
destroy() {
handle?.delete();
handle = null;
owner.slots = [];
empty.dispose();
},
};
}
+4
View File
@@ -36,6 +36,8 @@ import { createNavaraMovers } from './movers/index.js';
import { createNavaraLines } from './lines/index.js';
import { createNavaraGround } from './ground/index.js';
import { createGroundPass } from './ground/pass.js';
import { createNavaraImagery } from './imagery/index.js';
import { createImageryPass } from './imagery/pass.js';
import { createNavaraOverlay } from './overlay.js';
import { createPostSampling } from './postSampling.js';
import {
@@ -173,6 +175,8 @@ export async function createNavaraGlobe({ container, search, hd = false }) {
}),
lines: createNavaraLines(view, { overlay }),
ground: createNavaraGround(view, { createPass: createGroundPass }),
imagery: (parts) =>
createNavaraImagery(view, { ...parts, createPass: createImageryPass }),
});
const camera = engine.camera;
let ground = Number.NaN;