mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 10:12:18 +00:00
Draw weather, wind and Bhote Koshi through engine.imagery, one display each
engine.imagery gains what these rasters need, on every engine: - geographic (EPSG:4326) tile schemes and a transform applied to each decoded tile (the satellite infrared mask); - staged source changes, which keep the drawn source until the new one has loaded (the weather frame swap), and credit-only changes in place; - raised layers that draw on a shell above terrain and 3D tiles, rising with the camera, with a detail image inside a rectangle. On Cesium this is the weather shell primitive, moved into the engine; on Navara the pixel's ray meets the ellipsoid grown by the height. Rain radar, satellite clouds, lightning, the wind field and the Bhote Koshi event and locator each draw through one render/display.js on both engines; their Navara renderers and Navara's weather surface pass go. Cesium's pixels are unchanged in every compared scene. On Navara the Bhote Koshi images are no longer upside down. Two engine-specific parts stay behind one backend option each: the wind's streamlines and the Bhote Koshi story entities. The coupling report now counts defineGroundEffect calls, not its own declaration. Coupling: Navara renderer lines fall from 2304 to 1695, Navara ground passes from 3 to 1 (the Global Context pulses), engine kind checks from 5 to 2. The contract suite passes on both engines (Cesium 71/71, Navara 74/74).
This commit is contained in:
1 parent
b53b6a48a7
commit
c73c5382d4
39 files changed
+4677
-1114
No files matched your search
+410
-176
@@ -1,13 +1,18 @@
|
||||
// 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.
|
||||
// alike, or, raised, on a shell above the ellipsoid. 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 or geographic 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), each through the source's
|
||||
// transform. A staged source builds its own texture or atlas while the
|
||||
// drawn one shows and takes its place once it is complete. A raised
|
||||
// layer's detail is a second slot right over its own, which the pass
|
||||
// draws in place of the layer inside the detail's rectangle. 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,
|
||||
@@ -28,6 +33,7 @@ import {
|
||||
imageryTilePlan,
|
||||
imageryTileUrl,
|
||||
isPixelImage,
|
||||
raisedLift,
|
||||
wrapsGlobe,
|
||||
} from '../../imagery.js';
|
||||
/** Layers one frame of the pass draws (pass.js samples one texture each). */
|
||||
@@ -118,24 +124,36 @@ export function createNavaraImagery(
|
||||
const pass = createPass(view);
|
||||
const entries = new Map();
|
||||
let warned = false;
|
||||
// The metres every raised layer rises at the camera's height now.
|
||||
let lift = 0;
|
||||
const liftNow = () => {
|
||||
try {
|
||||
return raisedLift(camera.pose().cartographic.height);
|
||||
} catch {
|
||||
// Before the first frame the camera has no pose yet.
|
||||
return lift;
|
||||
}
|
||||
};
|
||||
|
||||
const compose = () => {
|
||||
lift = liftNow();
|
||||
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) {
|
||||
const slots = drawn.flatMap((entry) => entry.slots());
|
||||
if (slots.length > MAX_IMAGERY_SLOTS && !warned) {
|
||||
warned = true;
|
||||
console.warn(
|
||||
`[Imagery] Navara draws the top ${MAX_IMAGERY_SLOTS} of ${drawn.length} layers`,
|
||||
`[Imagery] Navara draws the top ${MAX_IMAGERY_SLOTS} of ${slots.length} slots`,
|
||||
);
|
||||
}
|
||||
pass.set(
|
||||
drawn.slice(-MAX_IMAGERY_SLOTS).map((entry) => entry.slot()),
|
||||
registry.imagery.splitPosition(),
|
||||
);
|
||||
// A detail never draws without its layer under it.
|
||||
let top = slots.slice(-MAX_IMAGERY_SLOTS);
|
||||
if (top[0]?.detailOf) top = top.slice(1);
|
||||
pass.set(top, registry.imagery.splitPosition());
|
||||
view.forceUpdate();
|
||||
};
|
||||
|
||||
@@ -148,84 +166,182 @@ export function createNavaraImagery(
|
||||
entry.releaseCredit = credit ? credits.addStatic(credit) : null;
|
||||
}
|
||||
|
||||
// A raised layer's height on the pass, lifted with the camera.
|
||||
const raiseOf = (entry) =>
|
||||
entry.state.options.raise === null ? 0 : entry.state.options.raise + lift;
|
||||
|
||||
// One image source's texture: { texture, image, source } built from a
|
||||
// decoded image, or loaded from its URL (`then(texture | null)`).
|
||||
function textureFor(next, source, previous = null) {
|
||||
const wrap = wrapsGlobe(source.rectangle);
|
||||
if (
|
||||
previous &&
|
||||
previous.image === next &&
|
||||
previous.texture.wrapS === (wrap ? RepeatWrapping : ClampToEdgeWrapping)
|
||||
) {
|
||||
// The same canvas or bytes again: their new pixels.
|
||||
previous.texture.needsUpdate = true;
|
||||
return previous;
|
||||
}
|
||||
return { texture: imageTexture(next, wrap), image: next };
|
||||
}
|
||||
function loadImage(source, controller) {
|
||||
return Promise.resolve()
|
||||
.then(() => load(source.url, controller.signal))
|
||||
.then(
|
||||
(decoded) => {
|
||||
if (controller.signal.aborted) {
|
||||
decoded?.close?.();
|
||||
return null;
|
||||
}
|
||||
return decoded;
|
||||
},
|
||||
(error) => {
|
||||
if (!controller.signal.aborted)
|
||||
console.warn('[Imagery] image failed to load:', error);
|
||||
return null;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function imageEntry(entry) {
|
||||
let texture = null,
|
||||
image = null,
|
||||
loading = null;
|
||||
const drop = () => {
|
||||
texture?.dispose();
|
||||
texture = null;
|
||||
let drawn = null,
|
||||
loading = null,
|
||||
staging = null,
|
||||
detail = null;
|
||||
const drop = (held) => {
|
||||
if (held && held !== drawn) held.texture.dispose();
|
||||
};
|
||||
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;
|
||||
const dropDrawn = () => {
|
||||
drawn?.texture.dispose();
|
||||
drawn = null;
|
||||
};
|
||||
const cancelStage = () => {
|
||||
staging?.controller.abort();
|
||||
if (staging?.built) drop(staging.built);
|
||||
staging = null;
|
||||
};
|
||||
const slotOf = (held, rectangle) => {
|
||||
const rect = unwrapped(rectangle);
|
||||
return {
|
||||
texture: held.texture,
|
||||
rect,
|
||||
bounds: rect,
|
||||
look: [entry.state.alpha, SIDE[entry.state.split], 0, 0],
|
||||
raise: raiseOf(entry),
|
||||
};
|
||||
};
|
||||
return {
|
||||
source() {
|
||||
const { source } = entry.state;
|
||||
loading?.abort();
|
||||
loading = null;
|
||||
cancelStage();
|
||||
if (source.image) {
|
||||
show(source.image, source);
|
||||
const next = textureFor(source.image, source, drawn);
|
||||
if (next !== drawn) dropDrawn();
|
||||
drawn = next;
|
||||
return;
|
||||
}
|
||||
drop();
|
||||
image = null;
|
||||
dropDrawn();
|
||||
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);
|
||||
},
|
||||
);
|
||||
loadImage(source, controller).then((decoded) => {
|
||||
if (!decoded || entry.state.destroyed || loading !== controller) {
|
||||
decoded?.close?.();
|
||||
return;
|
||||
}
|
||||
loading = null;
|
||||
drawn = textureFor(decoded, source);
|
||||
compose();
|
||||
});
|
||||
},
|
||||
stage(source, finish) {
|
||||
cancelStage();
|
||||
const controller = new AbortController();
|
||||
const job = { controller, built: null };
|
||||
staging = job;
|
||||
const swap = (decoded) => {
|
||||
if (staging !== job || entry.state.destroyed) {
|
||||
if (!source.image) decoded?.close?.();
|
||||
return;
|
||||
}
|
||||
if (!decoded) {
|
||||
staging = null;
|
||||
finish(false);
|
||||
return;
|
||||
}
|
||||
// The drawn texture goes as the staged one takes its place: three
|
||||
// uploads it on the frame that draws it.
|
||||
loading?.abort();
|
||||
loading = null;
|
||||
job.built = textureFor(decoded, source, drawn);
|
||||
staging = null;
|
||||
if (job.built !== drawn) dropDrawn();
|
||||
drawn = job.built;
|
||||
finish(true);
|
||||
syncCredit(entry);
|
||||
compose();
|
||||
};
|
||||
// Never in the call itself: a newer source can still replace it.
|
||||
if (source.image) queueMicrotask(() => swap(source.image));
|
||||
else loadImage(source, controller).then(swap);
|
||||
},
|
||||
unstage: cancelStage,
|
||||
detail(next, finish) {
|
||||
detail?.held.texture.dispose();
|
||||
detail = null;
|
||||
if (next) {
|
||||
detail = {
|
||||
held: { texture: imageTexture(next.image, false) },
|
||||
rectangle: next.rectangle,
|
||||
};
|
||||
finish(true);
|
||||
}
|
||||
compose();
|
||||
},
|
||||
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],
|
||||
};
|
||||
return drawn ? slotOf(drawn, entry.state.source.rectangle) : null;
|
||||
},
|
||||
ready: () => texture !== null,
|
||||
slots() {
|
||||
const main = this.slot();
|
||||
if (!main) return [];
|
||||
if (!detail) return [main];
|
||||
main.look[3] = 1;
|
||||
return [
|
||||
main,
|
||||
{ ...slotOf(detail.held, detail.rectangle), detailOf: main },
|
||||
];
|
||||
},
|
||||
ready: () => drawn !== null,
|
||||
cameraChanged: () => false,
|
||||
destroy() {
|
||||
loading?.abort();
|
||||
loading = null;
|
||||
drop();
|
||||
image = null;
|
||||
cancelStage();
|
||||
dropDrawn();
|
||||
detail?.held.texture.dispose();
|
||||
detail = null;
|
||||
},
|
||||
diagnostics: () => ({ kind: 'image', loaded: texture !== null }),
|
||||
diagnostics: () => ({
|
||||
kind: 'image',
|
||||
loaded: drawn !== null,
|
||||
staging: staging !== null,
|
||||
detail: detail !== null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function tilesEntry(entry) {
|
||||
let atlas = null,
|
||||
queue = null;
|
||||
// The atlas of one tiles source over the view, its loads `limit` at a
|
||||
// time; `onTile()` after each tile settles.
|
||||
function createTiler(source, onTile) {
|
||||
const scheme = source.scheme;
|
||||
const queue = createImageryTileQueue({
|
||||
load,
|
||||
limit: source.maxRequests ?? 6,
|
||||
});
|
||||
let atlas = null;
|
||||
let disposed = false;
|
||||
const disposeAtlas = () => {
|
||||
const current = atlas;
|
||||
atlas = null;
|
||||
@@ -233,127 +349,116 @@ export function createNavaraImagery(
|
||||
for (const controller of current.controllers) controller.abort();
|
||||
current.texture.dispose();
|
||||
current.canvas.width = current.canvas.height = 0;
|
||||
queue?.prune();
|
||||
queue.prune();
|
||||
};
|
||||
// The source's rectangle within Web Mercator's latitudes; across the
|
||||
// The source's rectangle within the tiling's latitudes; across the
|
||||
// antimeridian the atlas covers every longitude.
|
||||
const limit = scheme === 'geographic' ? 90 : WEB_MERCATOR_LIMIT;
|
||||
const box = () => {
|
||||
const { west, south, east, north } = entry.state.source.rectangle;
|
||||
const { west, south, east, north } = 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),
|
||||
south: Math.max(south, -limit),
|
||||
north: Math.min(north, 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,
|
||||
source,
|
||||
atlas: () => atlas,
|
||||
/** The atlas for the view; true when it changed. */
|
||||
update(shown) {
|
||||
if (disposed) return false;
|
||||
if (!shown) {
|
||||
if (!atlas) return false;
|
||||
disposeAtlas();
|
||||
return true;
|
||||
}
|
||||
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,
|
||||
scheme,
|
||||
}),
|
||||
),
|
||||
);
|
||||
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],
|
||||
const plan = imageryTilePlan(
|
||||
box(),
|
||||
camera.viewRectangle(),
|
||||
level,
|
||||
scheme,
|
||||
);
|
||||
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: () => !disposed && atlas === current,
|
||||
draw(image) {
|
||||
const drawn = source.transform
|
||||
? source.transform(image)
|
||||
: image;
|
||||
context.drawImage(drawn, x * tile, y * tile, tile, tile);
|
||||
current.loaded++;
|
||||
texture.needsUpdate = true;
|
||||
view.forceUpdate();
|
||||
onTile();
|
||||
},
|
||||
fail() {
|
||||
current.failed++;
|
||||
onTile();
|
||||
},
|
||||
});
|
||||
queue.add(tasks);
|
||||
return true;
|
||||
},
|
||||
ready: () => true,
|
||||
cameraChanged: update,
|
||||
look: update,
|
||||
destroy() {
|
||||
queue?.destroy();
|
||||
queue = null;
|
||||
/** Every tile of the view's atlas settled (none: nothing to load). */
|
||||
complete: () =>
|
||||
!atlas ||
|
||||
atlas.loaded + atlas.failed === atlas.plan.width * atlas.plan.height,
|
||||
failed: () => (atlas?.failed ?? 0) > 0,
|
||||
dispose() {
|
||||
disposed = true;
|
||||
queue.destroy();
|
||||
disposeAtlas();
|
||||
},
|
||||
diagnostics: () => ({
|
||||
kind: 'tiles',
|
||||
...(queue?.diagnostics() ?? {}),
|
||||
...queue.diagnostics(),
|
||||
atlas: atlas
|
||||
? {
|
||||
level: atlas.plan.z,
|
||||
@@ -366,6 +471,94 @@ export function createNavaraImagery(
|
||||
};
|
||||
}
|
||||
|
||||
function tilesEntry(entry) {
|
||||
let tiler = null;
|
||||
// The staged source's tiler and its finish.
|
||||
let staged = null;
|
||||
const settleStaged = () => {
|
||||
const job = staged;
|
||||
if (!job) return;
|
||||
const shown = entry.state.shown;
|
||||
if (shown && !job.tiler.complete()) return;
|
||||
staged = null;
|
||||
if (shown && job.tiler.failed()) {
|
||||
job.tiler.dispose();
|
||||
job.finish(false);
|
||||
return;
|
||||
}
|
||||
tiler?.dispose();
|
||||
tiler = job.tiler;
|
||||
job.finish(true);
|
||||
syncCredit(entry);
|
||||
compose();
|
||||
};
|
||||
const dropStaged = () => {
|
||||
staged?.tiler.dispose();
|
||||
staged = null;
|
||||
};
|
||||
const update = () => {
|
||||
const changed = tiler?.update(entry.state.shown) ?? false;
|
||||
staged?.tiler.update(entry.state.shown);
|
||||
settleStaged();
|
||||
return changed;
|
||||
};
|
||||
return {
|
||||
source() {
|
||||
dropStaged();
|
||||
tiler?.dispose();
|
||||
tiler = createTiler(entry.state.source, () => {});
|
||||
update();
|
||||
},
|
||||
stage(source, finish) {
|
||||
dropStaged();
|
||||
const job = { finish, tiler: null };
|
||||
job.tiler = createTiler(source, () => {
|
||||
if (staged === job) queueMicrotask(settleStaged);
|
||||
});
|
||||
staged = job;
|
||||
update();
|
||||
},
|
||||
unstage: dropStaged,
|
||||
slot() {
|
||||
const atlas = tiler?.atlas();
|
||||
if (!atlas) return null;
|
||||
const source = tiler.source;
|
||||
const [west, south, east, north] = unwrapped(source.rectangle);
|
||||
const mercator = source.scheme !== 'geographic';
|
||||
const limit = mercator ? WEB_MERCATOR_LIMIT : 90;
|
||||
return {
|
||||
texture: atlas.texture,
|
||||
rect: [west, Math.max(south, -limit), east, Math.min(north, limit)],
|
||||
bounds: atlas.plan.bounds,
|
||||
look: [
|
||||
entry.state.alpha,
|
||||
SIDE[entry.state.split],
|
||||
mercator ? 1 : 0,
|
||||
0,
|
||||
],
|
||||
raise: 0,
|
||||
};
|
||||
},
|
||||
slots() {
|
||||
const main = this.slot();
|
||||
return main ? [main] : [];
|
||||
},
|
||||
ready: () => true,
|
||||
cameraChanged: update,
|
||||
look: update,
|
||||
destroy() {
|
||||
dropStaged();
|
||||
tiler?.dispose();
|
||||
tiler = null;
|
||||
},
|
||||
diagnostics: () => ({
|
||||
kind: 'tiles',
|
||||
...(tiler?.diagnostics() ?? {}),
|
||||
staging: staged ? staged.tiler.diagnostics() : null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// One drawing per source kind; a new kind replaces it.
|
||||
function drawingFor(entry) {
|
||||
const kind = entry.state.source.kind;
|
||||
@@ -384,6 +577,7 @@ export function createNavaraImagery(
|
||||
credit: null,
|
||||
releaseCredit: null,
|
||||
slot: () => entry.drawing?.slot() ?? null,
|
||||
slots: () => entry.drawing?.slots() ?? [],
|
||||
};
|
||||
entries.set(state, entry);
|
||||
drawingFor(entry).source();
|
||||
@@ -395,14 +589,51 @@ export function createNavaraImagery(
|
||||
syncCredit(entry);
|
||||
compose();
|
||||
},
|
||||
credit() {
|
||||
syncCredit(entry);
|
||||
compose();
|
||||
},
|
||||
// A staged source of another kind builds the other drawing aside.
|
||||
stage(source, finish) {
|
||||
if (source.kind === entry.drawing.kind) {
|
||||
entry.drawing.stage(source, finish);
|
||||
return;
|
||||
}
|
||||
const aside =
|
||||
source.kind === 'image' ? imageEntry(entry) : tilesEntry(entry);
|
||||
aside.kind = source.kind;
|
||||
entry.aside?.destroy();
|
||||
entry.aside = aside;
|
||||
aside.stage(source, (ok) => {
|
||||
if (entry.aside !== aside) return;
|
||||
entry.aside = null;
|
||||
if (ok) {
|
||||
entry.drawing.destroy();
|
||||
entry.drawing = aside;
|
||||
} else aside.destroy();
|
||||
finish(ok);
|
||||
syncCredit(entry);
|
||||
compose();
|
||||
});
|
||||
},
|
||||
unstage() {
|
||||
entry.drawing.unstage();
|
||||
entry.aside?.destroy();
|
||||
entry.aside = null;
|
||||
},
|
||||
detail(detail, finish) {
|
||||
entry.drawing.detail?.(detail, finish);
|
||||
},
|
||||
look() {
|
||||
entry.drawing.look?.();
|
||||
entry.aside?.look?.();
|
||||
syncCredit(entry);
|
||||
compose();
|
||||
},
|
||||
ready: () => entry.drawing.ready(),
|
||||
destroy() {
|
||||
entries.delete(state);
|
||||
entry.aside?.destroy();
|
||||
entry.drawing.destroy();
|
||||
entry.releaseCredit?.();
|
||||
entry.releaseCredit = null;
|
||||
@@ -418,9 +649,12 @@ export function createNavaraImagery(
|
||||
|
||||
const offCamera = camera.changed.addEventListener(() => {
|
||||
let changed = false;
|
||||
for (const entry of entries.values())
|
||||
for (const entry of entries.values()) {
|
||||
changed = entry.drawing.cameraChanged() || changed;
|
||||
if (changed) compose();
|
||||
entry.aside?.cameraChanged();
|
||||
}
|
||||
// Raised layers rise with the camera.
|
||||
if (changed || liftNow() !== lift) compose();
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -198,3 +198,109 @@ test('a hidden tiles layer drops its atlas; shown again it builds one at the vie
|
||||
assert.ok(f.diagnostics().a.atlas);
|
||||
assert.equal(f.last().slots.length, 1);
|
||||
});
|
||||
|
||||
test('geographic tiles draw in degrees through the source’s transform', async () => {
|
||||
const f = fixture();
|
||||
const masked = [];
|
||||
f.imagery.createLayer({
|
||||
id: 'radar',
|
||||
source: tiles({
|
||||
url: 'https://weather.example/tile?z={z}&x={x}&y={y}',
|
||||
scheme: 'geographic',
|
||||
maxLevel: 6,
|
||||
transform: (image) => {
|
||||
masked.push(image);
|
||||
return { masked: image };
|
||||
},
|
||||
}),
|
||||
});
|
||||
await tick();
|
||||
const { atlas } = f.diagnostics().radar;
|
||||
assert.equal(atlas.level, 6, 'the source’s top level');
|
||||
const [slot] = f.last().slots;
|
||||
assert.equal(slot.look[2], 0, 'sampled in degrees');
|
||||
const [west, south, east, north] = slot.bounds;
|
||||
assert.ok(west <= BOX.west && east >= BOX.east);
|
||||
assert.ok(south <= BOX.south && north >= BOX.north);
|
||||
assert.match(f.jobs[0].url, /z=6&x=\d+&y=\d+$/);
|
||||
const tile = { close() {} };
|
||||
f.jobs[0].resolve(tile);
|
||||
await tick();
|
||||
assert.deepEqual(masked, [tile]);
|
||||
assert.deepEqual(f.draws, [{ masked: tile }]);
|
||||
});
|
||||
|
||||
test('a staged tiles source builds its own atlas under the drawn one and takes its place when complete', async () => {
|
||||
const f = fixture();
|
||||
const layer = f.imagery.createLayer({ id: 'a', source: tiles() });
|
||||
await tick();
|
||||
const drawn = f.last().slots[0].texture;
|
||||
const firstJobs = f.jobs.length;
|
||||
const staged = layer.setSource(
|
||||
tiles({ url: 'https://next.example/{z}/{x}/{y}.png', credit: 'Next' }),
|
||||
{ staged: true },
|
||||
);
|
||||
await tick();
|
||||
assert.equal(f.last().slots[0].texture, drawn, 'the drawn atlas stays');
|
||||
assert.ok(f.diagnostics().a.staging, 'the staged atlas loads');
|
||||
const next = f.jobs.slice(firstJobs);
|
||||
assert.ok(next.length > 0 && next.every((job) => /next/.test(job.url)));
|
||||
let done;
|
||||
staged.then((value) => (done = value));
|
||||
// Every tile of the staged atlas in: it takes the drawn one's place.
|
||||
for (let round = 0; round < 20 && done === undefined; round++) {
|
||||
for (const job of f.jobs.slice(firstJobs)) job.resolve({ close() {} });
|
||||
await tick();
|
||||
}
|
||||
assert.equal(done, true);
|
||||
assert.notEqual(f.last().slots[0].texture, drawn);
|
||||
assert.equal(f.credits.get('Next'), 1);
|
||||
assert.equal(f.credits.get('NASA GIBS'), 0);
|
||||
// A failed tile leaves the drawn atlas.
|
||||
const before = f.last().slots[0].texture;
|
||||
const from = f.jobs.length;
|
||||
const failed = layer.setSource(
|
||||
tiles({ url: 'https://broken.example/{z}/{x}/{y}.png' }),
|
||||
{ staged: true },
|
||||
);
|
||||
await tick();
|
||||
f.jobs[from].resolve(Promise.reject(new Error('404')));
|
||||
let result;
|
||||
failed.then((value) => (result = value));
|
||||
for (let round = 0; round < 20 && result === undefined; round++) {
|
||||
for (const job of f.jobs.slice(from + 1)) job.resolve({ close() {} });
|
||||
await tick();
|
||||
}
|
||||
assert.equal(result, false);
|
||||
assert.equal(f.last().slots[0].texture, before);
|
||||
});
|
||||
|
||||
test('a raised image is lifted with the camera; its detail is a slot over it', async () => {
|
||||
const f = fixture();
|
||||
const image = { width: 2, height: 2, data: new Uint8Array(16) };
|
||||
const layer = f.imagery.createLayer({
|
||||
id: 'shell',
|
||||
source: { kind: 'image', image, rectangle: BOX },
|
||||
raise: 6000,
|
||||
});
|
||||
const [slot] = f.last().slots;
|
||||
// 12 km up: a 0 m lift (48 m rounds to 0).
|
||||
assert.equal(slot.raise, 6000);
|
||||
const detailRectangle = { ...BOX, east: -97.74 };
|
||||
assert.equal(
|
||||
await layer.setDetail({ image, rectangle: detailRectangle }),
|
||||
true,
|
||||
);
|
||||
const [main, detail] = f.last().slots;
|
||||
assert.equal(main.look[3], 1, 'the next slot is its detail');
|
||||
assert.deepEqual(detail.rect, [
|
||||
detailRectangle.west,
|
||||
detailRectangle.south,
|
||||
detailRectangle.east,
|
||||
detailRectangle.north,
|
||||
]);
|
||||
assert.equal(detail.raise, 6000);
|
||||
await layer.setDetail(null);
|
||||
assert.equal(f.last().slots.length, 1);
|
||||
assert.equal(f.last().slots[0].look[3], 0);
|
||||
});
|
||||
@@ -5,11 +5,15 @@
|
||||
// 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).
|
||||
// an image or a geographic atlas in longitude and latitude, a Web Mercator
|
||||
// atlas in Web Mercator. A raised slot is sampled where the pixel's ray
|
||||
// meets the ellipsoid grown by its height, wherever nothing of the scene
|
||||
// is nearer (over 3D tiles and the sky's edge too). A slot followed by its
|
||||
// detail draws nothing inside the detail's rectangle. 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 each
|
||||
// slot's position, taken outside any divergent 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';
|
||||
@@ -32,7 +36,8 @@ ${SLOTS.map(
|
||||
(i) => `uniform sampler2D tImage${i};
|
||||
uniform vec4 uRect${i};
|
||||
uniform vec4 uBounds${i};
|
||||
uniform vec4 uLook${i};`,
|
||||
uniform vec4 uLook${i};
|
||||
uniform float uRaise${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));
|
||||
@@ -40,16 +45,52 @@ vec3 toDisplay(vec3 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
|
||||
// Geodetic longitude and latitude (Bowring) of a world point, degrees.
|
||||
vec2 geodetic(vec3 point) {
|
||||
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);
|
||||
return vec2(atan(point.y, point.x), latitude) * 57.29577951308232;
|
||||
}
|
||||
vec2 mercator(vec2 geo) {
|
||||
float clamped = clamp(geo.y * 0.017453292519943295, -1.4844222297, 1.4844222297);
|
||||
return vec2((geo.x + 180.0) / 360.0,
|
||||
(1.0 - log(tan(0.7853981633974483 + clamped * 0.5)) / 3.141592653589793) / 2.0);
|
||||
}
|
||||
// Where the ray from the camera meets the ellipsoid grown by raise metres,
|
||||
// in front of the scene (sceneRange along the ray); 0 when it does not.
|
||||
float raised(float raise, vec3 origin, vec3 ray, float sceneRange, out vec2 geo) {
|
||||
vec3 radii = vec3(6378137.0, 6378137.0, 6356752.314245) + raise;
|
||||
vec3 o = origin / radii;
|
||||
vec3 d = ray / radii;
|
||||
float a = dot(d, d);
|
||||
float b = dot(o, d);
|
||||
float c = dot(o, o) - 1.0;
|
||||
float disc = b * b - a * c;
|
||||
float root = sqrt(max(disc, 0.0));
|
||||
float range = (-b - root) / a;
|
||||
if (range <= 0.0) range = (-b + root) / a;
|
||||
geo = geodetic(origin + max(range, 0.0) * ray);
|
||||
return step(0.0, disc) * step(1e-3, range) * step(range, sceneRange + 1.0);
|
||||
}
|
||||
bool inRect(vec2 geo, vec4 rect) {
|
||||
float lon = geo.x < rect.x ? geo.x + 360.0 : geo.x;
|
||||
return lon <= rect.z && geo.y >= rect.y && geo.y <= rect.w;
|
||||
}
|
||||
// One slot 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;
|
||||
// x, y, width, height), look its alpha, side (-1 left, 1 right, 0 both),
|
||||
// projection (1 Web Mercator) and whether the next slot is its detail
|
||||
// (cut, that slot's rect: it draws nothing there).
|
||||
vec3 paint(vec3 color, sampler2D image, vec4 rect, vec4 bounds, vec4 look, vec4 cut,
|
||||
vec2 geo, vec2 geoDx, vec2 geoDy, vec2 merc, vec2 mercDx, vec2 mercDy, float x, float drawn) {
|
||||
if (look.x <= 0.0 || drawn < 0.5) return color;
|
||||
if ((look.y < 0.0 && x > uSplit) || (look.y > 0.0 && x < uSplit)) return color;
|
||||
if (!inRect(geo, rect)) return color;
|
||||
if (look.w > 0.5 && inRect(geo, cut)) 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;
|
||||
@@ -68,47 +109,68 @@ vec3 paint(vec3 color, sampler2D image, vec4 rect, vec4 bounds, vec4 look,
|
||||
vec4 texel = textureGrad(image, at, dx, dy);
|
||||
return mix(color, texel.rgb, texel.a * look.x);
|
||||
}
|
||||
// Derivatives of a position, the antimeridian's longitude step wrapped and
|
||||
// none across the edge of what is drawn.
|
||||
void derivatives(vec2 geo, vec2 merc, float drawn, out vec2 geoDx, out vec2 geoDy,
|
||||
out vec2 mercDx, out vec2 mercDy) {
|
||||
geoDx = dFdx(geo);
|
||||
geoDy = dFdy(geo);
|
||||
mercDx = dFdx(merc);
|
||||
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 edge = 1.0 - step(0.5, abs(dFdx(drawn)) + abs(dFdy(drawn)));
|
||||
geoDx *= edge;
|
||||
geoDy *= edge;
|
||||
mercDx *= edge;
|
||||
mercDy *= edge;
|
||||
}
|
||||
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;
|
||||
// The ground: the scene depth where it is the surface (the packed depth
|
||||
// also holds forward meshes, which are not ground).
|
||||
float ground = (1.0 - step(1.0, depth)) *
|
||||
step(texture2D(tSurfaceDepth, uv).r - 2e-7, depth);
|
||||
vec2 geo = geodetic(point);
|
||||
vec2 merc = mercator(geo);
|
||||
// Derivatives before any divergent branch.
|
||||
vec2 geoDx;
|
||||
vec2 geoDy;
|
||||
vec2 mercDx;
|
||||
vec2 mercDy;
|
||||
derivatives(geo, merc, ground, geoDx, geoDy, mercDx, mercDy);
|
||||
// A raised slot's ray, and the scene's range along it (the sky: none).
|
||||
vec3 origin = uWorld[3].xyz;
|
||||
vec3 direction = normalize(mat3(uWorld) * ray.xyz);
|
||||
float sceneRange = depth >= 1.0 ? 1.0e12 : distance * length(ray.xyz) / -ray.z;
|
||||
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);
|
||||
vec3 start = color;
|
||||
${SLOTS.map((i) => {
|
||||
const cut = i + 1 < SLOTS.length ? `uRect${i + 1}` : 'vec4(0.0)';
|
||||
return `{
|
||||
vec2 g = geo;
|
||||
vec2 m = merc;
|
||||
vec2 gx = geoDx;
|
||||
vec2 gy = geoDy;
|
||||
vec2 mx = mercDx;
|
||||
vec2 my = mercDy;
|
||||
float drawn = ground;
|
||||
// A uniform branch: the derivatives inside it are defined.
|
||||
if (uRaise${i} > 0.0) {
|
||||
drawn = raised(uRaise${i}, origin, direction, sceneRange, g);
|
||||
m = mercator(g);
|
||||
derivatives(g, m, drawn, gx, gy, mx, my);
|
||||
}
|
||||
color = paint(color, tImage${i}, uRect${i}, uBounds${i}, uLook${i}, ${cut}, g, gx, gy, m, mx, my, uv.x, drawn);
|
||||
}`;
|
||||
}).join('\n ')}
|
||||
if (color != start) outputColor = vec4(toLinear(color), inputColor.a);
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -153,6 +215,7 @@ class ImageryEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
|
||||
[`uRect${i}`, new Uniform([0, 0, 0, 0])],
|
||||
[`uBounds${i}`, new Uniform([0, 0, 1, 1])],
|
||||
[`uLook${i}`, new Uniform([0, 0, 0, 0])],
|
||||
[`uRaise${i}`, new Uniform(0)],
|
||||
]),
|
||||
]),
|
||||
});
|
||||
@@ -179,6 +242,7 @@ class ImageryEffectDesc extends withPassDisposal(withFrameUpdates(EffectDesc)) {
|
||||
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];
|
||||
u.get(`uRaise${i}`).value = slot?.raise ?? 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -187,8 +251,9 @@ 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).
|
||||
* slots ({ texture, rect, bounds, look, raise }, bottom first; none: the
|
||||
* effect hidden) with the split at `split` (a fraction of the width from
|
||||
* the left). `raise` is the slot's shell height in metres (0: draped).
|
||||
*/
|
||||
export function createImageryPass(view) {
|
||||
if (!registered.has(view)) {
|
||||
|
||||
Reference in new issue
Block a user