feat(aircraft): draw far-away aircraft as shaded sprites seen from the camera's angle

Aircraft on the map were flat, top-down SVG silhouettes turned along
their course: from an oblique camera they read as paper cut-outs lying
on the ground.

Each aircraft class (and each helicopter rotor frame) is now rendered in
Blender from a sphere of directions into one sheet of shaded sprites
(public/sprites/aircraft-views.webp: 302 views a class, 7.5 degrees
apart from straight above to 30 degrees below the horizon, 4096 x 3648,
grey, 3.1 MB). The renderer lays a contact flat on the ground along its
course, works out where the eye is in that frame and draws the nearest
view, mirrored for the port side. The view is a card standing at the
contact, square to the direction it was rendered from, so between views
the sprite is tilted (foreshortened and turned) as the aircraft would
be; views are not blended. Sprites are neutral, so the fleet, tracked
and military tints still apply.

Renderer: a new `viewSheets` capability, `DrawPort.views(id, sheet)` and
an image `{views, first, fallback}` for icon items (src/data/viewSheet.js
holds the layout and maths, in JS and GLSL). A view row draws from the
sheet's own texture, kept as luminance and alpha; until the sheet has
loaded, and if it cannot load, it draws its flat `fallback` along its
course as before. View sheets are offered on WebGL 2 only, and on
WebGL 1 the icon shader is as it was.

Layers: Flights, Military Flights (fleet and tracked contact) and Local
ADS-B draw views; the TR-3B, airport vehicles, ground stations and
Cockpit's far pips stay flat, as does any renderer without the
capability.

Tools: `npm run build:aircraft-views` bakes the sheet from the repo's
own fleet models (about 7 minutes); scripts/qa-aircraft-view-sheet.mjs
writes contact sheets of a bake and scripts/qa-aircraft-views.mjs
photographs a grid of every class in the app from above, tilted, from
below and round an orbit.

With 5,000 contacts on an M3 Max the frame takes 5.9-6.1 ms against
5.9 ms with the flat glyphs.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Mazeyar Moeini FeizabadiandClaude Fable 5.2 committed 2026-11-23 01:21:39 +01:00
1 parent d9d79ebc4d
commit efdac0ba70
40 files changed
+3535 -109

No files matched your search

