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

+42 -12
View File
@@ -33,6 +33,7 @@ import {
} from './aircraftIcons.js';
import { cockpitContactDotImage } from './cockpitContactDot.js';
import { rotorFrame, rotorTurns } from './rotorFrames.js';
import { registerAircraftViews, withAircraftView } from './aircraftViews.js';
import { aircraftRecedeSpec } from './aircraftRecession.js';
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
@@ -436,6 +437,8 @@ function fixedDelay(ms) {
* Where a host-supplied placement draws a live contact at a wall time,
* written into `out` (`placeAircraftAt`), or null when it does not place
* it; none without a placement.
* @param {(url: string) => string} [options.resolveAsset] The layer's asset
* URL resolver, for the aircraft view sheet's image.
*/
export function createAircraftIcons({
state,
@@ -453,10 +456,14 @@ export function createAircraftIcons({
afterSettle = () => {},
onForget = () => {},
placeAt = null,
resolveAsset = (url) => url,
}) {
const { focusPassIsNeeded } = services.focus;
// The near-image switch the rows were last written with (CSS px).
let switchPx = nearImageSwitchPx(1);
/** Whether the renderer draws icons along their course from the aircraft
* view sheet (`aircraftViews.js`), set when the draw set is made. */
let views = false;
/**
* Airborne helicopters drawn as their glyph, whose rotor turns: the rotor
* frame each was last drawn at, and the frame it was last judged at
@@ -544,9 +551,9 @@ export function createAircraftIcons({
sceneClock = followsClock();
sentDelayMs = sceneClock ? NaN : displayDelay.currentMs;
switchPx = _imageSwitchPx(viewer);
state._icons = createContactIcons(set, {
capabilities: rendererOf(viewer)?.capabilities ?? null,
});
const capabilities = rendererOf(viewer)?.capabilities ?? null;
views = registerAircraftViews(drawOf(viewer), capabilities, resolveAsset);
state._icons = createContactIcons(set, { capabilities });
return set.id;
}
@@ -555,6 +562,7 @@ export function createAircraftIcons({
state._icons?.dispose();
state._icons = null;
liveSet = null;
views = false;
rotors.clear();
planFrom.clear();
easeEnds.clear();
@@ -962,19 +970,26 @@ export function createAircraftIcons({
* How a contact's icon is drawn outside Cockpit: its image (and the sharper
* one it switches to up close), size, scale and scale by distance. The
* tracked contact's own icon is drawn with this too, so selecting a contact
* changes its colour and nothing else.
* changes its colour and nothing else. Drawn along its course
* (`alongCourse`) on a renderer that draws view sheets, a kind with
* rendered views draws from the aircraft view sheet, with no near image
* (`aircraftViews.js`); otherwise it is the flat glyph.
* @param {string} icao24
* @param {object} [info] Its record.
* @returns {{image: string, imageLod: {near: string, switchPx: number},
* @param {number} [frame] A helicopter's rotor frame.
* @param {{alongCourse?: boolean}} [options]
* @returns {{image: string|{views: string, first: number},
* imageLod: {near: string, switchPx: number}|undefined,
* size: [number, number], scale: number, scaleByDistance: object}}
*/
function _fleetLook(
icao24,
info = state.records.data.get(icao24),
frame = _rotorFrameOf(icao24, info, Date.now()),
{ alongCourse = false } = {},
) {
const rendering = parts.rendering;
return {
const look = {
image: aircraftIcon(
rendering._iconKind(icao24, info?.klass),
FLEET_ICON_PX,
@@ -992,6 +1007,17 @@ export function createAircraftIcons({
scale: rendering._fleetBillboardScale(icao24),
scaleByDistance: NORMAL_SCALE_BY_DISTANCE,
};
return withAircraftView(look, {
views,
kind: rendering._iconKind(icao24, info?.klass),
frame,
rotationMode: alongCourse ? 'course' : undefined,
});
}
/** Whether contacts drawn along their course draw from the view sheet. */
function _drawsViews() {
return views;
}
/**
@@ -1051,6 +1077,7 @@ export function createAircraftIcons({
id,
state.records.data.get(id),
frame,
{ alongCourse: icons.item(id)?.rotationMode === 'course' },
);
icons.update(id, { image, imageLod });
}
@@ -1064,6 +1091,11 @@ export function createAircraftIcons({
const rendering = parts.rendering;
const info = state.records.data.get(icao24);
const tracked = icao24 === state._trackedIcao;
// A helicopter's rotor frame, chosen once for its look and its rotor.
const heliFrame = _rotorFrameOf(icao24, info, Date.now());
// A ground station's mast stands upright; every other glyph turns
// along its course.
const station = info?.klass === 'station';
const cockpitDot =
state._cockpitContactMode &&
!tracked &&
@@ -1079,21 +1111,18 @@ export function createAircraftIcons({
rotationMode: 'screen',
}
: {
..._fleetLook(icao24, info),
..._fleetLook(icao24, info, heliFrame, { alongCourse: !station }),
color: rgba(rendering._fleetBillboardColor(icao24, info)),
rotationMode: 'course',
};
// A ground station's mast stands upright.
if (!cockpitDot && info?.klass === 'station') {
if (!cockpitDot && station) {
look.rotationMode = 'screen';
look.rotation = 0;
}
look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1;
icons.update(icao24, look);
// An airborne helicopter drawn as its glyph turns its rotor.
const frame = cockpitDot
? undefined
: _rotorFrameOf(icao24, info, Date.now());
const frame = cockpitDot ? undefined : heliFrame;
if (frame === undefined || !rotorTurns(_rotorState(info))) {
// A tracked helicopter that lands shows the still frame at once.
if (rotors.delete(icao24) && tracked)
@@ -1176,6 +1205,7 @@ export function createAircraftIcons({
_focusIcons,
_applyIconPresentation,
_fleetLook,
_drawsViews,
_turnRotors,
_rotorsTurning,
_addIcon,
+180
View File
@@ -481,3 +481,183 @@ test('back at live, a placed contact eases from where it is drawn over a recover
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
/**
* An icon layer on a renderer that does (or does not) draw view sheets,
* over contacts `records` (by id), all held at one place.
*/
function viewsFixture(
records,
{ viewSheets = true, kinds = {}, resolveAsset } = {},
) {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer, {
capabilities: new Set(viewSheets ? ['viewSheets'] : []),
});
const state = {
_viewer: viewer,
now: () => Date.now(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (id, klass) => kinds[id] ?? klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1.25,
_cockpitContactColor: () => [1, 0, 0, 1],
},
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
resolveAsset,
});
icons._createIcons(viewer);
const here = fromDegrees(0, 30, 300);
for (const id of records.keys()) {
state._icons.put(
{ id, pos: here, motion: { kind: 'hold', courseDeg: 0 }, size: [20, 20] },
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
return { state, icons, registered: draw.viewSheets, here, unbind };
}
test('with view sheets, every aircraft class draws from the sheet along its course, with no near image', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const records = new Map([
['p1', { klass: 'airliner' }],
['p2', { klass: 'glider' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, icons, registered, unbind } = viewsFixture(records);
t.after(unbind);
assert.deepEqual(registered, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftViewRef('airliner'));
assert.equal(p1.imageLod, undefined);
assert.equal(p1.rotationMode, 'course');
// Everything else is as the flat glyph draws it.
assert.deepEqual(p1.size, [20, 20]);
assert.equal(p1.scale, 1.25);
assert.deepEqual(p1.color, [1, 1, 1, 1]);
assert.equal(p1.scaleByDistance.nearValue, 3);
assert.equal(state._icons.item('p2').image, aircraftViewRef('glider'));
assert.equal(
state._icons.item('h1').image,
aircraftViewRef('helicopter', ROTOR_STILL_FRAME),
);
// The plain fleet look (the tracked icon's sizing, a screen-rotated
// caller) stays the flat glyph.
assert.equal(
icons._fleetLook('p1').image,
aircraftIcon('airliner', FLEET_ICON_PX),
);
assert.equal(
icons._fleetLook('p1', undefined, undefined, { alongCourse: true }).image,
aircraftViewRef('airliner'),
);
assert.equal(icons._drawsViews(), true);
icons._disposeIcons();
assert.equal(icons._drawsViews(), false);
});
test('without view sheets the icons are the flat glyphs with their near image, as before', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([['p1', { klass: 'airliner' }]]);
const { state, icons, registered, unbind } = viewsFixture(records, {
viewSheets: false,
});
t.after(unbind);
assert.deepEqual(registered, [], 'no sheet is registered');
const p1 = state._icons.item('p1');
assert.equal(p1.image, aircraftIcon('airliner', FLEET_ICON_PX));
assert.equal(p1.imageLod.near, aircraftIcon('airliner', 192));
assert.equal(p1.rotationMode, 'course');
assert.equal(icons._drawsViews(), false);
});
test('with view sheets, the TR-3B, airport vehicles and ground stations stay flat', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['x1', { klass: 'airliner' }],
['v1', { klass: 'vehicle' }],
['s1', { klass: 'station' }],
]);
const { state, unbind } = viewsFixture(records, {
kinds: { x1: 'tr3b' },
});
t.after(unbind);
assert.equal(
state._icons.item('x1').image,
aircraftIcon('tr3b', FLEET_ICON_PX),
);
assert.ok(state._icons.item('x1').imageLod);
assert.equal(
state._icons.item('v1').image,
aircraftIcon('vehicle', FLEET_ICON_PX),
);
const mast = state._icons.item('s1');
assert.equal(mast.image, aircraftIcon('station', FLEET_ICON_PX));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('with view sheets, an airborne helicopter turns its rotor through the sheet’s three blocks', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { aircraftViewRef } = await import('./aircraftViews.js');
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
const { state, icons, unbind } = viewsFixture(records);
t.after(unbind);
const seen = new Set();
for (let step = 0; step <= 12; step++) {
if (step) t.mock.timers.tick(80);
icons._turnRotors(Date.now(), Date.now());
const item = state._icons.item('h1');
assert.equal(item.imageLod, undefined);
seen.add(item.image);
}
assert.deepEqual(
new Set(seen),
new Set([0, 1, 2].map((frame) => aircraftViewRef('helicopter', frame))),
);
});
test('the layer registers the view sheet at its own asset URL', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const { AIRCRAFT_VIEWS } = await import('./viewSheet.js');
const { registered, unbind } = viewsFixture(
new Map([['p1', { klass: 'airliner' }]]),
{ resolveAsset: (url) => `/gev/${url.replace(/^\//, '')}` },
);
t.after(unbind);
assert.equal(registered.length, 1);
assert.equal(registered[0][0], AIRCRAFT_VIEWS.id);
assert.equal(registered[0][1].image, '/gev/sprites/aircraft-views.webp');
});
test('a view carries the contact’s flat glyph as its fallback', async (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([
['p1', { klass: 'turboprop' }],
['h1', { klass: 'helicopter', onGround: true }],
]);
const { state, unbind } = viewsFixture(records);
t.after(unbind);
assert.equal(
state._icons.item('p1').image.fallback,
aircraftIcon('turboprop', FLEET_ICON_PX),
);
assert.equal(
state._icons.item('h1').image.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
});
+138
View File
@@ -0,0 +1,138 @@
/**
* @module data/aircraftViews
* @description Which block of the aircraft view sheet (`viewSheet.js`) a
* contact's icon draws from. Each aircraft class is rendered there from a
* sphere of camera angles; a renderer with the `viewSheets` capability lays
* the icon flat on the earth along its course and draws the view that
* matches where the eye is, so an oblique contact looks solid instead of
* like a paper cut-out. Only an icon drawn along its course
* (`rotationMode: 'course'`) can do this: a screen-rotated or upright icon
* keeps its flat glyph. Kinds with no rendered views (the TR-3B triangle,
* airport vehicles, ground stations) keep their flat glyph as well.
*/
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import {
aircraftIcon,
FLEET_ICON_PX,
ROTOR_FRAMES,
ROTOR_STILL_FRAME,
} from './aircraftIcons.js';
/** The renderer capability that draws view sheets. */
export const VIEW_SHEETS_CAPABILITY = 'viewSheets';
/** Kinds drawn from the sheet with one block each (helicopters have three). */
const STILL_KINDS = new Set([
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
]);
/** One frozen image ref per block, so equal refs are the same object. */
const refs = new Map();
/**
* The ref of the block at `first`, with the flat glyph of `kind` (and its
* rotor `frame`) as its fallback: what the renderer draws until the sheet
* has loaded, and for good if it cannot load.
*/
function refAt(first, kind, frame) {
let ref = refs.get(first);
if (!ref) {
ref = Object.freeze({
views: AIRCRAFT_VIEWS.id,
first,
fallback: aircraftIcon(kind, FLEET_ICON_PX, frame),
});
refs.set(first, ref);
}
return ref;
}
/**
* The view image of an icon kind: `{views, first, fallback}`, the sheet's
* id, the first cell of the kind's block and its flat glyph (drawn while
* the sheet loads, or if it fails), or null for a kind with no views.
* @param {string} kind An icon kind (`rendering._iconKind`).
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
* (the still frame otherwise, as `aircraftIcon` takes it).
* @returns {{views: string, first: number, fallback: string}|null}
*/
export function aircraftViewRef(kind, frame) {
const subjects = AIRCRAFT_VIEWS.subjects;
if (kind === 'helicopter') {
const f =
Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
? frame
: ROTOR_STILL_FRAME;
const first = subjects[`helicopter${f}`];
return Number.isInteger(first) ? refAt(first, kind, f) : null;
}
if (!STILL_KINDS.has(kind)) return null;
const first = subjects[kind];
return Number.isInteger(first) ? refAt(first, kind) : null;
}
/** Whether an icon image is a view-sheet ref. */
export function isAircraftViewRef(image) {
return Boolean(image) && typeof image === 'object' && 'views' in image;
}
/** Draw ports the sheet is registered on. */
const registered = new WeakSet();
/**
* Register the aircraft view sheet on a draw port, once per port, when its
* renderer draws view sheets, its image URL resolved as the layer resolves
* its other assets (the fleet models'). Safe to call any number of times.
* @param {{views?: Function}|null} drawPort
* @param {ReadonlySet<string>|null} [capabilities] The renderer's.
* @param {(url: string) => string} [resolveAsset] The layer's asset URL
* resolver.
* @returns {boolean} Whether icons on this port can draw views.
*/
export function registerAircraftViews(
drawPort,
capabilities,
resolveAsset = (url) => url,
) {
if (!drawPort || typeof drawPort.views !== 'function') return false;
if (!capabilities?.has?.(VIEW_SHEETS_CAPABILITY)) return false;
if (!registered.has(drawPort)) {
const sheet = AIRCRAFT_VIEWS.sheet;
drawPort.views(AIRCRAFT_VIEWS.id, {
...sheet,
image: resolveAsset(sheet.image),
});
registered.add(drawPort);
}
return true;
}
/**
* An icon's look drawn from the view sheet where it can be: with views on,
* the item drawn along its course and the kind rendered, the image is the
* view ref and there is no near image (`imageLod: undefined`, so an update
* clears it); otherwise the look as given, the very same object.
* @template {{image: unknown, imageLod?: unknown}} T
* @param {T} look
* @param {object} options
* @param {boolean} options.views Whether the renderer draws views
* (`registerAircraftViews`).
* @param {string} options.kind The icon kind.
* @param {number} [options.frame] A helicopter's rotor frame.
* @param {string} [options.rotationMode] How the item is rotated.
* @returns {T}
*/
export function withAircraftView(look, { views, kind, frame, rotationMode }) {
if (!views || rotationMode !== 'course') return look;
const ref = aircraftViewRef(kind, frame);
if (!ref) return look;
return { ...look, image: ref, imageLod: undefined };
}
+175
View File
@@ -0,0 +1,175 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
aircraftViewRef,
isAircraftViewRef,
registerAircraftViews,
VIEW_SHEETS_CAPABILITY,
withAircraftView,
} from './aircraftViews.js';
import { AIRCRAFT_VIEWS } from './viewSheet.js';
import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './rotorFrames.js';
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
const STILL_KINDS = [
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
];
test('every aircraft class draws its own block of the view sheet', () => {
for (const kind of STILL_KINDS)
assert.deepEqual(
aircraftViewRef(kind),
{
views: AIRCRAFT_VIEWS.id,
first: AIRCRAFT_VIEWS.subjects[kind],
fallback: aircraftIcon(kind, FLEET_ICON_PX),
},
kind,
);
const firsts = STILL_KINDS.map((kind) => aircraftViewRef(kind).first);
assert.equal(
new Set(firsts).size,
STILL_KINDS.length,
'no two share a block',
);
assert.equal(
aircraftViewRef('airliner'),
aircraftViewRef('airliner'),
'one ref per block, so an unchanged image writes nothing',
);
assert.ok(Object.isFrozen(aircraftViewRef('airliner')));
});
test('a helicopter draws the block of its rotor frame, the still frame by default', () => {
assert.equal(ROTOR_FRAMES, 3);
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
const ref = aircraftViewRef('helicopter', frame);
assert.equal(
ref.first,
AIRCRAFT_VIEWS.subjects[`helicopter${frame}`],
`frame ${frame}`,
);
assert.equal(
ref.fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, frame),
`its fallback is the glyph of rotor frame ${frame}`,
);
}
assert.equal(
aircraftViewRef('helicopter').fallback,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
const still = AIRCRAFT_VIEWS.subjects[`helicopter${ROTOR_STILL_FRAME}`];
for (const frame of [undefined, -1, 3, 1.5, NaN])
assert.equal(aircraftViewRef('helicopter', frame).first, still, `${frame}`);
});
test('the TR-3B, airport vehicles, ground stations and unknown kinds have no views', () => {
for (const kind of [
'tr3b',
'tr3bHot',
'vehicle',
'station',
'jet',
'',
undefined,
])
assert.equal(aircraftViewRef(kind), null, String(kind));
assert.equal(
aircraftViewRef('airliner', 1).first,
0,
'a frame means nothing to a fixed wing',
);
});
test('a view ref is told apart from flat images', () => {
assert.equal(isAircraftViewRef(aircraftViewRef('glider')), true);
for (const image of [
'data:image/svg+xml;base64,AAA',
null,
undefined,
{ atlas: 'a', slot: 's' },
])
assert.equal(isAircraftViewRef(image), false, String(image));
});
test('the sheet is registered once per draw port, only with the capability', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
assert.equal(VIEW_SHEETS_CAPABILITY, 'viewSheets');
assert.equal(registerAircraftViews(port, new Set()), false);
assert.equal(registerAircraftViews(port, null), false);
assert.equal(calls.length, 0, 'nothing registered without the capability');
assert.equal(registerAircraftViews(port, caps), true);
assert.equal(registerAircraftViews(port, caps), true);
assert.deepEqual(calls, [[AIRCRAFT_VIEWS.id, AIRCRAFT_VIEWS.sheet]]);
const other = { views: (id) => calls.push([id]) };
assert.equal(registerAircraftViews(other, caps), true);
assert.equal(calls.length, 2, 'a second port registers its own');
assert.equal(
registerAircraftViews({}, caps),
false,
'a port without views()',
);
assert.equal(registerAircraftViews(null, caps), false);
});
test('a look takes the view only when views are on and it is drawn along its course', () => {
const look = {
image: 'flat',
imageLod: { near: 'near', switchPx: 30 },
size: [20, 20],
scale: 1.5,
};
const on = { views: true, kind: 'airliner', rotationMode: 'course' };
const viewed = withAircraftView(look, on);
assert.deepEqual(viewed, {
image: aircraftViewRef('airliner'),
imageLod: undefined,
size: [20, 20],
scale: 1.5,
});
assert.ok('imageLod' in viewed, 'imageLod is cleared, so an update drops it');
assert.equal(look.image, 'flat', 'the look given is left as it was');
assert.equal(withAircraftView(look, { ...on, views: false }), look);
assert.equal(withAircraftView(look, { ...on, rotationMode: 'screen' }), look);
assert.equal(
withAircraftView(look, { ...on, rotationMode: undefined }),
look,
);
assert.equal(withAircraftView(look, { ...on, kind: 'tr3b' }), look);
assert.equal(withAircraftView(look, { ...on, kind: 'station' }), look);
assert.equal(
withAircraftView(look, { ...on, kind: 'helicopter', frame: 2 }).image,
aircraftViewRef('helicopter', 2),
);
});
test('the sheet is registered with its image resolved as the layer resolves its assets', () => {
const calls = [];
const port = { views: (id, sheet) => calls.push([id, sheet]) };
const caps = new Set([VIEW_SHEETS_CAPABILITY]);
registerAircraftViews(port, caps, (url) => `https://cdn.example/app${url}`);
assert.equal(calls.length, 1);
const [id, sheet] = calls[0];
assert.equal(id, AIRCRAFT_VIEWS.id);
assert.equal(
sheet.image,
'https://cdn.example/app/sprites/aircraft-views.webp',
);
assert.deepEqual(
{ ...sheet, image: AIRCRAFT_VIEWS.sheet.image },
{ ...AIRCRAFT_VIEWS.sheet },
'the layout as it is',
);
assert.equal(AIRCRAFT_VIEWS.sheet.image, '/sprites/aircraft-views.webp');
});
+2 -2
View File
@@ -42,8 +42,8 @@ export const MAX_ICON_SLOTS = 176;
export const MIN_ICON_SLOTS = 64;
/**
* Vertex uniform vectors the icon shader keeps for everything else: its own
* and the renderer's (about 34), with room for drivers that keep constants
* in uniforms.
* and the renderer's (about 45, the view sheet's layout among them), with
* room for drivers that keep constants in uniforms.
*/
const OTHER_VERTEX_UNIFORMS = 80;
+6
View File
@@ -100,6 +100,12 @@ export const ICON_RECEDES = 4;
* −31 m before its floor warms) otherwise reads as beyond the limb.
*/
export const ICON_CULL_LIFT = 8;
/**
* The row's image is a subject of the set's view sheet
* ({@link module:viewSheet}): its far image is the subject's first cell, and
* the renderer draws the frame that shows it from the eye.
*/
export const ICON_VIEWS = 16;
/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */
export const ICON_CULL_HEIGHT_M = HORIZON_LIFT_M;
/**
+20 -5
View File
@@ -15,8 +15,14 @@
* pick names the set and the contact's id, as the fleet icons' do.
* `visible` hides the icon while it stays shown (Cockpit flies the
* aircraft from its own seat).
*
* Given a view-sheet image (`aircraftViews.js`) and a course reader, it is
* drawn along that course instead (`rotationMode: 'course'`), as the fleet
* icons are, so the renderer draws the view of the aircraft that matches
* the eye and tracking a contact does not flatten it.
*/
import { findDraw, findFrame } from '../render/rendererOf.js';
import { isAircraftViewRef } from './aircraftViews.js';
/** Uniquifier for the sets' ids. */
let instances = 0;
@@ -105,18 +111,21 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
function draw() {
if (!shown || !set) return;
const pos = shown.position();
const alongCourse =
typeof shown.course === 'function' && isAircraftViewRef(shown.image);
const item = {
id: shown.id,
pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 },
show: Boolean(pos) && visible,
image: shown.image,
...(shown.imageLod ? { imageLod: shown.imageLod } : {}),
...(shown.imageLod && !alongCourse ? { imageLod: shown.imageLod } : {}),
size: [shown.sprite.width, shown.sprite.height],
scale: shown.sprite.scale,
scaleByDistance: shown.sprite.scaleByDistance,
color: shown.color(),
rotationMode: 'screen',
rotation: pos ? shown.rotation() : 0,
...(alongCourse
? { rotationMode: 'course', course: pos ? shown.course() : 0 }
: { rotationMode: 'screen', rotation: pos ? shown.rotation() : 0 }),
disableDepthTest: Number.POSITIVE_INFINITY,
};
if (
@@ -132,7 +141,9 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
written.size[0] === item.size[0] &&
written.size[1] === item.size[1] &&
written.scale === item.scale &&
written.rotationMode === item.rotationMode &&
written.rotation === item.rotation &&
written.course === item.course &&
sameColor(written.color, item.color)
)
return;
@@ -146,13 +157,17 @@ export function createTrackedAircraftIcon({ viewer, setPrefix }) {
* next one on.
* @param {object} target
* @param {string} target.id The contact's id.
* @param {string} target.image
* @param {string|{views: string, first: number}} target.image A flat
* glyph, or a view-sheet image (drawn along `course`).
* @param {{near: string, switchPx: number}} [target.imageLod] The
* sharper image it switches to once drawn larger than `switchPx`.
* sharper image a flat glyph switches to once drawn larger than
* `switchPx`.
* @param {{width: number, height: number, scale: number,
* scaleByDistance: object}} target.sprite Read each frame.
* @param {() => object|null} target.position ECEF this frame; none hides it.
* @param {() => number} target.rotation Screen radians, counter-clockwise.
* @param {() => number} [target.course] Degrees clockwise from north;
* required with a view-sheet image, which only draws along a course.
* @param {() => object} target.color The tint this frame.
*/
show(target) {
+49
View File
@@ -199,3 +199,52 @@ test('the tracked icon keeps its contact\'s colour; only the alpha changes', ()
assert.ok(Object.isFrozen(stale));
assert.deepEqual(trackedIconColor(amber, 0), [1, 0.72, 0, 0]);
});
test('given a view-sheet image and a course, the tracked icon is drawn along its course with no near image', async () => {
const { aircraftViewRef } = await import('./aircraftViews.js');
const { viewer, draw, tick } = harness();
const icon = createTrackedAircraftIcon({
viewer: () => viewer,
setPrefix: 'flights',
});
let course = 45;
let rotations = 0;
icon.show({
id: 'abc123',
image: aircraftViewRef('airliner'),
imageLod: { near: 'near', switchPx: 30 },
sprite: SPRITE,
position: () => ({ x: 1, y: 2, z: 3 }),
rotation: () => {
rotations++;
return 0.5;
},
course: () => course,
color: () => [0, 1, 1, 1],
});
const set = draw.find('flights-tracked-icon:');
tick();
const item = set.items.get('abc123');
assert.equal(item.image, aircraftViewRef('airliner'));
assert.equal('imageLod' in item, false);
assert.equal(item.rotationMode, 'course');
assert.equal(item.course, 45);
assert.equal('rotation' in item, false);
assert.equal(rotations, 0, 'no screen rotation is projected');
assert.deepEqual(item.size, [28, 28]);
const writes = set.writes;
tick();
assert.equal(set.writes, writes, 'an unchanged frame writes nothing');
course = 50;
tick();
assert.equal(set.items.get('abc123').course, 50);
// A flat image (a TR-3B conversion, a ground station) turns on screen again.
icon.setImage('data:image/svg+xml;base64,AAA', { near: 'near', switchPx: 30 });
tick();
const flat = set.items.get('abc123');
assert.equal(flat.rotationMode, 'screen');
assert.equal(flat.rotation, 0.5);
assert.deepEqual(flat.imageLod, { near: 'near', switchPx: 30 });
assert.equal('course' in flat, false);
icon.dispose();
});
+256
View File
@@ -0,0 +1,256 @@
/**
* @module viewSheet
* @description A view sheet: one image of small sprites showing a subject
* (an aircraft class) from a sphere of directions, and the maths that picks
* the sprite for where the eye is. Plain JavaScript and GLSL: no DOM, no
* engine. `scripts/build-aircraft-view-sheet.py` bakes the aircraft sheet to
* this layout; a renderer with the `viewSheets` capability draws it.
*
* **Frames.** A subject lies flat on the earth: up is the ground's normal,
* forward its course. `d` is the direction from the subject to the eye in
* the subject's own axes `[forward, right, up]`. A sheet holds each subject
* as a block of consecutive cells, row-major: rings of frames `ringStepDeg`
* apart, from straight above (ring 0) downward, ring `k` holding `rings[k]`
* frames from the eye dead ahead, round the right side, to dead astern. The
* left side is the right-side frame mirrored, so a sheet's subjects and
* their light are symmetric about their centre plane.
*
* **Roll.** A frame's image up is {@link frameUp}: forward, turned by the
* smallest rotation that takes up onto the frame's direction. Straight
* above, the nose points up the image; the roll then changes smoothly all
* the way round and below. It has no meaning only from straight below, so a
* sheet's last ring stays short of that.
*
* **Between frames.** The frame nearest the eye's direction is drawn
* ({@link viewFrame}), as a card standing where its subject is, square to
* the frame's own direction: seen from a little to one side it is tilted
* (foreshortened and turned) as the subject itself would be, until the next
* frame is the nearer. Frames are not blended.
*/
/** Rings a sheet may hold (the shader's uniform array); even. */
export const VIEW_RINGS_MAX = 18;
/** The aircraft classes' view sheet (`public/sprites/aircraft-views.json`). */
export const AIRCRAFT_VIEWS = Object.freeze({
id: 'aircraft-views',
sheet: Object.freeze({
image: '/sprites/aircraft-views.webp',
cellPx: 64,
columns: 64,
rows: 57,
ringStepDeg: 7.5,
rings: Object.freeze([
1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22,
]),
grey: true,
}),
/** Frames in each subject's block. */
frames: 302,
/** Each subject's first cell. */
subjects: Object.freeze({
airliner: 0,
widebody: 302,
quadjet: 604,
turboprop: 906,
light: 1208,
glider: 1510,
fastjet: 1812,
bizjet: 2114,
uav: 2416,
helicopter0: 2718,
helicopter1: 3020,
helicopter2: 3322,
}),
});
/**
* Check a sheet's layout, and return it with each ring's first frame.
* @param {{image: string, cellPx: number, columns: number, rows: number,
* ringStepDeg: number, rings: readonly number[], grey?: boolean}} sheet
* @returns {{columns: number, rows: number, ringStepRad: number,
* rings: number[], firsts: number[], frames: number}}
*/
export function viewLayout(sheet) {
const whole = (n) => Number.isInteger(n) && n > 0;
if (!sheet || typeof sheet.image !== 'string' || !sheet.image)
throw new TypeError('a view sheet needs its image URL');
if (!whole(sheet.cellPx) || !whole(sheet.columns) || !whole(sheet.rows))
throw new TypeError(
'a view sheet needs whole cellPx, columns and rows above 0',
);
const { rings, ringStepDeg } = sheet;
if (
!Array.isArray(rings) ||
rings.length < 1 ||
rings.length > VIEW_RINGS_MAX ||
!rings.every(whole)
)
throw new TypeError(
`a view sheet needs 1 to ${VIEW_RINGS_MAX} rings of whole frame counts`,
);
if (rings[0] !== 1)
throw new TypeError("a view sheet's first ring is the one frame above");
if (
!(ringStepDeg > 0) ||
!Number.isFinite(ringStepDeg) ||
(rings.length - 1) * ringStepDeg >= 180
)
throw new TypeError("a view sheet's rings stop short of straight below");
const firsts = [];
let frames = 0;
for (const count of rings) {
firsts.push(frames);
frames += count;
}
return {
columns: sheet.columns,
rows: sheet.rows,
ringStepRad: (ringStepDeg * Math.PI) / 180,
rings: [...rings],
firsts,
frames,
};
}
/**
* The frame that shows a subject from `d`.
* @param {ReturnType<typeof viewLayout>} layout
* @param {readonly [number, number, number]} d Toward the eye, as
* `[forward, right, up]`; any length above 0.
* @returns {{frame: number, ring: number, index: number, mirrored: boolean}}
* `frame` counts from the subject's first cell; `mirrored` draws it flipped
* left to right (the eye on the left side).
*/
export function viewFrame(layout, d) {
const length = Math.hypot(d[0], d[1], d[2]);
const up = length > 0 ? Math.min(1, Math.max(-1, d[2] / length)) : 1;
const ring = Math.min(
layout.rings.length - 1,
Math.floor(Math.acos(up) / layout.ringStepRad + 0.5),
);
const span = layout.rings[ring] - 1;
const side = Math.abs(d[1]);
const bearing = side + Math.abs(d[0]) > 0 ? Math.atan2(side, d[0]) : 0;
const index = span > 0 ? Math.floor((bearing / Math.PI) * span + 0.5) : 0;
return {
frame: layout.firsts[ring] + index,
ring,
index,
mirrored: d[1] < 0,
};
}
/**
* The direction a frame shows its subject from: a unit `[forward, right,
* up]`, on the right side (or the left, mirrored).
*/
export function frameDirection(layout, ring, index, mirrored = false) {
const off = ring * layout.ringStepRad;
const span = layout.rings[ring] - 1;
const turn = span > 0 ? (index / span) * Math.PI : 0;
return [
Math.sin(off) * Math.cos(turn),
Math.sin(off) * Math.sin(turn) * (mirrored ? -1 : 1),
Math.cos(off),
];
}
/**
* A frame's image up, for the unit direction `d` it shows its subject from:
* forward, turned as up turns onto `d`. A unit `[forward, right, up]`,
* perpendicular to `d`.
*/
export function frameUp(d) {
const k = 1 / Math.max(1 + d[2], 1e-6);
return [1 - d[0] * d[0] * k, -d[0] * d[1] * k, -d[0]];
}
/**
* A sheet's layout as the shader's uniforms: `grid`, and `rings` as one
* vector for each two rings (`[frames, first, frames, first]`).
*/
export function viewUniforms(layout) {
const rings = [];
for (let k = 0; k < VIEW_RINGS_MAX; k += 2)
rings.push([
layout.rings[k] ?? 1,
layout.firsts[k] ?? 0,
layout.rings[k + 1] ?? 1,
layout.firsts[k + 1] ?? 0,
]);
return {
grid: [
layout.columns,
layout.rows,
layout.ringStepRad,
layout.rings.length,
],
rings,
};
}
/**
* {@link viewFrame}, {@link frameDirection} and {@link frameUp} in GLSL, over `u_viewGrid` (columns, rows, ring step in radians, rings) and
* `u_viewRings` (each ring's frames and first frame, two rings a vector).
*/
export const VIEW_SHEET_GLSL = /* glsl */ `
uniform vec4 u_viewGrid;
uniform vec4 u_viewRings[${VIEW_RINGS_MAX / 2}];
// A ring's frames and its first frame, from the subject's first cell.
vec2 viewRing(float ring) {
vec4 pair = u_viewRings[int(ring * 0.5)];
return ring - 2.0 * floor(ring * 0.5) < 0.5 ? pair.xy : pair.zw;
}
// The frame that shows a subject from d (unit, toward the eye, as forward,
// right, up): its ring, its index in the ring, and 1 when it is drawn
// mirrored (the eye on the left side).
vec3 viewNearest(vec3 d) {
float ring = clamp(
floor(acos(clamp(d.z, -1.0, 1.0)) / u_viewGrid.z + 0.5),
0.0, u_viewGrid.w - 1.0);
float span = viewRing(ring).x - 1.0;
float side = abs(d.y);
float bearing = side + abs(d.x) > 0.0 ? atan(side, d.x) : 0.0;
return vec3(
ring,
span > 0.0 ? floor(bearing / 3.141592653589793 * span + 0.5) : 0.0,
d.y < 0.0 ? 1.0 : 0.0);
}
// The direction a frame shows its subject from (toward the eye, as forward,
// right, up; flip 1 for the left side) and the frame's image up.
void viewFrameAxes(float ring, float index, float flip, out vec3 toEye, out vec3 up) {
float span = viewRing(ring).x - 1.0;
float off = ring * u_viewGrid.z;
float turn = span > 0.0 ? index / span * 3.141592653589793 : 0.0;
toEye = vec3(
sin(off) * cos(turn),
sin(off) * sin(turn) * (1.0 - 2.0 * flip),
cos(off));
float k = 1.0 / max(1.0 + toEye.z, 1.0e-6);
up = vec3(1.0 - toEye.x * toEye.x * k, -toEye.x * toEye.y * k, -toEye.x);
}
`;
/**
* Reading a view sheet's cells in a fragment shader: `viewCell(cell, uv,
* lod)` is the colour of a cell at `uv` (0..1 across it, v down) and that
* level of detail, nothing outside it, from `u_views` over `u_viewGrid`.
*/
export const VIEW_SHEET_FRAGMENT_GLSL = /* glsl */ `
uniform sampler2D u_views;
uniform vec4 u_viewGrid;
vec4 viewCell(float cell, vec2 uv, float lod) {
float at = floor(cell + 0.5);
float row = floor((at + 0.5) / u_viewGrid.x);
float column = at - row * u_viewGrid.x;
vec2 inside = step(vec2(0.0), uv) * step(uv, vec2(1.0));
vec4 color = textureLod(
u_views, (vec2(column, row) + clamp(uv, 0.0, 1.0)) / u_viewGrid.xy, lod);
return color * (inside.x * inside.y);
}
`;
+379
View File
@@ -0,0 +1,379 @@
import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import {
AIRCRAFT_VIEWS,
frameDirection,
frameUp,
viewFrame,
viewLayout,
viewUniforms,
VIEW_RINGS_MAX,
} from './viewSheet.js';
const layout = viewLayout(AIRCRAFT_VIEWS.sheet);
const RAD = Math.PI / 180;
const HORIZON = 12; // the ring at 90° from straight above
/** The pinned layout: rings 7.5° apart, 302 frames a subject. */
const RINGS = [1, 4, 7, 10, 13, 16, 18, 20, 22, 23, 24, 25, 25, 25, 24, 23, 22];
const FIRSTS = [
0, 1, 5, 12, 22, 35, 51, 69, 89, 111, 134, 158, 183, 208, 233, 257, 280,
];
/** A unit `[forward, right, up]` `offDeg` from straight above, at `bearingDeg`
* from dead ahead toward the right side. */
function direction(offDeg, bearingDeg) {
const off = offDeg * RAD;
const bearing = bearingDeg * RAD;
return [
Math.sin(off) * Math.cos(bearing),
Math.sin(off) * Math.sin(bearing),
Math.cos(off),
];
}
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a, b) => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
const mirror = (v) => [v[0], -v[1], v[2]];
const near = (a, b, eps = 1e-9) =>
a.every((value, i) => Math.abs(value - b[i]) < eps);
/** The smallest rotation taking up onto `d`, applied to forward (Rodrigues). */
function rotatedForward(d) {
const up = [0, 0, 1];
const forward = [1, 0, 0];
const axis = cross(up, d);
const sin = Math.hypot(...axis);
const cos = dot(up, d);
if (sin < 1e-12) return forward;
const k = axis.map((value) => value / sin);
const kxv = cross(k, forward);
const kv = dot(k, forward);
return forward.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
}
test('viewLayout gives the aircraft sheet each ring’s first frame', () => {
assert.deepEqual(layout.rings, RINGS);
assert.deepEqual(layout.firsts, FIRSTS);
assert.equal(layout.frames, 302);
assert.equal(layout.columns, 64);
assert.equal(layout.rows, 57);
assert.equal(layout.ringStepRad, 7.5 * RAD);
assert.notEqual(layout.rings, AIRCRAFT_VIEWS.sheet.rings, 'a copy');
});
test('viewLayout refuses a sheet it cannot draw', () => {
const sheet = AIRCRAFT_VIEWS.sheet;
const bad = [
null,
{ ...sheet, image: '' },
{ ...sheet, image: undefined },
{ ...sheet, cellPx: 63.5 },
{ ...sheet, columns: 0 },
{ ...sheet, rows: -32 },
{ ...sheet, rings: [] },
{ ...sheet, rings: 'many' },
{ ...sheet, rings: Array(VIEW_RINGS_MAX + 1).fill(1) },
{ ...sheet, rings: [3, 5] },
{ ...sheet, rings: [1, 2.5] },
{ ...sheet, rings: [1, 0] },
{ ...sheet, ringStepDeg: 0 },
{ ...sheet, ringStepDeg: -15 },
{ ...sheet, ringStepDeg: Number.NaN },
{ ...sheet, ringStepDeg: Infinity },
// A ring straight below, or past it.
{ ...sheet, rings: [1, 4, 4, 1], ringStepDeg: 60 },
{ ...sheet, rings: Array(13).fill(1), ringStepDeg: 15 },
];
for (const sheetGiven of bad)
assert.throws(
() => viewLayout(sheetGiven),
TypeError,
JSON.stringify(sheetGiven),
);
// Short of straight below, and the most rings there may be, are drawn.
assert.equal(viewLayout({ ...sheet, rings: Array(12).fill(1) }).frames, 12);
assert.equal(
viewLayout({
...sheet,
rings: Array(VIEW_RINGS_MAX).fill(1),
ringStepDeg: 10,
}).rings.length,
VIEW_RINGS_MAX,
);
});
test('straight above is frame 0, whatever the course', () => {
assert.deepEqual(viewFrame(layout, [0, 0, 1]), {
frame: 0,
ring: 0,
index: 0,
mirrored: false,
});
assert.equal(viewFrame(layout, [0, 0, 42]).frame, 0, 'any length');
assert.equal(viewFrame(layout, direction(3.7, 135)).frame, 0);
assert.equal(viewFrame(layout, [0, 0, 0]).frame, 0, 'no direction: above');
});
test('on the horizon, dead ahead, abeam and astern are the first, middle and last frames of ring 12', () => {
const first = layout.firsts[HORIZON];
const ahead = viewFrame(layout, [1, 0, 0]);
assert.deepEqual(ahead, {
frame: first,
ring: 12,
index: 0,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [0, 1, 0]), {
frame: first + 12,
ring: 12,
index: 12,
mirrored: false,
});
assert.deepEqual(viewFrame(layout, [-1, 0, 0]), {
frame: first + 24,
ring: 12,
index: 24,
mirrored: false,
});
});
test('the left side draws the right side’s frame mirrored', () => {
for (const [off, bearing] of [
[30, 40],
[90, 90],
[105, 170],
[60, 1],
]) {
const right = viewFrame(layout, direction(off, bearing));
const left = viewFrame(layout, mirror(direction(off, bearing)));
assert.equal(left.frame, right.frame, `${off}/${bearing}`);
assert.equal(right.mirrored, false);
assert.equal(left.mirrored, true);
}
// Exactly on the centre plane it is not mirrored.
assert.equal(viewFrame(layout, [1, 0, 0]).mirrored, false);
assert.equal(viewFrame(layout, [1, -0, 0]).mirrored, false);
});
test('below the last ring the eye takes the last ring', () => {
const last = layout.rings.length - 1;
for (const off of [120, 126, 135, 170, 180]) {
const view = viewFrame(layout, direction(off, 90));
assert.equal(view.ring, last, `${off}°`);
}
assert.equal(viewFrame(layout, [0, 0, -1]).frame, layout.firsts[last]);
});
test('frames round to the nearest, between rings and between bearings', () => {
// Rings are 7.5° apart: 3.75° from straight above is between ring 0 and 1.
assert.equal(viewFrame(layout, direction(3.7, 0)).ring, 0);
assert.equal(viewFrame(layout, direction(3.8, 0)).ring, 1);
assert.equal(viewFrame(layout, direction(86.2, 0)).ring, 11);
assert.equal(viewFrame(layout, direction(86.3, 0)).ring, 12);
// The horizon ring's 25 frames are 7.5° of bearing apart.
assert.equal(viewFrame(layout, direction(90, 3.7)).index, 0);
assert.equal(viewFrame(layout, direction(90, 3.8)).index, 1);
assert.equal(viewFrame(layout, direction(90, 176.2)).index, 23);
assert.equal(viewFrame(layout, direction(90, 176.3)).index, 24);
// Ring 1's 4 frames are 60° apart.
assert.equal(viewFrame(layout, direction(7.5, 29.9)).index, 0);
assert.equal(viewFrame(layout, direction(7.5, 30.1)).index, 1);
});
test('frameDirection is where viewFrame finds each frame of the sheet', () => {
let frames = 0;
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
assert.ok(Math.abs(Math.hypot(...d) - 1) < 1e-12, 'unit');
const view = viewFrame(layout, d);
assert.equal(view.ring, ring, `${ring}/${index}`);
assert.equal(view.index, index, `${ring}/${index}`);
assert.equal(view.frame, layout.firsts[ring] + index);
// A frame on the centre plane is its own mirror image: either way
// draws it.
if (Math.abs(d[1]) > 1e-12) assert.equal(view.mirrored, mirrored);
}
frames++;
}
assert.equal(frames, AIRCRAFT_VIEWS.frames);
});
test('frameUp is a unit vector across the view, forward from straight above, and turns as the smallest rotation does', () => {
assert.ok(near(frameUp([0, 0, 1]), [1, 0, 0]), 'nose up the image');
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++)
for (const mirrored of [false, true]) {
const d = frameDirection(layout, ring, index, mirrored);
const up = frameUp(d);
const at = `${ring}/${index}${mirrored ? ' mirrored' : ''}`;
assert.ok(Math.abs(Math.hypot(...up) - 1) < 1e-9, `unit at ${at}`);
assert.ok(Math.abs(dot(up, d)) < 1e-9, `across the view at ${at}`);
assert.ok(
near(up, rotatedForward(d)),
`the smallest rotation at ${at}`,
);
// Mirroring the eye mirrors the image's up.
assert.ok(near(frameUp(mirror(d)), mirror(up)), `mirrored at ${at}`);
}
// On the horizon, abeam: the nose still points up the image.
assert.ok(near(frameUp([0, 1, 0]), [1, 0, 0]));
// Dead ahead on the horizon: the image's up is straight down the aircraft.
assert.ok(near(frameUp([1, 0, 0]), [0, 0, -1]));
});
test('viewUniforms packs the layout as the shader reads it', () => {
const { grid, rings } = viewUniforms(layout);
assert.deepEqual(grid, [64, 57, 7.5 * RAD, 17]);
// Two rings a vector: each ring's frames and its first frame.
assert.equal(rings.length, VIEW_RINGS_MAX / 2);
const pairs = [];
for (let k = 0; k < RINGS.length; k += 2)
pairs.push([RINGS[k], FIRSTS[k], RINGS[k + 1] ?? 1, FIRSTS[k + 1] ?? 0]);
assert.deepEqual(rings.slice(0, pairs.length), pairs);
for (const pair of rings.slice(pairs.length))
assert.deepEqual(pair, [1, 0, 1, 0], 'padding');
});
test('AIRCRAFT_VIEWS is consistent: a block a subject, every block on the sheet', () => {
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
assert.equal(
frames,
sheet.rings.reduce((a, b) => a + b, 0),
);
assert.equal(frames, 302);
assert.equal(sheet.cellPx * sheet.columns, 4096);
assert.equal(sheet.cellPx * sheet.rows, 3648);
assert.equal(sheet.grey, true, 'kept as grey and alpha');
const firsts = Object.values(subjects);
firsts.forEach((first, i) => {
assert.equal(first, i * frames, 'in order, one block after another');
assert.equal(first % frames, 0);
assert.ok(first + frames <= sheet.columns * sheet.rows, 'on the sheet');
});
assert.ok(Object.isFrozen(AIRCRAFT_VIEWS));
assert.ok(Object.isFrozen(sheet));
assert.ok(Object.isFrozen(sheet.rings));
assert.ok(Object.isFrozen(subjects));
});
const BAKE = new URL(
'../../scripts/build-aircraft-view-sheet.py',
import.meta.url,
);
const MANIFEST = new URL(
'../../public/sprites/aircraft-views.json',
import.meta.url,
);
test('the bake script lays the sheet out as AIRCRAFT_VIEWS says', () => {
const script = readFileSync(BAKE, 'utf8');
const constant = (name) => {
const match = new RegExp(`^${name} = (.+)$`, 'm').exec(script);
assert.ok(match, `${name} in the bake script`);
return JSON.parse(match[1]);
};
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
assert.equal(constant('RING_STEP_DEG'), sheet.ringStepDeg);
assert.deepEqual(constant('RINGS'), [...sheet.rings]);
assert.equal(constant('COLUMNS'), sheet.columns);
const list = /^SUBJECTS = \[([\s\S]*?)^\]/m.exec(script);
assert.ok(list, 'SUBJECTS in the bake script');
const names = [...list[1].matchAll(/^\s*\("(\w+)",/gm)].map((m) => m[1]);
assert.deepEqual(names, Object.keys(subjects), 'the same subjects in order');
// The script's rows: as many as its subjects' blocks take.
assert.equal(Math.ceil((names.length * frames) / sheet.columns), sheet.rows);
});
test(
'the baked manifest matches AIRCRAFT_VIEWS',
{ skip: !existsSync(MANIFEST) && 'no public/sprites/aircraft-views.json' },
() => {
const manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));
const { sheet, subjects } = AIRCRAFT_VIEWS;
assert.equal(manifest.cellPx, sheet.cellPx);
assert.equal(manifest.columns, sheet.columns);
assert.equal(manifest.rows, sheet.rows);
assert.equal(manifest.ringStepDeg, sheet.ringStepDeg);
assert.deepEqual(manifest.rings, [...sheet.rings]);
assert.equal(manifest.grey, true);
assert.equal(manifest.image, 'aircraft-views.webp');
assert.deepEqual(Object.keys(manifest.subjects), Object.keys(subjects));
for (const [name, first] of Object.entries(subjects))
assert.equal(manifest.subjects[name].first, first, name);
},
);
const SHEET = new URL(
'../../public/sprites/aircraft-views.webp',
import.meta.url,
);
test(
'the shipped sheet is the size the layout says, grey, and clear at every cell’s edge',
{ skip: !existsSync(SHEET) && 'no public/sprites/aircraft-views.webp' },
async () => {
const { default: sharp } = await import('sharp');
const { sheet, frames, subjects } = AIRCRAFT_VIEWS;
const { data, info } = await sharp(fileURLToPath(SHEET))
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
assert.equal(info.width, sheet.columns * sheet.cellPx);
assert.equal(info.height, sheet.rows * sheet.cellPx);
const at = (x, y) => (y * info.width + x) * 4;
// Grey: the renderer reads the red channel as the grey.
for (let i = 0; i < data.length; i += 4)
if (data[i] !== data[i + 1] || data[i] !== data[i + 2])
assert.fail(`not grey at pixel ${i / 4}`);
// Each used cell keeps its outer 2 px transparent (the mipmaps).
const used = Object.keys(subjects).length * frames;
const c = sheet.cellPx;
for (let n = 0; n < used; n++) {
const left = (n % sheet.columns) * c;
const top = Math.floor(n / sheet.columns) * c;
for (let y = 0; y < c; y++)
for (let x = 0; x < c; x++) {
if (x >= 2 && y >= 2 && x < c - 2 && y < c - 2) continue;
if (data[at(left + x, top + y) + 3] !== 0)
assert.fail(`cell ${n}: alpha at its edge (${x}, ${y})`);
}
}
},
);
test('in the bake’s axes (nose −X, starboard +Y, up +Z) a frame has the same up and direction', () => {
// The bake turns forward by Blender's rotation_difference(UP, d), in its
// own axes, which are mirrored from [forward, right, up]: the smallest
// rotation is the same rotation in either.
const toBake = (v) => [-v[0], v[1], v[2]];
const minimal = (from, to, v) => {
const axis = cross(from, to);
const sin = Math.hypot(...axis);
const cos = dot(from, to);
if (sin < 1e-12) return v;
const k = axis.map((value) => value / sin);
const kxv = cross(k, v);
const kv = dot(k, v);
return v.map(
(value, i) => value * cos + kxv[i] * sin + k[i] * kv * (1 - cos),
);
};
for (let ring = 0; ring < layout.rings.length; ring++)
for (let index = 0; index < layout.rings[ring]; index++) {
const d = frameDirection(layout, ring, index);
const bakeUp = minimal([0, 0, 1], toBake(d), toBake([1, 0, 0]));
assert.ok(near(toBake(frameUp(d)), bakeUp), `${ring}/${index}`);
}
});
/** A blend's weight by frame (a frame listed twice counts once, summed). */
+2 -1
View File
@@ -21,11 +21,12 @@ const PIN_TURN_DEG = 0.1;
* the grounded floor: a floor-pinned row holds a CPU position, so it is not
* planned, and settling a grounded contact puts it straight onto the floor.
*/
export function createIcons({ flightState, services, parts }) {
export function createIcons({ flightState, services, parts, resolveAsset }) {
const icons = createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'flights',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+9 -1
View File
@@ -948,7 +948,12 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
return parts.icons._fleetLook(flightState._trackedIcao);
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
}
/**
@@ -1130,6 +1135,9 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up.
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+34 -15
View File
@@ -1,5 +1,9 @@
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import {
aircraftViewRef,
registerAircraftViews,
} from '../../data/aircraftViews.js';
import { rotorFrame } from '../../data/rotorFrames.js';
import { KNOT_MPS } from '../../data/units.js';
import {
@@ -13,6 +17,7 @@ import {
findCamera,
findFrame,
findQuery,
rendererOf,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
@@ -148,6 +153,9 @@ export function createLocalAdsbLayer({
* @type {{markers: object, rings: object}|null}
*/
let sets = null;
/** Whether the renderer draws markers from the aircraft view sheet
* (`aircraftViews.js`), set at `init`. */
let views = false;
let enabled = false;
let unsubscribe = null;
let unsubscribeFeeds = null;
@@ -355,31 +363,36 @@ export function createLocalAdsbLayer({
/**
* A marker's icon, where and how it now draws: a helicopter's rotor frame
* at `at` (still on the ground), an airport vehicle in its own tint, a
* ground station's mast upright.
* ground station's mast upright. On a renderer that draws view sheets, a
* kind with rendered views is drawn from the sheet along its course;
* every other marker is its flat glyph turned on screen.
*/
function markerItem(marker, basis, at) {
const kind = marker.iconKind ?? 'airliner';
const frame =
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined;
const view = views ? aircraftViewRef(kind, frame) : null;
return {
id: marker.id,
pos: marker.position,
image: aircraftIcon(
kind,
undefined,
kind === 'helicopter'
? rotorFrame(marker.id, at, {
onGround: marker.onGround,
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
? marker.record.groundSpeedKt * KNOT_MPS
: null,
})
: undefined,
),
image: view ?? aircraftIcon(kind, undefined, frame),
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
scale: marker.iconScale ?? 1,
color: kind === 'vehicle' ? vehicleColor : color,
scaleByDistance: MARKER_SPRITE.scaleByDistance,
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
...(view
? { rotationMode: 'course', course: marker.courseDeg ?? 0 }
: {
rotationMode: 'screen',
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
}),
// The 3D model, once loaded and placed, is the visual instead.
show: !marker.modelOwnsVisual,
disableDepthTest: Number.POSITIVE_INFINITY,
@@ -773,6 +786,11 @@ export function createLocalAdsbLayer({
init(nextViewer) {
viewer = nextViewer;
const draw = drawOf(viewer);
views = registerAircraftViews(
draw,
rendererOf(viewer)?.capabilities ?? null,
resolveAsset,
);
const prefix = `${LAYER_ID}:${++instances}`;
sets = {
markers: draw.icons({
@@ -872,6 +890,7 @@ export function createLocalAdsbLayer({
models = null;
if (sets) for (const set of Object.values(sets)) set.dispose();
sets = null;
views = false;
viewer = null;
void receiver.destroy?.();
},
+58
View File
@@ -223,6 +223,7 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) {
feeds,
services: { ...services, ...options.services },
now: () => clock.now,
...(options.resolveAsset ? { resolveAsset: options.resolveAsset } : {}),
});
layer.init(viewer);
await layer.enable();
@@ -319,6 +320,63 @@ test('local aircraft use their class silhouette at one size in magenta', async (
assert.equal(detectable.type, 'AIR');
});
test('on a renderer that draws view sheets, local aircraft draw their view along their track; vehicles and masts stay flat', async (t) => {
const { aircraftViewRef } = await import('../../data/aircraftViews.js');
const { AIRCRAFT_VIEWS } = await import('../../data/viewSheet.js');
const viewer = { scene: {} };
const camera = fakeCameraPort({
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const { draw } = bindFakeDraw(viewer, {
camera: camera.port,
query: { drillPick: () => [] },
capabilities: new Set(['viewSheets']),
});
fakeInput(viewer);
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer } = await enabledLayer(receiver, clock, null, {
viewer: { draw, viewer },
resolveAsset: (url) => `/gev${url}`,
});
t.after(() => layer.destroy());
// Registered once, at the layer's own asset URL.
assert.deepEqual(draw.viewSheets, [
[
AIRCRAFT_VIEWS.id,
{ ...AIRCRAFT_VIEWS.sheet, image: '/gev/sprites/aircraft-views.webp' },
],
]);
receiver.set({
aircraft: [
record({ trackDeg: 0 }),
record({ icao: 'a0b702', category: 'A7' }),
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
],
});
await layer.update();
const icon = iconOf(draw, 'local-adsb:abc123');
assert.equal(icon.image, aircraftViewRef('airliner'));
assert.equal(icon.rotationMode, 'course');
assert.equal(icon.course, 0);
assert.equal('rotation' in icon, false);
assert.deepEqual(icon.size, [20, 20]);
assert.deepEqual(icon.color, MAGENTA);
assert.equal(
iconOf(draw, 'local-adsb:a0b702').image,
aircraftViewRef('helicopter', rotorFrame('local-adsb:a0b702', clock.now)),
'the rotor turns through the sheet',
);
const vehicle = iconOf(draw, 'local-adsb:a0c001');
assert.equal(vehicle.image, aircraftIcon('vehicle'));
assert.equal(vehicle.rotationMode, 'screen');
const mast = iconOf(draw, 'local-adsb:a0c003');
assert.equal(mast.image, aircraftIcon('station'));
assert.equal(mast.rotationMode, 'screen');
assert.equal(mast.rotation, 0);
});
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
+2 -1
View File
@@ -8,11 +8,12 @@ import {
} from './policy.js';
/** The military layer's contacts as one icon set (`createAircraftIcons`). */
export function createIcons({ flightState, services, parts }) {
export function createIcons({ flightState, services, parts, resolveAsset }) {
return createAircraftIcons({
state: flightState,
services,
parts,
resolveAsset,
layerId: 'military',
displayDelay: flightState._displayDelay,
followsClock: () => followsClock(flightState),
+9 -1
View File
@@ -396,7 +396,12 @@ export function createTracking({
/** The tracked billboard's images, from the current class/conversion: the
* fleet icon's own (`_fleetLook`), so selecting it changes only its colour. */
function _trackedBillboardLook() {
return parts.icons._fleetLook(flightState._trackedIcao);
// Drawn along its course, as the fleet icon is: from the view sheet
// where the renderer draws one.
const id = flightState._trackedIcao;
return parts.icons._fleetLook(id, undefined, undefined, {
alongCourse: true,
});
}
/**
@@ -1087,6 +1092,9 @@ export function createTracking({
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the tracked model is actually up (ready + shown).
color: _trackedIconColor,
// The course a view-sheet image is drawn along (the same display
// course the screen rotation below is projected from).
course: () => parts.motion._trackedDisplayCourse(),
// Screen-projected rotation, evaluated per frame on the camera's own
// axes, so it stays exact through a tracked orbit. The tracked target
// must never vanish into tile geometry — tracking a taxiing plane at
+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',
+2
View File
@@ -207,6 +207,8 @@ export type Capability =
| 'fields'
/** Rate-limited course easing (`IconItem.courseGlide`). */
| 'courseGlide'
/** Icons drawn from a sheet of views, by where the eye is (`ViewSheet`). */
| 'viewSheets'
/** Lines that fade with the age of their points (`LineItem.ageFade`). */
| 'lineAgeFade'
/** Lines drawn only within a span of the scene clock (`LineAgeFade.showMs`). */
+47 -1
View File
@@ -154,10 +154,48 @@ export interface Placed {
disableDepthTest?: number;
}
/** An image an icon draws: a URL, a slot in a shared atlas, or generated. */
/**
* `viewSheets`: one image of small sprites that show subjects from a sphere
* of directions, registered with `DrawPort.views`. An icon whose image is a
* view (`{views, first}`) lies flat on the ground, forward along its course,
* and is drawn as the sprite that shows it from where the eye is.
*
* The image is a grid of square cells, `cellPx` a side, `columns` across and
* `rows` down. A subject is a block of consecutive cells, row-major from its
* `first`: rings of frames `ringStepDeg` apart, from straight above (ring 0,
* one frame) downward, short of straight below; ring `k` holds `rings[k]`
* frames, from the eye dead ahead of the subject, round its right side, to
* dead astern. The eye on its left side draws the right side's frame
* mirrored. A frame's up is the subject's forward, turned by the smallest
* rotation that takes its up onto the frame's direction. The frame nearest
* the eye's direction is drawn, as a card square to its own direction, so
* between frames it is tilted as its subject is (`data/viewSheet.js` holds
* the maths).
*/
export interface ViewSheet {
/** The sheet's URL. */
image: string;
cellPx: number;
columns: number;
rows: number;
ringStepDeg: number;
/** Frames in each ring; the first is 1. At most 18 rings. */
rings: readonly number[];
/**
* The sheet's pixels are grey (red, green and blue equal): a renderer may
* keep it as one channel and alpha.
*/
grey?: boolean;
}
/**
* An image an icon draws: a URL, a slot in a shared atlas, generated, or
* (`viewSheets`, icons only) a subject of a view sheet by its first cell.
*/
export type ImageRef =
| string
| { atlas: string; slot: string }
| { views: string; first: number; fallback?: ImageRef }
| { svg: string }
| { blob: Blob }
| { canvas: HTMLCanvasElement | OffscreenCanvas; key: string };
@@ -211,6 +249,12 @@ export interface CourseGlide {
}
export interface IconItem extends Placed {
/**
* A view (`{views, first}`) needs `rotationMode: 'course'` and takes no
* `imageLod`; a set draws views from one sheet. Until its sheet is
* registered and loaded, and if that cannot load, it draws its `fallback`
* (any image but a view) along its course, or nothing without one.
*/
image: ImageRef;
/** Drawn size in CSS pixels. */
size: [width: number, height: number];
@@ -752,4 +796,6 @@ export interface DrawPort {
on(event: 'clampState', cb: (state: 'draped' | 'overlay') => void): Off;
/** Register an atlas of images icons refer to by slot. */
atlas(id: string, images: Record<string, ImageRef>): void;
/** `viewSheets`: register a sheet of views icons refer to by id. */
views?(id: string, sheet: ViewSheet): void;
}
+2
View File
@@ -41,6 +41,7 @@ export const CAPABILITIES = Object.freeze([
'meshes',
'fields',
'courseGlide',
'viewSheets',
'lineAgeFade',
'lineTimeWindow',
'lineBreaks',
@@ -174,6 +175,7 @@ export const PORTS = deepFreeze({
['quads', 'quads'],
['meshes', 'meshes'],
['field', 'fields'],
['views', 'viewSheets'],
]),
camera: Object.fromEntries([
...required(
+6
View File
@@ -23,6 +23,7 @@ import {
} from '../recession.js';
import { CLEAR_WEATHER, mergeWeather } from '../weather.js';
import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js';
import { viewLayout } from '../../data/viewSheet.js';
import { createStubCamera } from './camera.js';
import { motionPosition } from '../motion/iconMotion.js';
import { computeViewRectangle } from './viewRectangle.js';
@@ -704,6 +705,11 @@ export function createStubRenderer(options = {}) {
};
},
};
if (capabilities.has('viewSheets'))
draw.views = (id, sheet) => {
viewLayout(sheet); // refused as a renderer refuses it
log('draw', 'views', [id]);
};
if (capabilities.has('models'))
draw.models = (spec) => makeSet('models', spec);
if (capabilities.has('quads')) draw.quads = (spec) => makeSet('quads', spec);
+7
View File
@@ -8,6 +8,8 @@ import { bindRenderer } from '../render/rendererOf.js';
export function fakeDrawPort() {
const sets = new Map();
// Every `views(id, sheet)` call, in order.
const viewSheets = [];
const make = (kind) => (spec) => {
const live = sets.get(spec.id);
if (live && !live.disposed)
@@ -97,6 +99,11 @@ export function fakeDrawPort() {
clampState: () => 'draped',
on: () => () => {},
atlas() {},
/** The `views(id, sheet)` registrations, in order, as `[id, sheet]`. */
viewSheets,
views(id, sheet) {
viewSheets.push([id, sheet]);
},
};
}