Draw local ADS-B through the draw port

The local receiver layer draws its aircraft, the 978 MHz rings and the
selected aircraft's trail head through draw-port sets, updates them on
the frame port each frame, rotates icons from the camera port's screen
axes, and leaves the Cesium allow-list. The trail head now dims behind
terrain instead of vanishing, as the rest of the trail does.
This commit is contained in:
Sameh Khamis committed 2026-11-07 06:04:12 -08:00
1 parent 84e6f13725
commit be5a6f0fe5
5 files changed
+614 -292

No files matched your search

+213 -139
View File
@@ -1,11 +1,12 @@
import * as Cesium from 'cesium';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import {
horizonOccluder,
screenProjectedRotation,
stabilizeScreenRotation,
} from '../../data/iconOrientation.js';
import { fromDegreesInto, toLonLatH } from '../../geo/ellipsoid.js';
import { hexColor } from '../../render/color.js';
import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
import { routePlausible } from '../../data/routePlausible.js';
@@ -49,8 +50,19 @@ const CLICK_DRILL_LIMIT = 8;
const MARKER_SPRITE = Object.freeze({
width: 20,
height: 20,
scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8_000_000, 0.5),
scaleByDistance: Object.freeze({
near: 1000,
nearValue: 3.0,
far: 8_000_000,
farValue: 0.5,
}),
});
/** Markers and rings show within 2,000 km of the eye. */
const MARKER_RANGE = Object.freeze([0, 2_000_000]);
/** The longest the moving trail head waits to be drawn anew, ms. */
const HEAD_REDRAW_MS = 100;
/** Draw sets made, so each layer instance's sets have ids of their own. */
let instances = 0;
/** Trail lines pass through their aircraft; a click never stops on one. */
const TRAIL_PICK_PREFIX = 'gev-trail:';
/** The DISPLAY rail's first-run 3D preference, used when no reader is wired. */
@@ -120,13 +132,17 @@ export function createLocalAdsbLayer({
removeEntityContextsForLayer,
} = services.context;
const { registerPickOwner, unregisterPickOwner } = services.picking;
const color = Cesium.Color.fromCssColorString(LOCAL_ADSB_COLOR);
const uatRingColor = Cesium.Color.fromCssColorString(
LOCAL_ADSB_UAT_RING_COLOR,
);
const color = hexColor(LOCAL_ADSB_COLOR);
const uatRingColor = hexColor(LOCAL_ADSB_UAT_RING_COLOR);
let viewer = null;
let dataSource = null;
/**
* The layer's draw sets on its viewer's renderer (`drawOf`), made at
* `init`: the markers, the 978 MHz rings and the selected aircraft's live
* trail head. Shown while the layer is enabled.
* @type {{markers: object, rings: object, head: object}|null}
*/
let sets = null;
let enabled = false;
let unsubscribe = null;
let unsubscribeFeeds = null;
@@ -176,15 +192,21 @@ export function createLocalAdsbLayer({
);
}
function markerVisible(marker) {
if (!viewer?.camera?.positionWC || !marker.position) return true;
return horizonOccluder(viewer.camera).isPointVisible(marker.position);
/**
* The camera's screen axes, as the course projection reads them, from the
* camera port's pose; null without a camera.
*/
function cameraBasis() {
const pose = viewer ? findCamera(viewer)?.pose() : null;
return pose?.right && pose?.up
? { camera: { rightWC: pose.right, upWC: pose.up } }
: null;
}
function markerRotation(marker) {
if (!viewer?.scene || !marker.position) return marker.lastRotation;
function markerRotation(marker, basis = cameraBasis()) {
if (!basis || !marker.position) return marker.lastRotation;
const projected = screenProjectedRotation(
viewer.scene,
basis,
marker.position,
marker.courseDeg ?? 0,
marker.lastRotation,
@@ -222,10 +244,11 @@ export function createLocalAdsbLayer({
}
function fixPosition(marker, fix) {
return Cesium.Cartesian3.fromDegrees(
return fromDegreesInto(
fix.lon,
fix.lat,
renderHeightM(marker, fix.altitudeFt, fix.lat, fix.lon),
{ x: 0, y: 0, z: 0 },
);
}
@@ -234,12 +257,11 @@ export function createLocalAdsbLayer({
if (!display) return;
marker.lat = display.lat;
marker.lon = display.lon;
marker.position = Cesium.Cartesian3.fromDegrees(
marker.position = fromDegreesInto(
display.lon,
display.lat,
renderHeightM(marker, display.altitudeFt, display.lat, display.lon),
Cesium.Ellipsoid.WGS84,
marker.position || new Cesium.Cartesian3(),
marker.position || { x: 0, y: 0, z: 0 },
);
if (display.courseDeg !== null) marker.courseDeg = display.courseDeg;
}
@@ -258,17 +280,12 @@ export function createLocalAdsbLayer({
);
marker.evidence = evidence;
marker.klass = klass;
const billboard = marker.entity?.billboard;
if (!billboard) return;
if (marker.iconKind !== klass) {
marker.iconKind = klass;
billboard.image = aircraftIcon(klass);
}
if (!marker.carrier) return;
marker.iconKind = klass;
const scale = billboardScale(marker);
if (marker.iconScale !== scale) {
marker.iconScale = scale;
billboard.scale = scale;
entityRecord(marker.entity).sprite.scale = scale;
entityRecord(marker.carrier).sprite.scale = scale;
}
}
@@ -306,7 +323,8 @@ export function createLocalAdsbLayer({
return {
id,
layerId: LAYER_ID,
dataSource,
// Hidden with the layer: the context store reads its `show`.
dataSource: sets?.markers ?? null,
layerName: LAYER_NAME,
source: localAdsbSourceText(record),
label: localAdsbTitle(record),
@@ -331,20 +349,56 @@ export function createLocalAdsbLayer({
};
}
function uatRing(marker) {
return new Cesium.PointGraphics({
/** A marker's icon, where and how it now draws. */
function markerItem(marker, basis) {
return {
id: marker.id,
pos: marker.position,
image: aircraftIcon(marker.iconKind ?? 'airliner'),
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
scale: marker.iconScale ?? 1,
color,
scaleByDistance: MARKER_SPRITE.scaleByDistance,
rotationMode: 'screen',
rotation: markerRotation(marker, basis),
// The 3D model, once loaded and placed, is the visual instead.
show: !marker.modelOwnsVisual,
disableDepthTest: Number.POSITIVE_INFINITY,
displayRange: MARKER_RANGE,
};
}
/** The thin ring around an aircraft heard only on 978 MHz UAT. */
function ringItem(marker) {
return {
id: marker.id,
pos: marker.position,
pixelSize: 24,
color: Cesium.Color.TRANSPARENT,
color: [0, 0, 0, 0],
outlineColor: uatRingColor,
outlineWidth: 1.5,
scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8_000_000, 0.5),
show: new Cesium.CallbackProperty(() => markerVisible(marker), false),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
0,
2_000_000,
),
});
scaleByDistance: MARKER_SPRITE.scaleByDistance,
disableDepthTest: Number.POSITIVE_INFINITY,
displayRange: MARKER_RANGE,
// Rings pass picks through to their aircraft.
pickable: false,
};
}
/** Draw every marker, ring and the trail head as they now are. */
function drawMarkers() {
if (!sets) return;
const basis = cameraBasis();
const icons = [];
const rings = [];
for (const marker of markers.values()) {
if (!marker.position) continue;
icons.push(markerItem(marker, basis));
if (marker.uat) rings.push(ringItem(marker));
}
if (icons.length) sets.markers.upsert(icons);
if (rings.length) sets.rings.upsert(rings);
drawTrailHead();
}
// ── Trail of the selected aircraft ──────────────────────────────────────
@@ -352,16 +406,51 @@ export function createLocalAdsbLayer({
function releaseTrail() {
if (!selectedTrail) return;
selectedTrail.trail?.destroy();
if (selectedTrail.head && viewer && !viewer.isDestroyed?.()) {
try {
viewer.entities.remove(selectedTrail.head);
} catch {
/* torn down */
}
}
sets?.head.clear();
selectedTrail = null;
}
/**
* The live head: the last heard fix to the extrapolated marker, dimmed
* where the surface hides it. Nothing while either end is unknown.
*
* A line dimmed behind the surface is built anew when it moves, so the
* head is redrawn when its fix changes, and otherwise at most
* `HEAD_REDRAW_MS` apart while the aircraft flies on; a still aircraft
* costs nothing a frame.
*/
function drawTrailHead() {
if (!sets || !selectedTrail?.headId) return;
const current = markers.get(selectedTrail.id);
const from = selectedTrail.lastFix;
const positions =
current?.position && from ? [from, { ...current.position }] : [];
const key = positions.map(({ x, y, z }) => `${x},${y},${z}`).join(';');
if (key === selectedTrail.drawnKey) return;
const at = now();
if (
from === selectedTrail.drawnFrom &&
at - selectedTrail.drawnAt < HEAD_REDRAW_MS
)
return;
selectedTrail.drawnKey = key;
selectedTrail.drawnFrom = from;
selectedTrail.drawnAt = at;
sets.head.upsert([
{
// 'gev-trail' namespace: claimed by the trail pick owner so a click
// on the head segment never reads as empty space.
id: selectedTrail.headId,
positions,
widthPx: 2.5,
// Metres to a few km: straight is the ellipsoid's arc to the pixel.
mode: '3d',
style: { kind: 'solid', color: hexColor(LOCAL_ADSB_COLOR, 0.9) },
depthFailColor: hexColor(LOCAL_ADSB_COLOR, 0.45),
},
]);
}
function refreshTrail() {
const marker = selectedId ? markers.get(selectedId) : null;
if (!marker || !selectedTrail?.trail) return;
@@ -375,32 +464,20 @@ export function createLocalAdsbLayer({
function startTrail(marker) {
releaseTrail();
const createTrail = services.trails?.createTrail;
if (typeof createTrail !== 'function' || !viewer?.entities) return;
if (typeof createTrail !== 'function' || !viewer || !sets) return;
selectedTrail = {
id: marker.id,
trail: createTrail(viewer, { color: LOCAL_ADSB_COLOR, width: 2.5 }),
head: null,
// Live head: last heard fix → the extrapolated marker, every frame.
headId: `gev-trail:local-adsb-head-${++trailHeadSeq}`,
lastFix: null,
// Where, from which fix and when the head was last drawn.
drawnKey: null,
drawnFrom: null,
drawnAt: -Infinity,
};
// Live head: last heard fix → the extrapolated marker, every frame.
selectedTrail.head = viewer.entities.add({
// 'gev-trail' namespace: claimed by the trail pick owner so a click on
// the head segment never reads as empty space.
id: `gev-trail:local-adsb-head-${++trailHeadSeq}`,
polyline: {
positions: new Cesium.CallbackProperty(() => {
const current = markers.get(selectedTrail?.id);
const from = selectedTrail?.lastFix;
if (!current?.position || !from) return [];
return [from, Cesium.Cartesian3.clone(current.position)];
}, false),
width: 2.5,
material: color.withAlpha(0.9),
depthFailMaterial: color.withAlpha(0.45),
arcType: Cesium.ArcType.GEODESIC,
},
});
refreshTrail();
drawTrailHead();
}
// ── Markers ─────────────────────────────────────────────────────────────
@@ -411,7 +488,10 @@ export function createLocalAdsbLayer({
if (!marker) {
marker = {
id,
entity: null,
// What stands for the aircraft in the shared context store and the
// readout card.
carrier: null,
uat: false,
record,
motion: new LocalAdsbMotion(),
position: null,
@@ -435,45 +515,19 @@ export function createLocalAdsbLayer({
const newFix = marker.motion.observe(record, at);
rejectedFixes += marker.motion.rejectedFixes - rejectedBefore;
updateDisplay(marker, at);
if (!marker.entity) {
marker.entity = dataSource.entities.add({
id,
position: new Cesium.CallbackProperty(() => marker.position, false),
billboard: {
image: aircraftIcon('airliner'),
width: MARKER_SPRITE.width,
height: MARKER_SPRITE.height,
scale: 1,
color,
sizeInMeters: false,
scaleByDistance: MARKER_SPRITE.scaleByDistance,
alignedAxis: Cesium.Cartesian3.ZERO,
rotation: new Cesium.CallbackProperty(
() => markerRotation(marker),
false,
),
show: new Cesium.CallbackProperty(
() => !marker.modelOwnsVisual && markerVisible(marker),
false,
),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
0,
2_000_000,
),
},
});
entityRecord(marker.entity).trackedId = id;
// Sized from the app when Cesium tracks the marker (screen annotations).
entityRecord(marker.entity).sprite = { ...MARKER_SPRITE, scale: 1 };
entityRecord(marker.entity).displayPosition = () => marker.position;
if (!marker.carrier) {
marker.carrier = { id };
entityRecord(marker.carrier).trackedId = id;
// Sized from the record when the marker is followed (screen annotations).
entityRecord(marker.carrier).sprite = { ...MARKER_SPRITE, scale: 1 };
entityRecord(marker.carrier).displayPosition = () => marker.position;
}
refreshClass(marker);
const uat = localAdsbIsUat(record);
if (uat !== Boolean(marker.entity.point))
marker.entity.point = uat ? uatRing(marker) : undefined;
entityRecord(marker.entity).labelModel = cardModel(marker, at);
registerEntityContext(marker.entity, contextMetadata(id, marker));
if (marker.uat && !uat) sets?.rings.remove([id]);
marker.uat = uat;
entityRecord(marker.carrier).labelModel = cardModel(marker, at);
registerEntityContext(marker.carrier, contextMetadata(id, marker));
if (newFix && id === selectedId) refreshTrail();
return id;
}
@@ -488,8 +542,12 @@ export function createLocalAdsbLayer({
function refreshSelectedCard() {
const marker = selectedId ? markers.get(selectedId) : null;
if (!marker) return;
entityRecord(marker.entity).labelModel = cardModel(marker, now());
services.overlays?.refreshReadout?.(marker.entity);
entityRecord(marker.carrier).labelModel = cardModel(marker, now());
services.overlays?.refreshReadout?.(marker.carrier);
}
function showSets(show) {
if (sets) for (const set of Object.values(sets)) set.show = show;
}
function updateRenderHold() {
@@ -512,7 +570,7 @@ export function createLocalAdsbLayer({
function sync() {
clearTimeout(syncTimer);
syncTimer = null;
if (!dataSource) return;
if (!sets) return;
const at = now();
const live = new Set();
let added = false;
@@ -523,13 +581,18 @@ export function createLocalAdsbLayer({
live.add(upsertMarker(record, at));
}
}
let removed = false;
const gone = [];
const ringsGone = [];
for (const [id, marker] of markers) {
if (live.has(id)) continue;
if (marker.entity) dataSource.entities.remove(marker.entity);
markers.delete(id);
removed = true;
gone.push(id);
if (marker.uat) ringsGone.push(id);
}
const removed = gone.length > 0;
if (removed) sets.markers.remove(gone);
// A points set redraws on removal: only when a ring goes.
if (ringsGone.length) sets.rings.remove(ringsGone);
// Expired aircraft take their 3D models (and pending loads) with them.
if (removed) models?.retain(markers);
if (selectedId && !live.has(selectedId))
@@ -540,8 +603,9 @@ export function createLocalAdsbLayer({
if (getSelectedEntityContext()?.id !== selectedId) {
selectedId = null;
releaseTrail();
} else services.overlays?.refreshReadout?.(selected.entity);
} else services.overlays?.refreshReadout?.(selected.carrier);
}
drawMarkers();
requestEnrichment();
updateRenderHold();
if (live.size || removed) governorRequestRender('local-adsb-update');
@@ -556,6 +620,7 @@ export function createLocalAdsbLayer({
const at = now();
for (const marker of markers.values()) updateDisplay(marker, at);
models?.frame(markers, displayPreferences(), at);
drawMarkers();
}
function scheduleSync(nextState) {
@@ -574,21 +639,19 @@ export function createLocalAdsbLayer({
const reselect = id === selectedId && selectedTrail?.id === id;
selectedId = id;
enrichment.request(marker.record, { selected: true });
entityRecord(marker.entity).labelModel = cardModel(marker, now());
selectEntityContext(marker.entity);
entityRecord(marker.carrier).labelModel = cardModel(marker, now());
selectEntityContext(marker.carrier);
if (!reselect) startTrail(marker);
governorRequestRender('local-adsb-selection');
return true;
}
/**
* The id under a pick, through the shared pick-id resolver: a draw-set
* item's id (markers, the trail head) or a model's.
*/
function pickedId(picked) {
const resolved = services.picking.resolvePickId?.(picked);
if (resolved !== undefined) return resolved;
if (typeof picked?.id === 'string') return picked.id;
if (typeof picked?.id?.id === 'string') return picked.id.id;
return typeof picked?.primitive?.id === 'string'
? picked.primitive.id
: null;
return services.picking.resolvePickId?.(picked) ?? null;
}
function ownedElsewhere(id) {
@@ -626,7 +689,7 @@ export function createLocalAdsbLayer({
}
function installInteraction() {
if (clickSubscription || !viewer?.scene?.canvas) return;
if (clickSubscription || !viewer) return;
clickSubscription = inputFor(viewer).onClick((event) => {
if (!enabled) return;
const target = clickTarget(event);
@@ -652,8 +715,8 @@ export function createLocalAdsbLayer({
}
function installFrame() {
if (removePreRender || !viewer?.scene?.preRender?.addEventListener) return;
removePreRender = viewer.scene.preRender.addEventListener(frame);
if (removePreRender || !viewer) return;
removePreRender = findFrame(viewer)?.on('preRender', frame) ?? null;
}
function releaseFrame() {
@@ -667,12 +730,12 @@ export function createLocalAdsbLayer({
for (const marker of markers.values()) {
if (rows.length >= maxCount) break;
if (!marker.position) continue;
const carto = Cesium.Cartographic.fromCartesian(marker.position);
const carto = toLonLatH(marker.position);
rows.push({
id: marker.record.icao,
label: localAdsbTitle(marker.record),
callsign: marker.record.callsign,
position: Cesium.Cartesian3.clone(marker.position),
position: { ...marker.position },
latitude: marker.lat,
longitude: marker.lon,
altitudeM: carto?.height ?? 0,
@@ -695,18 +758,29 @@ export function createLocalAdsbLayer({
init(nextViewer) {
viewer = nextViewer;
dataSource = new Cesium.CustomDataSource(LAYER_ID);
dataSource.show = false;
viewer.dataSources.add(dataSource);
if (viewer.scene?.primitives) {
models = createLocalAdsbModels({
viewer,
color,
resolveAsset,
groundSnap: services.groundSnap?.createGroundSnap?.() || null,
...(loadModel ? { loadModel } : {}),
});
}
const draw = drawOf(viewer);
const prefix = `${LAYER_ID}:${++instances}`;
sets = {
markers: draw.icons({
id: `${prefix}:markers`,
horizonCull: true,
show: false,
}),
rings: draw.points({
id: `${prefix}:rings`,
horizonCull: true,
show: false,
pickable: false,
}),
head: draw.lines({ id: `${prefix}:trail-head`, show: false }),
};
models = createLocalAdsbModels({
viewer,
color: LOCAL_ADSB_COLOR,
resolveAsset,
groundSnap: services.groundSnap?.createGroundSnap?.() || null,
...(loadModel ? { loadModel } : {}),
});
services.geoid
?.ensureGeoidReady?.()
?.then(() => {
@@ -723,7 +797,7 @@ export function createLocalAdsbLayer({
async enable() {
enabled = true;
if (dataSource) dataSource.show = true;
showSets(true);
registerPickOwner(LAYER_ID, (pickedValue) => markers.has(pickedValue));
installInteraction();
installFrame();
@@ -749,7 +823,7 @@ export function createLocalAdsbLayer({
unregisterPickOwner(LAYER_ID);
sync();
models?.clear();
if (dataSource) dataSource.show = false;
showSets(false);
markSourcesChanged('local-adsb-disabled');
return true;
},
@@ -782,8 +856,8 @@ export function createLocalAdsbLayer({
updateRenderHold();
models?.destroy();
models = null;
if (viewer && dataSource) viewer.dataSources.remove(dataSource, true);
dataSource = null;
if (sets) for (const set of Object.values(sets)) set.dispose();
sets = null;
viewer = null;
void receiver.destroy?.();
},
+266 -147
View File
@@ -13,7 +13,31 @@ import {
localAdsbStatus,
} from './index.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { resolvePickId } from '../../data/pickRegistry.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { hexColor } from '../../render/color.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const MAGENTA = hexColor('#ff4fd8');
/** The layer's live draw set whose id ends with `suffix`. */
function layerSet(draw, suffix) {
return [...draw.sets.values()].find(
(record) =>
!record.disposed &&
record.spec.id.startsWith('local-adsb:') &&
record.spec.id.endsWith(suffix),
);
}
/** The icon drawn for an aircraft, or undefined. */
const iconOf = (draw, id) => layerSet(draw, ':markers')?.items.get(id);
/** The 978 MHz ring drawn for an aircraft, or undefined. */
const ringOf = (draw, id) => layerSet(draw, ':rings')?.items.get(id);
/** Degrees of latitude where an aircraft's icon now is. */
const latitudeOf = (draw, id) => toLonLatH(iconOf(draw, id).pos).lat;
function fakeReceiver(initial = {}) {
const state = {
@@ -49,7 +73,13 @@ function fakeReceiver(initial = {}) {
}
function fakeServices() {
const calls = { registered: [], selected: [], cleared: [], removed: [] };
const calls = {
registered: [],
selected: [],
cleared: [],
removed: [],
carriers: new Map(),
};
let selected = null;
return {
calls,
@@ -59,6 +89,7 @@ function fakeServices() {
registerEntityContext(entity, metadata) {
entityRecord(entity).contextId = metadata.id;
calls.registered.push(metadata);
calls.carriers.set(metadata.id, entity);
},
selectEntityContext(entity) {
selected = { id: readEntityRecord(entity)?.contextId, entity };
@@ -74,36 +105,29 @@ function fakeServices() {
calls.removed.push({ layerId, retainIds: options?.retainIds });
},
},
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
picking: {
registerPickOwner() {},
unregisterPickOwner() {},
resolvePickId,
},
detection: { markSourcesChanged() {} },
overlays: { refreshReadout() {} },
},
};
}
function fakeViewer() {
const sources = [];
const camera = {
rightWC: new Cesium.Cartesian3(0, 1, 0),
upWC: new Cesium.Cartesian3(0, 0, 1),
};
return {
sources,
viewer: {
camera,
scene: { camera },
entities: {
add: (entity) => entity,
remove() {},
},
dataSources: {
add(source) {
sources.push(source);
},
remove() {},
},
},
};
/**
* A viewer with a fake draw port and a camera port whose screen axes are
* east and north at (0°, 0°); `viewer` adds the Cesium-shaped members the
* 3D models read.
*/
function fakeViewer(viewer = { scene: {} }) {
const camera = fakeCameraPort({
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const { draw } = bindFakeDraw(viewer, { camera: camera.port });
const input = fakeInput(viewer);
return { draw, viewer, input };
}
function record(overrides = {}) {
@@ -160,9 +184,7 @@ function fakeFeeds(initial = {}) {
/** A viewer whose camera looks down on (0°, 0°) from 50 km, with primitives. */
function modelViewer(primitives) {
const base = fakeViewer();
const camera = {
...base.viewer.camera,
positionWC: new Cesium.Cartesian3(6_378_137 + 50_000, 0, 0),
positionCartographic: new Cesium.Cartographic(0, 0, 50_000),
directionWC: new Cesium.Cartesian3(-1, 0, 0),
@@ -172,28 +194,24 @@ function modelViewer(primitives) {
}),
},
};
return {
...base,
viewer: {
...base.viewer,
return fakeViewer({
camera,
scene: {
camera,
scene: {
camera,
primitives: {
add(collection) {
primitives.push(collection);
return collection;
},
remove() {},
primitives: {
add(collection) {
primitives.push(collection);
return collection;
},
remove() {},
},
},
};
});
}
async function enabledLayer(receiver, clock, feeds = null, options = {}) {
const { services, calls } = fakeServices();
const { sources, viewer } = options.viewer || fakeViewer();
const { draw, viewer } = options.viewer || fakeViewer();
const layer = createLocalAdsbLayer({
receiver,
feeds,
@@ -203,7 +221,7 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) {
});
layer.init(viewer);
await layer.enable();
return { layer, calls, sources };
return { layer, calls, draw };
}
test('enabling Local ADS-B asks the shared tuner for 1090 MHz; disabling leaves it alone', async (t) => {
@@ -225,47 +243,39 @@ test('enabling Local ADS-B asks the shared tuner for 1090 MHz; disabling leaves
test('local aircraft use their class silhouette and scale in magenta', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer, sources } = await enabledLayer(receiver, clock);
const { layer, draw, calls } = await enabledLayer(receiver, clock);
t.after(() => layer.destroy());
receiver.set({
aircraft: [record(), record({ icao: 'a0b702', category: 'A7' })],
});
await layer.update();
const entity = sources[0].entities.getById('local-adsb:abc123');
assert.ok(entity);
assert.equal(entity.point, undefined);
assert.equal(entity.label, undefined);
assert.equal(entity.billboard.image.getValue(), aircraftIcon('airliner'));
assert.equal(entity.billboard.width.getValue(), 20);
assert.ok(
Cesium.Color.equals(
entity.billboard.color.getValue(),
Cesium.Color.fromCssColorString('#ff4fd8'),
),
);
assert.ok(
Cesium.Cartesian3.equals(
entity.billboard.alignedAxis.getValue(),
Cesium.Cartesian3.ZERO,
),
);
assert.equal(entity.billboard.rotation.getValue(), 0);
assert.equal(readEntityRecord(entity)?.labelModel.title, 'LOCAL1');
assert.equal(typeof readEntityRecord(entity)?.displayPosition, 'function');
const icon = iconOf(draw, 'local-adsb:abc123');
assert.ok(icon);
assert.equal(ringOf(draw, 'local-adsb:abc123'), undefined);
assert.equal(icon.image, aircraftIcon('airliner'));
assert.deepEqual(icon.size, [20, 20]);
assert.deepEqual(icon.color, MAGENTA);
assert.equal(icon.rotationMode, 'screen', 'upright on screen, turned');
assert.equal(icon.rotation, 0);
assert.deepEqual(icon.displayRange, [0, 2_000_000]);
assert.equal(icon.disableDepthTest, Number.POSITIVE_INFINITY);
assert.equal(layerSet(draw, ':markers').spec.horizonCull, true);
const carrier = calls.carriers.get('local-adsb:abc123');
assert.equal(readEntityRecord(carrier)?.labelModel.title, 'LOCAL1');
assert.equal(typeof readEntityRecord(carrier)?.displayPosition, 'function');
const heli = sources[0].entities.getById('local-adsb:a0b702');
assert.equal(heli.billboard.image.getValue(), aircraftIcon('helicopter'));
assert.equal(heli.billboard.scale.getValue(), CLASS_SCALE_2D.helicopter);
assert.ok(
Cesium.Color.equals(
heli.billboard.color.getValue(),
Cesium.Color.fromCssColorString('#ff4fd8'),
),
const heli = () => iconOf(draw, 'local-adsb:a0b702');
assert.equal(heli().image, aircraftIcon('helicopter'));
assert.equal(heli().scale, CLASS_SCALE_2D.helicopter);
assert.deepEqual(
heli().color,
MAGENTA,
'the helicopter keeps the local magenta',
);
assert.equal(
readEntityRecord(heli)?.labelModel.details[1],
readEntityRecord(calls.carriers.get('local-adsb:a0b702'))?.labelModel
.details[1],
'Helicopter · A7',
);
@@ -281,10 +291,7 @@ test('local aircraft use their class silhouette and scale in magenta', async (t)
],
});
await layer.update();
assert.equal(
heli.billboard.scale.getValue(),
CLASS_SCALE_2D.helicopter * 0.8,
);
assert.equal(heli().scale, CLASS_SCALE_2D.helicopter * 0.8);
const [detectable] = layer.getDetectableObjects();
assert.equal(detectable.sourceId, 'a0b702');
@@ -294,12 +301,12 @@ test('local aircraft use their class silhouette and scale in magenta', async (t)
test('the heading slews toward a new track instead of snapping', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer, sources } = await enabledLayer(receiver, clock);
const { layer, draw } = await enabledLayer(receiver, clock);
t.after(() => layer.destroy());
receiver.set({ aircraft: [record()] });
await layer.update();
const entity = sources[0].entities.getById('local-adsb:abc123');
assert.equal(entity.billboard.rotation.getValue(), 0);
const rotation = () => iconOf(draw, 'local-adsb:abc123').rotation;
assert.equal(rotation(), 0);
clock.now = 101_000;
receiver.set({
@@ -313,7 +320,7 @@ test('the heading slews toward a new track instead of snapping', async (t) => {
],
});
await layer.update();
const first = entity.billboard.rotation.getValue();
const first = rotation();
assert.ok(
first > -Cesium.Math.PI_OVER_TWO && first <= 0,
'one frame does not swing the nose 90°',
@@ -323,8 +330,7 @@ test('the heading slews toward a new track instead of snapping', async (t) => {
await layer.update();
}
assert.ok(
Math.abs(entity.billboard.rotation.getValue() + Cesium.Math.PI_OVER_TWO) <
1e-6,
Math.abs(rotation() + Cesium.Math.PI_OVER_TWO) < 1e-6,
'the nose settles on the new track',
);
});
@@ -332,14 +338,9 @@ test('the heading slews toward a new track instead of snapping', async (t) => {
test('markers move in real time between fixes and never jump on a new fix', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer, sources } = await enabledLayer(receiver, clock);
const { layer, draw } = await enabledLayer(receiver, clock);
t.after(() => layer.destroy());
const latitude = () =>
Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(
sources[0].entities.getById('local-adsb:abc123').position.getValue(),
).latitude,
);
const latitude = () => latitudeOf(draw, 'local-adsb:abc123');
// 180 kt due north: 1 s covers 92.6 m, 0.000833° of latitude.
const degPerSecond = (180 * 1852) / 3600 / 111_195;
receiver.set({ aircraft: [record({ lastPositionAt: 99_000 })] });
@@ -376,7 +377,7 @@ test('markers move in real time between fixes and never jump on a new fix', asyn
test('an implausible jump in a feed record is ignored by the display', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer, sources } = await enabledLayer(receiver, clock);
const { layer, draw } = await enabledLayer(receiver, clock);
t.after(() => layer.destroy());
receiver.set({ aircraft: [record({ groundSpeedKt: 120, trackDeg: 0 })] });
await layer.update();
@@ -392,11 +393,7 @@ test('an implausible jump in a feed record is ignored by the display', async (t)
],
});
await layer.update();
const lat = Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(
sources[0].entities.getById('local-adsb:abc123').position.getValue(),
).latitude,
);
const lat = latitudeOf(draw, 'local-adsb:abc123');
assert.ok(lat < 0.001, `stayed on its track (${lat})`);
assert.equal(layer.getStats().rejectedPositions, 1);
});
@@ -447,11 +444,81 @@ test('selecting an aircraft draws a magenta trail of the fixes the receiver hear
assert.equal(trails[0].destroyed, true, 'the trail leaves with the aircraft');
});
test('the trail head runs from the last fix to the marker every frame, dimmed behind the surface', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const listeners = new Map();
const frame = {
on(event, callback) {
listeners.set(event, callback);
return () => listeners.delete(event);
},
};
const viewer = { scene: {} };
const camera = fakeCameraPort({
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const { draw } = bindFakeDraw(viewer, { camera: camera.port, frame });
const input = fakeInput(viewer);
const { layer } = await enabledLayer(receiver, clock, null, {
viewer: { draw, viewer, input },
services: {
trails: {
createTrail: () => ({ setPositions() {}, destroy() {} }),
},
},
});
t.after(() => layer.destroy());
receiver.set({ aircraft: [record()] });
await layer.update();
assert.equal(layer.selectAircraft('abc123'), true);
const heads = () => [...layerSet(draw, ':trail-head').items.values()];
const [head] = heads();
assert.match(head.id, /^gev-trail:local-adsb-head-\d+$/);
assert.equal(head.mode, '3d');
assert.equal(head.widthPx, 2.5);
assert.deepEqual(head.style, {
kind: 'solid',
color: hexColor('#ff4fd8', 0.9),
});
assert.deepEqual(
head.depthFailColor,
hexColor('#ff4fd8', 0.45),
'dimmed, not hidden, behind the surface',
);
assert.equal(head.positions.length, 2);
assert.deepEqual(
head.positions[1],
iconOf(draw, 'local-adsb:abc123').pos,
'it ends at the marker',
);
// A frame alone moves the marker, its icon and the head's end.
const before = latitudeOf(draw, 'local-adsb:abc123');
clock.now = 101_000;
listeners.get('preRender')();
const after = latitudeOf(draw, 'local-adsb:abc123');
assert.ok(after > before, `the marker flew north (${before} → ${after})`);
assert.ok(
Math.abs(toLonLatH(heads()[0].positions[1]).lat - after) < 1e-9,
'the head follows the marker',
);
// A frame where nothing moved leaves the head alone.
const writes = layerSet(draw, ':trail-head').writes;
listeners.get('preRender')();
assert.equal(layerSet(draw, ':trail-head').writes, writes);
await layer.disable();
assert.equal(listeners.has('preRender'), false, 'frames stop when off');
assert.equal(heads().length, 0, 'the head leaves with the selection');
});
test('adsbdb type, operator and route reach the card for the selected aircraft only', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const queries = [];
const { layer, sources } = await enabledLayer(receiver, clock, null, {
const { layer, calls } = await enabledLayer(receiver, clock, null, {
services: {
enrichment: {
async getEnrichment(query) {
@@ -480,7 +547,7 @@ test('adsbdb type, operator and route reach the card for the selected aircraft o
assert.equal(layer.selectAircraft('a0b702'), true);
await new Promise((resolve) => setTimeout(resolve, 400));
assert.deepEqual([...queries].sort(), ['route:EVC145', 'type:a0b702']);
const entity = sources[0].entities.getById('local-adsb:a0b702');
const entity = calls.carriers.get('local-adsb:a0b702');
assert.deepEqual(readEntityRecord(entity)?.labelModel.details.slice(0, 4), [
'ICAO A0B702 · EVC145',
'Helicopter · A7',
@@ -502,7 +569,7 @@ test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t
const loads = [];
const display = { models3d: true, models3dMode: 'proximity' };
const primitives = [];
const { layer, sources } = await enabledLayer(receiver, clock, null, {
const { layer, draw } = await enabledLayer(receiver, clock, null, {
services: { display: { getParams: () => display } },
viewer: modelViewer(primitives),
loadModel: async (options) => {
@@ -547,28 +614,24 @@ test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t
assert.equal(model.colorBlendMode, Cesium.ColorBlendMode.MIX);
assert.equal(model.colorBlendAmount, 0.94);
assert.equal(model.show, true);
const heli = sources[0].entities.getById('local-adsb:a0b702');
assert.equal(
heli.billboard.show.getValue(),
false,
'the model is the visual',
);
const heli = () => iconOf(draw, 'local-adsb:a0b702');
assert.equal(heli().show, false, 'the model is the visual');
const origin = Cesium.Matrix4.getTranslation(
model.modelMatrix,
new Cesium.Cartesian3(),
);
assert.ok(Cesium.Cartesian3.distance(origin, heli.position.getValue()) < 1);
assert.ok(Cesium.Cartesian3.distance(origin, heli().pos) < 1);
display.models3d = false;
await layer.update();
assert.equal(model.destroyed || !primitives[0].contains(model), true);
assert.equal(heli.billboard.show.getValue(), true, 'the billboard is back');
assert.equal(heli().show, true, 'the icon is back');
});
test('markers drop when the position is 60 s old and records when silent 60 s', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer, sources } = await enabledLayer(receiver, clock);
const { layer, draw } = await enabledLayer(receiver, clock);
t.after(() => layer.destroy());
receiver.set({
aircraft: [
@@ -583,7 +646,7 @@ test('markers drop when the position is 60 s old and records when silent 60 s',
],
});
await layer.update();
const entities = () => sources[0].entities.values.map((entity) => entity.id);
const entities = () => [...layerSet(draw, ':markers').items.keys()];
assert.deepEqual(
entities(),
['local-adsb:abc123'],
@@ -731,7 +794,7 @@ test('feed records merge with browser SDR records by ICAO and UAT-only aircraft
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const feeds = fakeFeeds();
const clock = { now: 100_000 };
const { layer, sources } = await enabledLayer(receiver, clock, feeds);
const { layer, draw, calls } = await enabledLayer(receiver, clock, feeds);
t.after(() => layer.destroy());
assert.deepEqual(feeds.calls, ['start'], 'the feeds poll while enabled');
@@ -750,31 +813,37 @@ test('feed records merge with browser SDR records by ICAO and UAT-only aircraft
],
});
await layer.update();
const shared = sources[0].entities.getById('local-adsb:abc123');
const uat = sources[0].entities.getById('local-adsb:a1b2c3');
assert.equal(sources[0].entities.values.length, 2);
assert.equal(
Cesium.Cartographic.fromCartesian(
shared.position.getValue(),
).latitude.toFixed(4),
Cesium.Math.toRadians(1).toFixed(4),
const shared = calls.carriers.get('local-adsb:abc123');
const uat = calls.carriers.get('local-adsb:a1b2c3');
assert.equal(layerSet(draw, ':markers').items.size, 2);
assert.ok(
Math.abs(latitudeOf(draw, 'local-adsb:abc123') - 1) < 0.002,
'the newer feed position wins',
);
assert.equal(shared.point, undefined, 'heard on 1090 too: no UAT ring');
assert.equal(
ringOf(draw, 'local-adsb:abc123'),
undefined,
'heard on 1090 too: no UAT ring',
);
assert.equal(
readEntityRecord(shared)?.labelModel.details.at(-1),
'Heard by your receiver · 1090 MHz + 978 MHz UAT · browser SDR + decoder feed',
);
assert.ok(uat.point, 'a UAT-only aircraft carries the ring');
assert.equal(uat.point.outlineWidth.getValue(), 1.5);
assert.ok(
Cesium.Color.equals(uat.point.color.getValue(), Cesium.Color.TRANSPARENT),
const ring = ringOf(draw, 'local-adsb:a1b2c3');
assert.ok(ring, 'a UAT-only aircraft carries the ring');
assert.equal(ring.outlineWidth, 1.5);
assert.deepEqual(ring.color, [0, 0, 0, 0]);
assert.deepEqual(ring.outlineColor, hexColor('#ffb3ef'));
assert.deepEqual(
ring.displayRange,
[0, 2_000_000],
'shown within 2,000 km, as its aircraft is',
);
assert.ok(
Cesium.Color.equals(
uat.billboard.color.getValue(),
Cesium.Color.fromCssColorString('#ff4fd8'),
),
assert.deepEqual(ring.pos, iconOf(draw, 'local-adsb:a1b2c3').pos);
assert.equal(layerSet(draw, ':rings').spec.horizonCull, true);
assert.deepEqual(
iconOf(draw, 'local-adsb:a1b2c3').color,
MAGENTA,
'same magenta marker family',
);
assert.equal(
@@ -786,8 +855,65 @@ test('feed records merge with browser SDR records by ICAO and UAT-only aircraft
assert.equal(stats.loadingLabel, '1 feed live · 2 heard');
assert.equal(stats.count, 2);
// Heard on 1090 as well later: the ring goes.
feeds.set({
records: [
record({
icao: 'a1b2c3',
callsign: 'N978UA',
band: '1090',
source: 'feed',
}),
],
});
await layer.update();
assert.equal(ringOf(draw, 'local-adsb:a1b2c3'), undefined);
await layer.disable();
assert.deepEqual(feeds.calls, ['start', 'stop']);
assert.equal(layerSet(draw, ':markers').show, false, 'hidden with the layer');
});
test('the layer draws into sets of its own, shown while it is enabled and let go when destroyed', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const feeds = fakeFeeds();
const clock = { now: 100_000 };
const first = fakeViewer();
const { layer, draw } = await enabledLayer(receiver, clock, feeds, {
viewer: first,
});
const other = await enabledLayer(fakeReceiver(), clock);
t.after(() => other.layer.destroy());
const ids = (port) =>
[...port.sets.values()]
.filter((record) => !record.disposed)
.map((record) => record.spec.id);
const mine = ids(draw);
assert.equal(mine.length, 3, 'markers, rings and the trail head');
assert.ok(
ids(other.draw).every((id) => !mine.includes(id)),
'a second layer has ids of its own',
);
for (const id of mine) assert.equal(draw.set(id).show, true, id);
feeds.set({
configured: true,
records: [record({ icao: 'a1b2c3', band: '978', source: 'feed' })],
});
await layer.update();
assert.ok(ringOf(draw, 'local-adsb:a1b2c3'));
// Silent long enough to expire: its ring goes with it.
clock.now = 200_000;
await layer.update();
assert.equal(iconOf(draw, 'local-adsb:a1b2c3'), undefined);
assert.equal(ringOf(draw, 'local-adsb:a1b2c3'), undefined);
await layer.disable();
for (const id of mine) assert.equal(draw.set(id).show, false, id);
await layer.enable();
for (const id of mine) assert.equal(draw.set(id).show, true, id);
layer.destroy();
assert.deepEqual(ids(draw), [], 'every set disposed');
});
test('row status reflects decoder feeds and the browser SDR together', () => {
@@ -1053,11 +1179,14 @@ test('the last aircraft expiring removes its 3D model and cancels a pending load
assert.equal(late.destroyed, true);
});
/** A pick on a draw-port icon of the layer's, as the renderer reports it. */
function iconPick(id) {
return { primitive: {}, id: { set: 'local-adsb:1:markers', id } };
}
/** A viewer with a canvas and scripted picks, plus the layer's click action. */
function clickHarness() {
const base = fakeViewer();
const scene = {
...base.viewer.scene,
canvas: {},
pickResult: null,
drillResult: [],
@@ -1068,13 +1197,12 @@ function clickHarness() {
return scene.drillResult;
},
};
const viewer = { ...base.viewer, scene };
const input = fakeInput(viewer);
const base = fakeViewer({ scene });
return {
scene,
viewer: { ...base, viewer },
viewer: base,
click() {
input.click(new Cesium.Cartesian2(10, 10));
base.input.click(new Cesium.Cartesian2(10, 10));
},
};
}
@@ -1089,9 +1217,7 @@ test('clicking the selected aircraft keeps it selected and republishes its card'
t.after(() => layer.destroy());
receiver.set({ aircraft: [record()] });
await layer.update();
const entity =
harness.viewer.sources[0].entities.getById('local-adsb:abc123');
harness.scene.pickResult = { id: entity, primitive: {} };
harness.scene.pickResult = iconPick('local-adsb:abc123');
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
// Its card may have been displaced (another readout, a camera move): a
@@ -1106,7 +1232,6 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
const clock = { now: 100_000 };
const harness = clickHarness();
const owners = new Map();
const { resolvePickId } = await import('../../data/pickRegistry.js');
const { layer, calls } = await enabledLayer(receiver, clock, null, {
viewer: harness.viewer,
services: {
@@ -1129,7 +1254,7 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
});
await layer.update();
const [first, second] = ['abc123', 'def456'].map((icao) =>
harness.viewer.sources[0].entities.getById(`local-adsb:${icao}`),
iconPick(`local-adsb:${icao}`),
);
// A photoreal tile (no pick id) drawn over the 3D model at this pixel.
harness.scene.pickResult = { primitive: { tileset: true } };
@@ -1142,19 +1267,13 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
// The selected aircraft's trail crosses another local aircraft's marker.
harness.scene.pickResult = { id: { id: 'gev-trail:local-adsb-head-1' } };
harness.scene.drillResult = [
harness.scene.pickResult,
{ id: second, primitive: {} },
];
harness.scene.drillResult = [harness.scene.pickResult, second];
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123', 'local-adsb:def456']);
// Another layer's own contact on top is that layer's click.
harness.scene.pickResult = { id: 'abc123', primitive: {} };
harness.scene.drillResult = [
harness.scene.pickResult,
{ id: first, primitive: {} },
];
harness.scene.drillResult = [harness.scene.pickResult, first];
harness.click();
assert.equal(calls.selected.length, 2, 'the Flights contact is not taken');
});
+7 -5
View File
@@ -36,11 +36,11 @@ const specKey = (spec) => `${spec.url}@${spec.scale}`;
* offset, and without a resolved ground it stays a billboard.
* @param {object} options
* @param {object} options.viewer Cesium viewer.
* @param {Cesium.Color} options.color Model tint.
* @param {string} options.color Model tint, a CSS colour.
* @param {(url: string) => string} options.resolveAsset
* @param {object|null} [options.groundSnap] `createGroundSnap()` instance.
* @param {(options: object) => Promise<object>} [options.loadModel]
* @returns {object}
* @returns {object|null} Null on a viewer that draws no primitives.
*/
export function createLocalAdsbModels({
viewer,
@@ -49,6 +49,8 @@ export function createLocalAdsbModels({
groundSnap = null,
loadModel = (options) => Cesium.Model.fromGltfAsync(options),
}) {
if (!viewer.scene?.primitives) return null;
const tint = Cesium.Color.fromCssColorString(color);
const collection = new Cesium.PrimitiveCollection();
viewer.scene.primitives.add(collection);
/** @type {Map<string, import('../../data/modelRecord.js').ModelRecord>} id -> admitted model */
@@ -97,7 +99,7 @@ export function createLocalAdsbModels({
environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
minimumPixelSize: MODEL_MIN_PX,
scale: spec.scale,
color,
color: tint,
colorBlendMode: Cesium.ColorBlendMode.MIX,
colorBlendAmount: spec.blendAmount,
id,
@@ -177,9 +179,9 @@ export function createLocalAdsbModels({
if (!marker.onGround) return marker.position;
const record = models.get(id);
// The vertical sample must hit the tile skin, not this aircraft's own
// billboard or model.
// model (its icon draws over depth, which height samples pass through).
const height = groundSnap?.heightFor?.(viewer, id, marker.position, () =>
[marker.entity, record?.model].filter(Boolean),
[record?.model].filter(Boolean),
);
if (!Number.isFinite(height)) return null;
const carto = Cesium.Cartographic.fromCartesian(
+128
View File
@@ -2695,3 +2695,131 @@ test('the directions layer draws its markers, flowing route and maneuver dots on
assert.equal(scene.added.length, 0, 'every set let go');
}
});
test('the local ADS-B layer draws its aircraft, 978 MHz rings and trail head on a viewer of its own', async (t) => {
// Materials check their uniforms against the DOM's image classes.
const names = ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas'];
const real = names.map((name) => globalThis[name]);
for (const name of names) globalThis[name] ??= class {};
t.after(() => names.forEach((name, i) => (globalThis[name] = real[i])));
await import('./frame.js');
const { createLocalAdsbLayer } = await import('../../layers/localAdsb/index.js');
const { fakeInput } = await import('../../input/testDoubles.mjs');
const { toLonLatH } = await import('../../geo/ellipsoid.js');
const scene = fakeScene();
// What a frame port over the scene listens to.
scene.preUpdate = new Cesium.Event();
scene.forceRender = () => {};
scene.pick = () => undefined;
scene.drillPick = () => [];
const viewer = {
scene,
clock: new Cesium.Clock(),
isDestroyed: () => false,
};
const clicks = fakeInput(viewer);
const noop = () => {};
const clock = { now: 100_000 };
const aircraft = (icao, band, lat) => ({
icao,
callsign: icao.toUpperCase(),
lat,
lon: 0,
altitudeFt: 10_000,
groundSpeedKt: 180,
trackDeg: 0,
verticalRateFpm: 0,
lastPositionAt: clock.now,
lastMessageAt: clock.now,
messageCount: 3,
band,
source: 'feed',
});
const records = [aircraft('abc123', '1090', 0), aircraft('a1b2c3', '978', 0.1)];
const layer = createLocalAdsbLayer({
receiver: {
getState: () => ({ aircraft: [] }),
subscribe: () => noop,
setMode: async () => true,
},
feeds: {
getState: () => ({ configured: true, feeds: [], records }),
subscribe: () => noop,
start: noop,
stop: noop,
},
services: {
render: { governorRequestRender: noop },
context: {
registerEntityContext: noop,
selectEntityContext: (carrier) => ({ id: 'local-adsb:abc123', carrier }),
getSelectedEntityContext: () => ({ id: 'local-adsb:abc123' }),
clearSelectedEntityContextForLayer: noop,
removeEntityContextsForLayer: noop,
},
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
trails: { createTrail: () => ({ setPositions: noop, destroy: noop }) },
},
now: () => clock.now,
});
layer.init(viewer);
await layer.enable();
await layer.update();
assert.equal(layer.selectAircraft('abc123'), true);
const hostOf = (suffix) =>
scene.added.find((host) => host.drawSetId?.endsWith(suffix));
// Aircraft: magenta icons drawn over depth out to 2,000 km.
const markers = hostOf(':markers');
assert.ok(markers instanceof Cesium.BillboardCollection);
assert.equal(markers.length, 2);
const icon = markers.get(0);
assert.equal(icon.id.id, 'local-adsb:abc123');
assert.equal(icon.disableDepthTestDistance, Infinity);
assert.equal(icon.distanceDisplayCondition.far, 2_000_000);
assert.ok(icon.scaleByDistance instanceof Cesium.NearFarScalar);
assert.deepEqual(
[icon.scaleByDistance.near, icon.scaleByDistance.nearValue],
[1000, 3],
);
assert.ok(
icon.color.equals(Cesium.Color.fromCssColorString('#ff4fd8')),
);
// The UAT-only aircraft's ring: an outline, shown as far as it is.
const rings = hostOf(':rings');
assert.ok(rings instanceof Cesium.PointPrimitiveCollection);
assert.equal(rings.length, 1);
const ring = rings.get(0);
assert.equal(ring.id.id, 'local-adsb:a1b2c3');
assert.equal(ring.outlineWidth, 1.5);
assert.equal(ring.color.alpha, 0);
assert.equal(ring.distanceDisplayCondition.far, 2_000_000);
// Selected at its fix, the head has no length yet.
const head = hostOf(':trail-head');
assert.equal(head.get(1).length, 0);
// A frame flies them on, in place.
const before = toLonLatH(icon.position).lat;
clock.now += 1_000;
scene.preRender.raiseEvent(scene, Cesium.JulianDate.now());
assert.equal(markers.get(0), icon, 'the same billboard');
assert.ok(toLonLatH(icon.position).lat > before);
assert.equal(rings.get(0).id.id, 'local-adsb:a1b2c3');
// The head now runs from the fix to the aircraft, dimmed, not hidden,
// behind the surface.
assert.equal(hostOf(':trail-head'), head, 'the same lines');
const deep = head.get(1);
assert.equal(deep.length, 1);
const line = deep.get(0);
assert.ok(line instanceof Cesium.Primitive);
assert.match(line.geometryInstances.id.id, /^gev-trail:local-adsb-head-/);
const fail = line.depthFailAppearance.material.uniforms.color;
assert.ok(
fail.equals(Cesium.Color.fromCssColorString('#ff4fd8').withAlpha(0.45)),
);
await layer.disable();
layer.destroy();
clicks.destroy();
assert.equal(hostOf(':markers'), undefined, 'every set let go');
});
-1
View File
@@ -50,7 +50,6 @@
"src/layers/launches/launchPad.js",
"src/layers/launches/orbitRendering.js",
"src/layers/launches/rendering.js",
"src/layers/localAdsb/index.js",
"src/layers/localAdsb/models.js",
"src/layers/military/lifecycle.js",
"src/layers/military/motion.js",