Compare commits

..
Author SHA1 Message Date
Sameh Khamis dbd6ee7aee Add the changelog entry for the base map through the globe port 2026-11-16 16:15:48 -08:00
Sameh Khamis 690314b399 Base map through the globe port
Cesium switches the map stacks through its globe port, as any renderer
does, rather than through a map engine of its own. Every route keeps its
behaviour:

- Google 3D turned off is kept hidden, and shown again without loading it
  anew; the key route's tiles take clamped marks, as the token routes' do.
- Esri goes to its deepest level (23); its "Map data not yet available"
  picture is a missing tile, so the parent's imagery stays.
- Cesium ion's world imagery is Bing over HTTPS on any page, with ion's
  credits; a token ion refuses refuses the switch, as before.
- Keyless terrain that does not answer is the flat ellipsoid, tried again
  behind it; world terrain asks ion first, as before.
- window.__godsEyeView.tileset is the Cesium photoreal tileset.
2026-11-16 15:58:45 -08:00
52 changed files with 624 additions and 3254 deletions

No files matched your search

-4
View File
@@ -1,4 +0,0 @@
- Preview what Context's card shows: a flight's photo, its route on a small
globe, its fleet model turning and the view from its cockpit; a vessel's
photo; and the ground beneath a satellite, with its altitude and speed
graphed (manjunath22466, samehkhamis, #1774).
+5
View File
@@ -0,0 +1,5 @@
- Switch the base map through the globe port on Cesium as well: Google 3D
turned off is kept and shown again without reloading, Esri reaches its
deepest level with the parent's imagery where it has none, and keyless
terrain that does not answer falls back to the flat ellipsoid (Sameh
Khamis, @samehkhamis, #1775).
+29 -31
View File
@@ -933,19 +933,6 @@ come through the regional brief service; earthquakes, tropical storms and
fire perimeters come from the same feeds as their layers, cached for five
minutes; satellite fire hits only while the FIRMS layer is on.
The card's top tile previews what is picked. A flight shows its
Planespotters photo once the flights layer has looked one up for the plane
it tracks, its route on a small globe (origin to destination, flown part
solid, the plane on it), its fleet model turning with callouts of what can
be worked out about the flight, and the view ahead from its cockpit with
speed and altitude tapes; the model and the cockpit view take turns. A
vessel shows its Open Vessel Photos photo, a satellite the ground beneath it
from Esri World Imagery with its altitude and speed graphed. The globe, model
and cockpit view are drawn by the renderer through its `cardPreviews`
application hook (`src/render/cesium/cardPreviews.js`), each in a small scene
of its own that frees its graphics context as it closes; the model comes from
the fleet set loaded at startup, so opening a card fetches no model.
## Wikidata cities pack — November 15, 2026
`src/data/local_data/wikidata_cities/cities.json` bundles 31,827 settlements of
@@ -8986,24 +8973,35 @@ request HTTPS tiles even on HTTP localhost, with the existing Content Security
Policy unchanged. Ion attribution and Bing's per-tile credits are preserved;
other ion imagery assets continue through the SDK's standard ion factory.
The imagery, terrain and 3D factories are the Cesium renderer's
(`src/render/cesium/mapImagery.js`, `mapTerrain.js`, `google3d.js`; the
package exports `./maps/imagery`, `./maps/terrain` and `./maps/3d` point
there). The catalog, the default registry and the controller are
Cesium-free: they reach those factories, and the scene operations a
switch makes (imagery layers, terrain, the globe's visibility, tilesets),
through the scene's map engine (`mapEngineFor` in `src/maps/engine.js`). The
Cesium plugin hands the application its own engine with each renderer it makes
(`src/render/cesium/mapEngine.js`, through `src/render/applicationHooks.js`),
and the application scene loads the photoreal base through it too. A renderer
whose plugin hands none switches through its globe port
(`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, ion's world
imagery as `world` imagery, photoreal as the port's photoreal base (turned off
while hidden, on again when shown), and world terrain, or without a key
Re:Earth's keyless terrain as `quantizedMesh` terrain at its URL
(`src/maps/keylessTerrain.js`), as the Cesium engine draws it; a renderer
without the `terrain` capability keeps the ellipsoid. A viewer with no renderer bound gets the Cesium engine, with the
other unbound ports, from the package's `./render/cesium/unbound` export.
The catalog, the default registry and the controller are Cesium-free: they
reach the map sources, and the scene operations a switch makes (imagery
layers, terrain, the globe's visibility, the photoreal base), through the
scene's map engine (`mapEngineFor` in `src/maps/engine.js`). Every renderer,
Cesium included, switches through its globe port (`src/maps/globeEngine.js`),
unless its plugin hands the application a map engine of its own
(`src/render/applicationHooks.js`):
- Esri World Imagery as `xyz` imagery to its deepest level (23); Esri's "Map
data not yet available" picture is answered as a missing tile, so the
parent's imagery stays, and a refused tile counts toward the fallback to
OSM. OSM as `xyz` imagery to level 19.
- Cesium ion's world imagery as `world` imagery; on Cesium that is Bing
through ion, its tiles over HTTPS on any page, with ion's credits
(`src/render/cesium/mapImagery.js`).
- Photoreal as the port's photoreal base, by the same routes as ever (the
Google key, else Google's session tokens, else the ion copy;
`src/render/cesium/google3d.js`). Turned off, Cesium's globe port keeps the
tileset hidden, and the same spec shows it again without loading it anew.
`window.__godsEyeView.tileset` is that Cesium tileset, shown or hidden.
- World terrain through ion, or without an ion token Re:Earth's keyless
terrain as `quantizedMesh` terrain at its URL (`src/maps/keylessTerrain.js`);
while the keyless terrain does not answer, the ellipsoid stands in and the
map stack tries it again behind it. A renderer without the `terrain`
capability keeps the ellipsoid.
A viewer with no renderer bound gets the Cesium engine
(`src/render/cesium/mapEngine.js`), with the other unbound ports, from the
package's `./render/cesium/unbound` export.
The controller accepts other source registries without adding provider branches.
Each instance caches source construction, ignores superseded scene changes and
+1 -1
View File
@@ -26,7 +26,7 @@
with the sources: src/materialSymbolsSubset.test.mjs fails when a source
names a glyph this list is missing, because a missing glyph does not draw
a box — the ligature never forms and the element renders the literal word. -->
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20,400,0,0&icon_names=add,adjust,ads_click,air,airline_seat_recline_normal,align_horizontal_left,align_horizontal_right,arrow_drop_down,arrow_forward,arrow_left,arrow_right,bolt,bug_report,category,chevron_left,chevron_right,close,close_fullscreen,cloud,cyclone,dark_mode,delete,directions_boat,draw,earthquake,east,eco,egg_alt,emergency_home,factory,filter_list,flare,flight,foggy,handyman,history,label,layers,layers_clear,light_mode,local_fire_department,location_city,location_off,location_on,more_horiz,movie,my_location,navigation,newspaper,normal,on,open_in_full,palette,partly_cloudy_day,pause,pedal_bike,pentagon,pest_control,pets,photo_camera,play_arrow,public,question_mark,radar,radio,radio_button_checked,radio_button_unchecked,rainy,raven,restart_alt,right_panel_close,right_panel_open,rocket_launch,satellite_alt,schedule,search,set_meal,settings,skip_next,skip_previous,star,streetview,sunny,thunderstorm,timeline,traffic,train,travel_explore,tune,umbrella,upload_file,videocam,view_in_ar,visibility,visibility_off,warning,water_drop,weather_snowy,zoom_in_map" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20,400,0,0&icon_names=add,adjust,ads_click,air,airline_seat_recline_normal,align_horizontal_left,align_horizontal_right,arrow_drop_down,arrow_forward,arrow_left,arrow_right,bolt,bug_report,category,chevron_left,chevron_right,close,close_fullscreen,cloud,cyclone,dark_mode,delete,directions_boat,draw,earthquake,east,eco,egg_alt,emergency_home,factory,filter_list,flare,flight,foggy,handyman,history,label,layers,layers_clear,light_mode,local_fire_department,location_city,location_off,location_on,more_horiz,movie,my_location,navigation,newspaper,normal,on,open_in_full,palette,partly_cloudy_day,pause,pedal_bike,pentagon,pest_control,pets,play_arrow,public,question_mark,radar,radio,radio_button_checked,radio_button_unchecked,rainy,raven,restart_alt,right_panel_close,right_panel_open,rocket_launch,satellite_alt,schedule,search,set_meal,settings,skip_next,skip_previous,star,streetview,sunny,thunderstorm,timeline,traffic,train,travel_explore,tune,umbrella,upload_file,videocam,view_in_ar,visibility,visibility_off,warning,water_drop,weather_snowy,zoom_in_map" rel="stylesheet" />
</head>
<body>
<div class="gev-view" data-gev-view="scene-chrome"></div>
+32 -20
View File
@@ -276,16 +276,7 @@
"src/ui/views/panels/EntityCard.vue",
"src/data/aircraftEmergency.js",
"src/data/aircraftClass.js",
"src/data/entityRecords.js",
"src/ui/views/panels/RouteGlobe.vue",
"src/maps/attribution.js",
"src/ui/views/panels/FlightCockpitView.vue",
"src/ui/views/panels/PreviewHud.vue",
"src/data/fleetTrailAnchors.js",
"src/ui/views/panels/SatelliteGroundView.vue",
"src/data/vesselTypes.js",
"src/data/fleetModels.js",
"src/ui/views/panels/AircraftModelHero.vue"
"src/data/entityRecords.js"
],
"external": ["vue", "pinia", "vue-i18n"]
},
@@ -1645,8 +1636,7 @@
"src/ui/stores/entityCard.js",
"src/ui/entityContextBridge.js",
"src/data/trackingClickGesture.js",
"src/ui/stores/sceneSharing.js",
"src/maps/attribution.js"
"src/ui/stores/sceneSharing.js"
],
"external": [
"cesium",
@@ -2432,8 +2422,7 @@
"src/render/vectorBase/paint.js",
"src/layers/wind/streamlines.js",
"src/layers/wind/model.js",
"src/sky/assets.js",
"src/render/cesium/cardPreviews.js"
"src/sky/assets.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile", "kdbush"]
},
@@ -2582,8 +2571,7 @@
"src/render/applicationHooks.js",
"src/maps/globeEngine.js",
"src/maps/engine.js",
"src/maps/keylessTerrain.js",
"src/maps/attribution.js"
"src/maps/keylessTerrain.js"
],
"external": ["cesium"]
},
@@ -5228,13 +5216,37 @@
"src/library/entries/wri-global-power-plants.json",
"src/library/entries/wv-statewide-imagery.json",
"src/library/formats.js",
"src/library/entries/gvp-holocene-volcanoes.json",
"src/library/entries/nasa-black-marble.json",
"src/library/entries/nasa-eonet-events.json",
"src/library/catalog.js",
"src/library/source.js",
"src/library/layers.js",
"src/library/controller.js",
"src/library/extent.js",
"src/library/camera.js",
"src/library/entries/imf-portwatch-disruptions.json",
"src/library/entries/imf-portwatch-chokepoints.json",
"src/library/entries/noaa-tide-stations.json",
"src/library/entries/nws-active-alerts.json",
"src/library/entries/wri-global-power-plants.json",
"src/library/entries/fema-usa-structures.json",
"src/library/entries/epc-england-wales.json",
"src/library/parquet.js",
"src/library/entries/bkg-topplus-open.json",
"src/library/entries/epa-superfund-sites.json",
"src/library/entries/epa-toxic-release-facilities.json",
"src/library/entries/gbif-occurrence-density.json",
"src/library/entries/gdacs-disaster-alerts.json",
"src/library/entries/gsi-japan-map.json",
"src/library/entries/ign-orthophotos-france.json",
"src/library/entries/gsi-japan-photo.json",
"src/library/entries/jrc-surface-water.json",
"src/library/entries/ntad-national-bridges.json",
"src/library/entries/usgs-hydrography.json",
"src/library/entries/macrostrat-geology.json",
"src/library/entries/swisstopo-swissimage.json",
"src/library/entries/usgs-topo.json",
"src/library/outlines.js",
"src/library/relief.js",
"src/sceneCommandRelease.js",
@@ -5432,8 +5444,7 @@
"src/ui/stores/omnibar.js",
"src/data/entityContext.js",
"src/ui/stores/entityCard.js",
"src/ui/entityContextBridge.js",
"src/render/cesium/cardPreviews.js"
"src/ui/entityContextBridge.js"
],
"external": [
"hls.js",
@@ -6202,6 +6213,8 @@
"src/layers/osmPlaces/index.js",
"src/app/layers/osmPlaces.js",
"src/layers/awareness/rangeRing.js",
"src/data/feedState.js",
"src/loadingFeedback.js",
"src/data/firmsIntensity.js",
"src/data/firmsHeatRaster.js",
"src/layers/firms/heatImagery.js",
@@ -6259,8 +6272,7 @@
"src/layers/flights/placed.js",
"src/data/placementProvider.js",
"src/data/courseFromFixes.js",
"src/time/frameWait.js",
"src/maps/attribution.js"
"src/time/frameWait.js"
],
"external": [
"hls.js",
+21 -18
View File
@@ -284,24 +284,27 @@ export function createApplicationTools({
// loop burning behind a hidden tab. (perf wave 2 fix)
syncVisibilitySuspension();
window.__godsEyeView = {
viewer,
styleManager,
tileset,
dataManager,
sceneDirector,
mapStackController,
annotations,
weatherEffects,
cockpitCloudEffects,
getRenderGovernorDiagnostics,
surfaceServices: operations.surface,
requestRender: governorRequestRender,
entityRecords: { read: readEntityRecord, write: entityRecord },
// What the renderer's plugin lets QA scripts read (the Cesium viewer,
// for the default renderer), in place of the scene object above.
...scene.qaHandles,
};
window.__godsEyeView = Object.defineProperties(
{
viewer,
styleManager,
tileset,
dataManager,
sceneDirector,
mapStackController,
annotations,
weatherEffects,
cockpitCloudEffects,
getRenderGovernorDiagnostics,
surfaceServices: operations.surface,
requestRender: governorRequestRender,
entityRecords: { read: readEntityRecord, write: entityRecord },
},
// What the renderer's plugin lets QA scripts read (the Cesium viewer and
// its photoreal tileset, for the default renderer), in place of the
// scene's objects above; read as they are when asked.
Object.getOwnPropertyDescriptors(scene.qaHandles ?? {}),
);
const debug = window.__godsEyeView;
defer(() => {
if (window.__godsEyeView === debug) delete window.__godsEyeView;
-40
View File
@@ -949,36 +949,6 @@ export function aircraftInsights(record, { nowMs = Date.now() } = {}) {
return out;
}
/**
* The item's photo, once its layer has looked one up: the tracked airliner's
* Planespotters photo, or the selected vessel's Open Vessel Photos photo.
* @returns {{src: string, link: string, photographer: string,
* licence: string}|null}
*/
function cardPhoto(dataManager, layerId, record) {
let photo = null;
try {
const layer = dataManager?.layers?.get?.(layerId)?.module;
if (layerId === 'ais-live-vessels')
photo = layer?.getVesselPhoto?.(text(record?.vesselId));
else if (layerId === 'flights') {
// Looked up only for the plane the layer tracks.
const tracked = layer?.getTrackedSubject?.();
if (tracked && text(tracked.id) === text(record?.icao24))
photo = tracked.photo;
}
} catch {
photo = null;
}
if (!text(photo?.src)) return null;
return {
src: text(photo.src),
link: text(photo.link),
photographer: text(photo.photographer),
licence: text(photo.licence),
};
}
export function describeEntity(
dataManager,
identity,
@@ -1054,16 +1024,6 @@ export function describeEntity(
warningWords: warnings.map((entry) => entry.words),
// For the aircraft card's model and route line.
aircraftClass,
// What picks the fleet model the globe draws this aircraft with.
aircraftModel:
kind.kind === 'aircraft' && record
? {
typeCode: text(record.typeCode ?? record.type) || null,
category: record.category ?? null,
callsign: text(record.callsign) || null,
}
: null,
photo: cardPhoto(dataManager, layerId, record),
// Its class's English name, for the UI to translate; null when unknown.
aircraftClassName: AIRCRAFT_CLASS_LABELS[aircraftClass] || null,
insights:
+38 -287
View File
@@ -37,20 +37,8 @@ const flights = Array.from({ length: 2500 }, (_, i) => ({
altitudeM: 10000,
}));
const dams = [
{
id: 'Grand Coulee Dam',
name: 'Grand Coulee Dam',
lat: 47.957,
lon: -118.981,
operator: 'Bureau of Reclamation',
},
{
id: '123456',
name: null,
lat: 47.9,
lon: -118.9,
operator: 'Some Utility',
},
{ id: 'Grand Coulee Dam', name: 'Grand Coulee Dam', lat: 47.957, lon: -118.981, operator: 'Bureau of Reclamation' },
{ id: '123456', name: null, lat: 47.9, lon: -118.9, operator: 'Some Utility' },
];
const dm = manager({
flights: { name: 'Live Flights', records: flights },
@@ -58,12 +46,7 @@ const dm = manager({
});
test('a click identity finds its record by key, past the first 2000 records', () => {
const record = findRecord(dm, {
layerId: 'flights',
id: 'a02400',
lat: 0,
lon: 0,
});
const record = findRecord(dm, { layerId: 'flights', id: 'a02400', lat: 0, lon: 0 });
assert.equal(record?.callsign, 'FLT2400');
});
@@ -91,9 +74,7 @@ test('a transit click finds its vehicle by the layer key and reads its state', (
lon: -97.71,
});
assert.equal(card?.title, 'M634');
const facts = Object.fromEntries(
card.facts.map((fact) => [fact.label, fact.value]),
);
const facts = Object.fromEntries(card.facts.map((fact) => [fact.label, fact.value]));
assert.equal(facts.Operator, 'CapMetro');
assert.equal(facts.Status, 'Heading to next stop');
assert.equal(facts.Key, undefined, 'the layer key is not shown');
@@ -105,20 +86,8 @@ test('transit vehicles break down by motion, mode and reported state', () => {
transit: {
name: 'Transit',
records: [
{
id: '1',
mode: 'bus',
motion: 'moving',
status: 'IN_TRANSIT_TO',
...at,
},
{
id: '2',
mode: 'bus',
motion: 'stopped',
status: 'STOPPED_AT',
...at,
},
{ id: '1', mode: 'bus', motion: 'moving', status: 'IN_TRANSIT_TO', ...at },
{ id: '2', mode: 'bus', motion: 'stopped', status: 'STOPPED_AT', ...at },
{ id: '3', mode: 'rail', motion: 'moving', occupancy: 'FULL', ...at },
],
},
@@ -126,28 +95,15 @@ test('transit vehicles break down by motion, mode and reported state', () => {
const breakdown = layerBreakdown(buses, 'transit');
assert.equal(breakdown.total, 3);
const split = (title) =>
Object.fromEntries(
breakdown.splits
.find((item) => item.title === title)
.parts.map((part) => [part.label, part.count]),
);
Object.fromEntries(breakdown.splits.find((item) => item.title === title).parts.map((part) => [part.label, part.count]));
assert.deepEqual(split('Motion'), { Moving: 2, Stopped: 1 });
assert.deepEqual(split('Mode'), { Bus: 2, Rail: 1 });
assert.deepEqual(split('Last reported'), {
'Heading to next stop': 1,
'Stopped at a stop': 1,
});
assert.deepEqual(split('Last reported'), { 'Heading to next stop': 1, 'Stopped at a stop': 1 });
assert.deepEqual(split('Crowding'), { Full: 1 });
});
test('a moving item never borrows a nearby craft when its key is unknown', () => {
const record = findRecord(dm, {
layerId: 'flights',
id: 'zzzzzz',
label: 'NOPE',
lat: 34.0004,
lon: -118.05,
});
const record = findRecord(dm, { layerId: 'flights', id: 'zzzzzz', label: 'NOPE', lat: 34.0004, lon: -118.05 });
assert.equal(record, null);
});
@@ -159,19 +115,12 @@ test('a card lists facts with units and keeps the title out of them', () => {
const card = describeEntity(dm, { layerId: 'flights', id: 'a00001' });
assert.equal(card.title, 'FLT1');
assert.equal(card.kind, 'aircraft');
assert.ok(
card.facts.some(
(fact) => fact.label === 'Altitude' && fact.value === '32,808 ft',
),
);
assert.ok(card.facts.some((fact) => fact.label === 'Altitude' && fact.value === '32,808 ft'));
assert.ok(!card.facts.some((fact) => fact.value === 'FLT1'));
});
test('nearby lists the closest of the same kind and one of each other layer', () => {
const card = describeEntity(dm, {
layerId: 'local-dams',
id: 'Grand Coulee Dam',
});
const card = describeEntity(dm, { layerId: 'local-dams', id: 'Grand Coulee Dam' });
const { same, other } = nearbyEntities(dm, card, { radiusKm: 2000 });
assert.equal(same[0].title, 'Some Utility');
assert.equal(other.length, 1);
@@ -189,10 +138,7 @@ test('fact formatting follows the field suffix', () => {
assert.equal(formatFact('speedMps', 100).value, '194 kt');
// Orbital speeds read in km/s, road and rail in km/h.
assert.equal(formatFact('speedMps', 7670).value, '7.67 km/s');
assert.equal(
formatFact('speedMps', 10, { kind: 'vehicle' }).value,
'36 km/h',
);
assert.equal(formatFact('speedMps', 10, { kind: 'vehicle' }).value, '36 km/h');
// Units follow the field's suffix; feed codes and bare words read as words.
assert.equal(formatFact('containedPct', 96).value, '96%');
assert.equal(formatFact('windKt', 30).value, '30 kt');
@@ -202,54 +148,21 @@ test('fact formatting follows the field suffix', () => {
assert.equal(formatFact('icao24', 'abcdef').value, 'abcdef');
assert.equal(formatFact('shipType', 70).value, 'Cargo');
assert.equal(formatFact('shipType', 'Tanker').value, 'Tanker');
assert.equal(
formatFact('discoveredTime', Date.UTC(2026, 5, 29)).value,
'29 Jun 2026',
);
assert.equal(
formatFact('updatedTime', 1_700_000_000_000, { nowMs: 1_700_000_060_000 })
.age,
60_000,
);
assert.equal(formatFact('discoveredTime', Date.UTC(2026, 5, 29)).value, '29 Jun 2026');
assert.equal(formatFact('updatedTime', 1_700_000_000_000, { nowMs: 1_700_000_060_000 }).age, 60_000);
assert.equal(formatFact('altitudeM', 420000).value, '420 km');
assert.equal(formatFact('confidence', 0.82).value, '82%');
assert.equal(formatFact('onGround', false), null);
assert.equal(
formatFact('lastContactAtMs', 1_700_000_000_000, {
nowMs: 1_700_000_060_000,
}).age,
60_000,
);
assert.equal(formatFact('lastContactAtMs', 1_700_000_000_000, { nowMs: 1_700_000_060_000 }).age, 60_000);
});
test('warnings lead with an emergency, then the squawk code, and stay out of the facts', () => {
assert.deepEqual(
recordWarnings({ emergency: true, emergencyKind: 'medical' }),
['Emergency: medical'],
);
assert.deepEqual(recordWarnings({ squawk: '7600' }), [
'Radio failure (squawk 7600)',
]);
assert.deepEqual(
recordWarnings({ squawk: '1200', emergencyKind: 'none' }),
[],
);
assert.deepEqual(recordWarnings({ emergency: true, emergencyKind: 'medical' }), ['Emergency: medical']);
assert.deepEqual(recordWarnings({ squawk: '7600' }), ['Radio failure (squawk 7600)']);
assert.deepEqual(recordWarnings({ squawk: '1200', emergencyKind: 'none' }), []);
assert.deepEqual(recordWarnings({ tsunami: 1 }), ['Tsunami warning issued']);
const urgent = manager({
flights: {
name: 'Live Flights',
records: [
{
id: 'X1',
icao24: 'x00001',
callsign: 'X1',
lat: 1,
lon: 1,
emergency: true,
emergencyKind: 'fuel',
},
],
},
flights: { name: 'Live Flights', records: [{ id: 'X1', icao24: 'x00001', callsign: 'X1', lat: 1, lon: 1, emergency: true, emergencyKind: 'fuel' }] },
});
const card = describeEntity(urgent, { layerId: 'flights', id: 'x00001' });
assert.deepEqual(card.warnings, ['Emergency: fuel']);
@@ -271,13 +184,7 @@ test('the view summary counts each layer inside the view, closest to the middle
test('flight insights work out phase, flight level, Mach, squawk meaning and signal age', () => {
const insights = aircraftInsights(
{
altitudeM: 10668,
verticalRateMps: 0,
speedMps: 230,
squawk: '7000',
lastContactAtMs: 1_000_000,
},
{ altitudeM: 10668, verticalRateMps: 0, speedMps: 230, squawk: '7000', lastContactAtMs: 1_000_000 },
{ nowMs: 1_012_000 },
);
const value = (label) => insights.find((item) => item.label === label)?.value;
@@ -285,57 +192,20 @@ test('flight insights work out phase, flight level, Mach, squawk meaning and sig
assert.equal(value('Flight level'), 'FL350');
assert.equal(value('Mach'), 'M 0.78');
assert.equal(value('Squawk {code}'), 'VFR conspicuity');
assert.deepEqual(
insights.find((item) => item.label === 'Squawk {code}').labelValues,
{ code: '7000' },
);
assert.deepEqual(insights.find((item) => item.label === 'Squawk {code}').labelValues, { code: '7000' });
assert.equal(value('Signal'), '12 s ago');
assert.equal(aircraftInsights({ onGround: true })[0].value, 'On the ground');
assert.match(
aircraftInsights({ verticalRateMps: -8 })[0].value,
/^Descending 1600 ft\/min$/,
);
assert.match(aircraftInsights({ verticalRateMps: -8 })[0].value, /^Descending 1600 ft\/min$/);
});
test('a layer breakdown splits aircraft by status and type, inside a view when given', () => {
const craft = [
{
id: 'A',
lat: 10,
lon: 10,
onGround: false,
military: false,
aircraftClass: 'airliner',
},
{
id: 'B',
lat: 10,
lon: 11,
onGround: false,
military: true,
aircraftClass: 'fastjet',
},
{
id: 'C',
lat: 10,
lon: 12,
onGround: true,
military: true,
aircraftClass: 'airliner',
},
{
id: 'D',
lat: 60,
lon: 12,
onGround: false,
military: false,
aircraftClass: 'airliner',
},
{ id: 'A', lat: 10, lon: 10, onGround: false, military: false, aircraftClass: 'airliner' },
{ id: 'B', lat: 10, lon: 11, onGround: false, military: true, aircraftClass: 'fastjet' },
{ id: 'C', lat: 10, lon: 12, onGround: true, military: true, aircraftClass: 'airliner' },
{ id: 'D', lat: 60, lon: 12, onGround: false, military: false, aircraftClass: 'airliner' },
];
const data = manager({
flights: { name: 'Live Flights', records: craft },
'local-dams': { name: 'Dams', records: dams },
});
const data = manager({ flights: { name: 'Live Flights', records: craft }, 'local-dams': { name: 'Dams', records: dams } });
const all = layerBreakdown(data, 'flights');
assert.equal(all.total, 4);
assert.deepEqual(all.splits[0].parts, [
@@ -347,52 +217,23 @@ test('a layer breakdown splits aircraft by status and type, inside a view when g
{ label: 'Airliners', count: 3 },
{ label: 'Fast jets', count: 1 },
]);
const near = layerBreakdown(data, 'flights', {
rect: { west: 9, east: 13, south: 9, north: 11 },
});
const near = layerBreakdown(data, 'flights', { rect: { west: 9, east: 13, south: 9, north: 11 } });
assert.equal(near.total, 3);
assert.equal(layerBreakdown(data, 'local-dams'), null);
});
test('a moving item with an unknown key is not matched to a craft right beside it', () => {
// About 110 m from FLT0: well inside any nearest-item reach.
assert.equal(
findRecord(dm, {
layerId: 'flights',
id: 'zzzzzz',
label: 'NOPE',
lat: 34.001,
lon: -118,
}),
null,
);
assert.equal(findRecord(dm, { layerId: 'flights', id: 'zzzzzz', label: 'NOPE', lat: 34.001, lon: -118 }), null);
});
test('sites that share a key are told apart by where the identity says they are', () => {
const sites = [
{
id: 'Amazon Web Services',
name: 'Amazon Web Services',
lat: -52.942,
lon: -70.849,
},
{
id: 'Amazon Web Services',
name: 'Amazon Web Services',
lat: -33.557,
lon: -70.813,
},
{ id: 'Amazon Web Services', name: 'Amazon Web Services', lat: -52.942, lon: -70.849 },
{ id: 'Amazon Web Services', name: 'Amazon Web Services', lat: -33.557, lon: -70.813 },
];
const data = manager({
'local-datacenters': { name: 'Datacenters', records: sites },
});
const identity = {
layerId: 'local-datacenters',
id: 'Amazon Web Services',
label: 'Amazon Web Services',
lat: -33.557,
lon: -70.813,
};
const data = manager({ 'local-datacenters': { name: 'Datacenters', records: sites } });
const identity = { layerId: 'local-datacenters', id: 'Amazon Web Services', label: 'Amazon Web Services', lat: -33.557, lon: -70.813 };
assert.equal(findRecord(data, identity), sites[1]);
const card = describeEntity(data, identity);
assert.equal(card.lat, -33.557);
@@ -401,106 +242,16 @@ test('sites that share a key are told apart by where the identity says they are'
});
test('a link is built only from a language code, and a level is not a warning', () => {
const site = {
id: 'X',
name: 'X',
lat: 1,
lon: 1,
wikipedia: 'evil.example/a#:Y',
};
const site = { id: 'X', name: 'X', lat: 1, lon: 1, wikipedia: 'evil.example/a#:Y' };
const data = manager({ 'local-dams': { name: 'Dams', records: [site] } });
assert.deepEqual(
describeEntity(data, { layerId: 'local-dams', id: 'X', lat: 1, lon: 1 })
.links,
[],
);
assert.deepEqual(describeEntity(data, { layerId: 'local-dams', id: 'X', lat: 1, lon: 1 }).links, []);
assert.deepEqual(recordWarnings({ alert: 'green' }), []);
});
test('a breakdown names "Other" once', () => {
const ships = [30, 30, 70, 70, 70, 80, 80, 60, 37, 52, 52, 90, 90, 90].map(
(shipType, i) => ({
id: `S${i}`,
mmsi: String(i),
lat: 1,
lon: 1 + i * 0.01,
shipType,
}),
);
const data = manager({
'ais-live-vessels': { name: 'Vessels', records: ships },
});
const labels = layerBreakdown(data, 'ais-live-vessels').splits[0].parts.map(
(part) => part.label,
);
const ships = [30, 30, 70, 70, 70, 80, 80, 60, 37, 52, 52, 90, 90, 90].map((shipType, i) => ({ id: `S${i}`, mmsi: String(i), lat: 1, lon: 1 + i * 0.01, shipType }));
const data = manager({ 'ais-live-vessels': { name: 'Vessels', records: ships } });
const labels = layerBreakdown(data, 'ais-live-vessels').splits[0].parts.map((part) => part.label);
assert.equal(labels.filter((label) => label === 'Other').length <= 1, true);
assert.equal(new Set(labels).size, labels.length);
});
test('a card shows the photo its layer looked up: the tracked airliner, the selected vessel', () => {
const photo = {
src: 'https://cdn.example/p.jpg',
link: 'https://example/p',
photographer: 'A. Spotter',
width: 640,
};
const planes = manager({
flights: {
name: 'Live Flights',
records: [
{
id: 'DAL1',
icao24: 'aa0001',
callsign: 'DAL1',
lat: 34,
lon: -118,
typeCode: 'B739',
category: 'A3',
},
{ id: 'DAL2', icao24: 'aa0002', callsign: 'DAL2', lat: 35, lon: -118 },
],
},
'ais-live-vessels': {
name: 'Vessels',
records: [
{
id: 'EVER GIVEN',
vesselId: 'v1',
mmsi: '353136000',
lat: 30,
lon: 32,
},
],
},
});
planes.layers.get('flights').module.getTrackedSubject = () => ({
id: 'aa0001',
photo,
});
planes.layers.get('ais-live-vessels').module.getVesselPhoto = (id) =>
id === 'v1' ? { ...photo, licence: 'CC BY 4.0' } : null;
const tracked = describeEntity(planes, { layerId: 'flights', id: 'aa0001' });
assert.deepEqual(tracked.photo, {
src: photo.src,
link: photo.link,
photographer: 'A. Spotter',
licence: '',
});
// What picks the globe's fleet model for it.
assert.deepEqual(tracked.aircraftModel, {
typeCode: 'B739',
category: 'A3',
callsign: 'DAL1',
});
// Photos are looked up for the tracked plane only.
assert.equal(
describeEntity(planes, { layerId: 'flights', id: 'aa0002' }).photo,
null,
);
assert.equal(
describeEntity(planes, { layerId: 'ais-live-vessels', id: 'EVER GIVEN' })
.photo.licence,
'CC BY 4.0',
);
});
-9
View File
@@ -538,15 +538,6 @@ export function fleetModelSet() {
return loaded;
}
/**
* The load a layer has started (resolving to the set), or null when none
* has: for a view that needs the set but does not fetch it itself.
* @returns {Promise<object>|null}
*/
export function fleetModelSetLoading() {
return loading;
}
/**
* Fetch the model set once for every layer: `catalog.json`, `types.json` and
* every GLB the catalog names, all up front, so no model is fetched while a
-4
View File
@@ -91,8 +91,6 @@ const FULL_INFO = {
verticalRate: -4.5,
onGround: false,
klass: 'airliner',
typeCode: 'B738',
category: 'A3',
originCountry: 'United States',
airline: 'Southwest Airlines',
route: { origin: { code: 'AUS' }, destination: { code: 'LAX' } },
@@ -116,8 +114,6 @@ test('flights analyst record: full record maps every contract field', () => {
onGround: false,
military: false,
aircraftClass: 'airliner',
typeCode: 'B738',
category: 'A3',
originCountry: 'United States',
operator: 'Southwest Airlines',
squawk: null,
+2 -4
View File
@@ -167,10 +167,8 @@ test('pointer input, camera holds and the stock clicks go through the one dispat
[
/\.enableInputs\s*=(?!=)/,
'writes enableInputs instead of suspendCamera()',
// The scene's camera-input holds, which own the flag; the Context
// card's previews turn it off in their own small scenes, which take
// no input at all.
['src/render/cesium/cameraInput.js', 'src/render/cesium/cardPreviews.js'],
// The scene's camera-input holds, which own the flag.
['src/render/cesium/cameraInput.js'],
],
[
/(?:screenSpaceEventHandler|stockHandler)\??\.removeInputAction\(/,
+1 -10
View File
@@ -4458,14 +4458,5 @@
"{h} h {m} min": "{h} س {m} د",
"{n} min": "{n} د",
"{speed} {direction}": "{speed} {direction}",
"{n} mm": "{n} مم",
"Scanning": "جارٍ المسح",
"Route": "المسار",
"3D model": "نموذج ثلاثي الأبعاد",
"3D": "3D",
"Cockpit view": "منظر قمرة القيادة",
"KT": "عقدة",
"Course to {code}: {course}": "المسار إلى {code}: {course}",
"Over {place}": "فوق {place}",
"Below": "في الأسفل"
"{n} mm": "{n} مم"
}
+1 -10
View File
@@ -4086,14 +4086,5 @@
"{h} h {m} min": "{h} Std. {m} Min.",
"{n} min": "{n} Min.",
"{speed} {direction}": "{speed} aus {direction}",
"{n} mm": "{n} mm",
"Scanning": "Scan läuft",
"Route": "Route",
"3D model": "3D-Modell",
"3D": "3D",
"Cockpit view": "Cockpitsicht",
"KT": "KT",
"Course to {code}: {course}": "Kurs nach {code}: {course}",
"Over {place}": "Über {place}",
"Below": "Darunter"
"{n} mm": "{n} mm"
}
+1 -10
View File
@@ -4179,14 +4179,5 @@
"{h} h {m} min": "{h} h {m} min",
"{n} min": "{n} min",
"{speed} {direction}": "{speed} del {direction}",
"{n} mm": "{n} mm",
"Scanning": "Escaneando",
"Route": "Ruta",
"3D model": "Modelo 3D",
"3D": "3D",
"Cockpit view": "Vista de cabina",
"KT": "KT",
"Course to {code}: {course}": "Rumbo a {code}: {course}",
"Over {place}": "Sobre {place}",
"Below": "Debajo"
"{n} mm": "{n} mm"
}
+1 -10
View File
@@ -4179,14 +4179,5 @@
"{h} h {m} min": "{h} h {m} min",
"{n} min": "{n} min",
"{speed} {direction}": "{speed} de {direction}",
"{n} mm": "{n} mm",
"Scanning": "Balayage",
"Route": "Itinéraire",
"3D model": "Modèle 3D",
"3D": "3D",
"Cockpit view": "Vue cockpit",
"KT": "KT",
"Course to {code}: {course}": "Cap vers {code} : {course}",
"Over {place}": "Au-dessus de {place}",
"Below": "En dessous"
"{n} mm": "{n} mm"
}
+1 -10
View File
@@ -4179,14 +4179,5 @@
"{h} h {m} min": "{h} שע׳ {m} דק׳",
"{n} min": "{n} דק׳",
"{speed} {direction}": "{speed} מ־{direction}",
"{n} mm": "{n} מ״מ",
"Scanning": "סורק",
"Route": "מסלול",
"3D model": "דגם תלת־ממדי",
"3D": "3D",
"Cockpit view": "מבט מתא הטייס",
"KT": "KT",
"Course to {code}: {course}": "כיוון אל {code}: {course}",
"Over {place}": "מעל {place}",
"Below": "מתחת"
"{n} mm": "{n} מ״מ"
}
+1 -10
View File
@@ -4179,14 +4179,5 @@
"{h} h {m} min": "{h} h {m} min",
"{n} min": "{n} min",
"{speed} {direction}": "{speed} da {direction}",
"{n} mm": "{n} mm",
"Scanning": "Scansione",
"Route": "Rotta",
"3D model": "Modello 3D",
"3D": "3D",
"Cockpit view": "Vista dalla cabina",
"KT": "KT",
"Course to {code}: {course}": "Rotta verso {code}: {course}",
"Over {place}": "Sopra {place}",
"Below": "Sotto"
"{n} mm": "{n} mm"
}
+1 -10
View File
@@ -3993,14 +3993,5 @@
"{h} h {m} min": "{h}時間{m}分",
"{n} min": "{n}分",
"{speed} {direction}": "{direction}の風 {speed}",
"{n} mm": "{n} mm",
"Scanning": "スキャン中",
"Route": "ルート",
"3D model": "3Dモデル",
"3D": "3D",
"Cockpit view": "コックピット視点",
"KT": "KT",
"Course to {code}: {course}": "{code}への針路: {course}",
"Over {place}": "{place}上空",
"Below": "直下"
"{n} mm": "{n} mm"
}
+1 -10
View File
@@ -4179,14 +4179,5 @@
"{h} h {m} min": "{h} h {m} min",
"{n} min": "{n} min",
"{speed} {direction}": "{speed} de {direction}",
"{n} mm": "{n} mm",
"Scanning": "Escaneando",
"Route": "Rota",
"3D model": "Modelo 3D",
"3D": "3D",
"Cockpit view": "Vista da cabine",
"KT": "KT",
"Course to {code}: {course}": "Rumo para {code}: {course}",
"Over {place}": "Sobre {place}",
"Below": "Abaixo"
"{n} mm": "{n} mm"
}
+1 -10
View File
@@ -4272,14 +4272,5 @@
"{h} h {m} min": "{h} ч {m} мин",
"{n} min": "{n} мин",
"{speed} {direction}": "{speed}, {direction}",
"{n} mm": "{n} мм",
"Scanning": "Сканирование",
"Route": "Маршрут",
"3D model": "3D-модель",
"3D": "3D",
"Cockpit view": "Вид из кабины",
"KT": "УЗ",
"Course to {code}: {course}": "Курс на {code}: {course}",
"Over {place}": "Над: {place}",
"Below": "Под спутником"
"{n} mm": "{n} мм"
}
+1 -10
View File
@@ -4086,14 +4086,5 @@
"{h} h {m} min": "{h} h {m} min",
"{n} min": "{n} min",
"{speed} {direction}": "{speed} från {direction}",
"{n} mm": "{n} mm",
"Scanning": "Skannar",
"Route": "Rutt",
"3D model": "3D-modell",
"3D": "3D",
"Cockpit view": "Cockpitvy",
"KT": "KT",
"Course to {code}: {course}": "Kurs mot {code}: {course}",
"Over {place}": "Över {place}",
"Below": "Nedanför"
"{n} mm": "{n} mm"
}
+1 -10
View File
@@ -4272,14 +4272,5 @@
"{h} h {m} min": "{h} год {m} хв",
"{n} min": "{n} хв",
"{speed} {direction}": "{speed}, {direction}",
"{n} mm": "{n} мм",
"Scanning": "Сканування",
"Route": "Маршрут",
"3D model": "3D-модель",
"3D": "3D",
"Cockpit view": "Вигляд з кабіни",
"KT": "ВУЗ",
"Course to {code}: {course}": "Курс на {code}: {course}",
"Over {place}": "Над: {place}",
"Below": "Під супутником"
"{n} mm": "{n} мм"
}
+1 -10
View File
@@ -3993,14 +3993,5 @@
"{h} h {m} min": "{h} 小时 {m} 分钟",
"{n} min": "{n} 分钟",
"{speed} {direction}": "{direction}风 {speed}",
"{n} mm": "{n} 毫米",
"Scanning": "扫描中",
"Route": "航线",
"3D model": "3D 模型",
"3D": "3D",
"Cockpit view": "驾驶舱视角",
"KT": "kt",
"Course to {code}: {course}": "前往 {code} 的航向:{course}",
"Over {place}": "{place}上空",
"Below": "下方"
"{n} mm": "{n} 毫米"
}
+1 -10
View File
@@ -3993,14 +3993,5 @@
"{h} h {m} min": "{h} 小時 {m} 分鐘",
"{n} min": "{n} 分鐘",
"{speed} {direction}": "{direction}風 {speed}",
"{n} mm": "{n} 毫米",
"Scanning": "掃描中",
"Route": "航線",
"3D model": "3D 模型",
"3D": "3D",
"Cockpit view": "駕駛艙視角",
"KT": "kt",
"Course to {code}: {course}": "前往 {code} 的航向:{course}",
"Over {place}": "{place}上空",
"Below": "下方"
"{n} mm": "{n} 毫米"
}
+13 -35
View File
@@ -55,8 +55,7 @@
"{n}%",
"{n} hPa",
"{kind} {name}",
"{speed} {direction}",
"3D"
"{speed} {direction}"
],
"de": [
"1090 MHz",
@@ -293,10 +292,7 @@
"{n} hPa",
"Turboprops",
"{kind} {name}",
"{n} mm",
"Route",
"3D",
"KT"
"{n} mm"
],
"es": [
"1 min/s",
@@ -488,9 +484,7 @@
"{kind} {name}",
"{h} h {m} min",
"{n} min",
"{n} mm",
"3D",
"KT"
"{n} mm"
],
"fr": [
"1 min/s",
@@ -746,9 +740,7 @@
"{kind} {name}",
"{h} h {m} min",
"{n} min",
"{n} mm",
"3D",
"KT"
"{n} mm"
],
"it": [
"1 min/s",
@@ -980,9 +972,7 @@
"{kind} {name}",
"{h} h {m} min",
"{n} min",
"{n} mm",
"3D",
"KT"
"{n} mm"
],
"ja": [
"1090 MHz",
@@ -1064,9 +1054,7 @@
"{n} MW",
"{n}%",
"{n} hPa",
"{n} mm",
"3D",
"KT"
"{n} mm"
],
"pt": [
"1 min/s",
@@ -1258,9 +1246,7 @@
"{kind} {name}",
"{h} h {m} min",
"{n} min",
"{n} mm",
"3D",
"KT"
"{n} mm"
],
"ru": [
"1900–1945",
@@ -1304,8 +1290,7 @@
"{n}°",
"M {n}",
"{n}%",
"{kind} {name}",
"3D"
"{kind} {name}"
],
"sv": [
"STATION",
@@ -1496,9 +1481,7 @@
"{kind} {name}",
"{h} h {m} min",
"{n} min",
"{n} mm",
"3D",
"KT"
"{n} mm"
],
"uk": [
"1900–1945",
@@ -1536,8 +1519,7 @@
"{n}°",
"M {n}",
"{n}%",
"{kind} {name}",
"3D"
"{kind} {name}"
],
"zh-CN": [
"1090 MHz",
@@ -1621,8 +1603,7 @@
"M {n}",
"{n} MW",
"{n}%",
"{n} hPa",
"3D"
"{n} hPa"
],
"zh-Hant": [
"1090 MHz",
@@ -1706,8 +1687,7 @@
"M {n}",
"{n} MW",
"{n}%",
"{n} hPa",
"3D"
"{n} hPa"
],
"he": [
"{speed} kn",
@@ -1822,8 +1802,6 @@
"{n} MW",
"{n}%",
"{n} hPa",
"{kind} {name}",
"3D",
"KT"
"{kind} {name}"
]
}
-3
View File
@@ -288,9 +288,6 @@ export function createQueries({
// A converted contact reports the class it RENDERS as, so an analyst
// filter/superlative agrees with the triangle on screen.
aircraftClass: tr3bAircraftClass(icao24, text(info?.klass)),
// What picks its fleet model, for the context card's turning model.
typeCode: text(info?.typeCode),
category: info?.category ?? null,
originCountry: text(info?.originCountry),
operator: text(info?.airline),
squawk: text(info?.squawk),
+1 -8
View File
@@ -1,15 +1,8 @@
/**
* @module maps/attribution
* @description The on-map credits of the map stacks' sources, and Esri
* World Imagery's tile address, which the globe and the card previews share.
* @description The on-map credits of the map stacks' sources.
*/
// Attribution and service rights are documented in DATA_SOURCES.md.
/** Esri World Imagery's tiles; Stories' card images draw from the same. */
export const ESRI_TILES =
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
/** Esri World Imagery's credit line, as plain text. */
export const ESRI_IMAGERY_CREDIT =
'Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community';
export const ESRI_ATTRIBUTION_HTML =
'<a href="https://www.esri.com" target="_blank" rel="noopener">Powered by Esri</a>';
+1 -1
View File
@@ -25,7 +25,7 @@ export function createDefaultMapSources({
id: hasIon ? 'world' : 'keyless',
create: hasIon
? (request) => engineOf().terrain.world(ionToken, request)
: () => engineOf().terrain.keyless(),
: (request) => engineOf().terrain.keyless(request),
};
return {
defaultId: googleTileset ? 'photoreal' : 'esri-imagery',
+129 -14
View File
@@ -13,9 +13,22 @@
* photoreal base is turned off through the port and on again when shown.
*/
import { findFrame, findGlobe, rendererOf } from '../render/rendererOf.js';
import { ESRI_IMAGERY_CREDIT, ESRI_TILES } from './attribution.js';
import { KEYLESS_TERRAIN_URL } from './keylessTerrain.js';
/** Esri World Imagery's tiles; Stories' card images draw from the same. */
export const ESRI_TILES =
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
/** Esri World Imagery's deepest level (its tile info lists levels 0–23). */
const ESRI_MAX_LEVEL = 23;
/**
* A tile Esri has no imagery for: it answers every such tile with this one
* "Map data not yet available" picture, the same bytes each time.
*/
const ESRI_MISSING_TILE =
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/23/0/0';
const OSM_MAX_LEVEL = 19;
const ESRI_CREDIT =
'Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community';
const OSM_TILES = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
const OSM_CREDIT = '© OpenStreetMap contributors';
/** Cesium ion's world imagery assets (`MAP_STACKS`' `style`). */
@@ -30,6 +43,90 @@ const shownGlobes = new WeakMap();
const credit = (text) => ({ text });
/** Esri's "no imagery here" picture's bytes, once read; null if unread. */
let esriMissing = null;
/** Read Esri's "no imagery here" picture, once; null while it cannot be. */
function esriMissingTile() {
esriMissing ??= fetch(ESRI_MISSING_TILE)
.then((response) => (response.ok ? response.arrayBuffer() : null))
.then((buffer) => (buffer ? new Uint8Array(buffer) : null))
.catch(() => null)
.then((bytes) => {
// Not read: asked for again with the next tile.
if (!bytes) esriMissing = null;
return bytes;
});
return esriMissing;
}
const sameBytes = (a, b) =>
a.length === b.length && a.every((byte, i) => byte === b[i]);
/**
* An Esri tile, fetched. Esri's "no imagery here" picture is a missing tile,
* drawn from its parent, as Cesium's own Esri provider discards it; a
* refused tile is a failed one, which counts toward the Esri source's
* fallback to OSM.
*/
async function fetchEsriTile({ url, signal }) {
const [response, missing] = await Promise.all([
fetch(url, { signal }),
esriMissingTile(),
]);
if (!response.ok) {
const error = new Error(`Esri tile answered ${response.status}`);
error.statusCode = response.status;
throw error;
}
const bytes = await response.arrayBuffer();
if (missing && sameBytes(new Uint8Array(bytes), missing))
return { missing: true };
const contentType = response.headers.get('content-type');
return { bytes, ...(contentType ? { contentType } : {}) };
}
/** Cesium World Terrain's ion asset. */
const ION_WORLD_TERRAIN = 1;
/**
* Ask Cesium ion for an asset's endpoint, as Cesium does before it draws
* one: a token ion refuses, or no answer, refuses the switch with ion's
* message, so the map stack stays where it was and says why.
* @param {number} asset
* @param {string} token
* @param {AbortSignal} [signal]
*/
async function ionEndpoint(asset, token, signal) {
const response = await fetch(
`https://api.cesium.com/v1/assets/${asset}/endpoint?access_token=${encodeURIComponent(token)}`,
{ signal },
);
const body = await response.json().catch(() => null);
if (!response.ok)
throw new Error(
body?.message ||
`Cesium ion answered ${response.status} for asset ${asset}`,
);
return body;
}
/**
* Whether the keyless terrain answers: its `layer.json`, read as any
* quantized-mesh terrain is read before its first tile.
*/
async function keylessTerrainAnswers(signal) {
try {
const response = await fetch(`${KEYLESS_TERRAIN_URL}/layer.json`, {
signal,
});
return response.ok;
} catch (error) {
if (signal?.aborted) throw error;
return false;
}
}
/**
* Turn a photoreal handle's base on or off. Turning it on can fail (the
* port answers route `none`, or rejects): the handle is then off again, so
@@ -123,7 +220,7 @@ export const globeMapEngine = Object.freeze({
kind: 'xyz',
url: OSM_TILES,
tiling: 'webMercator',
maxLevel: 19,
maxLevel: OSM_MAX_LEVEL,
credit: credit(OSM_CREDIT),
}),
esri: () =>
@@ -131,12 +228,18 @@ export const globeMapEngine = Object.freeze({
kind: 'xyz',
url: ESRI_TILES,
tiling: 'webMercator',
maxLevel: 19,
credit: credit(ESRI_IMAGERY_CREDIT),
maxLevel: ESRI_MAX_LEVEL,
fetchTile: fetchEsriTile,
credit: credit(ESRI_CREDIT),
}),
ion(style, accessToken) {
if (!String(accessToken || '').trim())
throw new Error('Ion imagery requires an explicit token');
async ion(style, accessToken, { signal } = {}) {
const token = String(accessToken || '').trim();
if (!token) throw new Error('Ion imagery requires an explicit token');
const endpoint = await ionEndpoint(style, token, signal);
if (endpoint?.type !== 'IMAGERY' || endpoint.externalType !== 'BING')
throw new Error(
'Ion world imagery did not return a Bing imagery endpoint',
);
return Object.freeze({
kind: 'world',
worldStyle: WORLD_STYLES[style] ?? 'aerial',
@@ -144,19 +247,31 @@ export const globeMapEngine = Object.freeze({
},
}),
terrain: Object.freeze({
world: async (accessToken) => {
if (!String(accessToken || '').trim())
world: async (accessToken, { signal } = {}) => {
const token = String(accessToken || '').trim();
if (!token)
throw new Error('World terrain requires an explicit ion token');
await ionEndpoint(ION_WORLD_TERRAIN, token, signal);
return {
provider: null,
spec: { kind: 'world', requestVertexNormals: true },
};
},
// Re:Earth's keyless terrain, as the Cesium map engine draws it.
keyless: async () => ({
provider: null,
spec: { kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL },
}),
/**
* Re:Earth's keyless terrain. While it does not answer, the ellipsoid
* stands in as a fallback the map stack tries the terrain again behind.
*/
keyless: async ({ signal } = {}) => {
if (await keylessTerrainAnswers(signal))
return {
provider: null,
spec: { kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL },
};
console.warn(
'[MapStack] Re:Earth terrain unavailable, falling back to flat ellipsoid terrain',
);
return { provider: null, spec: { kind: 'ellipsoid' }, fallback: true };
},
}),
createImageryLayer: (spec) => ({ spec, layer: null }),
requestRender(host) {
+160 -4
View File
@@ -70,6 +70,116 @@ test('the globe is shown and hidden through the port, read back without globe vi
assert.equal(engine.globeShown(visible.host), false);
});
/** Answer `fetch` from `answers` (url to response) while `run` runs. */
async function withFetch(answers, run) {
const real = globalThis.fetch;
const asked = [];
globalThis.fetch = async (url) => {
asked.push(String(url));
const answer = answers(String(url));
if (answer instanceof Error) throw answer;
return answer;
};
try {
return await run(asked);
} finally {
globalThis.fetch = real;
}
}
const bytesResponse = (bytes, status = 200) => ({
ok: status >= 200 && status < 300,
status,
headers: { get: (name) => (name === 'content-type' ? 'image/jpeg' : null) },
arrayBuffer: async () => new Uint8Array(bytes).buffer,
json: async () => JSON.parse(new TextDecoder().decode(new Uint8Array(bytes))),
});
const jsonResponse = (body, status = 200) =>
bytesResponse([...new TextEncoder().encode(JSON.stringify(body))], status);
/** Cesium ion's endpoints as a valid token is answered. */
const ionAnswers = (url) =>
/assets\/1\/endpoint/.test(url)
? jsonResponse({ type: 'TERRAIN', url: 'https://assets.ion.invalid/1/' })
: jsonResponse({ type: 'IMAGERY', externalType: 'BING', options: {} });
// Nothing here reaches the network: ion and the keyless terrain answer,
// offline.
globalThis.fetch = async (url) =>
String(url).startsWith('https://api.cesium.com/')
? ionAnswers(String(url))
: bytesResponse([1]);
test('Esri goes to its deepest level, its no-imagery picture drawn from the parent', async () => {
const spec = engine.imagery.esri();
assert.equal(spec.maxLevel, 23);
const placeholder = [9, 9, 9];
await withFetch(
(url) =>
url.endsWith('/tile/23/0/0')
? bytesResponse(placeholder)
: url.endsWith('/5/1/2')
? bytesResponse([1, 2, 3, 4])
: url.endsWith('/22/7/7')
? bytesResponse(placeholder)
: bytesResponse([], 503),
async (asked) => {
const signal = new AbortController().signal;
const tile = await spec.fetchTile({ url: `${'x'}/5/1/2`, signal });
assert.deepEqual([...new Uint8Array(tile.bytes)], [1, 2, 3, 4]);
assert.equal(tile.contentType, 'image/jpeg');
assert.deepEqual(
await spec.fetchTile({ url: 'x/22/7/7', signal }),
{ missing: true },
'the no-imagery picture is a missing tile',
);
await assert.rejects(
spec.fetchTile({ url: 'x/1/1/1', signal }),
(error) => error.statusCode === 503,
'a refused tile is a failed one',
);
assert.equal(
asked.filter((url) => url.endsWith('/tile/23/0/0')).length,
1,
'the no-imagery picture is read once',
);
},
);
});
test('keyless terrain that does not answer is the flat ellipsoid, marked a fallback', async () => {
await withFetch(
() => new TypeError('offline'),
async (asked) => {
const warn = console.warn;
console.warn = () => {};
try {
assert.deepEqual(await engine.terrain.keyless(), {
provider: null,
spec: { kind: 'ellipsoid' },
fallback: true,
});
} finally {
console.warn = warn;
}
assert.deepEqual(asked, [`${KEYLESS_TERRAIN_URL}/layer.json`]);
},
);
await withFetch(
() => bytesResponse([], 503),
async () => {
const warn = console.warn;
console.warn = () => {};
try {
assert.equal((await engine.terrain.keyless()).fallback, true);
} finally {
console.warn = warn;
}
},
);
});
test('terrain is the port’s world terrain, or the keyless quantized mesh without a token', async () => {
const { host, renderer } = scene(['terrain']);
await assert.rejects(engine.terrain.world(''), /ion token/);
@@ -78,20 +188,66 @@ test('terrain is the port’s world terrain, or the keyless quantized mesh witho
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [
{ kind: 'world', requestVertexNormals: true },
]);
engine.applyTerrain(host, await engine.terrain.keyless());
engine.applyTerrain(
host,
await withFetch(
() => bytesResponse([1]),
() => engine.terrain.keyless(),
),
);
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [
{ kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL },
]);
assert.throws(() => engine.imagery.ion(2, ''), /token/);
assert.deepEqual(engine.imagery.ion(3, 'token'), {
await assert.rejects(engine.imagery.ion(2, ''), /token/);
assert.deepEqual(await engine.imagery.ion(3, 'token'), {
kind: 'world',
worldStyle: 'aerialLabels',
});
});
test('a token ion refuses refuses the switch with ion’s message, as Cesium’s own route did', async () => {
await withFetch(
() =>
jsonResponse(
{ code: 'InvalidCredentials', message: 'Invalid access token' },
401,
),
async (asked) => {
await assert.rejects(
engine.imagery.ion(2, 'bad'),
/Invalid access token/,
);
await assert.rejects(engine.terrain.world('bad'), /Invalid access token/);
assert.match(asked[0], /\/v1\/assets\/2\/endpoint\?access_token=bad$/);
assert.match(asked[1], /\/v1\/assets\/1\/endpoint\?access_token=bad$/);
},
);
await withFetch(
() => jsonResponse({ type: 'IMAGERY', externalType: 'GOOGLE_2D_MAPS' }),
async () => {
await assert.rejects(
engine.imagery.ion(2, 'token'),
/Bing imagery endpoint/,
);
},
);
await withFetch(
() => new TypeError('offline'),
async () => {
await assert.rejects(engine.terrain.world('token'), /offline/);
},
);
});
test('where the renderer draws no terrain the ellipsoid stays', async () => {
const { host, renderer } = scene([]);
engine.applyTerrain(host, await engine.terrain.keyless());
engine.applyTerrain(
host,
await withFetch(
() => bytesResponse([1]),
() => engine.terrain.keyless(),
),
);
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [null]);
});
-5
View File
@@ -20,11 +20,6 @@
* - `renderFailureNotice({allowReload, store})`: a recoverable notice,
* published to `store`, when the renderer stops drawing
* (`src/render/cesium/renderFailure.js`); returns its removal.
* - `cardPreviews`: the Context card's previews of a picked aircraft (its
* model turning, its route on a small globe, the view from its cockpit),
* each drawn into an element the card gives it
* (`src/render/cesium/cardPreviews.js`); without it the card shows its
* photo and figures only.
*
* A plugin hands them as its `applicationHooks(renderer)`
* (`ApplicationHooks`, `contract/renderer.d.ts`); the application scene
+11 -12
View File
@@ -7,17 +7,15 @@
* The renderer it makes is transitional. Its ports are the shared Cesium
* ports (`ports.js`), the ones the conformance renderer is checked with,
* and it has every member of the contract. The application's base (the
* photoreal tiles, the map stack's imagery and terrain) is still loaded
* through the Cesium map engine (`mapEngine.js`), which the plugin hands
* the application with the renderer (its `applicationHooks`); the globe
* port drapes its imagery on that base as drawn (see `globe.js`).
* photoreal tiles, the map stack's imagery and terrain) is loaded through
* the globe port, as on any renderer (`src/maps/globeEngine.js`).
* `whenSettled` waits for the globe, the scene's 3D tiles and what the draw
* sets hold.
*
* What only this renderer needs at startup is set up here: the free-look
* height limit, keyboard access to the credits' expand link (in the page's
* language). The plugin's `applicationHooks` are what the application
* uses where a renderer has them: the map engine, stale command trimming,
* uses where a renderer has them: stale command trimming,
* whether an entity is the viewer's own, and the viewer QA scripts read.
* Adapter code reaches the viewer behind a renderer through
* `cesiumViewerOf` (`viewers.js`), never through a renderer member, so no
@@ -30,14 +28,13 @@ import { bindRenderer } from '../rendererOf.js';
import { FREE_LOOK_MAX_HEIGHT_METERS } from '../../globeInView.js';
import { createCesiumInput } from './input.js';
import { cesiumCapabilities, createCesiumPorts } from './ports.js';
import { cesiumMapEngine } from './mapEngine.js';
import { installFreeLookHeightLimit } from './freeLookLimit.js';
import { trimStaleSceneCommands } from './sceneCommandRelease.js';
import { configureCreditKeyboardAccess } from './creditKeyboard.js';
import { onLocaleChange } from '../../i18n/index.js';
import { cesiumViewerOf, recordViewer } from './viewers.js';
import { installRenderFailureNotice } from './renderFailure.js';
import { cesiumCardPreviews } from './cardPreviews.js';
import { cesiumPhotorealOf } from './globe.js';
export { cesiumViewerOf };
@@ -212,7 +209,6 @@ export function createCesiumRendererPlugin({
applicationHooks(renderer) {
const viewer = cesiumViewerOf(renderer);
return {
mapEngine: cesiumMapEngine,
// Cesium's credit display (#cesium-credits) shows the credits.
ownCreditDisplay: true,
// Drops the draw commands the scene keeps after it stops drawing
@@ -222,14 +218,17 @@ export function createCesiumRendererPlugin({
// the aircraft it flies still draws).
viewerDrawsEntity: (entity) => viewer.entities.contains(entity),
// QA scripts drive and read the viewer itself.
qaHandles: { viewer },
qaHandles: {
viewer,
/** The photoreal tileset the globe holds now, shown or hidden. */
get tileset() {
return cesiumPhotorealOf(viewer.scene);
},
},
// A recoverable notice when the globe stops drawing
// (renderFailure.js).
renderFailureNotice: (options) =>
installRenderFailureNotice(viewer, options),
// The Context card's previews, each in a small scene of its own
// (cardPreviews.js).
cardPreviews: cesiumCardPreviews,
};
},
});
+5 -2
View File
@@ -11,7 +11,6 @@ import {
releaseContinuousRender,
uninstallRenderGovernor,
} from '../../renderGovernor.js';
import { cesiumMapEngine } from './mapEngine.js';
import {
ReadonlySet,
cesiumRenderer,
@@ -150,7 +149,11 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async
'free look is limited to low heights from the start',
);
const hooks = plugin.applicationHooks(renderer);
assert.equal(hooks.mapEngine, cesiumMapEngine, 'the map stacks use Cesium');
assert.equal(
hooks.mapEngine,
undefined,
'the map stacks switch through the globe port',
);
assert.equal(hooks.ownCreditDisplay, true, 'Cesium shows its own credits');
assert.equal(hooks.qaHandles.viewer, viewer, 'QA scripts read the viewer');
assert.equal(hooks.viewerDrawsEntity({ own: true }), true);
-753
View File
@@ -1,753 +0,0 @@
/**
* @module render/cesium/cardPreviews
* @description The Context card's previews on the Cesium renderer: an
* aircraft's model turning on its own, its route on a small globe, and the
* view ahead from its cockpit. Each draws in a small Cesium scene of its own
* inside the element it is given, and is torn down with the card. The
* application reaches them through the `cardPreviews` application hook
* (`render/applicationHooks.js`); the card's words, figures and HUD stay
* the application's.
*
* Every preview is `{setActive(active), update(values), destroy()}`: a
* hidden one stops drawing and rests on its last frame, and shown again it
* draws once straight away so there is no gap. A preview that cannot be
* made calls its `onFailed`.
*/
import * as Cesium from 'cesium';
import { webglContext } from './internals.js';
import { createEsriImagery } from './mapImagery.js';
/**
* Destroy a preview's widget and free its WebGL context. A browser keeps
* only a handful of contexts open and drops the oldest, the main globe's,
* when there are too many; a destroyed widget's context is otherwise freed
* only when garbage is collected, so flicking through cards could push the
* globe's out.
* @param {Cesium.CesiumWidget|null} widget
*/
function destroyWidget(widget) {
if (!widget || widget.isDestroyed()) return;
let gl = null;
try {
gl = webglContext(widget.scene) ?? null;
} catch {
gl = null;
}
widget.destroy();
try {
gl?.getExtension?.('WEBGL_lose_context')?.loseContext();
} catch {
// Nothing more can be done; the context goes when it is collected.
}
}
/** A small widget with no input, credits or render-loop error panel. */
function createWidget(container, options) {
const widget = new Cesium.CesiumWidget(container, {
skyBox: false,
scene3DOnly: true,
shadows: false,
showRenderLoopErrors: false,
// The globe's own credits already show; a preview's go in its corner.
creditContainer: document.createElement('div'),
...options,
});
widget.scene.screenSpaceCameraController.enableInputs = false;
return widget;
}
/**
* Stops a hidden widget's render loop once `ready()` says it has something
* to rest on; shown again, it draws once at once.
*/
function renderLoopSwitch(widget, ready = () => true) {
let active = true;
const sync = () => {
if (widget.isDestroyed()) return;
const run = active || !ready();
if (run && !widget.useDefaultRenderLoop) {
widget.resize();
widget.render();
}
widget.useDefaultRenderLoop = run;
};
return {
sync,
set(next) {
active = Boolean(next);
sync();
},
};
}
const reducedMotion = () =>
globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true;
// ── The turning model ──────────────────────────────────────────────────
/** How long each look lasts, and each reveal between them, in turns. */
const PLAIN_TURNS = 1;
const SCAN_TURNS = 0.3;
const REVEAL_TURNS = 0.07;
/** How long (ms) the plain model holds after the reveal before a cycle ends. */
const HOLD_MS = 700;
/** How fast the model turns, in radians a millisecond (about 0.3 a second). */
const TURN_PER_MS = 0.0003;
// Model space, normalised so the craft reaches about 1.7 from its centre.
// u_reveal runs 0 to 2: from 0 to 1 the edge grows from the centre and
// leaves wire inside it; at 1 it is all wire; from 1 to 2 it grows again and
// leaves the model inside it. Outside that range the model draws as it is.
const LOOK_SHADER = `
void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
if (u_reveal <= 0.0 || u_reveal >= 2.0) return;
vec3 p = fsInput.attributes.positionMC / u_half;
bool entering = u_reveal < 1.0;
float r = length(p);
float front = mix(0.0, 1.8, entering ? u_reveal : u_reveal - 1.0);
float edge = 1.0 - smoothstep(0.0, 0.05, abs(r - front));
vec3 white = vec3(0.9, 0.96, 1.0);
bool wire = entering ? r < front : r > front;
if (!wire) {
material.emissive += white * edge * 1.4;
return;
}
// A fine grid: many small cells, hairline lines.
vec3 q = p * 18.0;
vec3 g = abs(fract(q - 0.5) - 0.5) / max(fwidth(q), vec3(1e-4));
float line = (1.0 - clamp(min(min(g.x, g.y), g.z) * 2.4, 0.0, 1.0)) * 0.7;
vec3 base = material.diffuse;
// Opaque: a near-black body with white lines on it and its own colour
// faintly through, which reads as a wireframe against the dark card (a
// translucent model does not blend onto this scene's transparent canvas).
material.diffuse = base * 0.12 + vec3(0.015, 0.02, 0.03);
material.specular = vec3(0.0);
material.emissive = white * line + base * 0.35 + white * edge * 1.4;
}`;
/**
* An aircraft's model turning slowly, with no globe, sky or imagery. Its
* look changes as it turns: a whole rotation as it is, then a short
* wireframe scan (under a third of a turn), then round again; each change is
* a reveal, a bright ring growing from the craft's centre to its edges. One
* custom shader does it, driven by a uniform, because a shader set on a
* model after it is ready does nothing in this Cesium. Under reduced motion
* there is no scan.
*
* `onPhase('plain'|'scan')` says when the look changes; `onCycle(ms)` when a
* look and its scan end, with the drawing time they took, so the card can
* give another view the same time.
* @param {HTMLElement} container
* @param {{gltf: Uint8Array|ArrayBuffer, basePath?: string, heading?: number,
* viewRange?: number}} model The GLB's bytes; the heading (degrees) it
* starts facing; how far the camera stands, in bounding radii.
* @param {{onPhase?: (phase: string) => void, onCycle?: (ms: number) => void,
* onFailed?: () => void}} [events]
*/
function modelPreview(
container,
{ gltf, basePath, heading = 0, viewRange = 1.9 },
{ onPhase = () => {}, onCycle = () => {}, onFailed = () => {} } = {},
) {
let widget = null;
let model = null;
let loaded = false;
let removeTick = null;
let loop = null;
const fail = () => {
if (!widget) return;
onFailed();
};
try {
widget = createWidget(container, {
globe: false,
skyAtmosphere: false,
baseLayer: false,
contextOptions: { webgl: { alpha: true, antialias: true } },
});
const { scene } = widget;
scene.backgroundColor = Cesium.Color.TRANSPARENT;
scene.light = new Cesium.DirectionalLight({
direction: Cesium.Cartesian3.normalize(
new Cesium.Cartesian3(-0.4, -0.6, -0.7),
new Cesium.Cartesian3(),
),
intensity: 2.4,
});
loop = renderLoopSwitch(widget, () => loaded);
} catch {
onFailed();
return { setActive() {}, update() {}, destroy() {} };
}
const shader = new Cesium.CustomShader({
uniforms: {
u_reveal: { type: Cesium.UniformType.FLOAT, value: 0 },
u_half: { type: Cesium.UniformType.FLOAT, value: 20 },
},
fragmentShaderText: LOOK_SHADER,
});
const origin = Cesium.Cartesian3.fromDegrees(0, 0, 0);
const start = (sphere) => {
// The craft reaches about 0.6 of its bounding radius from the centre.
shader.setUniform('u_half', sphere.radius * 0.6);
const first = Cesium.Math.toRadians(heading + 140);
let turn = first;
let phase = 'plain';
let cycleMs = 0;
let lastFrame = performance.now();
let holdMs = null;
const still = reducedMotion();
const range = sphere.radius * viewRange;
const pitch = Cesium.Math.toRadians(-18);
const ease = (x) => x * x * (3 - 2 * x);
const frame = () => {
// Only time spent drawing counts: a hidden preview stops drawing.
const now = performance.now();
const drawn = now - lastFrame < 250 ? now - lastFrame : 0;
lastFrame = now;
// A steady turn whatever the display's refresh rate; still under
// reduced motion.
if (!still) turn += TURN_PER_MS * drawn;
const turns = (turn - first) / (2 * Math.PI);
// Where in the scan it is, and from that how far each reveal has gone.
const into = (turns % (PLAIN_TURNS + SCAN_TURNS)) - PLAIN_TURNS;
let reveal = 0;
if (!still && into >= 0) {
if (into < REVEAL_TURNS) reveal = ease(into / REVEAL_TURNS);
else if (into > SCAN_TURNS - REVEAL_TURNS)
reveal =
1 + ease((into - (SCAN_TURNS - REVEAL_TURNS)) / REVEAL_TURNS);
else reveal = 1;
}
const next = reveal > 0 && reveal < 2 ? 'scan' : 'plain';
cycleMs += drawn;
// The cycle ends once the reveal back to the model has finished and
// the plain model has held a moment, never mid-reveal.
if (phase === 'scan' && next === 'plain') holdMs = 0;
if (holdMs !== null && next === 'plain') {
holdMs += drawn;
if (holdMs >= HOLD_MS) {
onCycle(cycleMs);
cycleMs = 0;
holdMs = null;
}
}
if (next !== phase) {
phase = next;
onPhase(phase);
}
shader.setUniform('u_reveal', reveal);
widget.camera.lookAt(
sphere.center,
new Cesium.HeadingPitchRange(turn, pitch, range),
);
};
frame();
removeTick = widget.scene.preRender.addEventListener(frame);
widget.render();
loaded = true;
loop.sync();
};
Cesium.Model.fromGltfAsync({
gltf,
basePath,
customShader: shader,
modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(origin),
// A light rim so the mesh reads against the dark card.
silhouetteColor: Cesium.Color.WHITE.withAlpha(0.3),
silhouetteSize: 1,
}).then((made) => {
if (!widget) {
made.destroy();
return;
}
model = widget.scene.primitives.add(made);
model.readyEvent.addEventListener(() => {
if (widget) start(model.boundingSphere);
});
model.errorEvent?.addEventListener?.(fail);
}, fail);
function move(atNow) {
const at = onRoute(from, to, atNow);
if (!widget || !at || !plane || flyingIn) return;
pose(plane, at);
if (flownLine) flownLine.polyline.positions = arc(from, at, 48);
if (aheadLine) aheadLine.polyline.positions = arc(at, to);
widget.scene.requestRender();
}
return {
setActive: (active) => loop.set(active),
update() {},
destroy() {
removeTick?.();
removeTick = null;
const gone = widget;
widget = null;
model = null;
destroyWidget(gone);
},
};
}
// ── The route globe ────────────────────────────────────────────────────
const CYAN = Cesium.Color.fromCssColorString('#36dcff');
const AMBER = Cesium.Color.fromCssColorString('#ffb86b');
/** Height (m) the route and the plane are drawn at, clear of the globe. */
const ROUTE_HEIGHT_M = 30_000;
// The plane: the Material "flight" silhouette, nose up (north), white with
// a cyan glow, drawn once as an image.
const PLANE_ICON = `data:image/svg+xml;utf8,${encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 32 32" width="64" height="64">' +
'<defs><filter id="g" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="1.4"/></filter></defs>' +
'<path filter="url(#g)" fill="#36dcff" d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>' +
'<path fill="#ffffff" stroke="#0b1820" stroke-width="0.6" d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>' +
'</svg>',
)}`;
/**
* An airport's code as an image, white with a dark outline, at the page's
* pixel ratio. The preview is a small scene of its own, so its two codes are
* drawn into it rather than on the world overlay, which belongs to the globe.
* @param {string} code
* @returns {{image: HTMLCanvasElement, width: number, height: number}}
* the image and its size on screen, CSS pixels
*/
function codeImage(code) {
const ratio = Math.min(3, Math.max(1, globalThis.devicePixelRatio || 1));
const font = `600 ${11 * ratio}px ui-monospace, monospace`;
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = font;
const pad = 3 * ratio;
canvas.width = Math.ceil(context.measureText(code).width + pad * 2);
canvas.height = Math.ceil(15 * ratio);
context.font = font;
context.textBaseline = 'middle';
context.lineJoin = 'round';
context.lineWidth = 3 * ratio;
context.strokeStyle = '#000';
context.fillStyle = '#fff';
context.strokeText(code, pad, canvas.height / 2);
context.fillText(code, pad, canvas.height / 2);
return {
image: canvas,
width: canvas.width / ratio,
height: canvas.height / ratio,
};
}
/** The initial bearing (degrees from north) of the great circle a → b. */
function bearing(a, b) {
const rad = Math.PI / 180;
const y = Math.sin((b.lon - a.lon) * rad) * Math.cos(b.lat * rad);
const x =
Math.cos(a.lat * rad) * Math.sin(b.lat * rad) -
Math.sin(a.lat * rad) *
Math.cos(b.lat * rad) *
Math.cos((b.lon - a.lon) * rad);
return (Math.atan2(y, x) / rad + 360) % 360;
}
const geodesic = (a, b) =>
new Cesium.EllipsoidGeodesic(
Cesium.Cartographic.fromDegrees(a.lon, a.lat),
Cesium.Cartographic.fromDegrees(b.lon, b.lat),
);
/** Points along the great circle from a to b, as far as `upTo` (0 to 1). */
function arc(a, b, steps = 64, upTo = 1) {
const line = geodesic(a, b);
const out = [];
const n = Math.max(2, Math.round(steps * upTo));
for (let i = 0; i <= n; i++) {
const c = line.interpolateUsingFraction((i / n) * upTo);
out.push(
Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, ROUTE_HEIGHT_M),
);
}
return out;
}
/**
* The point on the great circle from `from` to `to` nearest the craft. The
* craft is drawn there and the route split there, so the path stays one
* smooth arc: a craft a little off the direct line (vectors, airways, a
* detour) would otherwise bend it into a sharp corner.
*/
function onRoute(from, to, at) {
if (!at || !Number.isFinite(at.lat) || !Number.isFinite(at.lon)) return null;
const route = geodesic(from, to);
const here = Cesium.Cartesian3.fromDegrees(at.lon, at.lat);
const point = new Cesium.Cartesian3();
let best = null;
let bestDistance = Infinity;
const STEPS = 200;
for (let i = 0; i <= STEPS; i++) {
const c = route.interpolateUsingFraction(i / STEPS);
Cesium.Cartesian3.fromRadians(
c.longitude,
c.latitude,
0,
Cesium.Ellipsoid.WGS84,
point,
);
const d = Cesium.Cartesian3.distanceSquared(here, point);
if (d < bestDistance) {
bestDistance = d;
best = {
lat: Cesium.Math.toDegrees(c.latitude),
lon: Cesium.Math.toDegrees(c.longitude),
};
}
}
return best;
}
/**
* The plane's billboard pose, nose along `deg` from north: the icon's up is
* tied to the local north on the globe and turned from there, so it points
* the right way in this tilted view too.
*/
function planePose(at, deg) {
const position = Cesium.Cartesian3.fromDegrees(
at.lon,
at.lat,
ROUTE_HEIGHT_M,
);
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const north = Cesium.Matrix4.getColumn(frame, 1, new Cesium.Cartesian4());
return {
position,
rotation: -Cesium.Math.toRadians(deg),
alignedAxis: new Cesium.Cartesian3(north.x, north.y, north.z),
};
}
/**
* A flight's route on a small globe: the great circle from origin to
* destination, solid where it has flown and dashed ahead, the two airports
* marked with their codes, and a plane where the craft is now, pointing at
* the destination. On opening, the flown part draws out from the origin to
* the craft. The globe uses Cesium's bundled Natural Earth image, so it
* fetches no map tiles. It holds still, north up and framed on the route.
* @param {HTMLElement} container
* @param {{from: {code?: string, lat: number, lon: number},
* to: {code?: string, lat: number, lon: number},
* at?: {lat: number, lon: number}|null}} route
* @param {{onFailed?: () => void}} [events]
*/
function routePreview(container, route, { onFailed = () => {} } = {}) {
let widget = null;
let loop = null;
let { from, to } = route;
let plane = null;
let flownLine = null;
let aheadLine = null;
let removeGrow = null;
/** True while the plane flies in from the origin; moves wait for it. */
let flyingIn = false;
/** The craft's latest position, kept through the fly-in and the load. */
let latest = route.at;
const pose = (entity, where) => {
const next = planePose(where, bearing(where, to));
entity.position = next.position;
entity.billboard.rotation = next.rotation;
entity.billboard.alignedAxis = next.alignedAxis;
};
const draw = (atNow) => {
if (!widget) return;
const at = onRoute(from, to, atNow);
const { entities, scene } = widget;
removeGrow?.();
removeGrow = null;
entities.removeAll();
plane = flownLine = null;
const pin = (place, color) =>
entities.add({
position: Cesium.Cartesian3.fromDegrees(place.lon, place.lat),
point: {
pixelSize: 7,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.6),
outlineWidth: 1,
},
...(place.code
? {
billboard: {
...codeImage(place.code),
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -6),
},
}
: {}),
});
pin(from, CYAN.withAlpha(0.9));
pin(to, AMBER);
// Ahead of the craft, dashed; behind it, solid, drawing out on open.
aheadLine = entities.add({
polyline: {
positions: arc(at || from, to),
width: 1.5,
material: new Cesium.PolylineDashMaterialProperty({
color: AMBER.withAlpha(0.8),
dashLength: 10,
}),
arcType: Cesium.ArcType.NONE,
},
});
if (at) {
let progress = 0;
const flown = (flownLine = entities.add({
polyline: {
positions: new Cesium.CallbackProperty(
() => arc(from, at, 48, Math.max(0.02, progress)),
false,
),
width: 2.5,
material: new Cesium.PolylineGlowMaterialProperty({
color: CYAN,
glowPower: 0.25,
}),
arcType: Cesium.ArcType.NONE,
},
}));
// The plane starts at the origin and flies out along the flown line
// as it draws, arriving where the craft is now.
const first = planePose(from, bearing(from, to));
plane = entities.add({
position: first.position,
billboard: {
image: PLANE_ICON,
width: 26,
height: 26,
rotation: first.rotation,
alignedAxis: first.alignedAxis,
},
});
const leg = geodesic(from, at);
const ease = (x) => 1 - (1 - x) ** 3;
// The fly-in waits until the globe has drawn (its imagery loads a
// moment after the card opens), at most 1.5 s, so it is seen from the
// start. Under reduced motion it is there at once.
let began = reducedMotion() ? -Infinity : null;
const opened = performance.now();
flyingIn = true;
const grow = () => {
if (began === null) {
if (!scene.globe.tilesLoaded && performance.now() - opened < 1500)
return;
began = performance.now();
}
const raw = Math.min(1, (performance.now() - began) / 1600);
progress = ease(raw);
const c = leg.interpolateUsingFraction(progress);
pose(plane, {
lat: Cesium.Math.toDegrees(c.latitude),
lon: Cesium.Math.toDegrees(c.longitude),
});
if (raw >= 1) {
flyingIn = false;
flown.polyline.positions = arc(from, at, 48);
removeGrow?.();
removeGrow = null;
// The craft may have moved on while the plane flew in.
move(latest);
}
};
removeGrow = scene.preRender.addEventListener(grow);
}
// Frame the whole route, north up, looking down at a slight tilt; the
// view holds still so the plane and labels keep their bearings.
const points = [from, to, ...(at ? [at] : [])].map((p) =>
Cesium.Cartesian3.fromDegrees(p.lon, p.lat),
);
const sphere = Cesium.BoundingSphere.fromPoints(points);
const range = Math.max(1_800_000, sphere.radius * 3.2);
const center =
Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(sphere.center) ||
sphere.center;
widget.camera.lookAt(
center,
new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-62), range),
);
scene.requestRender();
};
try {
widget = createWidget(container, {
baseLayer: false,
skyAtmosphere: false,
contextOptions: { webgl: { alpha: true, antialias: true } },
});
const { scene } = widget;
scene.backgroundColor = Cesium.Color.TRANSPARENT;
scene.globe.baseColor = Cesium.Color.fromCssColorString('#0b1820');
scene.globe.showGroundAtmosphere = false;
scene.globe.enableLighting = false;
loop = renderLoopSwitch(widget);
} catch {
onFailed();
return { setActive() {}, update() {}, destroy() {} };
}
Cesium.TileMapServiceImageryProvider.fromUrl(
Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII'),
).then(
(imagery) => {
if (!widget) return;
const layer = widget.scene.imageryLayers.addImageryProvider(imagery);
// Dimmed and cooled, so the route reads over it.
layer.brightness = 0.55;
layer.saturation = 0.35;
layer.contrast = 1.1;
draw(latest);
},
() => widget && onFailed(),
);
function move(atNow) {
const at = onRoute(from, to, atNow);
if (!widget || !at || !plane || flyingIn) return;
pose(plane, at);
if (flownLine) flownLine.polyline.positions = arc(from, at, 48);
if (aheadLine) aheadLine.polyline.positions = arc(at, to);
widget.scene.requestRender();
}
return {
setActive: (active) => loop.set(active),
/**
* A new route redraws; the craft moving along it only moves its plane
* and the two lines, without replaying the opening draw.
*/
update(next) {
if (!widget) return;
latest = next.at;
if (next.from?.code !== from.code || next.to?.code !== to.code) {
({ from, to } = next);
draw(latest);
return;
}
move(latest);
},
destroy() {
removeGrow?.();
removeGrow = null;
const gone = widget;
widget = null;
destroyWidget(gone);
},
};
}
// ── The cockpit view ───────────────────────────────────────────────────
/** A floor for the eye, so a landed or taxiing craft is not underground. */
const MIN_EYE_M = 60;
/**
* What the crew sees: the view ahead from the aircraft's own position,
* height and heading, a little nose down, over Esri World Imagery (the
* app's keyless basemap) on a plain ellipsoid with the sky's haze. It draws
* only when asked: a still, moved along with the craft while it shows.
* @param {HTMLElement} container
* @param {{lat: number, lon: number, altitudeM?: number|null,
* heading?: number|null}} craft
* @param {{onFailed?: () => void}} [events]
*/
function cockpitPreview(container, craft, { onFailed = () => {} } = {}) {
let widget = null;
let loop = null;
let active = false;
let at = craft;
const place = () => {
if (!widget || !Number.isFinite(at?.lat) || !Number.isFinite(at?.lon))
return;
const height = Math.max(
MIN_EYE_M,
Number.isFinite(at.altitudeM) ? at.altitudeM : 0,
);
widget.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(at.lon, at.lat, height),
orientation: {
heading: Cesium.Math.toRadians(
Number.isFinite(at.heading) ? at.heading : 0,
),
pitch: Cesium.Math.toRadians(-9),
roll: 0,
},
});
widget.scene.requestRender();
};
try {
widget = createWidget(container, {
baseLayer: false,
requestRenderMode: true,
maximumRenderTimeChange: Infinity,
contextOptions: { webgl: { alpha: false, antialias: true } },
});
const { scene } = widget;
scene.globe.baseColor = Cesium.Color.fromCssColorString('#0b1820');
scene.globe.showGroundAtmosphere = true;
scene.fog.enabled = true;
scene.camera.frustum.fov = Cesium.Math.toRadians(70);
// Tiles arriving ask for a frame, so the still fills in as they load.
scene.globe.tileLoadProgressEvent.addEventListener(() =>
scene.requestRender(),
);
place();
// Hidden, it draws nothing at all, not even as tiles arrive.
loop = renderLoopSwitch(widget);
loop.set(active);
} catch {
onFailed();
return { setActive() {}, update() {}, destroy() {} };
}
createEsriImagery().then(
(imagery) => {
if (!widget) return;
widget.scene.imageryLayers.addImageryProvider(imagery);
widget.scene.requestRender();
},
() => widget && onFailed(),
);
return {
setActive(next) {
active = Boolean(next);
if (!widget) return;
loop.set(active);
if (active) place();
},
/** While it shows, the view keeps up with the craft. */
update(next) {
at = next;
if (active) place();
},
destroy() {
const gone = widget;
widget = null;
destroyWidget(gone);
},
};
}
/**
* The card previews, as the `cardPreviews` application hook hands them.
* @type {Readonly<{model: typeof modelPreview, route: typeof routePreview,
* cockpit: typeof cockpitPreview}>}
*/
export const cesiumCardPreviews = Object.freeze({
model: modelPreview,
route: routePreview,
cockpit: cockpitPreview,
});
+92 -12
View File
@@ -59,7 +59,15 @@ async function terrainProvider(spec, { worldDataToken }) {
throw new TypeError('Quantized-mesh terrain needs its url');
// Busy hosts are asked again as the keyless terrain is
// (`terrainRetry.js`); every tile's resource inherits the policy.
const policy = createTerrainRetryPolicy();
const policy = createTerrainRetryPolicy({
// One line per cooldown window, not per tile: a burst throttles dozens.
onThrottle: ({ statusCode, delayMs, inWindow }) => {
if (inWindow === 1)
console.warn(
`[MapStack] terrain answered ${statusCode}; retrying throttled tiles after ${Math.round(delayMs)} ms`,
);
},
});
const resource = new Cesium.Resource({
url: spec.url,
retryCallback: policy.retryCallback,
@@ -104,6 +112,19 @@ czm_material czm_getMaterial(czm_materialInput materialInput)
/** The last `surfaceVersion` any globe port handed out. */
let surfaceVersions = 0;
/** Each scene's photoreal tileset as a globe port holds it, shown or hidden. */
const photorealTilesets = new WeakMap();
/**
* The Cesium photoreal tileset a globe port over `scene` holds: shown, or
* hidden and kept to show again; null when it holds none. For QA scripts.
* @param {object} scene
* @returns {object | null}
*/
export function cesiumPhotorealOf(scene) {
return photorealTilesets.get(scene)?.() ?? null;
}
/**
* @param {object} widget A Cesium `CesiumWidget` or `Viewer`.
* @param {{capabilities: ReadonlySet<string>,
@@ -111,7 +132,8 @@ let surfaceVersions = 0;
* report?: (error: unknown) => void,
* credits?: import('../contract/credits').CreditsPort | null,
* credentials?: {googleApiKey?: string, googleTokens?: () => Promise<string>,
* worldDataToken?: string}}} options
* worldDataToken?: string},
* loadPhotoreal?: typeof loadPhotorealisticTileset}} options
* @returns {{port: import('../contract/globe').GlobePort, dispose: () => void}}
*/
export function createCesiumGlobe(
@@ -122,6 +144,8 @@ export function createCesiumGlobe(
report = uncaught,
credits = null,
credentials = {},
// Tests load their own.
loadPhotoreal = loadPhotorealisticTileset,
},
) {
const scene = widget.scene;
@@ -130,9 +154,17 @@ export function createCesiumGlobe(
// --- Base ------------------------------------------------------------------
/** The photoreal tileset this port loaded, if any. */
/** The photoreal tileset this port loaded, if any, and its spec. */
let photoreal = null;
let photorealSpec = null;
let photorealStatus = { route: 'none' };
/**
* The photoreal tileset last turned off, kept hidden with the spec and
* status it loaded with: that same spec shows it again at once, without
* loading it anew (Google counts each load).
*/
let parked = null;
photorealTilesets.set(scene, () => photoreal ?? parked?.tileset ?? null);
let photorealGen = 0;
let terrainGen = 0;
let baseGen = 0;
@@ -178,31 +210,74 @@ export function createCesiumGlobe(
worldDataToken: () => credentials.worldDataToken,
});
function removePhotoreal() {
if (!photoreal) return;
const tileset = photoreal;
photoreal = null;
// The layers draped on it move off before it takes them with it.
imagery.sync();
function destroyTileset(tileset) {
if (!tileset.isDestroyed() && !scene.primitives.remove(tileset))
tileset.destroy();
}
function removePhotoreal() {
if (!photoreal) return;
const tileset = photoreal;
photoreal = null;
photorealSpec = null;
// The layers draped on it move off before it takes them with it.
imagery.sync();
destroyTileset(tileset);
}
/** Hide the photoreal tileset, kept for its spec to show again. */
function parkPhotoreal() {
if (!photoreal) return;
if (parked) destroyTileset(parked.tileset);
parked = {
spec: photorealSpec,
status: photorealStatus,
tileset: photoreal,
};
photoreal.show = false;
photoreal = null;
photorealSpec = null;
imagery.sync();
}
/** Show the parked tileset again when `spec` is the one it loaded with. */
function unparkPhotoreal(spec) {
const kept = parked;
if (!kept || kept.spec !== spec || kept.tileset.isDestroyed()) return null;
parked = null;
removePhotoreal();
photoreal = kept.tileset;
photorealSpec = spec;
photoreal.show = true;
photorealStatus = kept.status;
imagery.sync();
requestRender('base');
return photorealStatus;
}
async function setPhotoreal(spec) {
const gen = ++photorealGen;
removePhotoreal();
photorealStatus = { route: 'none' };
if (!spec || !can('photoreal')) {
if (spec) removePhotoreal();
else parkPhotoreal();
photorealStatus = { route: 'none' };
requestRender('base');
return photorealStatus;
}
const shown = unparkPhotoreal(spec);
if (shown) return shown;
removePhotoreal();
if (parked) {
destroyTileset(parked.tileset);
parked = null;
}
photorealStatus = { route: 'none' };
// The spec's own route first: its key, else its tokens, else the
// renderer's credentials.
const googleApiKey =
spec.key ?? (spec.token ? '' : (credentials.googleApiKey ?? ''));
const token = spec.token ?? credentials.googleTokens;
const result = await loadPhotorealisticTileset(Cesium, {
const result = await loadPhotoreal(Cesium, {
googleApiKey,
// A renewal names the token it replaces.
googleTokens: token ? { token: (options) => token(options) } : null,
@@ -224,6 +299,7 @@ export function createCesiumGlobe(
};
} else {
photoreal = scene.primitives.add(result.tileset);
photorealSpec = spec;
photorealStatus = { route: ROUTES[result.route] ?? 'google' };
}
imagery.sync();
@@ -616,6 +692,10 @@ export function createCesiumGlobe(
if (disposed) return;
disposed = true;
photorealGen += 1;
if (parked) {
destroyTileset(parked.tileset);
parked = null;
}
terrainGen += 1;
baseGen += 1;
baseLoad?.abort();
+45 -1
View File
@@ -1,7 +1,11 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { createCesiumGlobe, markBaseTileset } from './globe.js';
import {
cesiumPhotorealOf,
createCesiumGlobe,
markBaseTileset,
} from './globe.js';
import { hookProvider, TILE_RETRY_DELAY_MS, xyzTileUrl } from './imagery.js';
const ALL = new Set([
@@ -805,3 +809,43 @@ test('hillshade shading owns a free globe material, follows the terrain, gives i
assert.equal(scene.globe.material, theirs);
dispose();
});
test('photoreal turned off is kept hidden, and the same spec shows it without loading it again', async () => {
const scene = fakeScene();
const loads = [];
const { port } = createCesiumGlobe(
{ scene },
{
capabilities: new Set(['photoreal']),
requestRender: () => {},
credentials: { worldDataToken: 'ion' },
loadPhotoreal: async (_sdk, credentials) => {
loads.push(credentials);
return { tileset: fakeTileset(), route: 'direct', errors: [] };
},
},
);
const spec = { provider: 'google', key: 'key', fallback: true };
assert.deepEqual(await port.setPhotoreal(spec), { route: 'google' });
assert.equal(loads.length, 1);
assert.equal(loads[0].googleApiKey, 'key');
assert.equal(loads[0].cesiumToken, 'ion');
const first = cesiumPhotorealOf(scene);
assert.equal(first.show, true);
assert.deepEqual(await port.setPhotoreal(null), { route: 'none' });
assert.equal(first.isDestroyed(), false, 'kept');
assert.equal(first.show, false, 'hidden');
assert.equal(cesiumPhotorealOf(scene), first, 'QA scripts still read it');
assert.deepEqual(await port.setPhotoreal(spec), { route: 'google' });
assert.equal(loads.length, 1, 'not loaded again');
assert.equal(cesiumPhotorealOf(scene), first);
assert.equal(first.show, true);
await port.setPhotoreal(null);
await port.setPhotoreal({ provider: 'google', key: 'other' });
assert.equal(loads.length, 2, 'another spec loads its own');
assert.equal(first.isDestroyed(), true, 'the kept one goes');
assert.notEqual(cesiumPhotorealOf(scene), first);
});
+3 -2
View File
@@ -59,10 +59,11 @@ export async function loadPhotorealisticTileset(
export function createGoogleDirectTileset(Cesium, key) {
key = clean(key);
if (!key) throw new Error('Google 3D requires an explicit browser key');
// Tiles keep drawing their own texture while draped weather loads.
// Tiles keep drawing their own texture while draped weather loads, and
// clamped marks land on them, as on the token routes' tiles.
return Cesium.createGooglePhotorealistic3DTileset(
{ key, onlyUsingWithGoogleGeocoder: true },
{ asynchronouslyLoadImagery: true },
{ asynchronouslyLoadImagery: true, enableCollision: true },
);
}
+5 -2
View File
@@ -32,6 +32,7 @@ import {
videoProvider,
} from './imageryFrames.js';
import { withTileRequestHook } from './tileRequests.js';
import { createIonImagery } from './mapImagery.js';
const SPLITS = { none: 'NONE', left: 'LEFT', right: 'RIGHT' };
const DRAPES = new Set(['surface', 'objects', 'all']);
@@ -157,9 +158,11 @@ export function providerFor(spec, { worldDataToken } = {}) {
throw new TypeError(
'World imagery needs the renderer’s world data token',
);
return Cesium.IonImageryProvider.fromAssetId(
// Bing through ion, its tiles over HTTPS on any page, with ion's
// credits, as the map stacks have always drawn it.
return createIonImagery(
WORLD_ASSETS[spec.worldStyle ?? 'aerial'] ?? WORLD_ASSETS.aerial,
{ accessToken },
accessToken,
);
}
// The app's own: the vector base's tiles, painted from its style.
+2 -2
View File
@@ -4,7 +4,6 @@
* World Imagery and Cesium ion's world imagery (Bing over HTTPS).
*/
import * as Cesium from 'cesium';
import { ESRI_IMAGERY_CREDIT } from '../../maps/attribution.js';
export { ESRI_ATTRIBUTION_HTML } from '../../maps/attribution.js';
@@ -19,7 +18,8 @@ export function createEsriImagery() {
return Cesium.ArcGisMapServerImageryProvider.fromUrl(
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
{
credit: ESRI_IMAGERY_CREDIT,
credit:
'Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community',
enablePickFeatures: false,
},
);
+1 -1
View File
@@ -329,7 +329,7 @@ test('both Google 3D routes keep tiles drawing while draped imagery loads', asyn
assert.equal(await createGoogleIonTileset(sdk, 'token'), 'ion');
assert.deepEqual(calls[0], [
{ key: 'key', onlyUsingWithGoogleGeocoder: true },
{ asynchronouslyLoadImagery: true },
{ asynchronouslyLoadImagery: true, enableCollision: true },
]);
assert.equal(calls[1][0].id, 2275207);
assert.equal(calls[1][0].accessToken, 'token');
-69
View File
@@ -67,75 +67,6 @@ export interface ApplicationHooks {
allowReload: boolean;
store: RenderFailureStore;
}): () => void;
/** The Context card's previews of a picked aircraft. */
cardPreviews?: CardPreviews;
}
/**
* Previews the Context card draws into an element of its own. Each returns
* at once; one that cannot be made calls its `onFailed`.
*/
export interface CardPreviews {
/**
* A model turning on its own, from its GLB's bytes, starting to face
* `heading` (degrees); `viewRange` is the camera's distance in bounding
* radii. `onPhase` says when it turns to wire for its scan and back;
* `onCycle` when a look and its scan end, with the drawing time they took.
*/
model(
container: HTMLElement,
model: {
gltf: Uint8Array | ArrayBuffer;
basePath?: string;
heading?: number;
viewRange?: number;
},
events?: {
onPhase?(phase: 'plain' | 'scan'): void;
onCycle?(ms: number): void;
onFailed?(): void;
},
): CardPreview<void>;
/** A flight's route from `from` to `to` on a small globe, the craft `at`. */
route(
container: HTMLElement,
route: CardRoute,
events?: { onFailed?(): void },
): CardPreview<CardRoute>;
/** The view ahead from an aircraft's position, height and heading. */
cockpit(
container: HTMLElement,
craft: CardCraft,
events?: { onFailed?(): void },
): CardPreview<CardCraft>;
}
/** A place on a card's route: an airport's code and position, degrees. */
export interface CardPlace {
code?: string;
lat: number;
lon: number;
}
export interface CardRoute {
from: CardPlace;
to: CardPlace;
at?: { lat: number; lon: number } | null;
}
/** An aircraft's position (degrees), height (metres) and heading (degrees). */
export interface CardCraft {
lat: number;
lon: number;
altitudeM?: number | null;
heading?: number | null;
}
/** One preview: hidden, it rests on its last frame. */
export interface CardPreview<Values> {
setActive(active: boolean): void;
update(values: Values): void;
destroy(): void;
}
/** Where a renderer's failure notice is published for the application to show. */
+1 -1
View File
@@ -4,7 +4,7 @@
* the same tiles, from the same host, that GEV's Esri map draws (and credits
* on screen); no other host is asked.
*/
import { ESRI_TILES } from '../maps/attribution.js';
import { ESRI_TILES } from '../maps/globeEngine.js';
const WIDTH = 320;
const HEIGHT = 180;
+1 -4
View File
@@ -6,8 +6,7 @@ import {
isTrackingClickGesture,
isTrackingSelectionGesture,
} from '../data/trackingClickGesture.js';
import { applicationHooksOf } from '../render/applicationHooks.js';
import { findCamera, rendererOf } from '../render/rendererOf.js';
import { findCamera } from '../render/rendererOf.js';
import { useCockpitStore } from './stores/cockpit.js';
import { useEntityCardStore } from './stores/entityCard.js';
import { useOmnibarStore } from './stores/omnibar.js';
@@ -201,8 +200,6 @@ export function installEntityContext({
letGo,
isOpen,
regionalBrief,
// The renderer's card previews, when it has them.
previews: () => applicationHooksOf(rendererOf(viewer)).cardPreviews ?? null,
ask,
askText,
cockpit,
-3
View File
@@ -304,8 +304,6 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
? shell.value.regionalBrief(lat, lon)
: Promise.resolve(null);
const canFollow = () => Boolean(shell.value?.canFollow?.(card.value));
/** The renderer's card previews (`CardPreviews`), or null without them. */
const previews = () => shell.value?.previews?.() ?? null;
/** Loaded items whose name or id matches typed text, for the omnibar. */
const search = (query, options) =>
shell.value
@@ -327,7 +325,6 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
follow,
ask,
readBrief,
previews,
canFollow,
isFollowing,
following,
File diff suppressed because it is too large. Load diff
-130
View File
@@ -1,130 +0,0 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { aircraftModelSpec, fleetModelSet, fleetModelSetLoading } from '../../../data/fleetModels.js';
import { t } from '../../../i18n/index.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
import PreviewHud from './PreviewHud.vue';
// The selected aircraft's own model, turning slowly at the top of its card:
// the same fleet model the globe draws for its type, from the bytes loaded at
// startup, so nothing is fetched when a card opens. The renderer draws it in
// a small scene of its own (the `cardPreviews` hook); this tile lays the
// callouts and HUD over it. As it turns it changes look: a whole rotation as
// it is, then a short wireframe scan, then round again.
//
// While it turns, one callout at a time sits in the frame's top-left corner,
// HUD-style, telling something worked out about the flight (phase, flight
// level, Mach, what its squawk means, signal age). Each runs three states:
// enter 0-2.3 s the label and value slide in;
// hold 2.3-5.2 s a thin timer under the value fills;
// exit 5.2-6.2 s the text fades; a short gap, then the next one.
const props = defineProps({
/** `{typeCode, category, callsign}`: what picks the aircraft's fleet model. */
aircraft: { type: Object, default: null },
/** The aircraft's heading, so the turntable starts facing its way. */
heading: { type: Number, default: 0 },
/** `[{label, value}]` figures to call out, in order. */
callouts: { type: Array, default: () => [] },
/** Whether the tile is the one showing; a hidden one stops drawing. */
active: { type: Boolean, default: true },
});
const emit = defineEmits(['failed', 'cycle']);
const store = useEntityCardStore();
const host = ref(null);
const failed = ref(false);
watch(failed, (now) => now && emit('failed'));
const phase = ref('plain');
let preview = null;
// One callout's whole life: enter 2.3 s + hold 2.9 s + exit 1.0 s + 0.3 s gap.
const CYCLE_MS = 6500;
const CALLOUT_TIMING = { enter: 2300, leave: 1000 };
const page = ref(0);
let cycle = null;
const shown = computed(() => {
const list = props.callouts;
if (!list.length) return null;
const index = page.value % list.length;
return { ...list[index], index, total: list.length };
});
const pad = (n) => String(n).padStart(2, '0');
/** The fleet model's spec and bytes, or null when it has none. */
function fleetModel(set, aircraft) {
if (!set || !aircraft) return null;
const spec = aircraftModelSpec(set, aircraft);
const gltf = set.bytes.get(spec.model);
return gltf ? { gltf, basePath: spec.url } : null;
}
let showing = 0;
async function show() {
preview?.destroy();
preview = null;
phase.value = 'plain';
const asked = ++showing;
// A card opened before the Flights layer's model set has loaded waits for
// that load rather than giving up.
let set = fleetModelSet();
if (!set) set = await fleetModelSetLoading()?.catch(() => null);
if (asked !== showing) return;
const previews = store.previews();
const model = fleetModel(set, props.aircraft);
if (!previews?.model || !model || !host.value) {
failed.value = true;
return;
}
preview = previews.model(
host.value,
{ ...model, heading: props.heading },
{
onPhase: (next) => (phase.value = next),
onCycle: (ms) => emit('cycle', ms),
onFailed: () => (failed.value = true),
},
);
preview.setActive(props.active);
}
onMounted(() => {
show();
// Under reduced motion the first set of callouts stays.
const still = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
if (!still) cycle = setInterval(() => page.value++, CYCLE_MS);
});
watch(
() => {
const a = props.aircraft;
return `${a?.typeCode ?? ''}|${a?.category ?? ''}|${a?.callsign ?? ''}`;
},
show,
);
watch(
() => props.active,
(active) => preview?.setActive(active),
);
onBeforeUnmount(() => {
showing++;
clearInterval(cycle);
preview?.destroy();
preview = null;
});
</script>
<template>
<div v-if="!failed" class="aircraft-hero">
<div ref="host" class="aircraft-hero__scene" aria-hidden="true"></div>
<PreviewHud variant="model" />
<Transition name="aircraft-hero-legend">
<p v-if="phase === 'scan'" class="aircraft-hero__scan" aria-hidden="true">{{ t('Scanning') }}</p>
</Transition>
<Transition name="aircraft-hero-callout" mode="out-in" :duration="CALLOUT_TIMING">
<div v-if="shown" :key="page" class="aircraft-hero__callout">
<span class="aircraft-hero__label">{{ shown.label }}<em>{{ pad(shown.index + 1) }} / {{ pad(shown.total) }}</em></span>
<strong class="aircraft-hero__value">{{ shown.value }}</strong>
<i class="aircraft-hero__timer" aria-hidden="true"></i>
</div>
</Transition>
</div>
</template>
+6 -19
View File
@@ -2,8 +2,7 @@
import { computed, ref, watch } from 'vue';
import { formatNumber, t } from '../../../i18n/index.js';
// A figure as a filled graph (an aircraft's altitude, the camera's height, a
// satellite's altitude and speed):
// A height as a filled graph (an aircraft's altitude, the camera's height):
// each reading since it opened, left to right. The scale fits the readings (never less than about
// 2,000 ft tall), so a climb or descent shows as a slope, and the fill
// fades from the line down to the baseline.
@@ -14,11 +13,7 @@ const props = defineProps({
tick: { type: Number, default: 0 },
/** The caption; 'Altitude' when not given. */
label: { type: String, default: '' },
/**
* 'feet' for aircraft; 'metric' reads in metres and kilometres on a log
* scale (the camera); 'km' is a height in kilometres and 'km/s' a speed
* (given in m/s), both on a straight scale (a satellite).
*/
/** 'feet' for aircraft; 'metric' reads in metres and kilometres. */
unit: { type: String, default: 'feet' },
/** Only the caption, the current figure and the line: no scale or change. */
compact: { type: Boolean, default: false },
@@ -48,14 +43,7 @@ const metric = (m) =>
: m >= 1000
? t('{n} km', { n: formatNumber(m / 1000, { minimumFractionDigits: 1, maximumFractionDigits: 1 }) })
: t('{n} m', { n: number(Math.round(m)) });
const SHOW = {
metric,
km: (m) => t('{n} km', { n: number(Math.round(m / 100) / 10) }),
'km/s': (m) => t('{n} km/s', { n: formatNumber(m / 1000, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }),
};
const shown = (m) => (SHOW[props.unit] || ((value) => t('{n} ft', { n: number(feet(value)) })))(m);
/** The least each scale spans, so a steady figure still reads as a line. */
const LEAST = { feet: MIN_RANGE_M, km: 2000, 'km/s': 20 };
const shown = (m) => (props.unit === 'metric' ? metric(m) : t('{n} ft', { n: number(feet(m)) }));
const graph = computed(() => {
const list = readings.value;
@@ -72,7 +60,7 @@ const graph = computed(() => {
const low = Math.min(...heights);
// The least the scale spans: about 2,000 ft for aircraft, half a decade
// for the camera.
const least = log ? 0.5 : LEAST[props.unit] || MIN_RANGE_M;
const least = log ? 0.5 : MIN_RANGE_M;
const pad = Math.max((least - (high - low)) / 2, (high - low) * 0.15);
const bottom = Math.max(0, low - pad);
const top = Math.max(high + pad, bottom + least);
@@ -83,9 +71,8 @@ const graph = computed(() => {
const points = list.length > 1 ? list.map((item) => [x(item.at), y(item.m)]) : [[0, y(first.m)], [WIDTH, y(first.m)]];
const line = points.map(([px, py], index) => `${index ? 'L' : 'M'}${px.toFixed(2)} ${py.toFixed(2)}`).join(' ');
const moved = last.m - first.m;
const feetScale = !SHOW[props.unit];
const change = feetScale ? feet(last.m) - feet(first.m) : Math.abs(moved) >= Math.max(1, last.m * (props.unit === 'metric' ? 0.005 : 0.0005)) ? moved : 0;
const changeText = feetScale ? t('{n} ft', { n: number(Math.abs(change)) }) : shown(Math.abs(moved));
const change = props.unit === 'metric' ? (Math.abs(moved) >= Math.max(1, last.m * 0.005) ? moved : 0) : feet(last.m) - feet(first.m);
const changeText = props.unit === 'metric' ? metric(Math.abs(moved)) : t('{n} ft', { n: number(Math.abs(change)) });
const minutes = Math.floor((last.at - first.at) / 60_000);
return {
line,
+7 -160
View File
@@ -1,14 +1,10 @@
<script setup>
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { computed, nextTick, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { formatNumber, t } from '../../../i18n/index.js';
import { factFigure, factLabel, factValue, sayWords, useEntityCardStore } from '../../stores/entityCard.js';
import AircraftModelHero from './AircraftModelHero.vue';
import SatelliteGroundView from './SatelliteGroundView.vue';
import FlightCockpitView from './FlightCockpitView.vue';
import AltitudeGraph from './AltitudeGraph.vue';
import { contextNeedle, contextSearchText, matchesContextSearch } from '../../contextSearch.js';
import RouteGlobe from './RouteGlobe.vue';
import CctvPreview from './CctvPreview.vue';
import { useCctvStore } from '../../stores/cctv.js';
import SpotConditions from './SpotConditions.vue';
@@ -93,31 +89,20 @@ const ageText = computed(() => {
// depth; a fire's power), in that order. The rest stay in the grid. An
// aircraft's altitude is left out: its graph already leads with the figure.
const altitudeGraphed = computed(() => card.value?.kind === 'aircraft' && Number.isFinite(card.value?.altitudeM));
// A satellite graphs its altitude and its speed, and leaves both out of the
// tiles and the grid.
const orbitGraphed = computed(() => card.value?.kind === 'satellite' && Number.isFinite(card.value?.altitudeM));
const graphedFields = computed(() => (orbitGraphed.value ? ['altitudeM', 'speedMps'] : altitudeGraphed.value ? ['altitudeM'] : []));
const tiles = computed(() => {
const facts = card.value?.facts || [];
return (card.value?.headline || [])
.filter((field) => !graphedFields.value.includes(field))
.filter((field) => !(altitudeGraphed.value && field === 'altitudeM'))
.map((field) => facts.find((fact) => fact.field === field))
.filter(Boolean)
.slice(0, 3);
});
const restFacts = computed(() => {
const shown = new Set(tiles.value.map((fact) => fact.field));
for (const field of graphedFields.value) shown.add(field);
if (altitudeGraphed.value) shown.add('altitudeM');
return (card.value?.facts || []).filter((fact) => !shown.has(fact.field));
});
// What the turning model's callout says: what can be worked out about the
// flight (its phase, flight level, Mach, what its squawk means, how fresh its
// signal is), which the facts below don't already show.
const callouts = computed(() =>
(card.value?.insights || []).map((item) => ({ label: t(item.label), value: sayWords(item.words, item.value) })),
);
// The line under the name: who runs it and what it is. The layer is already
// named on the line above the title.
@@ -201,116 +186,10 @@ watch(
{ immediate: true },
);
// The hero tile at the top of every card. A flight shows its photo, its route
// on a small globe, its 3D model and the view from its cockpit; a vessel, its
// photo; a satellite, the ground beneath it; a camera, its latest frame.
// The globe, model and cockpit view are the renderer's (`store.previews()`).
// The hero tile at the top of every card. A camera shows its latest frame.
// Anything else gets a quiet placeholder with its icon and its headline
// figures until it has imagery of its own. Previews stay mounted so switching
// shows the next one at once.
const routeFailed = ref(false);
const routeKnown = computed(() => Boolean(card.value?.route?.fromAt && card.value?.route?.toAt) && !routeFailed.value);
const modelFailed = ref(false);
const cockpitFailed = ref(false);
const hasPosition = computed(() => Number.isFinite(card.value?.lat) && Number.isFinite(card.value?.lon));
const cockpitKnown = computed(() => card.value?.kind === 'aircraft' && hasPosition.value && !cockpitFailed.value);
const modelKnown = computed(() => Boolean(card.value?.aircraftModel) && !modelFailed.value);
const preview = ref(null);
// The photo the item's layer looked up (Planespotters for a tracked
// airliner, Open Vessel Photos for a selected vessel), with its credit.
const failedPhoto = ref('');
const photo = computed(() => {
const found = card.value?.photo;
if (!found?.src || found.src === failedPhoto.value) return null;
const { photographer, licence } = found;
const credit = licence
? photographer
? t('Photo: {photographer} · {licence}', { photographer, licence })
: t('Photo · {licence}', { licence })
: photographer
? t('Photo © {photographer}', { photographer })
: '';
return { ...found, credit };
});
const photoAvailable = computed(() => Boolean(photo.value));
const onPhotoError = (event) => (failedPhoto.value = event.currentTarget.getAttribute('src'));
watch(() => props.withContacts, () => (preview.value = null));
// The model and the cockpit view take turns: after each of the model's
// cycles, the view ahead from the cockpit shows for as long as that cycle
// took. It is made only once it is first needed. A manual selection holds the
// preview until another view or another item is selected.
const modelTurn = ref('model');
const cockpitMade = ref(false);
const activeFlightPreview = computed(() => {
const chosen = preview.value;
if (photoAvailable.value && (chosen === null || chosen === 'photo')) return 'photo';
if (cockpitKnown.value && (chosen === 'cockpit' || modelTurn.value === 'other')) return 'cockpit';
if (routeKnown.value && (chosen !== 'model' || !modelKnown.value)) return 'route';
if (modelKnown.value) return 'model';
return photoAvailable.value ? 'photo' : null;
});
let turnTimer = 0;
function onCockpitFailed() {
cockpitFailed.value = true;
if (preview.value === 'cockpit') preview.value = null;
clearTimeout(turnTimer);
modelTurn.value = 'model';
}
function showOtherView(ms) {
if (preview.value !== null || !hasPosition.value) return;
if (!cockpitKnown.value || activeFlightPreview.value === 'photo') return;
clearTimeout(turnTimer);
modelTurn.value = 'other';
cockpitMade.value = true;
turnTimer = setTimeout(() => (modelTurn.value = 'model'), Math.min(Math.max(ms, 4000), 30000));
}
const heroKind = computed(() => {
if (card.value?.kind === 'aircraft' && (photoAvailable.value || routeKnown.value || modelKnown.value)) return 'flight';
if (card.value?.kind === 'vessel' && photoAvailable.value) return 'photo';
if (card.value?.layerId === 'satellites' && hasPosition.value) return 'satellite';
if (card.value?.layerId === 'cctv') return 'camera';
return 'none';
});
// The route globe has no cycle of its own: it shows for ROUTE_TURN_MS,
// then the cockpit view shows for as long, and round again.
const ROUTE_TURN_MS = 20_000;
let routeTimer = 0;
watch(
[heroKind, activeFlightPreview, preview, cockpitKnown, () => card.value?.key],
() => {
clearTimeout(routeTimer);
// Under reduced motion the views do not swap by themselves (the model
// shows no scan there either, so it never hands over).
if (globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) return;
if (preview.value === null && cockpitKnown.value && heroKind.value === 'flight' && activeFlightPreview.value === 'route')
routeTimer = setTimeout(() => showOtherView(ROUTE_TURN_MS), ROUTE_TURN_MS);
},
{ immediate: true },
);
// Picking a preview shows it at once, ending the cockpit view's turn.
function choosePreview(which) {
clearTimeout(turnTimer);
modelTurn.value = 'model';
preview.value = which;
if (which === 'cockpit') cockpitMade.value = true;
}
onBeforeUnmount(() => {
clearTimeout(turnTimer);
clearTimeout(routeTimer);
});
watch(
() => card.value?.key,
() => {
preview.value = null;
routeFailed.value = false;
modelFailed.value = false;
cockpitFailed.value = false;
clearTimeout(turnTimer);
modelTurn.value = 'model';
cockpitMade.value = false;
},
);
// figures until it has imagery of its own.
const heroKind = computed(() => (card.value?.layerId === 'cctv' ? 'camera' : 'none'));
// Things that move are read again only after they have gone a fair way, so
// following a jet does not ask for the weather every few seconds.
@@ -347,35 +226,7 @@ watch(
<Transition name="entity-card">
<section v-if="card" id="entity-card" class="entity-card" :aria-label="t('Selected on the map')" :data-layer="card.layerId">
<div class="entity-hero" :data-hero="heroKind">
<template v-if="heroKind === 'flight'">
<a
v-if="photoAvailable"
:key="photo.src"
class="entity-hero__layer entity-hero__photo"
:class="{ 'is-shown': activeFlightPreview === 'photo' }"
:href="photo.link || undefined"
target="_blank"
rel="noopener"
>
<img :src="photo.src" :alt="t('Photo of {name}', { name: shownTitle })" v-on="{ error: onPhotoError }" />
<small v-if="photo.credit">{{ photo.credit }}</small>
</a>
<RouteGlobe v-if="routeKnown" :key="`route-${card.key}`" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'route' }" :active="activeFlightPreview === 'route'" :from="card.route.fromAt" :to="card.route.toAt" :at="{ lat: card.lat, lon: card.lon }" @failed="routeFailed = true" />
<AircraftModelHero v-if="modelKnown" :key="card.key" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'model' }" :active="activeFlightPreview === 'model'" :aircraft="card.aircraftModel" :heading="card.heading || 0" :callouts="callouts" @failed="modelFailed = true" @cycle="showOtherView" />
<FlightCockpitView v-if="cockpitMade && cockpitKnown" :key="`cockpit-${card.key}`" class="entity-hero__layer" :class="{ 'is-shown': activeFlightPreview === 'cockpit' }" :active="activeFlightPreview === 'cockpit'" :lat="card.lat" :lon="card.lon" :altitude-m="card.altitudeM" :heading="card.heading" :speed-mps="card.speedMps" @failed="onCockpitFailed" />
<div v-if="cockpitKnown || (routeKnown && modelKnown) || (photoAvailable && (routeKnown || modelKnown))" class="entity-card__preview-switch" role="group" :aria-label="t('Preview')">
<button v-if="photoAvailable" type="button" :class="{ active: activeFlightPreview === 'photo' }" :aria-pressed="String(activeFlightPreview === 'photo')" :aria-label="t('Photos')" :title="t('Photos')" @click="choosePreview('photo')"><span class="material-symbols-outlined" aria-hidden="true">photo_camera</span></button>
<button v-if="routeKnown" type="button" :class="{ active: activeFlightPreview === 'route' }" :aria-pressed="String(activeFlightPreview === 'route')" :aria-label="t('Route')" :title="t('Route')" @click="choosePreview('route')"><span class="material-symbols-outlined" aria-hidden="true">timeline</span></button>
<button v-if="modelKnown" type="button" :class="{ active: activeFlightPreview === 'model' }" :aria-pressed="String(activeFlightPreview === 'model')" :title="t('3D model')" @click="choosePreview('model')">{{ t('3D') }}</button>
<button v-if="cockpitKnown" type="button" :class="{ active: activeFlightPreview === 'cockpit' }" :aria-pressed="String(activeFlightPreview === 'cockpit')" :aria-label="t('Cockpit view')" :title="t('Cockpit view')" @click="choosePreview('cockpit')"><span class="material-symbols-outlined" aria-hidden="true">visibility</span></button>
</div>
</template>
<a v-else-if="heroKind === 'photo'" :key="photo.src" class="entity-hero__layer entity-hero__photo is-shown" :href="photo.link || undefined" target="_blank" rel="noopener">
<img :src="photo.src" :alt="t('Photo of {name}', { name: shownTitle })" v-on="{ error: onPhotoError }" />
<small v-if="photo.credit">{{ photo.credit }}</small>
</a>
<SatelliteGroundView v-else-if="heroKind === 'satellite'" :key="`ground-${card.key}`" class="entity-hero__layer is-shown" active :lat="card.lat" :lon="card.lon" />
<CctvPreview v-else-if="heroKind === 'camera'" :camera-id="card.identity?.id || ''" />
<CctvPreview v-if="heroKind === 'camera'" :camera-id="card.identity?.id || ''" />
<!-- No imagery for it yet: its icon, with its headline figures beside it. -->
<div v-else class="entity-hero__placeholder" :class="{ 'entity-hero__placeholder--bare': props.withContacts || !tiles.length }">
<span class="material-symbols-outlined entity-hero__glyph" aria-hidden="true">{{ card.icon }}</span>
@@ -427,10 +278,6 @@ watch(
<span>{{ routePlaces.to }}</span>
</p>
<AltitudeGraph v-if="altitudeGraphed" v-show="!props.withContacts" :key="`altitude:${card.key}`" :altitude-m="lost ? null : card.altitudeM" :tick="tick" />
<template v-if="orbitGraphed">
<AltitudeGraph :key="`orbit-altitude:${card.key}`" :altitude-m="lost ? null : card.altitudeM" :tick="tick" unit="km" />
<AltitudeGraph v-if="Number.isFinite(card.speedMps)" :key="`orbit-speed:${card.key}`" :altitude-m="lost ? null : card.speedMps" :tick="tick" unit="km/s" :label="t('Speed')" />
</template>
<p
v-if="card.route && !card.route.verified"
class="entity-card__route-note"
-85
View File
@@ -1,85 +0,0 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { formatNumber, t } from '../../../i18n/index.js';
import { ESRI_IMAGERY_CREDIT } from '../../../maps/attribution.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
import PreviewHud from './PreviewHud.vue';
// What the crew sees: the view ahead from the aircraft's own position,
// height and heading, a little nose down, over Esri World Imagery. The
// renderer draws it (the `cardPreviews` hook) only when asked: a still,
// moved along with the craft while it shows. It takes turns with the turning
// model. Speed and altitude ride on tapes either side, as on a head-up
// display: the ticks roll as the figures change, with the figure boxed in
// the middle. Its credit line sits in the corner.
const props = defineProps({
lat: { type: Number, default: null },
lon: { type: Number, default: null },
/** Height above the ellipsoid, metres. */
altitudeM: { type: Number, default: null },
/** Degrees from north. */
heading: { type: Number, default: null },
/** Ground speed, metres a second. */
speedMps: { type: Number, default: null },
/** Whether the view is the one showing. */
active: { type: Boolean, default: false },
});
const emit = defineEmits(['failed']);
const store = useEntityCardStore();
const host = ref(null);
let preview = null;
const craft = () => ({ lat: props.lat, lon: props.lon, altitudeM: props.altitudeM, heading: props.heading });
onMounted(() => {
const previews = store.previews();
if (!previews?.cockpit || !host.value) {
emit('failed');
return;
}
preview = previews.cockpit(host.value, craft(), { onFailed: () => emit('failed') });
preview.setActive(props.active);
});
// While it shows, the view keeps up with the craft as the card refreshes.
watch(
() => [props.lat, props.lon, props.altitudeM, props.heading],
() => preview?.update(craft()),
);
watch(
() => props.active,
(active) => preview?.setActive(active),
);
onBeforeUnmount(() => {
preview?.destroy();
preview = null;
});
// The tapes: one tick every 10 kt and every 100 ft, 8 px apart; the ticks
// roll by the remainder, so a change in the figure moves them.
const TICK_PX = 8;
const knots = computed(() => (Number.isFinite(props.speedMps) ? Math.round(props.speedMps * 1.94384) : null));
const altFeet = computed(() => (Number.isFinite(props.altitudeM) ? Math.round(props.altitudeM * 3.28084) : null));
const feet = computed(() => (altFeet.value === null ? '' : t('{n} ft', { n: formatNumber(Math.round(altFeet.value / 100) * 100) })));
const roll = (value, per) => (value === null ? 0 : ((value % per) / per) * TICK_PX);
const speedRoll = computed(() => `${roll(knots.value, 10)}px`);
const altRoll = computed(() => `${roll(altFeet.value, 100)}px`);
const course = computed(() => (Number.isFinite(props.heading) ? `${String(Math.round(props.heading) % 360).padStart(3, '0')}°` : ''));
</script>
<template>
<div class="flight-cockpit" aria-hidden="true">
<div ref="host" class="flight-cockpit__scene"></div>
<PreviewHud variant="cockpit" :running="active" />
<span class="flight-cockpit__horizon"><i></i></span>
<span v-if="knots !== null" class="flight-cockpit__tape flight-cockpit__tape--speed">
<i class="flight-cockpit__ticks" :style="{ backgroundPositionY: speedRoll }"></i>
<b>{{ formatNumber(knots) }}</b><em>{{ t('KT') }}</em>
</span>
<span v-if="altFeet !== null" class="flight-cockpit__tape flight-cockpit__tape--alt">
<i class="flight-cockpit__ticks" :style="{ backgroundPositionY: altRoll }"></i>
<b>{{ formatNumber(altFeet) }}</b><em>{{ t('FT') }}</em>
</span>
<span class="flight-cockpit__label">{{ t('Cockpit view') }}<strong>{{ [feet, course].filter(Boolean).join(' · ') }}</strong></span>
<span class="flight-cockpit__credit">{{ ESRI_IMAGERY_CREDIT }}</span>
</div>
</template>
-93
View File
@@ -1,93 +0,0 @@
<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
// Small moving HUD marks laid over a card's preview, for look only: corner
// brackets, a ruler down the right edge with a marker riding it, a tick
// scale crawling along the bottom, a signal meter and a blinking dot at the
// top right, and a slow dashed ring round the centre with its four ticks.
// The ground view instead lays a square grid over the image, with cells lit
// one by one at random, each fading as the next lights, and a scan line
// sweeping down. Nothing here takes the pointer or says
// anything; it all stops under reduced motion.
const props = defineProps({
/** 'model' over the turning craft, 'ground' over the view beneath. */
variant: { type: String, default: 'model' },
/** Whether the preview is showing; the grid scan steps only while it is. */
running: { type: Boolean, default: true },
});
const CELL = 22;
const STEP_MS = 260;
const TRAIL = 4;
const root = ref(null);
const grid = ref({ cols: 0, rows: 0, left: 0, top: 0 });
const cells = ref([]);
let timer = 0;
let lit = [];
let serial = 0;
function measure() {
const box = root.value?.getBoundingClientRect();
if (!box?.width) return false;
const cols = Math.floor(box.width / CELL);
const rows = Math.floor(box.height / CELL);
// The grid is centred in the view.
grid.value = { cols, rows, left: (box.width - cols * CELL) / 2, top: (box.height - rows * CELL) / 2 };
return cols > 0 && rows > 0;
}
// Each step lights a random cell (never the one just lit) and dims the
// ones before it, so a few faint cells fade out behind the newest.
function step() {
if (!grid.value.cols && !measure()) return;
const { cols, rows, left, top } = grid.value;
let col;
let row;
do {
col = Math.floor(Math.random() * cols);
row = Math.floor(Math.random() * rows);
} while (cols * rows > 1 && lit[0]?.col === col && lit[0]?.row === row);
lit = [{ key: ++serial, col, row }, ...lit].slice(0, TRAIL);
cells.value = lit.map((cell, back) => ({
key: cell.key,
x: left + cell.col * CELL,
y: top + cell.row * CELL,
fade: 1 - back / TRAIL,
}));
}
function sync() {
clearInterval(timer);
timer = 0;
const still = globalThis.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
if (props.variant === 'ground' && props.running && !still) {
measure();
timer = setInterval(step, STEP_MS);
}
}
onMounted(sync);
watch(() => props.running, sync);
onBeforeUnmount(() => clearInterval(timer));
</script>
<template>
<div ref="root" class="preview-hud" :class="`preview-hud--${variant}`" aria-hidden="true">
<template v-if="variant === 'ground'">
<span class="preview-hud__grid" :style="{ left: `${grid.left}px`, top: `${grid.top}px`, width: `${grid.cols * CELL}px`, height: `${grid.rows * CELL}px` }"></span>
<i v-for="cell in cells" :key="cell.key" class="preview-hud__cell" :style="{ transform: `translate(${cell.x}px, ${cell.y}px)`, opacity: cell.fade }"></i>
</template>
<i class="preview-hud__corner preview-hud__corner--tl"></i>
<i class="preview-hud__corner preview-hud__corner--tr"></i>
<i class="preview-hud__corner preview-hud__corner--bl"></i>
<i class="preview-hud__corner preview-hud__corner--br"></i>
<span class="preview-hud__ruler"><i></i></span>
<span class="preview-hud__scale"></span>
<span class="preview-hud__meter"><i></i><i></i><i></i><i></i><b></b></span>
<svg class="preview-hud__ring" viewBox="-100 -100 200 200">
<circle r="92" class="preview-hud__dash" />
<path d="M0 -100 V-90 M0 90 V100 M-100 0 H-90 M90 0 H100" class="preview-hud__ticks" />
</svg>
<span v-if="variant === 'ground'" class="preview-hud__sweep"></span>
</div>
</template>
-97
View File
@@ -1,97 +0,0 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { msg, t } from '../../../i18n/index.js';
import { useEntityCardStore } from '../../stores/entityCard.js';
// A flight's route on a small globe of its own at the top of its card: the
// great circle from origin to destination, solid where it has flown and
// dashed ahead, the two airports marked with their codes, and a plane where
// the craft is now, pointing at the destination. The renderer draws it (the
// `cardPreviews` hook); this tile lays the compass over it. The card names
// the airports' cities under its progress bar.
const props = defineProps({
/** `{code, lat, lon}` of the origin airport. */
from: { type: Object, required: true },
/** `{code, lat, lon}` of the destination airport. */
to: { type: Object, required: true },
/** The craft's position now. */
at: { type: Object, default: null },
/** Whether the tile is the one showing; a hidden one stops drawing. */
active: { type: Boolean, default: true },
});
const emit = defineEmits(['failed']);
const store = useEntityCardStore();
const host = ref(null);
const failed = ref(false);
let preview = null;
// A globe that cannot draw tells the card, which then shows another view.
watch(failed, (now) => {
if (!now) return;
preview?.destroy();
preview = null;
emit('failed');
});
const place = (p) => ({ code: p?.code || '', lat: Number(p?.lat), lon: Number(p?.lon) });
const at = () =>
props.at && Number.isFinite(props.at.lat) && Number.isFinite(props.at.lon) ? { lat: props.at.lat, lon: props.at.lon } : null;
const route = () => ({ from: place(props.from), to: place(props.to), at: at() });
/** The initial bearing (degrees from north) of the great circle a → b. */
function bearing(a, b) {
const rad = Math.PI / 180;
const y = Math.sin((b.lon - a.lon) * rad) * Math.cos(b.lat * rad);
const x = Math.cos(a.lat * rad) * Math.sin(b.lat * rad) - Math.sin(a.lat * rad) * Math.cos(b.lat * rad) * Math.cos((b.lon - a.lon) * rad);
return (Math.atan2(y, x) / rad + 360) % 360;
}
// The compass: the view is north up, so N sits at the top; a cyan needle
// shows the course to the destination, with its bearing in degrees.
const course = computed(() => Math.round(bearing(at() || props.from, props.to)) % 360);
const POINTS = [msg('N'), msg('NE'), msg('E'), msg('SE'), msg('S'), msg('SW'), msg('W'), msg('NW')];
const courseLabel = computed(() => `${String(course.value).padStart(3, '0')}° ${t(POINTS[Math.round(course.value / 45) % 8])}`);
onMounted(() => {
const previews = store.previews();
if (!previews?.route || !host.value) {
failed.value = true;
return;
}
preview = previews.route(host.value, route(), { onFailed: () => (failed.value = true) });
preview.setActive(props.active);
});
// Watched as strings: a fresh object each card refresh would count as a
// change every two seconds.
watch(
() => `${props.from?.code}|${props.to?.code}|${props.at?.lat?.toFixed?.(4)}|${props.at?.lon?.toFixed?.(4)}`,
() => preview?.update(route()),
);
watch(
() => props.active,
(active) => preview?.setActive(active),
);
onBeforeUnmount(() => {
preview?.destroy();
preview = null;
});
</script>
<template>
<div v-if="!failed" class="route-globe">
<div ref="host" class="route-globe__scene" aria-hidden="true"></div>
<div class="route-globe__compass" :title="t('Course to {code}: {course}', { code: to.code, course: courseLabel })">
<svg viewBox="-24 -24 48 48" aria-hidden="true">
<circle r="19" class="route-globe__compass-ring" />
<g class="route-globe__compass-ticks">
<line v-for="deg in [0, 45, 90, 135, 180, 225, 270, 315]" :key="deg" :transform="`rotate(${deg})`" y1="-19" :y2="deg % 90 ? -16.5 : -15" />
</g>
<text y="-9.5" class="route-globe__compass-n">{{ t('N') }}</text>
<g :transform="`rotate(${course})`" class="route-globe__compass-needle">
<path d="M0 -14 L3 2 L0 0 L-3 2 Z" />
</g>
<circle r="1.6" class="route-globe__compass-hub" />
</svg>
<span>{{ courseLabel }}</span>
</div>
</div>
</template>
-106
View File
@@ -1,106 +0,0 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { t } from '../../../i18n/index.js';
import { nearestCity } from '../../../data/wikidataCities.js';
import { ESRI_IMAGERY_CREDIT, ESRI_TILES } from '../../../maps/attribution.js';
import PreviewHud from './PreviewHud.vue';
// What lies under a satellite: a dark, grey top-down image of the ground at
// the point beneath it, with rings on that spot. It is a still taken each
// time the view comes round, and its tiles load only while it shows (the craft moves several kilometres a second, so
// a live view would only blur), and it drifts in slowly while it shows.
// Near a town it looks close in, at street-block scale; over open water or
// empty land, where a close view would be a blank, it stands well back so
// coasts and terrain show. The image is Esri World Imagery, the app's
// keyless basemap, from its classic tile endpoint; its credit line sits in
// the corner.
const props = defineProps({
lat: { type: Number, default: null },
lon: { type: Number, default: null },
/** Whether the view is the one showing; each showing takes a new still. */
active: { type: Boolean, default: false },
});
const CLOSE_ZOOM = 13;
const WIDE_ZOOM = 4;
const TILE = 256;
/** The spot the still was taken at, how close it looks and what is near. */
const spot = ref(null);
let taking = 0;
async function take() {
if (!Number.isFinite(props.lat) || !Number.isFinite(props.lon)) return;
const lat = props.lat;
const lon = props.lon;
const turn = ++taking;
spot.value = null;
let city = null;
try {
city = await nearestCity(lat, lon, { radiusKm: 40, nearKm: 15 });
} catch {
city = null;
}
if (turn !== taking) return;
spot.value = { lat, lon, zoom: city ? CLOSE_ZOOM : WIDE_ZOOM, near: city?.name || '' };
}
watch(
() => props.active,
(now) => now && take(),
{ immediate: true },
);
// Web Mercator tile position of the spot, in tiles.
const at = computed(() => {
if (!spot.value) return null;
const n = 2 ** spot.value.zoom;
const lat = Math.max(-85, Math.min(85, spot.value.lat));
const x = ((spot.value.lon + 180) / 360) * n;
const rad = (lat * Math.PI) / 180;
const y = ((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * n;
return { x, y, n, zoom: spot.value.zoom };
});
// A 3 by 3 block of tiles round the spot, placed so the spot is at the centre.
const tiles = computed(() => {
const here = at.value;
if (!here) return [];
const cx = Math.floor(here.x);
const cy = Math.floor(here.y);
const list = [];
for (let dy = -1; dy <= 1; dy++)
for (let dx = -1; dx <= 1; dx++) {
const y = cy + dy;
if (y < 0 || y >= here.n) continue;
const x = (((cx + dx) % here.n) + here.n) % here.n;
list.push({
key: `${x}/${y}`,
src: ESRI_TILES.replace('{z}', here.zoom).replace('{y}', y).replace('{x}', x),
left: (cx + dx - here.x) * TILE,
top: (cy + dy - here.y) * TILE,
});
}
return list;
});
const where = computed(() => {
if (!spot.value) return '';
const { lat, lon } = spot.value;
return `${Math.abs(lat).toFixed(2)}°${lat >= 0 ? 'N' : 'S'} ${Math.abs(lon).toFixed(2)}°${lon >= 0 ? 'E' : 'W'}`;
});
</script>
<template>
<div class="satellite-ground" aria-hidden="true">
<div :key="where" class="satellite-ground__map" :class="{ 'is-drifting': active }">
<img v-for="tile in active ? tiles : []" :key="tile.key" class="satellite-ground__tile" :src="tile.src" alt="" draggable="false" :style="{ transform: `translate(${tile.left}px, ${tile.top}px)` }" />
</div>
<svg class="satellite-ground__rings" viewBox="-100 -100 200 200">
<circle r="88" class="satellite-ground__ring satellite-ground__ring--outer" />
<circle r="56" class="satellite-ground__ring satellite-ground__ring--middle" />
<circle r="34" class="satellite-ground__ring satellite-ground__ring--inner" />
</svg>
<PreviewHud variant="ground" :running="active" />
<span class="satellite-ground__label">{{ spot?.near ? t('Over {place}', { place: spot.near }) : t('Below') }}<strong>{{ where }}</strong></span>
<span class="satellite-ground__credit">{{ ESRI_IMAGERY_CREDIT }}</span>
</div>
</template>