Placed flights no longer replan in step: far ones less often, every row's atlas look-up cheaper

A placed contact's segment ran exactly a second, so a fleet planned
together ran out together: every second one or two fleet passes replanned
all of it (about ten thousand contacts) and rewrote every icon row, a frame
of 40-120 ms of work, longer on a busy machine.

Each contact's plans now run between half and one and a half times their
length, by its id, so the fleet's plans run out spread over the passes. A
contact out of view, or farther than 300 km from the eye, is planned for
4 s instead of 1 s: off screen its path is not seen, and that far a
straight segment of that length is well under a pixel off it. The fleet
pass hands the camera to the replan for this; any other plan (a new
report, a handover) is a near one.

The icon atlas finds a slot by URL, then size, instead of building a
"size|url" key string on every look-up; an aircraft's icon URL is an SVG
data URL of kilobytes, looked up twice for every row written.

Measured in Chrome over London with about ten thousand flights: icon rows
rewritten a second fell from about 1,700 to about 70, and the fleet pass's
longest tasks from 40-120 ms of CPU to 10-40 ms.
This commit is contained in:
Sameh Khamis committed 2026-11-23 19:29:15 -08:00
1 parent d50f04efeb
commit 170b817679
7 files changed
+236 -24

No files matched your search

+57 -11
View File
@@ -10,6 +10,7 @@ import { straightSegment } from './fixCurve.js';
import {
norm180,
distance,
distanceSquared,
clone,
copyInto,
toDegrees,
@@ -385,8 +386,32 @@ let instances = 0;
/** A plan that ran out longer ago than this (ms) is not eased away from. */
const RECOVER_STALE_PLAN_MS = 1_000;
/** How far ahead (ms) a placed contact's segment runs before it is asked again. */
/** How far ahead (ms) a placed contact's segment runs before it is asked
* again, in view and near the eye. */
const PLACED_PLAN_MS = 1000;
/** The same out of view, or farther than PLACED_NEAR_M from the eye: off
* screen a contact's path is not seen, and that far a straight segment
* over this long (half as long again at most, as spread) is well under a
* pixel off it. Asking for each contact every second would rewrite the
* whole fleet every second. */
const PLACED_FAR_PLAN_MS = 4000;
/** Nearer the eye than this (m), a placed contact in view is planned every
* PLACED_PLAN_MS. */
const PLACED_NEAR_M = 300_000;
/**
* Each contact's plans run between 1/2 and 3/2 of their length, by its id,
* so the fleet's plans run out spread over the passes, not together in one
* (contacts first planned in the same pass would otherwise stay in step).
*/
export function placedPlanSpread(id) {
let hash = 2166136261;
for (let i = 0; i < id.length; i++) {
hash ^= id.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return 0.5 + ((hash >>> 0) % 1024) / 1024;
}
/** A display delay that never changes (ms). */
function fixedDelay(ms) {
@@ -818,12 +843,28 @@ export function createAircraftIcons({
planFrom.set(icao24, validFrom);
}
/** The camera, while the fleet pass re-plans the rows that ran out:
* `{eye, inView(position)}` (null: every plan is a near one). */
let planView = null;
/** How long a placed contact at `position` is planned for (ms). */
function _placedPlanMs(icao24, position) {
const near =
!planView ||
(distanceSquared(planView.eye, position) <
PLACED_NEAR_M * PLACED_NEAR_M &&
planView.inView(position));
return (
(near ? PLACED_PLAN_MS : PLACED_FAR_PLAN_MS) * placedPlanSpread(icao24)
);
}
/**
* Plan a live contact a host-supplied placement places: from where it
* places it at `t` (display ms, the live clock's delayed time) to where it
* places it PLACED_PLAN_MS on, asked again when that runs out. Display
* time is wall time less the display delay, so the placement is asked at
* the wall times the segment's ends stand for.
* places it a plan's length on (`_placedPlanMs`), asked again when that
* runs out. Display time is wall time less the display delay, so the
* placement is asked at the wall times the segment's ends stand for.
* @returns {boolean} False when there is no placement, the layer follows
* the world clock, or it has no answer for this contact.
*/
@@ -842,7 +883,7 @@ export function createAircraftIcons({
)
return true;
easeEnds.delete(icao24);
const t1 = t + PLACED_PLAN_MS;
const t1 = t + _placedPlanMs(icao24, from);
const to = vec();
const end = placeAt(icao24, t1 + leadMs, info, history, to);
const motion = end
@@ -906,12 +947,17 @@ export function createAircraftIcons({
* moved back (a seek, or the clock run backward): it is drawn where it was
* then, as it is when the time moves on.
*/
function _replanExpired(t) {
if (followsClock() && t < replannedAt)
for (const [icao24, from] of planFrom)
if (from > t) _planIcon(icao24, { rewound: true });
replannedAt = t;
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
function _replanExpired(t, view = null) {
planView = view;
try {
if (followsClock() && t < replannedAt)
for (const [icao24, from] of planFrom)
if (from > t) _planIcon(icao24, { rewound: true });
replannedAt = t;
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
} finally {
planView = null;
}
}
/**
+108
View File
@@ -5,6 +5,7 @@ import {
createAircraftIcons,
createContactIcons,
floorCoastArc,
placedPlanSpread,
} from './aircraftIconLayer.js';
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
@@ -501,3 +502,110 @@ test('back at live, a placed contact eases from where it is drawn over a recover
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
/** A layer whose placement has every contact flying east from `at(id)`. */
function placedFleet(ids, at) {
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map(ids.map((id) => [id, [{ epochMs: WORLD_MS }]])),
records: { data: new Map(ids.map((id) => [id, {}])) },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
placeAt: (id, wallMs, _info, _history, out) => {
Object.assign(out, at(id, wallMs));
return { courseDeg: 90, speedMps: 200 };
},
});
for (const id of ids)
state._icons.put(
{
id,
pos: at(id, WORLD_MS),
motion: { kind: 'hold', courseDeg: 90 },
course: 90,
size: [20, 20],
},
{ expiresAt: -Infinity },
);
return { icons, set: state._icons };
}
test('a placed fleet planned in one pass runs out spread over the passes after it, not together', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const ids = Array.from({ length: 400 }, (_, i) =>
(0xa00000 + i * 37).toString(16),
);
const { icons, set } = placedFleet(ids, () => fromDegrees(0, 30, 3_000));
icons._replanExpired(Date.now());
const ends = ids.map((id) => set.expires(id) - WORLD_MS);
for (const ms of ends) assert.ok(ms >= 500 && ms < 1_500, `${ms} ms`);
// An 80 ms pass (the fleet's tick) has an eighth of the fleet at most.
const perPass = new Map();
for (const ms of ends) {
const pass = Math.floor(ms / 80);
perPass.set(pass, (perPass.get(pass) ?? 0) + 1);
}
assert.ok(
Math.max(...perPass.values()) <= ids.length / 8,
`${Math.max(...perPass.values())} in one pass`,
);
// Planned again when it runs out, each runs as long as before, from then.
const first = new Map(ids.map((id) => [id, set.expires(id)]));
t.mock.timers.tick(1_500);
icons._replanExpired(Date.now());
for (const id of ids) {
const item = set.item(id);
assert.equal(item.motion.t0, Date.now(), id);
assert.equal(
set.expires(id) - Date.now(),
first.get(id) - WORLD_MS,
`${id} runs as long`,
);
}
});
test('a placed contact far from the eye or out of view is planned for longer than a near one in view', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const where = {
n: fromDegrees(0, 30, 3_000),
f: fromDegrees(10, 30, 3_000),
o: fromDegrees(0.01, 30, 3_000),
};
const ids = Object.keys(where);
const { icons, set } = placedFleet(ids, (id) => where[id]);
const eye = fromDegrees(0, 30, 60_000);
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
// In view: all but 'o', told apart by where the placement puts it.
const view = { eye, inView: (p) => metres(p, where.o) > 1 };
const length = (id) =>
(set.expires(id) - set.item(id).motion.t0) / placedPlanSpread(id);
icons._replanExpired(Date.now(), view);
assert.ok(Math.abs(length('n') - 1_000) < 1, `near ${length('n')}`);
assert.ok(Math.abs(length('f') - 4_000) < 1, `far ${length('f')}`);
assert.ok(Math.abs(length('o') - 4_000) < 1, `out of view ${length('o')}`);
// The camera is the pass's only: a contact planned after it, as a new
// report plans it, takes a near plan, even after a pass that threw.
icons._planIcon('f');
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a pass ${length('f')}`);
t.mock.timers.tick(5_000);
assert.throws(() =>
icons._replanExpired(Date.now(), {
eye,
inView: () => {
throw new Error('camera gone');
},
}),
);
icons._planIcon('f');
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a throw ${length('f')}`);
});
+8 -1
View File
@@ -1041,7 +1041,14 @@ export function createAircraftModels({
if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts();
parts.icons._syncImageSwitch();
parts.icons._replanExpired(t);
// Far and out-of-view contacts are planned for longer (the camera says
// which are which).
parts.icons._replanExpired(
t,
pose?.position
? { eye: pose.position, inView: (position) => inView(pose, position) }
: null,
);
const renderTime = parts.motion._displayTimeAt(
t,
state._scratchFleetRenderTime,
+19 -1
View File
@@ -114,11 +114,14 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
};
let now = 1_000_000;
let iconRecedeSyncs = 0;
const replanViews = [];
const parts = {
icons: {
_displayMs: () => now,
_syncImageSwitch() {},
_replanExpired() {},
_replanExpired(_t, view) {
replanViews.push(view);
},
_focusIcons() {},
_occluder: () => null,
_aboveHorizon: () => true,
@@ -160,6 +163,9 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
failNextUpsert: () => (failNextUpsert = true),
/** How often the icons were told to recede by the tuning as it is now. */
iconRecedeSyncs: () => iconRecedeSyncs,
/** The camera each fleet tick re-planned the icons with. */
replanViews,
eye,
/** Mark a contact as not there yet at the time drawn, or there again. */
setUnseen(id, value) {
if (value) unseenIds.add(id);
@@ -476,3 +482,15 @@ test('the selected contact keeps a loaded, hidden fleet model that takes it back
assert.equal(f.fleet().items.get('a1').show, true);
assert.equal(f.shown.get('a1'), false);
});
test('the fleet tick re-plans the icons with the camera: its eye, and what it sees', () => {
const f = fleetFixture(new Map([['a1', far(1)]]));
f.tick();
const [view] = f.replanViews;
assert.equal(view.eye, f.eye);
// The camera looks along -z: ahead of the eye is in view, behind it not.
const ahead = { x: f.eye.x, y: f.eye.y, z: f.eye.z - 10_000 };
const behind = { x: f.eye.x, y: f.eye.y, z: f.eye.z + 10_000 };
assert.equal(view.inView(ahead), true);
assert.equal(view.inView(behind), false);
});
+9 -5
View File
@@ -65,7 +65,10 @@ const START_SIZE_PX = 1024;
const MAX_SIZE_PX = 4096;
function createAtlas() {
const slotOfKey = new Map();
// By URL, then by size: a URL is hashed once as it is, where a key built
// from it would be a new string to hash on every look-up (an SVG data URL
// runs to kilobytes, and a fleet's write looks up two a row).
const slotsOfUrl = new Map();
const entries = [];
const listeners = new Set();
const atlas = {
@@ -90,8 +93,8 @@ function createAtlas() {
* @returns {number}
*/
slot(url, sizePx, source) {
const key = `${sizePx}|${url}`;
const known = slotOfKey.get(key);
let bySize = slotsOfUrl.get(url);
const known = bySize?.get(sizePx);
if (known !== undefined) return known;
if (entries.length >= MAX_ICON_SLOTS)
throw new RangeError(
@@ -100,7 +103,8 @@ function createAtlas() {
const slot = entries.length;
const entry = { url, sizePx, image: null, x: 0, y: 0 };
entries.push(entry);
slotOfKey.set(key, slot);
if (!bySize) slotsOfUrl.set(url, (bySize = new Map()));
bySize.set(sizePx, slot);
if (source) placeLoaded(entry, source);
else load(entry);
return slot;
@@ -108,7 +112,7 @@ function createAtlas() {
/** Whether `url` at `sizePx` already has a slot. */
has(url, sizePx) {
return slotOfKey.has(`${sizePx}|${url}`);
return slotsOfUrl.get(url)?.has(sizePx) === true;
},
/** Whether a slot's image is packed and drawable. */
+24
View File
@@ -0,0 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { iconAtlas } from './iconAtlas.js';
test('an atlas slot is one per image and size, and has() agrees with slot()', () => {
const url = `data:image/svg+xml;charset=utf-8,${'%3Csvg%3E'.repeat(400)}#slots`;
const other = `${url}-other`;
assert.equal(iconAtlas.has(url, 20), false);
const small = iconAtlas.slot(url, 20);
assert.equal(iconAtlas.has(url, 20), true);
assert.equal(iconAtlas.slot(url, 20), small, 'the same image and size');
// A copy of the URL, not the same string, finds it too.
assert.equal(iconAtlas.slot(url.slice(0), 20), small);
assert.equal(iconAtlas.has(url, 40), false, 'another size is another slot');
const large = iconAtlas.slot(url, 40);
assert.notEqual(large, small);
assert.equal(iconAtlas.has(url, 40), true);
assert.equal(
iconAtlas.has(other, 20),
false,
'another image is another slot',
);
assert.notEqual(iconAtlas.slot(other, 20), small);
});
+11 -6
View File
@@ -3,7 +3,10 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createFlightState } from './state.js';
import { createIcons } from './icons.js';
import { createContactIcons } from '../../data/aircraftIconLayer.js';
import {
createContactIcons,
placedPlanSpread,
} from '../../data/aircraftIconLayer.js';
import { layerPlacement } from '../../data/placementProvider.js';
import {
aircraftMotionRegime,
@@ -269,8 +272,10 @@ test('a live contact a placement places is drawn along where it places it', (t)
const now = icons._displayMs();
const leadMs = Date.now() - now;
icons._planIcon('p');
// A plan's length, as this contact's are spread (a second on average).
const planMs = 1000 * placedPlanSpread('p');
// Asked for the wall times the segment's ends stand for.
assert.deepEqual(asked, [now + leadMs, now + 1000 + leadMs]);
assert.deepEqual(asked, [now + leadMs, now + planMs + leadMs]);
assert.equal(regimes.length, 0, 'its own motion is not planned');
const item = set.item('p');
assert.equal(item.motion.kind, 'lerp');
@@ -284,16 +289,16 @@ test('a live contact a placement places is drawn along where it places it', (t)
Cesium.Cartesian3.distance(
item.motion.to,
Cesium.Cartesian3.fromDegrees(
(now + 1000 + leadMs - t0) / 10_000,
(now + planMs + leadMs - t0) / 10_000,
30,
2000,
),
) < 1e-6,
);
assert.equal(item.motion.t0, now);
assert.equal(item.motion.t1, now + 1000);
assert.ok(Math.abs(item.motion.courseSlopeDeg - 1) < 1e-9);
assert.equal(set.expires('p'), now + 1000);
assert.equal(item.motion.t1, now + planMs);
assert.ok(Math.abs(item.motion.courseSlopeDeg - planMs / 1000) < 1e-9);
assert.equal(set.expires('p'), now + planMs);
// No answer: the layer's own motion plans it.
places = false;