Draw Local ADS-B aircraft models through the draw port

Local ADS-B's 3D aircraft are now one models set of the renderer's draw
port, re-posed in place each frame, instead of Cesium models of their own.
Ground placement samples heights through the query port and sees through
the layer's sets by id; clicks read the dispatcher's draw-set hit and the
query port's drill. A class change keeps the drawn model, at its own belly
offset, until the new asset is ready; a scale-only change applies at once.
The models file leaves the Cesium allow-list.

Cesium model sets retry a failed load when its item is next updated after
a short wait, and parse an item's tint only when it changes.
This commit is contained in:
Sameh Khamis committed 2026-11-07 15:43:33 -08:00
1 parent 20155ff3fa
commit 20fdfd492e
10 files changed
+502 -375

No files matched your search

+11 -7
View File
@@ -19,13 +19,6 @@ const SOURCES = [
name: 'militaryFlights', name: 'militaryFlights',
source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)), source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)),
}, },
{
name: 'localAdsb',
source: readFileSync(
new URL('../layers/localAdsb/models.js', import.meta.url),
'utf8',
),
},
]; ];
test('the shared option turns the dynamic environment map off', () => { test('the shared option turns the dynamic environment map off', () => {
@@ -49,3 +42,14 @@ for (const { name, source } of SOURCES) {
); );
}); });
} }
test('localAdsb: its draw-port models skip the dynamic environment map', () => {
const source = readFileSync(
new URL('../layers/localAdsb/models.js', import.meta.url),
'utf8',
);
assert.match(
source,
/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/,
);
});
+37 -21
View File
@@ -6,7 +6,12 @@ import {
} from '../../data/iconOrientation.js'; } from '../../data/iconOrientation.js';
import { fromDegreesInto, toLonLatH } from '../../geo/ellipsoid.js'; import { fromDegreesInto, toLonLatH } from '../../geo/ellipsoid.js';
import { hexColor } from '../../render/color.js'; import { hexColor } from '../../render/color.js';
import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js'; import {
drawOf,
findCamera,
findFrame,
findQuery,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js'; import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js'; import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
import { routePlausible } from '../../data/routePlausible.js'; import { routePlausible } from '../../data/routePlausible.js';
@@ -105,8 +110,6 @@ const DEFAULT_DISPLAY = Object.freeze({
* (`createGroundSnap`). * (`createGroundSnap`).
* @param {() => number} [options.now] Clock, injectable for tests. * @param {() => number} [options.now] Clock, injectable for tests.
* @param {(url: string) => string} [options.resolveAsset] Model URL resolver. * @param {(url: string) => string} [options.resolveAsset] Model URL resolver.
* @param {(options: object) => Promise<object>} [options.loadModel] Model
* loader, injectable for tests.
* @returns {object} Data-layer module. * @returns {object} Data-layer module.
*/ */
export function createLocalAdsbLayer({ export function createLocalAdsbLayer({
@@ -115,7 +118,6 @@ export function createLocalAdsbLayer({
services, services,
now = Date.now, now = Date.now,
resolveAsset = (url) => url, resolveAsset = (url) => url,
loadModel,
}) { }) {
if (typeof receiver?.getState !== 'function') if (typeof receiver?.getState !== 'function')
throw new TypeError('Local ADS-B requires a receiver session'); throw new TypeError('Local ADS-B requires a receiver session');
@@ -534,6 +536,7 @@ export function createLocalAdsbLayer({
function showSets(show) { function showSets(show) {
if (sets) for (const set of Object.values(sets)) set.show = show; if (sets) for (const set of Object.values(sets)) set.show = show;
if (models) models.show = show;
} }
function updateRenderHold() { function updateRenderHold() {
@@ -632,12 +635,12 @@ export function createLocalAdsbLayer({
return true; return true;
} }
/** /** A local aircraft's id when `hit` is one of its markers or models. */
* The id under a pick, through the shared pick-id resolver: a draw-set function ownHit(hit) {
* item's id (markers, the trail head) or a model's. if (!hit || hit.surface || !markers.has(hit.id)) return null;
*/ return hit.set === sets?.markers.id || hit.set === models?.setId
function pickedId(picked) { ? hit.id
return services.picking.resolvePickId?.(picked) ?? null; : null;
} }
function ownedElsewhere(id) { function ownedElsewhere(id) {
@@ -651,25 +654,35 @@ export function createLocalAdsbLayer({
* *
* The frontmost pick decides, except that something no layer owns (a * The frontmost pick decides, except that something no layer owns (a
* photoreal tile, a ring) or a trail line drawn over or through a local * photoreal tile, a ring) or a trail line drawn over or through a local
* aircraft does not hide it: the click looks underneath for the aircraft. * aircraft does not hide it: the click looks underneath, through the
* renderer's draw-set picks, for the aircraft.
*/ */
function clickTarget(event) { function clickTarget(event) {
const top = pickedId(event.pick); const top = event.drawHit;
if (top && markers.has(top)) return top; const own = ownHit(top);
const trail = Boolean(top) && String(top).startsWith(TRAIL_PICK_PREFIX); if (own) return own;
if (ownedElsewhere(top) && !trail) return 'other'; // What is on top when it is no draw-set item: a sibling's contact
// drawn on its own, a tile, or (on a coarse pointer) a contact found
// under the touch.
const topId = top ? top.id : event.id;
if (!top && topId && markers.has(topId)) return topId;
const trail = Boolean(topId) && String(topId).startsWith(TRAIL_PICK_PREFIX);
if (ownedElsewhere(topId) && !trail) return 'other';
let hits = []; let hits = [];
try { try {
hits = event.drill(CLICK_DRILL_LIMIT); hits =
findQuery(viewer)?.drillPick(event.position.x, event.position.y, {
limit: CLICK_DRILL_LIMIT,
}) ?? [];
} catch { } catch {
hits = []; hits = [];
} }
for (const hit of hits) { for (const hit of hits) {
const id = pickedId(hit); const id = ownHit(hit);
if (id && markers.has(id)) return id; if (id) return id;
if (id && String(id).startsWith(TRAIL_PICK_PREFIX)) continue; if (String(hit.id).startsWith(TRAIL_PICK_PREFIX)) continue;
// A sibling layer's contact above ours takes the click. // A sibling layer's contact above ours takes the click.
if (ownedElsewhere(id)) return 'other'; if (ownedElsewhere(hit.id)) return 'other';
} }
return trail ? 'trail' : null; return trail ? 'trail' : null;
} }
@@ -761,10 +774,13 @@ export function createLocalAdsbLayer({
}; };
models = createLocalAdsbModels({ models = createLocalAdsbModels({
viewer, viewer,
draw,
camera: findCamera(viewer),
setId: `${prefix}:models`,
seeThrough: [sets.markers.id, sets.rings.id],
color: LOCAL_ADSB_COLOR, color: LOCAL_ADSB_COLOR,
resolveAsset, resolveAsset,
groundSnap: services.groundSnap?.createGroundSnap?.() || null, groundSnap: services.groundSnap?.createGroundSnap?.() || null,
...(loadModel ? { loadModel } : {}),
}); });
services.geoid services.geoid
?.ensureGeoidReady?.() ?.ensureGeoidReady?.()
+150 -159
View File
@@ -12,9 +12,10 @@ import {
localAdsbReceiverLine, localAdsbReceiverLine,
localAdsbStatus, localAdsbStatus,
} from './index.js'; } from './index.js';
import { createLocalAdsbModels } from './models.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { resolvePickId } from '../../data/pickRegistry.js'; import { resolvePickId } from '../../data/pickRegistry.js';
import { toLonLatH } from '../../geo/ellipsoid.js'; import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { fakeInput } from '../../input/testDoubles.mjs'; import { fakeInput } from '../../input/testDoubles.mjs';
import { hexColor } from '../../render/color.js'; import { hexColor } from '../../render/color.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
@@ -117,17 +118,21 @@ function fakeServices() {
} }
/** /**
* A viewer with a fake draw port and a camera port whose screen axes are * A viewer with a fake draw port, a camera port whose screen axes are east
* east and north at (0°, 0°); `viewer` adds the Cesium-shaped members the * and north at (0°, 0°), and a query port whose drill picks are the
* 3D models read. * viewer's `drillHits`; `pose` sets the camera.
*/ */
function fakeViewer(viewer = { scene: {} }) { function fakeViewer(viewer = { scene: {} }, pose = {}) {
const camera = fakeCameraPort({ const camera = fakeCameraPort({
pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } }, pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 }, ...pose },
}); });
const { draw } = bindFakeDraw(viewer, { camera: camera.port }); const query = {
drillPick: (x, y, { limit } = {}) =>
(viewer.drillHits ?? []).slice(0, limit),
};
const { draw } = bindFakeDraw(viewer, { camera: camera.port, query });
const input = fakeInput(viewer); const input = fakeInput(viewer);
return { draw, viewer, input }; return { draw, viewer, input, camera };
} }
function record(overrides = {}) { function record(overrides = {}) {
@@ -182,31 +187,16 @@ function fakeFeeds(initial = {}) {
}; };
} }
/** A viewer whose camera looks down on (0°, 0°) from 50 km, with primitives. */ /** A viewer whose camera looks down on (0°, 0°) from 50 km. */
function modelViewer(primitives) { function modelViewer() {
const camera = { return fakeViewer(
positionWC: new Cesium.Cartesian3(6_378_137 + 50_000, 0, 0), { scene: {} },
positionCartographic: new Cesium.Cartographic(0, 0, 50_000), {
directionWC: new Cesium.Cartesian3(-1, 0, 0), height: 50_000,
frustum: { position: { x: 6_378_137 + 50_000, y: 0, z: 0 },
computeCullingVolume: () => ({ direction: { x: -1, y: 0, z: 0 },
computeVisibility: () => Cesium.Intersect.INSIDE,
}),
}, },
}; );
return fakeViewer({
camera,
scene: {
camera,
primitives: {
add(collection) {
primitives.push(collection);
return collection;
},
remove() {},
},
},
});
} }
async function enabledLayer(receiver, clock, feeds = null, options = {}) { async function enabledLayer(receiver, clock, feeds = null, options = {}) {
@@ -217,7 +207,6 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) {
feeds, feeds,
services: { ...services, ...options.services }, services: { ...services, ...options.services },
now: () => clock.now, now: () => clock.now,
loadModel: options.loadModel,
}); });
layer.init(viewer); layer.init(viewer);
await layer.enable(); await layer.enable();
@@ -572,65 +561,43 @@ test('adsbdb type, operator and route reach the card for the selected aircraft o
test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t) => { test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 }; const clock = { now: 100_000 };
const loads = [];
const display = { models3d: true, models3dMode: 'proximity' }; const display = { models3d: true, models3dMode: 'proximity' };
const primitives = [];
const { layer, draw } = await enabledLayer(receiver, clock, null, { const { layer, draw } = await enabledLayer(receiver, clock, null, {
services: { display: { getParams: () => display } }, services: { display: { getParams: () => display } },
viewer: modelViewer(primitives), viewer: modelViewer(),
loadModel: async (options) => {
const model = {
...options,
ready: true,
show: true,
modelMatrix: new Cesium.Matrix4(),
destroyed: false,
destroy() {
this.destroyed = true;
},
isDestroyed() {
return this.destroyed;
},
update() {},
};
loads.push(model);
return model;
},
}); });
t.after(() => layer.destroy()); t.after(() => layer.destroy());
receiver.set({ aircraft: [record({ icao: 'a0b702', category: 'A7' })] }); receiver.set({ aircraft: [record({ icao: 'a0b702', category: 'A7' })] });
await layer.update(); await layer.update();
await new Promise((resolve) => setImmediate(resolve)); const models = layerSet(draw, ':models');
await layer.update(); const model = () => models.items.get('local-adsb:a0b702');
assert.equal(loads.length, 1); assert.ok(model(), 'admitted');
const [model] = loads; assert.equal(model().url, '/models/bell206.glb', 'the Flights helicopter');
assert.equal( assert.equal(model().scale, 1);
model.url, assert.deepEqual(model().tint, MAGENTA);
'/models/bell206.glb', assert.deepEqual(model().colorBlend, { mode: 'mix', amount: 0.94 });
'the Flights helicopter model', assert.equal(model().environmentMap, false);
);
assert.equal(model.scale, 1);
assert.equal(model.id, 'local-adsb:a0b702');
assert.ok(
Cesium.Color.equals(
model.color,
Cesium.Color.fromCssColorString('#ff4fd8'),
),
);
assert.equal(model.colorBlendMode, Cesium.ColorBlendMode.MIX);
assert.equal(model.colorBlendAmount, 0.94);
assert.equal(model.show, true);
const heli = () => iconOf(draw, 'local-adsb:a0b702'); const heli = () => iconOf(draw, 'local-adsb:a0b702');
assert.equal(heli().show, true, 'the icon until the model is ready');
draw.ready(models.spec.id, 'local-adsb:a0b702');
await layer.update();
assert.equal(model().show, true);
assert.equal(heli().show, false, 'the model is the visual'); assert.equal(heli().show, false, 'the model is the visual');
const origin = Cesium.Matrix4.getTranslation( assert.ok(
model.modelMatrix, Math.hypot(
new Cesium.Cartesian3(), model().pos.x - heli().pos.x,
model().pos.y - heli().pos.y,
model().pos.z - heli().pos.z,
) < 1,
'where its icon is',
); );
assert.ok(Cesium.Cartesian3.distance(origin, heli().pos) < 1); const writes = models.writes;
await layer.update();
assert.ok(models.writes > writes, 'moved in place each frame');
display.models3d = false; display.models3d = false;
await layer.update(); await layer.update();
assert.equal(model.destroyed || !primitives[0].contains(model), true); assert.equal(models.items.size, 0, 'models dropped');
assert.equal(heli().show, true, 'the icon is back'); assert.equal(heli().show, true, 'the icon is back');
}); });
@@ -895,7 +862,7 @@ test('the layer draws into sets of its own, shown while it is enabled and let go
.filter((record) => !record.disposed) .filter((record) => !record.disposed)
.map((record) => record.spec.id); .map((record) => record.spec.id);
const mine = ids(draw); const mine = ids(draw);
assert.equal(mine.length, 2, 'markers and rings'); assert.equal(mine.length, 3, 'markers, rings and models');
assert.ok( assert.ok(
ids(other.draw).every((id) => !mine.includes(id)), ids(other.draw).every((id) => !mine.includes(id)),
'a second layer has ids of its own', 'a second layer has ids of its own',
@@ -1107,87 +1074,35 @@ test('row status names two same-band feeds by their ordinal labels', () => {
); );
}); });
function fakeModel(options) { test('the last aircraft expiring removes its 3D model', async (t) => {
return {
...options,
ready: true,
show: true,
modelMatrix: new Cesium.Matrix4(),
destroyed: false,
destroy() {
this.destroyed = true;
},
isDestroyed() {
return this.destroyed;
},
update() {},
};
}
test('the last aircraft expiring removes its 3D model and cancels a pending load', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 }; const clock = { now: 100_000 };
const primitives = []; const { layer, draw } = await enabledLayer(receiver, clock, null, {
const loads = [];
const deferred = [];
const { layer } = await enabledLayer(receiver, clock, null, {
services: { services: {
display: { display: {
getParams: () => ({ models3d: true, models3dMode: 'proximity' }), getParams: () => ({ models3d: true, models3dMode: 'proximity' }),
}, },
}, },
viewer: modelViewer(primitives), viewer: modelViewer(),
loadModel: (options) => {
const model = fakeModel(options);
loads.push(model);
if (options.id === 'local-adsb:abc123') return Promise.resolve(model);
return new Promise((resolve) => deferred.push(() => resolve(model)));
},
}); });
t.after(() => layer.destroy()); t.after(() => layer.destroy());
receiver.set({ aircraft: [record({ category: 'A7' })] }); receiver.set({ aircraft: [record({ category: 'A7' })] });
await layer.update(); await layer.update();
await new Promise((resolve) => setImmediate(resolve)); const models = layerSet(draw, ':models');
await layer.update(); assert.ok(models.items.has('local-adsb:abc123'));
const [model] = loads;
assert.equal(model.show, true, 'the model is the visual');
assert.ok(primitives[0].contains(model));
// Its position ages out: no markers remain, so no per-frame model pass. // Its position ages out: no markers remain, so no per-frame model pass.
clock.now = 160_000; clock.now = 160_000;
await layer.update(); await layer.update();
assert.equal( assert.equal(models.items.size, 0, 'no model left behind');
model.destroyed || !primitives[0].contains(model),
true,
'the expired aircraft leaves no model behind',
);
// A load still in flight when its aircraft expires is never admitted. layer.destroy();
clock.now = 200_000; assert.equal(models.disposed, true, 'the set goes with the layer');
receiver.set({
aircraft: [
record({
icao: 'def456',
lastPositionAt: 200_000,
lastMessageAt: 200_000,
}),
],
});
await layer.update();
clock.now = 260_000;
await layer.update();
assert.equal(deferred.length, 1, 'a load was in flight');
deferred[0]();
await new Promise((resolve) => setImmediate(resolve));
const late = loads.at(-1);
assert.equal(late.id, 'local-adsb:def456');
assert.equal(primitives[0].contains(late), false);
assert.equal(late.destroyed, true);
}); });
/** A pick on a draw-port icon of the layer's, as the renderer reports it. */ /** A pick on a draw-port icon of the layer's, as the renderer reports it. */
function iconPick(id) { function iconPick(draw, id) {
return { primitive: {}, id: { set: 'local-adsb:1:markers', id } }; return { primitive: {}, id: { set: layerSet(draw, ':markers').spec.id, id } };
} }
/** A viewer with a canvas and scripted picks, plus the layer's click action. */ /** A viewer with a canvas and scripted picks, plus the layer's click action. */
@@ -1195,13 +1110,9 @@ function clickHarness() {
const scene = { const scene = {
canvas: {}, canvas: {},
pickResult: null, pickResult: null,
drillResult: [],
pick() { pick() {
return scene.pickResult; return scene.pickResult;
}, },
drillPick() {
return scene.drillResult;
},
}; };
const base = fakeViewer({ scene }); const base = fakeViewer({ scene });
return { return {
@@ -1217,13 +1128,13 @@ test('clicking the selected aircraft keeps it selected and republishes its card'
const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 }; const clock = { now: 100_000 };
const harness = clickHarness(); const harness = clickHarness();
const { layer, calls } = await enabledLayer(receiver, clock, null, { const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
viewer: harness.viewer, viewer: harness.viewer,
}); });
t.after(() => layer.destroy()); t.after(() => layer.destroy());
receiver.set({ aircraft: [record()] }); receiver.set({ aircraft: [record()] });
await layer.update(); await layer.update();
harness.scene.pickResult = iconPick('local-adsb:abc123'); harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123');
harness.click(); harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']); assert.deepEqual(calls.selected, ['local-adsb:abc123']);
// Its card may have been displaced (another readout, a camera move): a // Its card may have been displaced (another readout, a camera move): a
@@ -1238,7 +1149,7 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
const clock = { now: 100_000 }; const clock = { now: 100_000 };
const harness = clickHarness(); const harness = clickHarness();
const owners = new Map(); const owners = new Map();
const { layer, calls } = await enabledLayer(receiver, clock, null, { const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
viewer: harness.viewer, viewer: harness.viewer,
services: { services: {
picking: { picking: {
@@ -1259,27 +1170,107 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
aircraft: [record(), record({ icao: 'def456', lat: 0.01 })], aircraft: [record(), record({ icao: 'def456', lat: 0.01 })],
}); });
await layer.update(); await layer.update();
const [first, second] = ['abc123', 'def456'].map((icao) => const hit = (suffix, id) => ({
iconPick(`local-adsb:${icao}`), set: suffix.startsWith(':') ? layerSet(draw, suffix).spec.id : suffix,
); id,
surface: false,
});
const second = hit(':markers', 'local-adsb:def456');
// A photoreal tile (no pick id) drawn over the 3D model at this pixel. // A photoreal tile (no pick id) drawn over the 3D model at this pixel.
harness.scene.pickResult = { primitive: { tileset: true } }; harness.scene.pickResult = { primitive: { tileset: true } };
harness.scene.drillResult = [ harness.viewer.viewer.drillHits = [hit(':models', 'local-adsb:abc123')];
harness.scene.pickResult,
{ primitive: { id: 'local-adsb:abc123' }, id: 'local-adsb:abc123' },
];
harness.click(); harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']); assert.deepEqual(calls.selected, ['local-adsb:abc123']);
// The selected aircraft's trail crosses another local aircraft's marker. // The selected aircraft's trail crosses another local aircraft's marker.
harness.scene.pickResult = { id: { id: 'gev-trail:local-adsb-head-1' } }; const trail = hit('trail:1', 'gev-trail:1:head');
harness.scene.drillResult = [harness.scene.pickResult, second]; harness.scene.pickResult = { primitive: {}, id: trail };
harness.viewer.viewer.drillHits = [trail, second];
harness.click(); harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123', 'local-adsb:def456']); assert.deepEqual(calls.selected, ['local-adsb:abc123', 'local-adsb:def456']);
// Another layer's own contact on top is that layer's click. // Another layer's own contact on top is that layer's click.
harness.scene.pickResult = { id: 'abc123', primitive: {} }; harness.scene.pickResult = { id: 'abc123', primitive: {} };
harness.scene.drillResult = [harness.scene.pickResult, first]; harness.viewer.viewer.drillHits = [hit(':markers', 'local-adsb:abc123')];
harness.click(); harness.click();
assert.equal(calls.selected.length, 2, 'the Flights contact is not taken'); assert.equal(calls.selected.length, 2, 'the Flights contact is not taken');
}); });
test('a grounded aircraft changing class keeps its drawn model on its own belly offset until the new one is ready', () => {
const { draw, viewer, camera } = modelViewer();
const models = createLocalAdsbModels({
viewer,
draw,
camera: camera.port,
setId: 'test:models',
color: '#ff00ff',
resolveAsset: (url) => url,
groundSnap: { heightFor: () => 100, forget() {}, clear() {} },
});
const marker = {
position: fromDegrees(0, 0, 0),
courseDeg: 0,
klass: 'light',
onGround: true,
};
const markers = new Map([['a', marker]]);
const display = { models3d: true, models3dMode: 'proximity' };
const height = () =>
toLonLatH(draw.sets.get('test:models').items.get('a').pos).height;
models.frame(markers, display, 100_000);
draw.ready('test:models', 'a');
models.frame(markers, display, 100_001);
assert.ok(Math.abs(height() - 101.36) < 0.01, 'light: its belly offset');
marker.klass = 'widebody';
models.frame(markers, display, 200_000);
assert.equal(
draw.sets.get('test:models').items.get('a').url,
'/models/b789.glb',
);
assert.ok(Math.abs(height() - 101.36) < 0.01, 'the light model still draws');
draw.ready('test:models', 'a');
models.frame(markers, display, 200_001);
assert.ok(Math.abs(height() - 107.81) < 0.01, 'the widebody, on its own');
models.destroy();
});
test('a class change takes its belly offset with the new model, however soon it is ready; a scale-only change at once', () => {
const { draw, viewer, camera } = modelViewer();
const models = createLocalAdsbModels({
viewer,
draw,
camera: camera.port,
setId: 'test:models',
color: '#ff00ff',
resolveAsset: (url) => url,
groundSnap: { heightFor: () => 100, forget() {}, clear() {} },
});
const marker = {
position: fromDegrees(0, 0, 0),
courseDeg: 0,
klass: 'narrowbody',
onGround: true,
};
const markers = new Map([['a', marker]]);
const display = { models3d: true, models3dMode: 'proximity' };
const item = () => draw.sets.get('test:models').items.get('a');
const height = () => toLonLatH(item().pos).height;
models.frame(markers, display, 100_000);
draw.ready('test:models', 'a');
models.frame(markers, display, 100_001);
assert.ok(Math.abs(height() - 106.719) < 0.01, 'narrowbody');
// The same asset at another scale: no load, no ready.
marker.klass = 'glider';
models.frame(markers, display, 100_002);
assert.equal(item().url, '/models/airplane.glb');
assert.equal(item().scale, 0.75);
assert.ok(Math.abs(height() - 105.03925) < 0.01, 'at once');
// Another asset, ready before the next eligibility pass.
marker.klass = 'widebody';
models.frame(markers, display, 100_003);
assert.ok(Math.abs(height() - 105.03925) < 0.01, 'the old model draws');
draw.ready('test:models', 'a');
models.frame(markers, display, 100_004);
assert.ok(Math.abs(height() - 107.81) < 0.01, 'the widebody, on its own');
models.destroy();
});
+169 -169
View File
@@ -1,6 +1,13 @@
import * as Cesium from 'cesium';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { selectModelEligible } from '../../data/modelEligibility.js'; import { selectModelEligible } from '../../data/modelEligibility.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
import {
distanceSquared,
dot,
RADIANS_PER_DEGREE,
sub,
} from '../../geo/vector.js';
import { cssColor } from '../../render/color.js';
import { civilAircraftModelSpec } from '../flights/modelSpec.js'; import { civilAircraftModelSpec } from '../flights/modelSpec.js';
import { import {
FLEET_DR_INTERVAL_MS, FLEET_DR_INTERVAL_MS,
@@ -15,154 +22,147 @@ import {
MODEL_PROX_KEEP_M, MODEL_PROX_KEEP_M,
} from '../flights/policy.js'; } from '../flights/policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
import {
createModelRecord,
placeModel,
showModel,
} from '../../data/modelRecord.js';
const specKey = (spec) => `${spec.url}@${spec.scale}`; /** Whether `point` is inside the eye's view cone (`pose`), a metre's slack. */
function inView(pose, point) {
const v = sub(point, pose.position);
const depth = dot(v, pose.direction);
if (depth < -1) return false;
const tanY = Math.tan(pose.fovy / 2);
const tanX = tanY * pose.aspectRatio;
return (
Math.abs(dot(v, pose.right)) <= Math.max(0, depth) * tanX + 1 &&
Math.abs(dot(v, pose.up)) <= Math.max(0, depth) * tanY + 1
);
}
/** /**
* 3D models for Local ADS-B aircraft under the DISPLAY rail's 3D toggle. * 3D models for Local ADS-B aircraft under the DISPLAY rail's 3D toggle,
* drawn as one `models` set of the renderer's draw port.
* *
* Mirrors the public Flights fleet: models only below the altitude ceiling, * Mirrors the public Flights fleet: models only below the altitude ceiling,
* the same proximity/all caps and add/keep radii, the same visible-first * the same proximity/all caps and add/keep radii, the same visible-first
* eligibility (`selectModelEligible`), the same per-class asset and scale * eligibility (`selectModelEligible`), the same per-class asset and scale
* (`civilAircraftModelSpec`) and the same tint path (a MIX colour blend, here * (`civilAircraftModelSpec`) and the same tint path (a MIX colour blend, here
* magenta, as Flights tints military amber). Each model owns its matrix. A * magenta, as Flights tints military amber). A billboard stays the visual
* billboard stays the visual until its model is loaded AND placed; a grounded * until its model is ready (the set's `ready`) AND placed; a grounded
* aircraft's model rides the one-shot ground snap plus the class belly * aircraft's model rides the one-shot ground snap plus the class belly
* offset, and without a resolved ground it stays a billboard. * offset, and without a resolved ground it stays a billboard. Models move
* and turn in place each frame; only a class change loads another asset.
* @param {object} options * @param {object} options
* @param {object} options.viewer Cesium viewer. * @param {object} options.viewer The viewer the layer draws on; the ground
* snap samples through it.
* @param {object} options.draw Draw port (`drawOf(viewer)`).
* @param {object} options.camera Camera port (`findCamera(viewer)`).
* @param {string} options.setId The models set's id.
* @param {string[]} [options.seeThrough] The layer's other set ids ground
* samples see through (its markers).
* @param {string} options.color Model tint, a CSS colour. * @param {string} options.color Model tint, a CSS colour.
* @param {(url: string) => string} options.resolveAsset * @param {(url: string) => string} options.resolveAsset
* @param {object|null} [options.groundSnap] `createGroundSnap()` instance. * @param {object|null} [options.groundSnap] `createGroundSnap()` instance.
* @param {(options: object) => Promise<object>} [options.loadModel] * @returns {object|null} Null where the renderer draws no models.
* @returns {object|null} Null on a viewer that draws no primitives.
*/ */
export function createLocalAdsbModels({ export function createLocalAdsbModels({
viewer, viewer,
draw,
camera,
setId,
seeThrough = [],
color, color,
resolveAsset, resolveAsset,
groundSnap = null, groundSnap = null,
loadModel = (options) => Cesium.Model.fromGltfAsync(options),
}) { }) {
if (!viewer.scene?.primitives) return null; if (typeof draw?.models !== 'function' || !camera) return null;
const tint = Cesium.Color.fromCssColorString(color); const tint = cssColor(color) ?? color;
const collection = new Cesium.PrimitiveCollection(); const set = draw.models({ id: setId, show: false });
viewer.scene.primitives.add(collection); /** What ground samples see through, by set id (with every set not drawn as ground). */
/** @type {Map<string, import('../../data/modelRecord.js').ModelRecord>} id -> admitted model */ const groundSets = [setId, ...seeThrough];
/**
* id -> admitted model. `bellyM` is the offset of the model drawn;
* `nextBellyM` a new asset's, taken once that model is ready (the old one
* draws, at its own offset, until then). `sentUrl` is the asset last
* asked for, `drawnUrl` the one whose model is ready.
* @type {Map<string, {bellyM: number,
* nextBellyM: number|null, sentUrl: string|null,
* drawnUrl: string|null, ready: boolean}>}
*/
const models = new Map(); const models = new Map();
/** @type {Map<string, number>} id -> generation of an in-flight load */
const pending = new Map();
let generation = 0;
let destroyed = false; let destroyed = false;
let lastEligibilityAt = 0; let lastEligibilityAt = 0;
let eligible = new Set(); let eligible = new Set();
const scratchHpr = new Cesium.HeadingPitchRoll(); const offReady = set.on('ready', (id) => {
const scratchMatrix = new Cesium.Matrix4();
const scratchSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.ZERO, 1);
const scratchCarto = new Cesium.Cartographic();
const scratchGround = new Cesium.Cartesian3();
function release(id) {
pending.delete(id);
const record = models.get(id); const record = models.get(id);
if (!record) return; if (!record) return;
models.delete(id); record.ready = true;
if (!collection.isDestroyed()) collection.remove(record.model); record.drawnUrl = record.sentUrl;
groundSnap?.forget?.(id); if (record.nextBellyM !== null) {
record.bellyM = record.nextBellyM;
record.nextBellyM = null;
}
});
function release(ids) {
const gone = [];
for (const id of ids) {
if (!models.delete(id)) continue;
gone.push(id);
groundSnap?.forget?.(id);
}
if (gone.length && !destroyed) set.remove(gone);
} }
function releaseAll() { function releaseAll() {
for (const id of [...models.keys()]) release(id); for (const id of models.keys()) groundSnap?.forget?.(id);
pending.clear(); if (models.size && !destroyed) set.clear();
generation += 1; models.clear();
} }
async function ensure(id, marker, cap) { /**
const spec = civilAircraftModelSpec(marker.klass); * Admit a model for `id`. One admitted keeps its slot through a class
const key = specKey(spec); * change: the frame pass asks for the new asset, loaded in place.
const current = models.get(id); */
if (current?.specKey === key) return; function admit(id, marker, cap) {
if (current) release(id); if (models.has(id) || models.size >= cap) return;
if (pending.has(id) || models.size + pending.size >= cap) return; models.set(id, {
const loadGeneration = generation; bellyM: civilAircraftModelSpec(marker.klass).bellyM,
pending.set(id, loadGeneration); nextBellyM: null,
let model; sentUrl: null,
try { drawnUrl: null,
model = await loadModel({ ready: false,
url: resolveAsset(spec.url),
asynchronous: false,
environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
minimumPixelSize: MODEL_MIN_PX,
scale: spec.scale,
color: tint,
colorBlendMode: Cesium.ColorBlendMode.MIX,
colorBlendAmount: spec.blendAmount,
id,
});
} catch {
if (pending.get(id) === loadGeneration) pending.delete(id);
return;
}
const stale =
destroyed ||
pending.get(id) !== loadGeneration ||
generation !== loadGeneration ||
!eligible.has(id) ||
models.has(id) ||
specKey(civilAircraftModelSpec(marker.klass)) !== key;
if (pending.get(id) === loadGeneration) pending.delete(id);
if (stale) {
model.destroy?.();
return;
}
model.id = id;
const record = createModelRecord(model, {
specKey: key,
bellyM: spec.bellyM,
}); });
// Admitted, not yet the visual: placement turns it on.
showModel(record, false);
collection.add(model);
models.set(id, record);
} }
function regime(preferences) { /**
* The asset `record` is about to ask for: the same model (a scale-only
* class change, or none) takes the offset now; another waits for its
* model's `ready`.
*/
function noteAsset(record, url, bellyM) {
record.sentUrl = url;
if (!record.ready || url === record.drawnUrl) {
record.bellyM = bellyM;
record.nextBellyM = null;
} else {
record.nextBellyM = bellyM;
}
}
function regime(preferences, pose) {
if (!preferences?.models3d) return false; if (!preferences?.models3d) return false;
const height = viewer.camera?.positionCartographic?.height ?? Infinity; return pose.height < MODEL_ALT_CEIL_M;
return height < MODEL_ALT_CEIL_M;
} }
function refreshEligibility(markers, preferences) { function refreshEligibility(markers, preferences, pose) {
const all = preferences.models3dMode === 'all'; const all = preferences.models3dMode === 'all';
const cap = all ? MODEL_MAX_ALL : MODEL_MAX; const cap = all ? MODEL_MAX_ALL : MODEL_MAX;
const addM = all ? MODEL_ALL_ADD_M : MODEL_PROX_ADD_M; const addM = all ? MODEL_ALL_ADD_M : MODEL_PROX_ADD_M;
const keepM = all ? MODEL_ALL_KEEP_M : MODEL_PROX_KEEP_M; const keepM = all ? MODEL_ALL_KEEP_M : MODEL_PROX_KEEP_M;
const camera = viewer.camera;
const cameraPosition = camera.positionWC;
const cull = camera.frustum.computeCullingVolume(
cameraPosition,
camera.directionWC,
camera.upWC,
);
const candidates = []; const candidates = [];
for (const [id, marker] of markers) { for (const [id, marker] of markers) {
if (!marker.position) continue; if (!marker.position) continue;
const distanceSq = Cesium.Cartesian3.distanceSquared( const distanceSq = distanceSquared(pose.position, marker.position);
cameraPosition,
marker.position,
);
if (distanceSq > keepM * keepM) continue; if (distanceSq > keepM * keepM) continue;
Cesium.Cartesian3.clone(marker.position, scratchSphere.center); candidates.push([id, distanceSq, inView(pose, marker.position)]);
candidates.push([
id,
distanceSq,
cull.computeVisibility(scratchSphere) !== Cesium.Intersect.OUTSIDE,
]);
} }
candidates.sort((a, b) => a[1] - b[1]); candidates.sort((a, b) => a[1] - b[1]);
eligible = selectModelEligible(candidates, { eligible = selectModelEligible(candidates, {
@@ -170,32 +170,22 @@ export function createLocalAdsbModels({
addDistSq: addM * addM, addDistSq: addM * addM,
isModeled: (id) => models.has(id), isModeled: (id) => models.has(id),
}); });
for (const id of [...models.keys(), ...pending.keys()]) release([...models.keys()].filter((id) => !eligible.has(id)));
if (!eligible.has(id)) release(id); for (const id of eligible) admit(id, markers.get(id), cap);
for (const id of eligible) void ensure(id, markers.get(id), cap);
} }
function placement(id, marker) { function placement(id, marker) {
if (!marker.onGround) return marker.position; if (!marker.onGround) return marker.position;
const record = models.get(id); const record = models.get(id);
// The vertical sample must hit the tile skin, not this aircraft's own // Height samples see through the draw sets (this set and the markers):
// model (its icon draws over depth, which height samples pass through). // the vertical sample hits the tile skin, not this aircraft.
const height = groundSnap?.heightFor?.(viewer, id, marker.position, () => const height = groundSnap?.heightFor?.(viewer, id, marker.position, {
[record?.model].filter(Boolean), sets: groundSets,
); });
if (!Number.isFinite(height)) return null; if (!Number.isFinite(height)) return null;
const carto = Cesium.Cartographic.fromCartesian( const at = toLonLatH(marker.position);
marker.position, if (!at) return null;
Cesium.Ellipsoid.WGS84, return fromDegrees(at.lon, at.lat, height + (record?.bellyM || 0));
scratchCarto,
);
return Cesium.Cartesian3.fromRadians(
carto.longitude,
carto.latitude,
height + (record?.bellyM || 0),
Cesium.Ellipsoid.WGS84,
scratchGround,
);
} }
return { return {
@@ -215,67 +205,66 @@ export function createLocalAdsbModels({
*/ */
frame(markers, preferences, nowMs) { frame(markers, preferences, nowMs) {
if (destroyed) return; if (destroyed) return;
if (!regime(preferences)) { const pose = camera.pose();
if (models.size || pending.size) releaseAll(); if (!regime(preferences, pose)) {
if (models.size) releaseAll();
eligible = new Set(); eligible = new Set();
for (const marker of markers.values()) marker.modelOwnsVisual = false; for (const marker of markers.values()) marker.modelOwnsVisual = false;
return; return;
} }
if (nowMs - lastEligibilityAt >= FLEET_DR_INTERVAL_MS) { if (nowMs - lastEligibilityAt >= FLEET_DR_INTERVAL_MS) {
lastEligibilityAt = nowMs; lastEligibilityAt = nowMs;
refreshEligibility(markers, preferences); refreshEligibility(markers, preferences, pose);
} }
const occluder = horizonOccluder(viewer.camera); const horizon = horizonFrom(pose.position);
const items = [];
for (const [id, marker] of markers) { for (const [id, marker] of markers) {
const record = models.get(id); const record = models.get(id);
marker.modelOwnsVisual = false; marker.modelOwnsVisual = false;
if (!record || !marker.position) continue; if (!record || !marker.position) continue;
const spec = civilAircraftModelSpec(marker.klass);
const url = resolveAsset(spec.url);
noteAsset(record, url, spec.bellyM);
const position = placement(id, marker); const position = placement(id, marker);
if (!position || !occluder.isPointVisible(marker.position)) { const shown =
showModel(record, false); Boolean(position) && horizon.isPointVisible(marker.position);
continue; items.push({
} id,
scratchHpr.heading = Cesium.Math.toRadians( // Unplaced, it waits hidden where it last was (or at the marker).
(marker.courseDeg || 0) + MODEL_HEADING_OFFSET_DEG, pos: position ?? marker.position,
); url,
scratchHpr.pitch = 0; orientation: {
scratchHpr.roll = 0; heading:
placeModel( ((marker.courseDeg || 0) + MODEL_HEADING_OFFSET_DEG) *
record, RADIANS_PER_DEGREE,
Cesium.Transforms.headingPitchRollToFixedFrame( pitch: 0,
position, roll: 0,
scratchHpr, },
Cesium.Ellipsoid.WGS84, scale: spec.scale,
undefined, minPixelSize: MODEL_MIN_PX,
scratchMatrix, tint,
), colorBlend: { mode: 'mix', amount: spec.blendAmount },
); environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
if (!record.model.ready) { show: shown,
showModel(record, false); });
continue; if (shown && record.ready) marker.modelOwnsVisual = true;
}
showModel(record, true);
marker.modelOwnsVisual = true;
} }
for (const id of [...models.keys()]) if (!markers.has(id)) release(id); if (items.length) set.upsert(items);
release([...models.keys()].filter((id) => !markers.has(id)));
}, },
/** /**
* Drop the model, and any load still in flight, of every aircraft that * Drop the model of every aircraft that is no longer a marker. The
* is no longer a marker. The layer calls this whenever markers expire: * layer calls this whenever markers expire: the per-frame pass does not
* the per-frame pass does not run once the last marker is gone. * run once the last marker is gone.
* @param {Map<string, object>|Set<string>} live Current marker ids. * @param {Map<string, object>|Set<string>} live Current marker ids.
*/ */
retain(live) { retain(live) {
if (destroyed) return; if (destroyed) return;
let dropped = false; const gone = [...models.keys()].filter((id) => !live.has(id));
for (const id of [...models.keys(), ...pending.keys()]) { if (!gone.length) return;
if (live.has(id)) continue; release(gone);
release(id); eligible = new Set([...eligible].filter((id) => live.has(id)));
eligible.delete(id);
dropped = true;
}
if (dropped) eligible = new Set(eligible);
}, },
/** Drop every model (3D off, layer disabled). */ /** Drop every model (3D off, layer disabled). */
@@ -286,12 +275,23 @@ export function createLocalAdsbModels({
return models.size; return models.size;
}, },
/** The models set's id, for picks and height queries. */
setId,
/** Whether the set draws (with the layer). */
get show() {
return set.show;
},
set show(value) {
if (!destroyed) set.show = value;
},
destroy() { destroy() {
destroyed = true;
releaseAll(); releaseAll();
destroyed = true;
offReady();
groundSnap?.clear?.(); groundSnap?.clear?.();
if (!viewer.isDestroyed?.() && !collection.isDestroyed()) set.dispose();
viewer.scene.primitives.remove(collection);
}, },
}; };
} }
+47
View File
@@ -4,6 +4,7 @@ import test from 'node:test';
import { bindRenderer, drawOf, findDraw } from '../rendererOf.js'; import { bindRenderer, drawOf, findDraw } from '../rendererOf.js';
import { createCesiumDraw, revealUniform, unboundDrawPart } from './draw.js'; import { createCesiumDraw, revealUniform, unboundDrawPart } from './draw.js';
import { drawHitOf } from './drawHit.js'; import { drawHitOf } from './drawHit.js';
import { MODEL_RETRY_MS } from './drawModels.js';
// Node has no WebGL context to report line-width limits. // Node has no WebGL context to report line-width limits.
Cesium.ContextLimits._minimumAliasedLineWidth = 1; Cesium.ContextLimits._minimumAliasedLineWidth = 1;
@@ -3838,6 +3839,52 @@ test('a model load superseded or failed settles once', async () => {
} }
}); });
test('a failed model load is tried again on a later update, after a wait', async () => {
const { loads, restore } = fakeModelLoads();
const realNow = Date.now;
let now = 1_000_000;
Date.now = () => now;
try {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.models({ id: 'm' });
const item = {
id: 'a',
pos: { lon: 0, lat: 0 },
url: 'a.glb',
orientation: { heading: 0, pitch: 0, roll: 0 },
};
set.upsert([item]);
const host = scene.added[0];
loads[0].reject(new Error('network'));
await settle();
assert.equal(host.failed, 1);
now += MODEL_RETRY_MS - 1;
set.upsert([{ ...item }]);
assert.equal(loads.length, 1, 'not before the wait');
now += 1;
set.upsert([{ ...item }]);
assert.equal(loads.length, 2, 'the same url again');
assert.equal(host.failed, 0, 'loading again, not failed');
assert.equal(host.loading, 1);
const ready = [];
set.on('ready', (id) => ready.push(id));
loads[1].resolve();
await settle();
loads[1].ready();
assert.deepEqual(ready, ['a']);
set.upsert([{ ...item }]);
assert.equal(loads.length, 2, 'a loaded model is not loaded again');
set.dispose();
} finally {
Date.now = realNow;
restore();
}
});
test('a model past its pixel cap is scaled down each frame; fades and culls too', async () => { test('a model past its pixel cap is scaled down each frame; fades and culls too', async () => {
const { loads, restore } = fakeModelLoads(); const { loads, restore } = fakeModelLoads();
try { try {
+37 -10
View File
@@ -15,6 +15,9 @@
* measures `minPixelSize`), `scaleByDistance`, `fadeByDistance` (the tint's * measures `minPixelSize`), `scaleByDistance`, `fadeByDistance` (the tint's
* alpha) and the set's `horizonCull`. * alpha) and the set's `horizonCull`.
* *
* A failed load is tried again when its item is next updated, once
* `MODEL_RETRY_MS` has passed.
*
* `shading: 'thermal'` draws the model unlit and white-hot (its texture * `shading: 'thermal'` draws the model unlit and white-hot (its texture
* left out), then tinted as asked: a hot target, as the thermal views draw * left out), then tinted as asked: a hot target, as the thermal views draw
* them. Heights are absolute: models clamp nothing. * them. Heights are absolute: models clamp nothing.
@@ -27,6 +30,13 @@ const BLEND_MODES = {
mix: Cesium.ColorBlendMode.MIX, mix: Cesium.ColorBlendMode.MIX,
}; };
/**
* How long a failed load waits before an update of its item tries the url
* again (a fleet updates every frame; a dropped request or a server
* hiccup should not leave the item without its model for good).
*/
export const MODEL_RETRY_MS = 5000;
/** Cesium's own blend amount, for a `mix` that names none. */ /** Cesium's own blend amount, for a `mix` that names none. */
const DEFAULT_MIX = 0.5; const DEFAULT_MIX = 0.5;
@@ -80,8 +90,10 @@ const scratchHpr = new Cesium.HeadingPitchRoll();
const scratchMatrix = new Cesium.Matrix4(); const scratchMatrix = new Cesium.Matrix4();
const scratchSphere = new Cesium.BoundingSphere(); const scratchSphere = new Cesium.BoundingSphere();
const scratchColor = new Cesium.Color(); const scratchColor = new Cesium.Color();
/** The colour last written to each model, as a key. */ /** The colour last written to each model. */
const writtenColors = new WeakMap(); const writtenColors = new WeakMap();
/** What the per-frame pass found, for a model it does not run on. */
const STILL = Object.freeze({ scale: 1, alpha: 1, shown: true });
/** An item's position as Cesium's, into `result`. */ /** An item's position as Cesium's, into `result`. */
function positionOf(pos, result) { function positionOf(pos, result) {
@@ -96,6 +108,14 @@ function positionOf(pos, result) {
); );
} }
/** A tint as a key: a CSS string as it is, an RGBA array joined. */
const tintKey = (tint) =>
tint === undefined || tint === null
? null
: typeof tint === 'string'
? tint
: tint.join(',');
/** Whether an item needs the per-frame pass. */ /** Whether an item needs the per-frame pass. */
const needsFrame = (item, spec) => const needsFrame = (item, spec) =>
item.maxPixelSize > 0 || item.maxPixelSize > 0 ||
@@ -171,6 +191,7 @@ export function createModelSets({
host.loading -= 1; host.loading -= 1;
if (failed && entry.token === token) { if (failed && entry.token === token) {
entry.failed = true; entry.failed = true;
entry.failedAt = Date.now();
host.failed += 1; host.failed += 1;
} }
requestRender(); requestRender();
@@ -284,10 +305,9 @@ export function createModelSets({
if (model.colorBlendAmount !== amount) model.colorBlendAmount = amount; if (model.colorBlendAmount !== amount) model.colorBlendAmount = amount;
// An empty `displayRange` shows nothing. // An empty `displayRange` shows nothing.
const hidden = range && !(range[1] > range[0]); const hidden = range && !(range[1] > range[0]);
entry.styled = { range: rangeKey }; if (entry.styled?.range !== rangeKey) entry.styled = { range: rangeKey };
entry.dynamic = needsFrame(item, record.spec); entry.dynamic = needsFrame(item, record.spec);
const frame = entry.frame ?? { scale: 1, alpha: 1, shown: true }; apply(entry, model, entry.frame ?? STILL, hidden);
apply(entry, model, frame, hidden);
} }
/** /**
@@ -305,9 +325,9 @@ export function createModelSets({
color.alpha *= frame.alpha; color.alpha *= frame.alpha;
// Written only when what is asked changes, so a theme's own write to a // Written only when what is asked changes, so a theme's own write to a
// model's colour stands until then. // model's colour stands until then.
const key = `${color.red},${color.green},${color.blue},${color.alpha}`; const written = writtenColors.get(model);
if (writtenColors.get(model) !== key) { if (!written || !Cesium.Color.equals(written, color)) {
writtenColors.set(model, key); writtenColors.set(model, Cesium.Color.clone(color, written));
model.color = color; model.color = color;
} }
const show = const show =
@@ -334,10 +354,12 @@ export function createModelSets({
model: null, model: null,
at: new Cesium.Cartesian3(), at: new Cesium.Cartesian3(),
tint: null, tint: null,
tintKey: undefined,
radius: 0, radius: 0,
next: null, next: null,
token: null, token: null,
failed: false, failed: false,
failedAt: 0,
settleLoad: null, settleLoad: null,
styled: null, styled: null,
dynamic: false, dynamic: false,
@@ -352,8 +374,12 @@ export function createModelSets({
entry.pickId.lodGroup = item.lodGroup; entry.pickId.lodGroup = item.lodGroup;
} }
positionOf(item.pos, entry.at); positionOf(item.pos, entry.at);
entry.tint = // A fleet re-poses every frame with the same tint: parsed when it changes.
item.tint === undefined || item.tint === null ? null : toColor(item.tint); const tint = tintKey(item.tint);
if (entry.tintKey !== tint) {
entry.tintKey = tint;
entry.tint = tint === null ? null : toColor(item.tint);
}
if (entry.url !== item.url && item.url === entry.modelUrl) { if (entry.url !== item.url && item.url === entry.modelUrl) {
// Back to the url it draws: the load in between is not wanted. // Back to the url it draws: the load in between is not wanted.
cancel(record, entry); cancel(record, entry);
@@ -362,7 +388,8 @@ export function createModelSets({
// The model it draws keeps up while another loads. // The model it draws keeps up while another loads.
for (const model of [entry.model, entry.next]) for (const model of [entry.model, entry.next])
if (model) style(record, entry, model); if (model) style(record, entry, model);
if (entry.url !== item.url) load(record, entry); const retry = entry.failed && Date.now() - entry.failedAt >= MODEL_RETRY_MS;
if (entry.url !== item.url || retry) load(record, entry);
} }
/** Stop the entry's load in flight, keeping the model it draws. */ /** Stop the entry's load in flight, keeping the model it draws. */
-1
View File
@@ -43,7 +43,6 @@
"src/layers/launches/launchPad.js", "src/layers/launches/launchPad.js",
"src/layers/launches/orbitRendering.js", "src/layers/launches/orbitRendering.js",
"src/layers/launches/rendering.js", "src/layers/launches/rendering.js",
"src/layers/localAdsb/models.js",
"src/layers/military/lifecycle.js", "src/layers/military/lifecycle.js",
"src/layers/military/motion.js", "src/layers/military/motion.js",
"src/layers/military/policy.js", "src/layers/military/policy.js",
+16 -7
View File
@@ -48,6 +48,7 @@
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { heightsFor } from '../render/cesium/heights.js'; import { heightsFor } from '../render/cesium/heights.js';
import { heightsOf } from '../queries/heights.js';
// The application operations entry reaches the annotation resolver and // The application operations entry reaches the annotation resolver and
// locations.js, whose flights and heights go through the camera and query // locations.js, whose flights and heights go through the camera and query
// ports and which cannot load the Cesium adapter themselves; this listed // ports and which cannot load the Cesium adapter themselves; this listed
@@ -169,7 +170,8 @@ function _tilesReady(viewer) {
* Create a per-layer ground-snap cache. * Create a per-layer ground-snap cache.
* @returns {{ * @returns {{
* heightFor: (viewer: Cesium.Viewer, icao: string, pos: Cesium.Cartesian3, * heightFor: (viewer: Cesium.Viewer, icao: string, pos: Cesium.Cartesian3,
* getExclusions?: () => Array<unknown>) => number|null, * getExclusions?: (() => Array<unknown>)|{sets: string[]})
* => number|null,
* forget: (icao: string) => void, * forget: (icao: string) => void,
* clear: () => void, * clear: () => void,
* }} * }}
@@ -287,7 +289,10 @@ export function createGroundSnap({ groundFloor }) {
* @param {(() => Array<unknown>)|undefined} getExclusions - Lazily builds the * @param {(() => Array<unknown>)|undefined} getExclusions - Lazily builds the
* scene.sampleHeight objectsToExclude list (own billboards/models/entities — * scene.sampleHeight objectsToExclude list (own billboards/models/entities —
* the vertical pick ray at a plane's OWN lat/lon lands on its icon/model * the vertical pick ray at a plane's OWN lat/lon lands on its icon/model
* otherwise). Only invoked when a sample actually fires. * otherwise). Only invoked when a sample actually fires. `{sets}` (draw
* set ids) instead samples through the renderer's query port
* (`heightsOf`), which sees through every draw set not drawn as ground
* and these: for a caller whose markers and models are on the draw port.
* @returns {number|null} * @returns {number|null}
*/ */
function heightFor(viewer, icao, pos, getExclusions) { function heightFor(viewer, icao, pos, getExclusions) {
@@ -359,11 +364,15 @@ export function createGroundSnap({ groundFloor }) {
Cesium.Ellipsoid.WGS84, Cesium.Ellipsoid.WGS84,
scratchCarto, scratchCarto,
); );
const sampled = carto // Draw-set exclusions ask the renderer's query port, which sees through
? heightsFor(viewer.scene).now(carto, { // every draw set not drawn as ground (the caller's markers and models).
exclude: getExclusions ? getExclusions() : undefined, const sampled = !carto
}) ? null
: null; : Array.isArray(getExclusions?.sets)
? heightsOf(viewer).now(carto, { exclude: getExclusions.sets })
: heightsFor(viewer.scene).now(carto, {
exclude: getExclusions ? getExclusions() : undefined,
});
// Same sanity floor as cctv.js's sampleGroundHeight: a hit far below the // Same sanity floor as cctv.js's sampleGroundHeight: a hit far below the
// ellipsoid is pick garbage, not ground. // ellipsoid is pick garbage, not ground.
if (!Number.isFinite(sampled) || sampled < -150) return miss(); if (!Number.isFinite(sampled) || sampled < -150) return miss();
+24
View File
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { createGroundSnap } from './groundSnap.js'; import { createGroundSnap } from './groundSnap.js';
import { bindRenderer } from '../render/rendererOf.js';
const groundFloor = { const groundFloor = {
cachedMeshFloor: () => null, cachedMeshFloor: () => null,
@@ -60,3 +61,26 @@ test('a retry backoff stamped before the clock stepped back does not wait for it
assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650); assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650);
assert.equal(viewer.calls.samples, 1); assert.equal(viewer.calls.samples, 1);
}); });
test('draw-set exclusions sample through the renderer’s query port', () => {
const viewer = makeViewer();
const asked = [];
bindRenderer(viewer, {
query: {
sampleHeightNow(point, options) {
asked.push({ point, options });
return 1655;
},
},
});
const snap = createGroundSnap({ groundFloor });
assert.equal(
snap.heightFor(viewer, 'a00001', atDenverAirport, {
sets: ['mine:models'],
}),
1655,
);
assert.equal(viewer.calls.samples, 0, 'not the scene’s own sample');
assert.deepEqual(asked[0].options, { exclude: ['mine:models'] });
assert.ok(Math.abs(asked[0].point.lon + 104.6737) < 1e-6);
});
+11 -1
View File
@@ -19,6 +19,7 @@ export function fakeDrawPort() {
show: spec.show !== false, show: spec.show !== false,
disposed: false, disposed: false,
writes: 0, writes: 0,
ready: new Set(),
}; };
sets.set(spec.id, record); sets.set(spec.id, record);
const write = (fn) => { const write = (fn) => {
@@ -53,7 +54,11 @@ export function fakeDrawPort() {
set show(value) { set show(value) {
record.show = value; record.show = value;
}, },
on: () => () => {}, on(event, cb) {
if (event !== 'ready') return () => {};
record.ready.add(cb);
return () => record.ready.delete(cb);
},
dispose() { dispose() {
record.disposed = true; record.disposed = true;
}, },
@@ -72,6 +77,11 @@ export function fakeDrawPort() {
points: make('points'), points: make('points'),
lines: make('lines'), lines: make('lines'),
shapes: make('shapes'), shapes: make('shapes'),
models: make('models'),
/** Fire a models set's `ready` for an item, as a load finishing does. */
ready(setId, id) {
for (const cb of [...(sets.get(setId)?.ready ?? [])]) cb(id);
},
clampState: () => 'draped', clampState: () => 'draped',
on: () => () => {}, on: () => () => {},
atlas() {}, atlas() {},