+40 -5
View File
@@ -37,7 +37,8 @@ import { alongLength } from '../../geo/polyline.js';
import { clusterScreenPoints } from '../../geo/screenCluster.js';
import { provideUnboundDraw } from '../rendererOf.js';
import { blobUrl, listenerList, toCartesian, uncaught } from './common.js';
import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { createGpuIcons, gpuIconCapabilities } from './gpuIcons.js';
import { viewLayout } from '../../data/viewSheet.js';
import { blendHost } from './setBlend.js';
import { createModelSets } from './drawModels.js';
import { materialTexture } from './internals.js';
@@ -714,7 +715,7 @@ const animating = (record) => record.gpu?.animating();
export function createCesiumDraw({
scene,
report,
capabilities = new Set(GPU_ICON_CAPABILITIES),
capabilities = new Set(gpuIconCapabilities(scene)),
requestRender: requestFrame = null,
date = null,
now = () => performance.now(),
@@ -1129,6 +1130,7 @@ export function createCesiumDraw({
toColor,
imageOf: (record, image) => iconImage(record, image),
peekImage: (image) => atlases.get(image.atlas)?.[image.slot],
viewsOf: (id) => viewSheets.get(id),
requestRender: (reason) => {
if (!live()) return;
if (requestFrame) requestFrame(reason);
@@ -1146,9 +1148,9 @@ export function createCesiumDraw({
function onGpu(record, list, replacing = false, force = false) {
if (record.kind !== 'icons') return false;
if (!record.gpu && !force && !gpu.wants(list, record.spec)) return false;
gpu.check(list, record.spec);
gpu.check(list, record.spec, record);
if (record.gpu) return true;
if (!replacing) gpu.check(record.items.values(), record.spec);
if (!replacing) gpu.check(record.items.values(), record.spec, record);
record.gpu = gpu.attach(record);
record.billboards = null;
record.billboardHost = null;
@@ -1670,6 +1672,9 @@ export function createCesiumDraw({
// when its icon is drawn, and registering an atlas again swaps the images
// of the icons that drew from it.
const atlases = new Map();
// View sheets icons draw subjects of, by id (`viewSheets`): each as its
// image and checked layout, a new object whenever it is registered.
const viewSheets = new Map();
/** The blob each material or quad draws, held while it lives (`holdImage`). */
const heldBlobs = new WeakMap();
@@ -6024,6 +6029,32 @@ export function createCesiumDraw({
}
if (changed) scene.requestRender();
},
...(capabilities.has('viewSheets')
? {
views(id, sheet) {
viewSheets.set(
id,
Object.freeze({
image: sheet.image,
layout: viewLayout(sheet),
grey: sheet.grey === true,
}),
);
let changed = false;
for (const record of sets.values())
if (
record.kind === 'icons' &&
record.gpu &&
record.views === id
) {
record.gpu.reviews();
setsVersion += 1;
changed = true;
}
if (changed) scene.requestRender();
},
}
: {}),
};
return {
@@ -6148,7 +6179,11 @@ provideUnboundDraw((viewer) => {
const part = createCesiumDraw({
scene,
report: uncaught,
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields', 'modelParts']),
capabilities: new Set([
...gpuIconCapabilities(scene),
'fields',
'modelParts',
]),
});
unboundParts.set(part.port, part);
const offs = [
+36
View File
@@ -8873,3 +8873,39 @@ test('a disposed set, and every set once the port is disposed, does nothing on l
restore();
}
});
test('a draw port registers view sheets only with viewSheets, each port its own', async () => {
const { PORTS } = await import('../contract/index.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
assert.equal(PORTS.draw.views, 'viewSheets', 'an optional port method');
const report = (error) => assert.fail(error);
const without = createCesiumDraw({
scene: fakeScene(),
report,
capabilities: new Set(['motionSegments']),
});
assert.equal(typeof without.port.views, 'undefined');
// Two viewers: a sheet registered on one is not drawn by the other.
const one = createCesiumDraw({ scene: fakeScene(), report });
const two = createCesiumDraw({ scene: fakeScene(), report });
assert.equal(typeof one.port.views, 'function');
const view = {
id: 'a',
pos: { ...Cesium.Cartesian3.fromDegrees(4, 52, 1000) },
image: { views: AIRCRAFT_VIEWS.id, first: AIRCRAFT_VIEWS.subjects.uav },
size: [20, 20],
rotationMode: 'course',
course: 0,
};
const setOne = one.port.icons({ id: 'views:one' });
const setTwo = two.port.icons({ id: 'views:two' });
setOne.set([view]);
setTwo.set([view]);
one.port.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
const rowsOne = one.sets.get('views:one').gpu.set;
const rowsTwo = two.sets.get('views:two').gpu.set;
assert.equal(rowsOne.imageFar(rowsOne.row('a')), AIRCRAFT_VIEWS.subjects.uav);
assert.equal(rowsTwo.imageFar(rowsTwo.row('a')), -1, 'not on this port');
setOne.dispose();
setTwo.dispose();
});
+122 -13
View File
@@ -31,6 +31,14 @@
* root's larger `width`/`height`, as a billboard rasterises it), any other
* image at the item's larger side.
*
* A view (`{views, first}`, `viewSheets`) is not in that atlas: its sheet is
* a texture of its own, and its row draws the frame that shows its subject
* from the eye (`data/viewSheet.js`), lying flat on the ground along its
* course. Until the sheet is registered and loaded, and if it cannot load,
* the row draws the view's `fallback` image along its course (nothing
* without one). A set draws views from one sheet; a view of another is
* refused.
*
* Choices the contract leaves open, taken conservatively:
* - `horizonCull` judges each row no lower than `ICON_CULL_HEIGHT_M` above
* the ellipsoid, as the layers drawing their own icon sets do for sea
@@ -53,6 +61,7 @@ import {
ICON_GROUND_RELATIVE,
ICON_RECEDES,
ICON_ROTATES,
ICON_VIEWS,
} from '../../data/iconSet.js';
import {
writeArcSegment,
@@ -77,6 +86,26 @@ export const GPU_ICON_CAPABILITIES = Object.freeze([
'courseGlide',
]);
/**
* The capabilities GPU icon sets bring on `scene`: `viewSheets` too, but on
* WebGL 1, where a set that draws views could not also draw what its rows
* read from their extras (a display range, a fade, an offset), and a layer
* that uses those would lose its icons to the sheet.
* @param {object} [scene] A Cesium scene; none (a test's) is taken as WebGL 2.
*/
export function gpuIconCapabilities(scene) {
return scene?.context?.webgl2 === false
? [...GPU_ICON_CAPABILITIES]
: [...GPU_ICON_CAPABILITIES, 'viewSheets'];
}
/** Whether an image is a subject of a view sheet (`{views, first}`). */
const isView = (image) => typeof image?.views === 'string';
/** Whether a subject's block of frames, from its first cell, is in `layout`. */
const blockFits = (first, layout) =>
first + layout.frames <= layout.columns * layout.rows;
const nonZero = (v) =>
Boolean(v) && (v.x !== 0 || v.y !== 0 || (v.z ?? 0) !== 0);
@@ -204,10 +233,12 @@ function rasterPxOf(url, item) {
* toColor: (color: unknown) => Cesium.Color,
* imageOf: (record: object, image: unknown) => unknown,
* peekImage: (ref: {atlas: string, slot: string}) => unknown,
* viewsOf?: (id: string) => ({image: string, layout: object}|undefined),
* requestRender: (reason: string) => void}} options `date` is the epoch
* ms a `live` motion clock reads (null: the system clock's); `imageOf` reads an atlas slot
* through the draw port's atlases (undefined while it is not registered),
* noting that the set draws from it; `peekImage` only reads it.
* noting that the set draws from it; `peekImage` only reads it;
* `viewsOf` reads a registered view sheet (undefined while it is not).
*/
export function createGpuIcons({
scene,
@@ -216,9 +247,15 @@ export function createGpuIcons({
toColor,
imageOf,
peekImage,
viewsOf = () => undefined,
requestRender,
}) {
const can = (capability) => capabilities.has(capability);
/** Whether a view's frames are in its sheet (true while not registered). */
const viewFits = (view) => {
const sheet = viewsOf(view.views);
return !sheet || blockFits(view.first, sheet.layout);
};
/** Whether drawing these items (in a set of `spec`) needs a GPU icon set. */
function wants(items, spec = {}) {
@@ -228,7 +265,10 @@ export function createGpuIcons({
(item.motion && can('motionSegments')) ||
(item.courseGlide && can('courseGlide')) ||
item.pickProxy ||
item.imageLod
item.imageLod ||
// A view turns along its course: an item that does not is not asked
// for its image here.
(item.rotationMode === 'course' && isView(item.image))
)
return true;
}
@@ -236,13 +276,33 @@ export function createGpuIcons({
}
/** Refuse what a GPU icon set cannot draw, before anything changes. */
function check(items, spec = {}) {
function check(items, spec = {}, record = null) {
// Atlas slots these items would take anew: they must all fit.
const fresh = new Set();
// The one sheet the set draws views from: its record's, else the first
// of these items'.
let sheet = record?.views ?? null;
for (const item of items) {
const refuse = (what) => {
throw new Error(`the Cesium renderer's GPU icons have no ${what}`);
};
if (isView(item.imageLod?.near)) refuse('views as near images');
if (isView(item.image?.fallback)) refuse('views as fallbacks');
if (isView(item.image)) {
if (!can('viewSheets')) refuse('view sheets');
if (!Number.isInteger(item.image.first) || item.image.first < 0)
throw new TypeError("a view's first cell is a whole number from 0");
if (!viewFits(item.image))
throw new RangeError("a view's frames run past its sheet");
if (item.rotationMode !== 'course')
refuse("views but along a course (rotationMode: 'course')");
if (item.imageLod) refuse('imageLod for a view');
sheet ??= item.image.views;
if (item.image.views !== sheet)
refuse(
`views from two sheets in a set (${sheet}, ${item.image.views})`,
);
}
if (item.offsetScalesByDistance && nonZero(item.pixelOffset))
refuse('pixel offsets scaled by distance');
// What a row reads from its extras texture, which WebGL 1 has not.
@@ -258,7 +318,12 @@ export function createGpuIcons({
if (item.rotationMode === 'screen' && (item.rotation ?? 0) !== 0)
refuse('screen rotation on WebGL 1');
}
for (const given of [item.image, item.imageLod?.near]) {
for (const given of [
// A view is not in the atlas; the image it falls back to is.
isView(item.image) ? item.image.fallback : item.image,
item.imageLod?.near,
]) {
if (given === undefined) continue;
// An atlas slot as what it holds now (none yet draws once it does).
const image =
typeof given?.atlas === 'string' ? peekImage(given) : given;
@@ -316,6 +381,7 @@ export function createGpuIcons({
cull: () => spec.horizonCull === true,
recede: () => spec.recede,
translucent: () => spec.blend === 'translucent',
views: () => (record.views ? (viewsOf(record.views) ?? null) : null),
// Picked as the draw port's other items are: `{set, id, meta}` as
// the item now is, hidden row by row for drill picks.
pickObject: (id, _set, primitive) => ({
@@ -411,14 +477,34 @@ export function createGpuIcons({
const added = row < 0;
if (added) row = set.add(item.id);
const [width = 0, height = 0] = item.size ?? [];
const far = slotOf(item.image, item);
const near = item.imageLod ? slotOf(item.imageLod.near, item) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
const view = isView(item.image);
if (view) {
// Its subject's first cell, once its sheet is registered, and the
// slot of the image drawn in its place until the sheet has loaded.
// (A subject past the sheet, registered since, draws no cell.)
record.views ??= item.image.views;
const sheet = viewsOf(item.image.views);
const first =
sheet && blockFits(item.image.first, sheet.layout)
? item.image.first
: -1;
const fallback =
item.image.fallback === undefined
? -1
: slotOf(item.image.fallback, item);
set.setImage(row, first, fallback);
set.setImageSwitch(row, 0);
} else {
const far = slotOf(item.image, item);
const near = item.imageLod ? slotOf(item.imageLod.near, item) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
}
set.setFlag(row, ICON_VIEWS, view);
set.setSize(row, width, height);
set.setScale(row, item.scale ?? 1);
set.setAlpha(row, item.alpha ?? 1);
@@ -747,11 +833,21 @@ export function createGpuIcons({
reatlas(id) {
const drawing = [];
for (const item of record.items.values())
if (item.image?.atlas === id || item.imageLod?.near?.atlas === id)
if (
item.image?.atlas === id ||
item.image?.fallback?.atlas === id ||
item.imageLod?.near?.atlas === id
)
drawing.push(item);
if (fresh) return sync();
for (const item of drawing) writeRow(item);
},
/** Rewrite the rows drawing views, once their sheet is registered. */
reviews() {
if (fresh) return sync();
for (const item of record.items.values())
if (isView(item.image)) writeRow(item);
},
/**
* After a frame: sample the ground under clamped rows' segment ends,
* from `budget` (`{ends, surface}`, spent). Whether a row's ground
@@ -879,6 +975,19 @@ export function createGpuIcons({
let loading = false;
for (let row = 0; row < set.count; row++) {
if (!set.shown(row)) continue;
if (set.flags(row) & ICON_VIEWS) {
// Its sheet, or while that is not drawn, the image it falls
// back to.
const views = host.viewsState();
if (views === 'ready' && set.imageFar(row) >= 0) continue;
const fallback = set.imageNear(row);
if (fallback < 0) {
if (views === 'failed') return 'failed';
loading = true;
} else if (iconAtlas.failed(fallback)) return 'failed';
else if (!iconAtlas.ready(fallback)) loading = true;
continue;
}
for (const slot of [set.imageFar(row), set.imageNear(row)]) {
if (slot < 0) continue;
if (iconAtlas.failed(slot)) return 'failed';
+259
View File
@@ -3,13 +3,16 @@ import * as Cesium from 'cesium';
import test from 'node:test';
import { createCesiumDraw } from './draw.js';
import { drawHitOf } from './drawHit.js';
import { gpuIconCapabilities } from './gpuIcons.js';
import { IconSetPrimitive } from './iconSetPrimitive.js';
import { MAX_ICON_SLOTS } from '../../data/iconAtlas.js';
import {
ICON_CULL_LIFT,
ICON_RECEDES,
ICON_ROTATES,
ICON_VIEWS,
} from '../../data/iconSet.js';
import { AIRCRAFT_VIEWS, viewLayout } from '../../data/viewSheet.js';
import {
iconCourse,
iconPosition,
@@ -1187,3 +1190,259 @@ test('a live motion clock reads the date the draw port is given', () => {
0.1,
);
});
/** An item drawn from the aircraft view sheet's subject at `first`. */
const viewIcon = (id, first = AIRCRAFT_VIEWS.subjects.widebody, extra = {}) =>
icon(id, {
image: { views: AIRCRAFT_VIEWS.id, first },
rotationMode: 'course',
course: 30,
...extra,
});
test('a view takes its set onto the GPU, its row flagged and drawing its subject’s first cell once the sheet is registered', () => {
const { scene, part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:views' });
set.set([viewIcon('a')]);
assert.ok(scene.added[0] instanceof IconSetPrimitive, 'a GPU icon set');
const { set: s } = rows(part, 'gpu:views');
const a = s.row('a');
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
assert.equal(s.flags(a) & ICON_ROTATES, ICON_ROTATES, 'along its course');
assert.equal(s.imageFar(a), -1, 'its sheet not registered yet: not drawn');
const host = part.sets.get('gpu:views').host;
assert.equal(host._views(), null);
const before = part.version();
const renders = scene.renders;
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.widebody);
assert.equal(s.imageNear(a), -1, 'no fallback given');
assert.equal(s.imageSwitch(a), 0, 'one image at any size');
assert.ok(part.version() > before);
assert.ok(scene.renders > renders, 'a frame is asked for');
const sheet = host._views();
assert.equal(sheet.image, AIRCRAFT_VIEWS.sheet.image);
assert.deepEqual(
sheet.layout.firsts,
viewLayout(AIRCRAFT_VIEWS.sheet).firsts,
);
assert.equal(sheet.layout.frames, AIRCRAFT_VIEWS.frames);
// Registered again: a new sheet the host reads afresh.
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.notEqual(host._views(), sheet);
// A row added once it is registered draws at once.
set.upsert([viewIcon('b', AIRCRAFT_VIEWS.subjects.helicopter2)]);
assert.equal(s.imageFar(s.row('b')), AIRCRAFT_VIEWS.subjects.helicopter2);
set.dispose();
});
test('a row switching between a view and a flat image changes its flag and its image', () => {
const { part, draw } = drawOver();
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
const set = draw.icons({ id: 'gpu:view-flat' });
set.set([viewIcon('a')]);
const { set: s } = rows(part, 'gpu:view-flat');
const a = s.row('a');
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
set.upsert([
icon('a', {
rotationMode: 'course',
course: 30,
imageLod: { near: 'ship-large.png', switchPx: 60 },
}),
]);
assert.equal(s.row('a'), a, 'the same row');
assert.equal(s.flags(a) & ICON_VIEWS, 0, 'flat');
assert.ok(s.imageFar(a) >= 0, 'an atlas slot');
assert.notEqual(s.imageNear(a), s.imageFar(a));
assert.equal(s.imageSwitch(a), 60);
set.upsert([viewIcon('a', AIRCRAFT_VIEWS.subjects.glider)]);
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS, 'a view again');
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.glider);
assert.equal(s.imageNear(a), -1, 'no fallback given');
assert.equal(s.imageSwitch(a), 0);
set.dispose();
});
test('a view’s fallback is the atlas image its row draws until the sheet is', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-fallback' });
const view = (first) => ({
views: AIRCRAFT_VIEWS.id,
first,
fallback: 'glyph.png',
});
set.set([{ ...viewIcon('a'), image: view(AIRCRAFT_VIEWS.subjects.light) }]);
const { set: s } = rows(part, 'gpu:view-fallback');
const a = s.row('a');
// Not registered: no cell yet, its fallback's slot as its near image.
assert.equal(s.flags(a) & ICON_VIEWS, ICON_VIEWS);
assert.equal(s.imageFar(a), -1);
const slot = s.imageNear(a);
assert.ok(slot >= 0, 'the fallback has an atlas slot');
assert.equal(s.imageSwitch(a), 0);
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(a), AIRCRAFT_VIEWS.subjects.light);
assert.equal(s.imageNear(a), slot, 'kept for a sheet that fails to load');
// A view cannot be what a view falls back to.
assert.throws(
() =>
set.upsert([
{
...viewIcon('b'),
image: {
views: AIRCRAFT_VIEWS.id,
first: 0,
fallback: {
views: AIRCRAFT_VIEWS.id,
first: AIRCRAFT_VIEWS.subjects.widebody,
},
},
},
]),
/views as fallbacks/,
);
assert.equal(s.row('b'), -1, 'refused, changing nothing');
set.dispose();
});
test('a GPU icon set refuses, changing nothing, views it cannot draw', () => {
const { part, draw } = drawOver();
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
draw.views('other-views', AIRCRAFT_VIEWS.sheet);
const set = draw.icons({ id: 'gpu:view-refuse' });
set.set([viewIcon('a')]);
const refused = [
[viewIcon('b', 1.5), /first cell is a whole number/],
[viewIcon('b', -1), /first cell is a whole number/],
[
viewIcon('b', String(AIRCRAFT_VIEWS.frames)),
/first cell is a whole number/,
],
// The last block that fits ends at the sheet's last cell; one cell on
// runs past.
[
viewIcon(
'b',
AIRCRAFT_VIEWS.sheet.columns * AIRCRAFT_VIEWS.sheet.rows -
AIRCRAFT_VIEWS.frames +
1,
),
/run past its sheet/,
],
[viewIcon('b', 0, { rotationMode: 'screen' }), /views but along a course/],
[viewIcon('b', 0, { rotationMode: undefined }), /views but along a course/],
[
viewIcon('b', 0, { imageLod: { near: 'ship.png', switchPx: 30 } }),
/imageLod for a view/,
],
[
icon('b', {
motion: { kind: 'hold' },
imageLod: {
near: { views: AIRCRAFT_VIEWS.id, first: 0 },
switchPx: 30,
},
}),
/views as near images/,
],
[
icon('b', {
image: { views: 'other-views', first: 0 },
rotationMode: 'course',
}),
/views from two sheets/,
],
];
for (const [item, pattern] of refused)
assert.throws(() => set.upsert([item]), pattern, JSON.stringify(item));
assert.equal(set.size(), 1);
assert.equal(rows(part, 'gpu:view-refuse').set.count, 1);
// Two sheets in one write to a fresh set.
const fresh = draw.icons({ id: 'gpu:view-two' });
assert.throws(
() =>
fresh.set([
viewIcon('a'),
icon('b', {
image: { views: 'other-views', first: 0 },
rotationMode: 'course',
}),
]),
/views from two sheets/,
);
assert.equal(fresh.size(), 0);
});
test('without viewSheets the draw port has no views(), and refuses a view', () => {
const { part, draw } = drawOver({
capabilities: new Set(['motionSegments', 'columns']),
});
assert.equal('views' in draw, false);
const set = draw.icons({ id: 'gpu:no-views' });
set.set([icon('a', { motion: { kind: 'hold' } })]);
assert.throws(() => set.upsert([viewIcon('b')]), /no view sheets/);
assert.equal(set.size(), 1);
assert.equal(rows(part, 'gpu:no-views').set.count, 1);
// A set of billboards refuses one too: it cannot take it onto the GPU.
const billboards = draw.icons({ id: 'gpu:no-views-billboards' });
assert.throws(() => billboards.set([viewIcon('a')]), /no view sheets/);
assert.equal(billboards.size(), 0);
});
test('a view sheet is checked when it is registered', () => {
const { draw } = drawOver();
assert.throws(
() => draw.views('bad', { ...AIRCRAFT_VIEWS.sheet, rings: [2, 3] }),
TypeError,
);
assert.throws(
() => draw.views('bad', { ...AIRCRAFT_VIEWS.sheet, image: '' }),
TypeError,
);
});
test('view rows load with their sheet: loading until it is ready, failed when it cannot load', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-load' });
set.set([viewIcon('a')]);
const record = part.sets.get('gpu:view-load');
assert.equal(record.gpu.imageState(), 'loading', 'no sheet registered');
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(record.host.viewsState(), 'loading', 'registered, not drawn');
assert.equal(record.gpu.imageState(), 'loading');
// Node has no Image: the sheet's texture cannot load on this context.
record.host._syncViews({});
assert.equal(record.host.viewsState(), 'failed');
assert.equal(record.gpu.imageState(), 'failed');
// A hidden view row waits on nothing.
set.upsert([viewIcon('a', undefined, { show: false })]);
assert.equal(record.gpu.imageState(), 'settled');
set.dispose();
});
test('view sheets are offered on WebGL 2, not on WebGL 1', () => {
// A row that draws views is on the GPU, where WebGL 1 has no extras: a
// layer whose icons carry a display range would lose them to the sheet.
assert.ok(
gpuIconCapabilities({ context: { webgl2: true } }).includes('viewSheets'),
);
assert.ok(gpuIconCapabilities().includes('viewSheets'), 'no scene: a test');
const webgl1 = gpuIconCapabilities({ context: { webgl2: false } });
assert.equal(webgl1.includes('viewSheets'), false);
assert.deepEqual(webgl1, ['columns', 'motionSegments', 'courseGlide']);
});
test('a view registered past the sheet after its row was written draws no cell', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:view-late' });
// Accepted while its sheet is unknown: a block that runs one cell past
// the end of the sheet.
const { columns, rows: sheetRows } = AIRCRAFT_VIEWS.sheet;
set.set([viewIcon('a', columns * sheetRows - AIRCRAFT_VIEWS.frames + 1)]);
const { set: s } = rows(part, 'gpu:view-late');
draw.views(AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet);
assert.equal(s.imageFar(s.row('a')), -1, 'no cell: its fallback, or nothing');
set.dispose();
});
+281 -20
View File
@@ -20,6 +20,17 @@
* above, taken between the heights under its segment's two ends. On WebGL 1
* the extras are not drawn (the draw port refuses rows that need them).
*
* A row flagged `ICON_VIEWS` draws from the set's view sheet
* ({@link module:viewSheet}), a texture of its own, in place of the atlas
* (on WebGL 2; the shader has none of it on WebGL 1): it lies flat on the
* ground, forward along its course, and draws the frame nearest the eye's
* direction, mirrored for the eye on its left. The frame is a card standing
* at the row's anchor, square to the frame's own direction, so between
* frames the sprite is tilted (foreshortened and turned) as its subject is,
* with no blending of frames; the row's quad stays upright on screen. Until the
* sheet has loaded it draws its near image from the atlas, turned along its
* course as any row, if it has one.
*
* This module is the one place the icon sets touch Cesium's renderer internals.
*/
import * as Cesium from 'cesium';
@@ -29,6 +40,7 @@ import {
ICON_CULL_HEIGHT_M,
ICON_CULL_LIFT,
ICON_EXTRA_TEXELS,
ICON_VIEWS,
STYLE_STRIDE,
} from '../../data/iconSet.js';
import {
@@ -39,6 +51,13 @@ import {
NEAR_IMAGE_DEVICE_PX,
} from '../../data/iconAtlas.js';
import { recedeFrame, recedeParams } from '../recession.js';
import { rawTexture, webglContext } from './internals.js';
import {
VIEW_RINGS_MAX,
VIEW_SHEET_FRAGMENT_GLSL,
VIEW_SHEET_GLSL,
viewUniforms,
} from '../../data/viewSheet.js';
/** The parameters the uniforms hold while the set does not recede. */
const NO_RECEDE = recedeParams({});
@@ -84,6 +103,7 @@ uniform vec3 u_recessionFloors; // scale, alpha, combined alpha
uniform vec4 u_slots[ICON_SLOTS]; // ICON_SLOTS: as many as the context addresses
uniform float u_cull; // 1: hide rows past the ellipsoid's horizon
uniform float u_pickPass; // 1 while drawing for a pick
uniform float u_viewsReady; // 1 once the set's view sheet is loaded
#ifdef ICON_EXTRAS
uniform highp sampler2D u_extras; // ICON_EXTRA_TEXELS texels a row, ICON_EXTRA_ROWS rows a line
#endif
@@ -93,12 +113,42 @@ out vec4 v_color;
out vec4 v_pickColor;
out float v_proxy;
out float v_overDepth; // 1 for a row drawn over depth, on the near plane
out float v_views; // 1 for a row drawn from the view sheet
#ifdef ICON_VIEW_SHEETS
// A view row's frame: its cell in the sheet (v_uv is then this corner's
// place in that cell, not in the atlas).
out float v_viewCell;
#endif
// The row's anchor in clip space before screen offsets, for effects that wrap
// main() (sonar) and must not change geometry or picks.
vec4 iconAnchorClip = vec4(0.0, 0.0, 0.0, -1.0);
${ICON_SEGMENT_GLSL}
#ifdef ICON_VIEW_SHEETS
${VIEW_SHEET_GLSL}
// Where a corner of the row's quad falls in a frame's cell (0..1 across it,
// v down). The frame is a card standing at the row's anchor, square to the
// direction it shows its subject from: the corner (offset, in the eye's
// axes) is carried along the eye's ray onto that card, so a frame seen from
// a little off its direction is tilted (foreshortened and turned) as its
// subject is, until the next frame is the nearer.
// axes takes the subject's forward, right and up to the eye's axes; cardHalf
// is the card's half size, in the offset's units.
vec2 viewCardUv(float ring, float index, float flip, mat3 axes, vec3 offset, vec3 ray, vec2 cardHalf) {
vec3 toEye;
vec3 up;
viewFrameAxes(ring, index, flip, toEye, up);
vec3 normal = axes * toEye;
vec3 cardUp = axes * up;
vec3 cardRight = cross(cardUp, normal);
// The ray meets the card head on, or nearly: never edge on.
vec3 on = offset - ray * (dot(offset, normal) / min(dot(ray, normal), -0.2));
vec2 at = vec2(dot(on, cardRight), dot(on, cardUp)) / cardHalf;
return vec2(0.5 + 0.5 * (flip > 0.5 ? -at.x : at.x), 0.5 - 0.5 * at.y);
}
#endif
bool iconFlag(float flags, float bit) {
return mod(floor(flags / bit), 2.0) == 1.0;
@@ -127,6 +177,10 @@ void main() {
v_color = vec4(0.0);
v_proxy = 0.0;
v_overDepth = 0.0;
v_views = 0.0;
#ifdef ICON_VIEW_SHEETS
v_viewCell = 0.0;
#endif
gl_Position = vec4(0.0, 0.0, 2.0, 1.0); // outside the clip volume: not drawn
float flags = style1.z;
@@ -195,11 +249,25 @@ void main() {
bool nearImage = style3.x > 0.0
? glyphPx / czm_pixelRatio > style3.x
: glyphPx > ${NEAR_IMAGE_DEVICE_PX.toFixed(1)};
// A view row's far image is its subject's first cell in the view sheet,
// its near image the atlas slot drawn in its place while the sheet is not
// registered or loaded.
bool views = false;
vec2 viewUv = vec2(0.0);
float slot = nearImage ? style1.y : style1.x;
if (iconFlag(flags, ${ICON_VIEWS.toFixed(1)})) {
#ifdef ICON_VIEW_SHEETS
views = u_viewsReady > 0.5 && style1.x >= 0.0;
#endif
slot = views ? style1.x : style1.y;
}
if (slot < 0.0) return; // no image set
if (slot >= float(ICON_SLOTS)) return; // past what this context addresses
vec4 rect = u_slots[int(slot)];
if (rect.z <= 0.0) return; // image not loaded yet
vec4 rect = vec4(0.0, 0.0, 1.0, 1.0);
if (!views) {
if (slot >= float(ICON_SLOTS)) return; // past what this context addresses
rect = u_slots[int(slot)];
if (rect.z <= 0.0) return; // image not loaded yet
}
vec2 halfSize = style0.xy * (scale * distanceScale * 0.5) * corner;
vec2 shift = vec2(0.0);
@@ -222,15 +290,44 @@ void main() {
vec3 east = dot(horizontal, horizontal) > 1.0 ? normalize(vec3(horizontal, 0.0)) : vec3(0.0, 1.0, 0.0);
vec3 north = cross(up, east);
vec3 forward = east * sin(course) + north * cos(course);
float dx = dot(forward, u_cameraRight);
float dy = -dot(forward, u_cameraUp);
// Heading into or out of the screen: no stable direction, stay upright
// (screenProjectedRotation's 0.5 m of a 2 km probe).
if (dx * dx + dy * dy >= 6.25e-8) {
float rotation = atan(-dx, -dy);
float c = cos(rotation);
float s = sin(rotation);
halfSize = mat2(c, s, -s, c) * halfSize;
#ifdef ICON_VIEW_SHEETS
if (views) {
// A view lies flat on the ground, forward along its course, and draws
// the frame nearest the eye's direction. Its quad stays upright on
// screen; the frame is put on it where its card falls.
vec3 right = cross(forward, up);
vec3 toEye = normalize(-rte);
vec3 frame = viewNearest(
vec3(dot(toEye, forward), dot(toEye, right), dot(toEye, up)));
// The subject's axes in the eye's (x right, y up, z back).
mat3 axes = transpose(mat3(u_cameraRight, u_cameraUp, cross(u_cameraRight, u_cameraUp))) *
mat3(forward, right, up);
// This corner, square to the eye's ray (the eye's right and up, turned
// as its back turns onto the ray): a card facing the eye then fills
// the quad wherever on screen it is, without the stretch a wide view
// gives what is off its centre.
vec3 ray = normalize(positionEC.xyz);
vec3 turned = vec3(0.0, 0.0, 1.0) - ray;
vec3 offset =
(vec3(1.0, 0.0, 0.0) + turned * (ray.x / turned.z)) * halfSize.x +
(vec3(0.0, 1.0, 0.0) + turned * (ray.y / turned.z)) * halfSize.y;
viewUv = viewCardUv(
frame.x, frame.y, frame.z, axes, offset, ray,
style0.xy * (scale * distanceScale * 0.5));
v_viewCell = slot + viewRing(frame.x).y + frame.y;
} else
#endif
{
float dx = dot(forward, u_cameraRight);
float dy = -dot(forward, u_cameraUp);
// Heading into or out of the screen: no stable direction, stay upright
// (screenProjectedRotation's 0.5 m of a 2 km probe).
if (dx * dx + dy * dy >= 6.25e-8) {
float rotation = atan(-dx, -dy);
float c = cos(rotation);
float s = sin(rotation);
halfSize = mat2(c, s, -s, c) * halfSize;
}
}
}
#ifdef ICON_EXTRAS
@@ -267,22 +364,39 @@ void main() {
v_overDepth = 1.0;
}
v_uv = mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5));
v_uv = views
? viewUv
: mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5));
v_views = views ? 1.0 : 0.0;
v_color = vec4(color.rgb, color.a * alpha);
}
`;
const FRAGMENT_SHADER = /* glsl */ `
uniform sampler2D u_atlas;
#ifdef ICON_VIEW_SHEETS
${VIEW_SHEET_FRAGMENT_GLSL}
in float v_viewCell;
#endif
in vec2 v_uv;
in vec4 v_color;
in vec4 v_pickColor;
in float v_proxy;
in float v_overDepth;
in float v_views;
void main() {
vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv));
vec4 color = texture(u_atlas, v_uv);
#ifdef ICON_VIEW_SHEETS
// How small the sheet's cells are drawn (v_uv runs 0..1 across a view
// row's cell), worked out for every row so the cell can be read inside
// the branch.
vec2 texels = v_uv * (float(textureSize(u_views, 0).x) / max(u_viewGrid.x, 1.0));
float lod = log2(max(max(length(dFdx(texels)), length(dFdy(texels))), 1.0e-6));
if (v_views > 0.5) color = viewCell(v_viewCell, v_uv, lod);
#endif
color = czm_gammaCorrect(color);
color *= czm_gammaCorrect(v_color);
// A pick proxy is picked wherever it covers, drawn or not.
if (v_proxy > 0.5) color = vec4(1.0);
@@ -308,6 +422,100 @@ void main() {
}
`;
/** The coarsest mip level a view sheet is sampled at (half-size cells). */
const VIEW_SHEET_MAX_LOD = 1;
/** Each context's view sheet textures, by URL. */
const sheetTextures = new WeakMap();
/**
* A view sheet's image as a texture on `context`, loaded once however many
* icon sets draw from it: `{state, texture}`, `state` going from `loading`
* to `ready` (its `texture` set) or `failed`. `onChange` runs when it does.
* Mipmapped where the context can (to `VIEW_SHEET_MAX_LOD`), so a sprite
* drawn smaller than its cell stays smooth; a cell's transparent margin
* keeps its neighbours out. The texture lives as long as its context.
* A sheet larger than the context's textures fails, as one that cannot load.
* @param {object} context A Cesium Context.
* @param {string} url
* @param {() => void} [onChange]
* @param {boolean} [grey] The sheet's pixels are grey: kept as one channel
* and alpha.
*/
export function viewSheetTexture(context, url, onChange, grey = false) {
let byUrl = sheetTextures.get(context);
if (!byUrl) sheetTextures.set(context, (byUrl = new Map()));
const key = `${grey ? 'grey' : 'colour'}|${url}`;
let entry = byUrl.get(key);
if (!entry) {
entry = { state: 'loading', texture: null, listeners: new Set() };
byUrl.set(key, entry);
const settle = (state) => {
entry.state = state;
for (const listener of entry.listeners) listener();
entry.listeners.clear();
};
if (typeof Image === 'undefined') settle('failed');
else {
const image = new Image();
image.decoding = 'async';
// A cross-origin image would taint the upload.
image.crossOrigin = 'anonymous';
image.onload = () => {
if (context.isDestroyed?.()) return;
// This context's own limit (Cesium's is the last context's made).
const gl = webglContext({ context });
const limit = gl.getParameter(gl.MAX_TEXTURE_SIZE);
if (Math.max(image.naturalWidth, image.naturalHeight) > limit) {
console.warn(
`[iconSetPrimitive] View sheet is larger than this context's textures (${limit} px): ${url}`,
);
settle('failed');
return;
}
const mipmapped = context.webgl2 === true;
entry.texture = new Cesium.Texture({
context,
source: image,
// A grey sheet as its grey (its red) and alpha: half the memory.
pixelFormat: grey
? Cesium.PixelFormat.LUMINANCE_ALPHA
: Cesium.PixelFormat.RGBA,
flipY: false,
sampler: new Cesium.Sampler({
wrapS: Cesium.TextureWrap.CLAMP_TO_EDGE,
wrapT: Cesium.TextureWrap.CLAMP_TO_EDGE,
minificationFilter: mipmapped
? Cesium.TextureMinificationFilter.LINEAR_MIPMAP_LINEAR
: Cesium.TextureMinificationFilter.LINEAR,
magnificationFilter: Cesium.TextureMagnificationFilter.LINEAR,
}),
});
if (mipmapped) {
entry.texture.generateMipmap();
// No coarser than this: past it a cell's transparent margin is
// under a texel, and its neighbours would show at its edges.
gl.bindTexture(gl.TEXTURE_2D, rawTexture(entry.texture));
gl.texParameterf(
gl.TEXTURE_2D,
gl.TEXTURE_MAX_LOD,
VIEW_SHEET_MAX_LOD,
);
gl.bindTexture(gl.TEXTURE_2D, null);
}
settle('ready');
};
image.onerror = () => {
console.warn(`[iconSetPrimitive] View sheet failed to load: ${url}`);
settle('failed');
};
image.src = url;
}
}
if (onChange && entry.state === 'loading') entry.listeners.add(onChange);
return entry;
}
/**
* How many atlas slots the icon shader addresses on `context`: as many as
* the vertex uniform limit leaves room for (Cesium's ContextLimits, which
@@ -344,7 +552,9 @@ const EARTH_BOUNDS = new Cesium.BoundingSphere(
* Cesium's `BlendOption.TRANSLUCENT` billboards are, in place of an opaque
* pass and a translucent one (by default never). `pickObject` builds a row's pick object around the
* `primitive` drill picks hide it by (by default `{ id, iconSet, meta,
* primitive }`).
* primitive }`). `views` gives the view sheet the set's view rows draw from
* (`{image, layout, grey}`, `layout` as `viewLayout` returns; null: none),
* the same object until the sheet changes.
*/
export class IconSetPrimitive {
constructor({
@@ -355,9 +565,22 @@ export class IconSetPrimitive {
recede,
translucent,
pickObject,
views,
}) {
this.set = set;
this.renderTime = renderTime;
this._requestRender = requestRender ?? null;
// The set's view sheet: what it was last read as, its texture's entry
// and its layout as uniforms.
this._views = views ?? (() => null);
this._viewsFrom = null;
this._viewEntry = null;
this._viewGrid = new Cesium.Cartesian4();
this._viewRings = Array.from(
{ length: VIEW_RINGS_MAX / 2 },
() => new Cesium.Cartesian4(1, 0, 1, 0),
);
this._blank = null;
this._cull = cull ?? (() => true);
// The set's `recede`, and the parameters last made from it.
this._recede = recede ?? (() => null);
@@ -410,7 +633,11 @@ export class IconSetPrimitive {
u_recession: () => primitive._recession,
u_recessionFloors: () => primitive._recessionFloors,
u_slots: () => primitive._slotUniform,
u_atlas: () => primitive._texture,
u_atlas: () => primitive._texture ?? primitive._blank,
u_views: () => primitive._viewEntry?.texture ?? primitive._blank,
u_viewsReady: () => (primitive._viewEntry?.texture ? 1 : 0),
u_viewGrid: () => primitive._viewGrid,
u_viewRings: () => primitive._viewRings,
u_extras: () => primitive._extras,
u_cull: () => (primitive._cull() ? 1 : 0),
u_pickPass: () => primitive._pickPass,
@@ -431,7 +658,10 @@ export class IconSetPrimitive {
return;
const context = frameState.context;
this._syncAtlas(context);
if (!this._texture) return;
this._syncViews(context);
// Nothing to draw from yet: no atlas image packed, no view sheet.
if (!this._texture && !this._viewEntry) return;
this._blank = context.defaultTexture;
// Read as the commands run, which they do right after this update.
this._pickPass = frameState.passes.pick ? 1 : 0;
const renderTime = this.renderTime(frameState);
@@ -485,6 +715,31 @@ export class IconSetPrimitive {
Cesium.Cartesian4.unpack(iconAtlas.rects, slot * 4, this._slots[slot]);
}
/** Follow the set's view sheet: its layout's uniforms and its texture. */
_syncViews(context) {
const sheet = this._views();
if (sheet === this._viewsFrom) return;
this._viewsFrom = sheet;
this._viewEntry = null;
if (!sheet) return;
const { grid, rings } = viewUniforms(sheet.layout);
Cesium.Cartesian4.fromArray(grid, 0, this._viewGrid);
rings.forEach((pair, k) =>
Cesium.Cartesian4.fromArray(pair, 0, this._viewRings[k]),
);
this._viewEntry = viewSheetTexture(
context,
sheet.image,
() => this._requestRender?.(),
sheet.grey === true,
);
}
/** The set's view sheet: `none`, `loading`, `failed` or `ready`. */
viewsState() {
return this._viewEntry?.state ?? (this._views() ? 'loading' : 'none');
}
_allocate(context) {
const set = this.set;
this._destroyBuffers();
@@ -749,12 +1004,16 @@ export class IconSetPrimitive {
_createCommands(context) {
this._slotCount = contextIconSlots(context);
this._slotUniform = this._slots.slice(0, this._slotCount);
// View sheets are drawn on WebGL 2 only (as the draw port offers them):
// on WebGL 1 the shader is as it was without them.
const viewDefines = context?.webgl2 ? ['ICON_VIEW_SHEETS'] : [];
const programFor = (pass) =>
Cesium.ShaderProgram.fromCache({
context,
vertexShaderSource: new Cesium.ShaderSource({
defines: [
`ICON_SLOTS ${this._slotCount}`,
...viewDefines,
...(this._extras
? [
'ICON_EXTRAS',
@@ -766,12 +1025,14 @@ export class IconSetPrimitive {
sources: [VERTEX_SHADER],
}),
fragmentShaderSource: new Cesium.ShaderSource({
defines:
pass === 'opaque'
defines: [
...viewDefines,
...(pass === 'opaque'
? ['OPAQUE']
: pass === 'translucent'
? ['TRANSLUCENT']
: [],
: []),
],
sources: [FRAGMENT_SHADER],
}),
attributeLocations: ATTRIBUTE_LOCATIONS,
+2 -2
View File
@@ -18,7 +18,7 @@ import { createControlledCamera } from './controlledCamera.js';
import { listenerList, toCartesian, uncaught } from './common.js';
import { createCesiumCredits } from './credits.js';
import { createCesiumDraw } from './draw.js';
import { GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { gpuIconCapabilities } from './gpuIcons.js';
import { createCesiumEffects } from './effects.js';
import { renderNow, willDraw } from './frame.js';
import { createCesiumGlobe } from './globe.js';
@@ -100,7 +100,7 @@ export function cesiumCapabilities(scene, only) {
...(scene?.screenSpaceCameraController && scene?.preRender
? ['keepEarthFramed']
: []),
...GPU_ICON_CAPABILITIES,
...gpuIconCapabilities(scene),
// Icon sets cluster on screen, on billboards and the GPU (`draw.js`).
'cluster',
'styles',
+1
View File
@@ -18,6 +18,7 @@ test('capabilities follow what the scene supports', () => {
'columns',
'motionSegments',
'courseGlide',
'viewSheets',
'cluster',
'styles',
'bloom',