The renderer seam: clicks go to the newest tool, recession and display groups through the contract, drawing at parity with Cesium

- Clicks: when two tools want the globe's clicks, the newest takes them and the older is told and turns itself off; a click is decided when it arrives, and ambient selection fires only when no tool holds the pointer. The "map is busy" paths and their strings are removed.
- Recession: the limb fade is shared (src/render/recession.js) and reaches icon and model sets through SetSpec.recede; tuning applies on the next frame.
- Display panel groups are published through src/ui/displayGroups.js; the Weather group and src/viewWeather.js are removed.
- Draw port: a set whose icons only move is moved in place, and models that did not change are not restyled each frame, so moving fleets cost what they did when drawn directly; an untinted, fully opaque model is drawn without a colour.
- Conformance: input.lease.lost checks the new lease inside onLost and reports a throwing onLost; draw.sets.recede covers model sets.
- QA scripts read the renderer host instead of internals the seam replaced.
This commit is contained in:
Sameh Khamis committed 2026-11-15 17:03:09 -08:00
1 parent a0d299523d
commit 0ab31d4fb8
130 files changed
+5438 -1674

No files matched your search

+113 -11
View File
@@ -32,6 +32,8 @@ import {
TRACKED_ICON_PX,
} from './aircraftIcons.js';
import { cockpitContactDotImage } from './cockpitContactDot.js';
import { aircraftRecedeSpec } from './aircraftRecession.js';
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
/** Raster size of the cockpit contact pip (cockpitContactDot.js draws 16 px). */
const COCKPIT_DOT_PX = 16;
@@ -97,6 +99,14 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
const book = createIconBook(null, { capabilities });
const pending = new Map();
const removed = new Set();
// Ids not drawn whatever their item says: following the clock, the time
// drawn is before the contact was there (`setUnseen`).
const unseen = new Set();
/** The item as the draw set takes it: hidden while unseen. */
const drawnItem = (item) =>
unseen.has(item.id) && item.show !== false
? { ...item, show: false }
: item;
// The ids the draw set holds.
const sent = new Set();
let queued = false;
@@ -157,7 +167,7 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
return p && result ? copyInto(p, result) : p;
},
course: (id, t) => book.course(id, t),
shown: (id) => book.item(id)?.show !== false,
shown: (id) => book.item(id)?.show !== false && !unseen.has(id),
focus: (id) => book.focus(id),
alpha: (id) => book.item(id)?.alpha ?? 1,
scale: (id) => book.item(id)?.scale ?? 1,
@@ -165,7 +175,7 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
put(item, options) {
book.put(item, options);
removed.delete(item.id);
pending.set(item.id, item);
pending.set(item.id, drawnItem(item));
schedule();
},
/**
@@ -190,10 +200,25 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
return true;
},
setShown: (id, value) => icons.update(id, { show: value !== false }),
/**
* Keep an id from being drawn (true) whatever its item's `show` says, or
* draw it as its item says again (false).
*/
setUnseen(id, value) {
const item = book.item(id);
if (!item || unseen.has(id) === Boolean(value)) return;
if (value) unseen.add(id);
else unseen.delete(id);
pending.set(id, drawnItem(item));
schedule();
},
/** Whether an id is kept from being drawn (`setUnseen`). */
unseen: (id) => unseen.has(id),
setFocus: (id, factor) => icons.update(id, { focus: factor }),
remove(id) {
if (!book.has(id)) return;
book.remove(id);
unseen.delete(id);
pending.delete(id);
if (sent.has(id)) {
removed.add(id);
@@ -202,6 +227,7 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
},
clear() {
for (const id of book.ids()) book.remove(id);
unseen.clear();
pending.clear();
removed.clear();
sent.clear();
@@ -211,6 +237,7 @@ export function createContactIcons(drawSet = null, { capabilities } = {}) {
flush,
dispose() {
for (const id of book.ids()) book.remove(id);
unseen.clear();
pending.clear();
removed.clear();
sent.clear();
@@ -438,6 +465,16 @@ export function createAircraftIcons({
let liveSet = null;
let sceneClock = false;
let sentDelayMs = NaN;
// The `recede` the set was last sent.
let sentRecede = null;
/**
* From when (display ms) each planned row's motion holds: a row whose
* motion starts after the time drawn is planned again when the time moves
* back before it (`_replanExpired`).
*/
const planFrom = new Map();
/** The display time the rows were last checked against. */
let replannedAt = -Infinity;
/** The motion clock for whether the layer follows the world clock. */
const motionClock = (scene) =>
@@ -464,15 +501,27 @@ export function createAircraftIcons({
liveSet.setOptions({ motionClock: motionClock(scene) });
}
/** The set recedes by the aircraft tuning: sent again when it changes. */
function _syncRecede() {
if (!liveSet) return;
const recede = aircraftRecedeSpec();
if (recede === sentRecede) return;
sentRecede = recede;
liveSet.setOptions({ recede });
}
/**
* Create the draw set for one layer lifetime, drawn over depth and culled
* at the horizon on the delayed live clock, stacked by the sprite order.
* Create the draw set for one layer lifetime, drawn over depth, culled at
* the horizon and receding toward the limb on the delayed live clock,
* stacked by the sprite order.
* @returns {string} The set's id.
*/
function _createIcons(viewer) {
sentRecede = aircraftRecedeSpec();
const set = drawOf(viewer).icons({
id: `${layerId}-icons:${++instances}`,
horizonCull: true,
recede: sentRecede,
motionClock: motionClock(followsClock()),
drawOrder: services.sprites?.spriteDrawOrder?.(layerId) ?? 0,
});
@@ -494,6 +543,8 @@ export function createAircraftIcons({
state._icons?.dispose();
state._icons = null;
liveSet = null;
planFrom.clear();
replannedAt = -Infinity;
}
/** The near-image switch in CSS px for the scene's pixel ratio. */
@@ -553,11 +604,16 @@ export function createAircraftIcons({
* oldest fix, or the coast arc past the newest. The displayed nose glides
* from where it is onto the new course at the fleet's slew cap; a hovering
* contact keeps its nose. The item expires when the regime would change.
* Following the clock, a contact not there yet at the time drawn
* (`regime.unseen`) is not drawn until its warm-up begins.
* @param {string} icao24
* @param {{fromCourseDeg?: number|null}} [options] Nose to glide from when
* the row's own motion is not what was on screen (tracking handoff).
* @param {{fromCourseDeg?: number|null, rewound?: boolean}} [options]
* `fromCourseDeg`: nose to glide from when the row's own motion is not
* what was on screen (tracking handoff). `rewound`: the time drawn moved
* back before the row's motion; it is drawn where it was then, with no
* easing from where it is drawn now.
*/
function _planIcon(icao24, { fromCourseDeg } = {}) {
function _planIcon(icao24, { fromCourseDeg, rewound = false } = {}) {
const icons = state._icons;
if (!icons?.has(icao24) || holdsPlan(icao24)) return;
const history = state._positionHistory.get(icao24);
@@ -575,11 +631,31 @@ export function createAircraftIcons({
if (_planPlaced(icao24, info, history, t)) return;
const regime = parts.motion._motionRegime(history, info, renderTime);
if (regime.unseen) {
// Held at its first fix, not drawn, until its warm-up begins.
const course = regime.heading;
icons.setUnseen(icao24, true);
icons.update(
icao24,
{
pos: clone(regime.fix.position),
course,
motion: { kind: 'hold', courseDeg: course },
courseGlide: undefined,
},
{ expiresAt: fixMs(regime.fix) - TIMELINE_UNSEEN_MS },
);
planFrom.set(icao24, -Infinity);
return;
}
icons.setUnseen(icao24, false);
let speed;
let motion;
let pos;
let course;
let expiresAt = Infinity;
// From when the motion holds: before it, the time drawn has moved back.
let validFrom = t;
if (regime.kind === 'between' && regime.piece) {
// Along the curve between the two reports, a piece at a time.
const segment = regime.piece.segment;
@@ -588,6 +664,7 @@ export function createAircraftIcons({
pos = clone(segment.fix);
course = motionCourse(motion, undefined, t);
expiresAt = regime.piece.t1;
validFrom = regime.piece.t0;
} else if (regime.kind === 'between') {
const { a, b, span, trackFrom, trackTo, chordCourse } = regime;
speed = regime.speed;
@@ -609,10 +686,19 @@ export function createAircraftIcons({
motion = { kind: 'hold', courseDeg: course };
}
expiresAt = fixMs(b);
validFrom = fixMs(a);
} else {
const { fix, heading } = regime;
speed = regime.speed;
const t0 = fixMs(fix);
// A warm-up runs back to its start (a contact following the clock on
// its own fixes is unseen before that); a coast holds from its fix.
validFrom =
regime.maxDt === 0 && t0 > t
? history[0].timeline === true
? t0 - TIMELINE_UNSEEN_MS
: -Infinity
: t0;
pos = clone(fix.position);
course = heading;
motion =
@@ -643,6 +729,7 @@ export function createAircraftIcons({
motion = floored.motion;
pos = floored.pos;
course = floored.course;
validFrom = t;
}
expiresAt = Math.min(expiresAt, floored.expiresAt);
}
@@ -656,6 +743,7 @@ export function createAircraftIcons({
// whose motion ran out long ago, is simply drawn where it is now).
if (
fromCourseDeg == null &&
!rewound &&
icons.shown(icao24) &&
icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS
) {
@@ -680,6 +768,7 @@ export function createAircraftIcons({
pos = clone(drawn);
course = motionCourse(motion, undefined, t);
expiresAt = end;
validFrom = t;
}
}
// Below hover speed the nose holds what is on screen (or, for a new row,
@@ -703,6 +792,7 @@ export function createAircraftIcons({
};
}
icons.update(icao24, { pos, course, motion, courseGlide }, { expiresAt });
planFrom.set(icao24, validFrom);
}
/**
@@ -735,16 +825,27 @@ export function createAircraftIcons({
courseSlopeDeg: norm180(end.courseDeg - course),
}
: { kind: 'hold', courseDeg: course };
state._icons.setUnseen(icao24, false);
state._icons.update(
icao24,
{ pos: clone(from), course, motion, courseGlide: undefined },
{ expiresAt: t1 },
);
planFrom.set(icao24, t);
return true;
}
/** Re-plan every row whose regime ended by `t` (epoch ms). */
/**
* Re-plan every row whose regime ended by `t` (epoch ms), and, following
* the clock, every row whose motion starts after `t` once the time drawn
* 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);
}
@@ -889,6 +990,7 @@ export function createAircraftIcons({
/** Drop a contact and everything the layer keeps for it. */
function _forgetContact(icao24) {
state._icons?.remove(icao24);
planFrom.delete(icao24);
parts.rendering._releaseModel(icao24);
state.records.forget(icao24);
// The host-supplied placement, if any, forgets it as well.
@@ -907,6 +1009,7 @@ export function createAircraftIcons({
return {
_displayMs,
_syncMotionClock,
_syncRecede,
_createIcons,
_disposeIcons,
_syncImageSwitch,
@@ -930,8 +1033,8 @@ export function createAircraftIcons({
/**
* A contact's icon item before it is styled or planned: held at the origin
* (as a fresh row of the icon set was), always drawn over depth, receding
* toward the limb, picked as `{layer, id}`. Its image comes with its style
* (as a fresh row of the icon set was), always drawn over depth (receding
* toward the limb, as its set does), picked as `{layer, id}`. Its image comes with its style
* (`_applyIconPresentation`), before the item is first written.
*/
function baseContactItem(layerId, icao24, show) {
@@ -942,7 +1045,6 @@ function baseContactItem(layerId, icao24, show) {
course: 0,
size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX],
rotationMode: 'course',
recede: true,
disableDepthTest: Infinity,
focus: 1,
show,
+9 -2
View File
@@ -787,6 +787,9 @@ export function createAircraftModels({
// clock. (The tracked trail moves on in its own pass before each frame.)
if (state._viewer) parts.tracking._staleCueTick?.();
try {
// Every frame too: the icons recede by the tuning as it is now, so a
// change shows on the next frame, shown or not.
parts.icons._syncRecede?.();
_fleetPass();
} finally {
// The models first, then the icons they take over from, so a pass
@@ -921,9 +924,13 @@ export function createAircraftModels({
if (icao24 === state._trackedIcao) continue;
if (!icons.has(icao24)) continue;
const position = icons.position(icao24, t);
if (!parts.icons._aboveHorizon(position, occluder)) {
if (
icons.unseen?.(icao24) ||
!parts.icons._aboveHorizon(position, occluder)
) {
// A model that crossed the limb would keep drawing through the
// hidden globe; the icon's own cull is on the GPU.
// hidden globe; the icon's own cull is on the GPU. A contact not
// there yet at the time drawn is hidden as one beyond it.
const hidden = state._models.get(icao24);
if (hidden?.show) {
showModel(hidden, false);
+95 -2
View File
@@ -84,6 +84,9 @@ function fleetFixture(positions) {
},
});
const shown = new Map([...positions.keys()].map((id) => [id, true]));
let alphaOf = 1;
let focusOf = 1;
const unseenIds = new Set();
const icons = {
show: true,
setId: 'flights-icons:1',
@@ -91,9 +94,10 @@ function fleetFixture(positions) {
has: (id) => positions.has(id),
position: (id) => positions.get(id),
course: () => 90,
alpha: () => 1,
focus: () => 1,
alpha: () => alphaOf,
focus: () => focusOf,
setShown: (id, value) => shown.set(id, value),
unseen: (id) => unseenIds.has(id),
flush() {},
};
const state = {
@@ -116,6 +120,7 @@ function fleetFixture(positions) {
},
};
let now = 1_000_000;
let iconRecedeSyncs = 0;
const parts = {
icons: {
_displayMs: () => now,
@@ -124,6 +129,9 @@ function fleetFixture(positions) {
_focusIcons() {},
_occluder: () => null,
_aboveHorizon: () => true,
_syncRecede() {
iconRecedeSyncs += 1;
},
},
motion: { _displayTimeAt: () => null },
tracking: {
@@ -157,6 +165,18 @@ function fleetFixture(positions) {
removes,
shown,
failNextUpsert: () => (failNextUpsert = true),
/** How often the icons were told to recede by the tuning as it is now. */
iconRecedeSyncs: () => iconRecedeSyncs,
/** Mark a contact as not there yet at the time drawn, or there again. */
setUnseen(id, value) {
if (value) unseenIds.add(id);
else unseenIds.delete(id);
},
/** The icons' alpha and focus the fleet models take. */
look(alpha, focus) {
alphaOf = alpha;
focusOf = focus;
},
/** One fleet tick, past the tick interval. */
tick() {
now += 1000;
@@ -296,3 +316,76 @@ test('a fleet model whose load failed is loaded again after a wait, not before',
Date.now = realNow;
}
});
test('fleet model alpha is worked out once a fleet tick from the camera then, as base × max(floor, focus × haze); the IR boost draws full strength', async () => {
const {
aircraftTreatmentAlpha,
setAircraftRecessionParams,
resetAircraftRecessionParams,
} = await import('./aircraftRecession.js');
const position = near(1);
const f = fleetFixture(new Map([['a1', position]]));
assert.equal(f.fleet().spec.recede ?? null, null, 'the set does not recede');
const eye = fromDegrees(-97.71, 30.21, 30_000);
const expected = (focusFactor) =>
aircraftTreatmentAlpha({
baseAlpha: 0.8,
focusFactor,
cameraDistanceM: Math.hypot(
eye.x - position.x,
eye.y - position.y,
eye.z - position.z,
),
cameraHeightM: 30_000,
});
try {
// Recede from the eye on, so the haze is not 1 here.
setAircraftRecessionParams({ startLimbRatio: 0, alphaFloor: 0.05 });
f.look(0.8, 0.5);
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
const item = f.fleet().items.get('a1');
assert.equal(item.tint[3], expected(0.5), 'the tint carries it all');
assert.equal(item.focus ?? 1, 1, 'with no focus for the set to compose');
// A frame inside the fleet interval writes nothing, whatever changed.
f.look(0.8, 0.25);
f.models._fleetTick();
assert.equal(f.fleet().items.get('a1').tint[3], item.tint[3]);
f.tick();
assert.equal(
f.fleet().items.get('a1').tint[3],
expected(0.25),
'the next tick takes it',
);
} finally {
resetAircraftRecessionParams();
}
f.state._irBoost = true;
f.models._reloadModelsForIrBoost();
f.tick();
assert.equal(f.fleet().items.get('a1').tint[3], 1, 'boosted: full strength');
});
test('a tuning change reaches the icons on the next frame, icons shown or not', async () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.state._icons.show = false;
const before = f.iconRecedeSyncs();
f.models._fleetTick();
assert.ok(f.iconRecedeSyncs() > before, 'the icons are told');
});
test('a contact not there yet at the time drawn has its fleet model hidden, as one beyond the horizon', () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.fleet().items.get('a1').show, true, 'drawn while there');
f.setUnseen('a1', true);
f.tick();
assert.equal(f.fleet().items.get('a1').show, false, 'hidden while unseen');
f.setUnseen('a1', false);
f.tick();
f.tick();
assert.equal(f.fleet().items.get('a1').show, true, 'drawn again');
});
+19 -2
View File
@@ -8,6 +8,7 @@ import {
} from '../geo/julian.js';
import { clone, distance } from '../geo/vector.js';
import { curvePieceAt, fixCurveCached } from './fixCurve.js';
import { historyBracketIndex, historyUnseenAt } from './timelineHistory.js';
import {
COAST_MAX_SPEED_MPS,
courseBetweenCartesians,
@@ -136,6 +137,7 @@ export function createMotionRegime() {
turnRateDps: 0,
minDt: 0,
maxDt: 0,
unseen: false,
};
}
@@ -164,7 +166,9 @@ export function createMotionRegime() {
* five minutes past it, then stops (SIGNAL LOST). A contact last heard on
* or near the ground holds there instead (`staleHoldsForFix`, decided once
* per report), and a chain of synthetic fixes never coasts further than
* the real report they were built from would.
* the real report they were built from would. Following the clock, a
* warm-up well before a contact's own first fix is `unseen`: it was not
* there yet, and is not drawn (`historyUnseenAt`).
*
* @param {Array<object>} history Non-empty, oldest first.
* @param {object|undefined} info The contact's record.
@@ -186,13 +190,24 @@ export function aircraftMotionRegime(
// contact is drawn report to report, as its trail is.
let report = history.length - 1;
while (report >= 0 && isSyntheticFix(history[report])) report--;
// The pairs are read back from the fix after the first one at or after
// the render time (so a fix at exactly that time takes the later pair, as
// it always did; past any superseded synthetic fix there), found by
// halving, and stop at the first pair wholly before it: a contact
// following the clock keeps a long history.
let start = Math.min(
historyBracketIndex(history, renderTime) + 1,
history.length - 1,
);
while (start < report && isSyntheticFix(history[start])) start++;
let b = null;
for (let i = history.length - 1; i >= 0; i--) {
for (let i = start; i >= 0; i--) {
const a = history[i];
if (i < report && isSyntheticFix(a)) continue;
const pairB = b;
b = a;
if (!pairB) continue;
if (julianLessThan(pairB.time, renderTime)) break;
if (
!julianLessThanOrEquals(a.time, renderTime) ||
!julianLessThanOrEquals(renderTime, pairB.time)
@@ -219,6 +234,7 @@ export function aircraftMotionRegime(
result.chordCourse =
blend > 0 ? courseBetweenCartesians(a.position, pairB.position) : null;
result.blend = blend;
result.unseen = false;
return result;
}
const newest = history[history.length - 1];
@@ -226,6 +242,7 @@ export function aircraftMotionRegime(
result.kind = 'fix';
result.piece = null;
result.fix = warming ? history[0] : newest;
result.unseen = warming && historyUnseenAt(history, renderTime);
result.speed = fixSpeedMps(result.fix, info, fields);
result.heading = fixTrackDeg(result.fix, info, fields);
// Past the newest report it flies straight on along its course: a turn
+46 -100
View File
@@ -1,29 +1,33 @@
/**
* Limb-relative recession for distant aircraft: the factors icon sets apply in
* their shader (ICON_RECEDES) and models apply through their colour alpha.
* Limb-relative recession for distant aircraft: the tuning the aircraft icon
* and model sets recede by (`aircraftRecedeSpec`), and the factors and alpha
* those sets draw with, for evidence and checks.
*
* It multiplies an icon's ordinary scale, which composes with its locked
* NearFarScalar. It never edits that scalar, culls a contact, or allows alpha
* to reach zero.
* to reach zero. The maths is the Cesium-free `render/recession.js`,
* which the sets drawing aircraft recede by (`SetSpec.recede`).
*/
import {
RECEDE_DEFAULTS,
limbDistanceM,
recedeFactors,
recedeFrame,
recedeParams,
recededAlpha,
} from '../render/recession.js';
export const DEFAULT_AIRCRAFT_RECESSION_PARAMS = Object.freeze({
startLimbRatio: 0.5,
scaleFloor: 0.45,
alphaFloor: 0.35,
combinedAlphaFloor: 0.2,
globeViewBlendStartM: 3_500_000,
globeViewBlendEndM: 4_500_000,
earthRadiusM: 6_378_137,
...RECEDE_DEFAULTS,
writeEpsilon: 0.005,
});
let _params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS };
const _scratchFactors = { scale: 1, alpha: 1, limbRatio: null };
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
const _scratchFrame = { active: false, limbM: 1, strength: 0 };
// The tuning `_recede` was made from, and the set option made from it.
let _recedeFor = null;
let _recede = null;
function resolvedParams(overrides) {
if (!overrides || overrides === _params) return _params;
@@ -36,47 +40,12 @@ function aircraftRecessionFactorsResolved(
tuning,
result,
) {
if (
!Number.isFinite(cameraDistanceM) ||
cameraDistanceM < 0 ||
!Number.isFinite(cameraHeightM) ||
cameraHeightM <= 0 ||
cameraHeightM >= tuning.globeViewBlendEndM
) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
return result;
}
const limbDistance = cameraLimbDistanceM(cameraHeightM, tuning.earthRadiusM);
if (!Number.isFinite(limbDistance) || limbDistance <= 0) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
return result;
}
const limbRatio = cameraDistanceM / limbDistance;
if (limbRatio <= tuning.startLimbRatio) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = limbRatio;
return result;
}
const rawT =
(limbRatio - tuning.startLimbRatio) / (1 - tuning.startLimbRatio);
const t = clamp(rawT, 0, 1);
const limbEase = t * t * (3 - 2 * t); // smoothstep: zero slope at both band edges
const globeRawT =
(cameraHeightM - tuning.globeViewBlendStartM) /
(tuning.globeViewBlendEndM - tuning.globeViewBlendStartM);
const globeT = clamp(globeRawT, 0, 1);
const globeEase = globeT * globeT * (3 - 2 * globeT);
const strength = 1 - globeEase;
result.scale = 1 + (tuning.scaleFloor - 1) * limbEase * strength;
result.alpha = 1 + (tuning.alphaFloor - 1) * limbEase * strength;
result.limbRatio = limbRatio;
return result;
return recedeFactors(
cameraDistanceM,
recedeFrame(cameraHeightM, tuning, _scratchFrame),
tuning,
result,
);
}
/**
@@ -85,45 +54,34 @@ function aircraftRecessionFactorsResolved(
* @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS}
*/
export function setAircraftRecessionParams(patch = {}) {
const next = { ..._params };
if (Number.isFinite(patch.startLimbRatio)) {
next.startLimbRatio = clamp(patch.startLimbRatio, 0, 0.99);
}
if (Number.isFinite(patch.scaleFloor))
next.scaleFloor = clamp(patch.scaleFloor, 0.05, 1);
if (Number.isFinite(patch.alphaFloor))
next.alphaFloor = clamp(patch.alphaFloor, 0.05, 1);
if (Number.isFinite(patch.combinedAlphaFloor)) {
next.combinedAlphaFloor = clamp(patch.combinedAlphaFloor, 0.05, 1);
}
if (Number.isFinite(patch.globeViewBlendStartM)) {
next.globeViewBlendStartM = Math.max(1, patch.globeViewBlendStartM);
}
if (Number.isFinite(patch.globeViewBlendEndM)) {
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
patch.globeViewBlendEndM,
);
}
// Backward-compatible evidence override: the former hard threshold now
// names the identity end of the blend band.
if (Number.isFinite(patch.globeViewHeightM)) {
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
patch.globeViewHeightM,
);
}
if (next.globeViewBlendStartM >= next.globeViewBlendEndM) {
next.globeViewBlendStartM = Math.max(1, next.globeViewBlendEndM - 1);
}
if (Number.isFinite(patch.earthRadiusM))
next.earthRadiusM = Math.max(1, patch.earthRadiusM);
const given = Number.isFinite(patch.globeViewHeightM)
? { ...patch, globeViewBlendEndM: patch.globeViewHeightM }
: patch;
const next = {
...recedeParams(given, _params),
writeEpsilon: _params.writeEpsilon,
};
if (Number.isFinite(patch.writeEpsilon))
next.writeEpsilon = Math.max(0, patch.writeEpsilon);
_params = next;
return { ..._params };
}
/**
* The tuning as the `recede` of the sets that draw aircraft: the same
* object until the tuning changes.
* @returns {import('../render/contract/index').RecedeSpec}
*/
export function aircraftRecedeSpec() {
if (_recedeFor !== _params) {
_recedeFor = _params;
_recede = Object.freeze(recedeParams(_params));
}
return _recede;
}
/** @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS} Current tuning. */
export function getAircraftRecessionParams() {
return _params;
@@ -142,13 +100,7 @@ export function resetAircraftRecessionParams() {
* @param {number} [earthRadiusM]
* @returns {number}
*/
export function cameraLimbDistanceM(
cameraHeightM,
earthRadiusM = DEFAULT_AIRCRAFT_RECESSION_PARAMS.earthRadiusM,
) {
if (!Number.isFinite(cameraHeightM) || cameraHeightM <= 0) return Number.NaN;
return Math.sqrt(cameraHeightM * (2 * earthRadiusM + cameraHeightM));
}
export const cameraLimbDistanceM = limbDistanceM;
/**
* Pure recession factors for one aircraft.
@@ -196,13 +148,7 @@ export function aircraftTreatmentAlpha({
tuning,
_scratchFactors,
);
return (
baseAlpha *
Math.max(
tuning.combinedAlphaFloor,
clamp(focusFactor, 0, 1) * factors.alpha,
)
);
return baseAlpha * recededAlpha(focusFactor, factors.alpha, tuning);
}
/**
+21
View File
@@ -97,3 +97,24 @@ test('model hue changes at constant alpha, then clears without redundant writes'
assert.equal(applyAircraftModelTreatment({model,baseColor:color(1,1,1),alpha:0.65}),1);
assert.equal(model.color.green,1);
});
test('the aircraft sets recede by the tuning: one object until it changes', async () => {
const {
aircraftRecedeSpec,
setAircraftRecessionParams,
resetAircraftRecessionParams,
} = await import('./aircraftRecession.js');
const { RECEDE_DEFAULTS } = await import('../render/recession.js');
resetAircraftRecessionParams();
const first = aircraftRecedeSpec();
assert.deepEqual(first, { ...RECEDE_DEFAULTS });
assert.equal(aircraftRecedeSpec(), first);
setAircraftRecessionParams({ scaleFloor: 0.6, globeViewHeightM: 4_000_000 });
const tuned = aircraftRecedeSpec();
assert.notEqual(tuned, first);
assert.equal(tuned.scaleFloor, 0.6);
assert.equal(tuned.globeViewBlendEndM, 4_000_000);
assert.equal('writeEpsilon' in tuned, false);
resetAircraftRecessionParams();
assert.deepEqual(aircraftRecedeSpec(), first);
});
+1 -1
View File
@@ -124,7 +124,7 @@ export function depthToViewDistance(depth, near, far, logDepth) {
if (logDepth)
return near + Math.pow(2, depth * Math.log2(far - near + 1)) - 1;
// Standard depth needs a near plane in front of the eye; log depth does not
// (as WebGL log depth writes it, with none).
// (it can be written with none, as log2(1 + d) / log2(far + 1)).
if (!(near > 0)) return Number.NaN;
return (near * far) / (far - depth * (far - near));
}
+1 -2
View File
@@ -114,8 +114,7 @@ test('the ends of the depth range, and a bad range, mean nothing was drawn', ()
assert.ok(Number.isNaN(depthToViewDistance(0.5, 0, 100, false)));
});
test('log depth with no near plane decodes as it is written with none', () => {
// Written as log2(1 + d) / log2(far + 1).
test('log depth with no near plane decodes as log2(1 + d) / log2(far + 1)', () => {
const depth = Math.log2(1 + 400) / Math.log2(100_000 + 1);
assert.ok(
Math.abs(depthToViewDistance(depth, 0, 100_000, true) - 400) < 1e-6,
-2
View File
@@ -45,7 +45,6 @@ export {
DIRECTIONS_MODES,
DIRECTIONS_POINTER_OWNER,
DIRECTIONS_ROUTE_COLOR,
POINTER_TOOL_EXITS,
STEP_ANCHOR_DEADLINE_MS,
STEP_ANCHOR_FAST_ATTEMPTS,
STEP_ANCHOR_RETRY_MS,
@@ -60,7 +59,6 @@ export {
directionsStepList,
normalizeDirectionsParams,
normalizeRoutePayload,
pointerBlockedMessage,
stepAnchorDelayMs,
stepIndexAtDistance,
stepMarkerHeightM,
+33 -101
View File
@@ -21,8 +21,6 @@ import {
stepIndexAtDistance,
stepMarkerHeightM,
stepMarkerIndices,
pointerBlockedMessage,
POINTER_TOOL_EXITS,
STEP_ANCHOR_DEADLINE_MS,
STEP_ANCHOR_RETRY_MS,
STEP_ANCHOR_SLOW_RETRY_MS,
@@ -440,12 +438,6 @@ test('the FLY chip reports a flight in progress', () => {
assert.equal(flying.active, true);
});
test('a blocked pointer is reported instead of silently doing nothing', () => {
const blocked = directionsStats({ ...idle, pointerBlocked: true });
assert.match(blocked.error, /Another map tool is using clicks/);
assert.equal(blocked.count, 0);
});
test('a step selection can be requested and cleared through params', () => {
assert.deepEqual(normalizeDirectionsParams({ step: 3 }), { step: 3 });
assert.deepEqual(normalizeDirectionsParams({ step: 0 }), { step: 0 });
@@ -517,37 +509,40 @@ test('placing an endpoint takes the pointer, and every exit path gives it back',
assert.equal(isPointerFree(), true, 'destroy releases');
});
test('arming is refused, and said so, while another tool holds the pointer', (t) => {
test('arming takes the pointer from another tool, which is told', (t) => {
ownershipFixture(t);
const releaseDraw = claimAs('draw');
assert.equal(
directionsLayer.setParams({ arm: 'a' }),
true,
'the write is accepted',
);
assert.equal(
pointerOwner(),
'draw',
"the other tool's claim is never stolen",
);
let lost = 0;
claimPointer('draw', { onLost: () => (lost += 1) });
assert.equal(directionsLayer.setParams({ arm: 'a' }), true);
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER, 'the newest wins');
assert.equal(lost, 1, 'the other tool is told once');
const chips = directionsLayer.getRowControls().chips;
assert.equal(
chips.find((chip) => chip.id === 'set-a').active,
false,
'nothing is armed',
);
assert.match(
directionsLayer.getStats().error,
/Another map tool is using clicks/,
'the row says why the click did nothing',
);
assert.equal(chips.find((chip) => chip.id === 'set-a').active, true);
assert.equal(directionsLayer.getStats().error, null);
});
// Once the other tool lets go, arming works and the complaint clears.
test('a newer tool taking the pointer disarms, as Escape would', (t) => {
ownershipFixture(t);
let told = 0;
directionsLayer.setRowControlsListener(() => (told += 1));
t.after(() => directionsLayer.setRowControlsListener(null));
directionsLayer.setParams({ arm: 'b' });
told = 0;
const releaseDraw = claimAs('draw');
const chips = directionsLayer.getRowControls().chips;
assert.equal(chips.find((chip) => chip.id === 'set-b').active, false);
assert.ok(told > 0, 'the row hears it');
assert.equal(
directionsLayer.getStats().error,
null,
'nothing to complain of',
);
// Its own later release frees nothing of the newer tool's.
directionsLayer.setParams({ arm: null });
assert.equal(pointerOwner(), 'draw');
assert.equal(releaseDraw(), true);
directionsLayer.setParams({ arm: 'a' });
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
assert.equal(directionsLayer.getStats().error, null);
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER, 'it arms again');
});
test('a release names this layer, so it cannot free a successor tool claim', (t) => {
@@ -567,11 +562,10 @@ test('a release names this layer, so it cannot free a successor tool claim', (t)
test('the pointer claim outlives the click that consumed it', async (t) => {
ownershipFixture(t);
// Every layer binds its own handler to the same canvas and they all run
// inside ONE browser event. Releasing the claim the moment the endpoint is
// placed hands the rest of that same click to every ambient handler
// registered after this one — which is how placing A on top of a bikeshare
// station also deselected the station.
// The renderer's click comes from the pointer's up, and the browser's own
// `click` on the canvas follows inside ONE input event; DOM listeners there
// ask `isPointerFree()` then. Releasing the claim the moment the endpoint is
// placed hands the rest of that same click to them.
directionsLayer.setParams({ arm: 'a' });
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
@@ -727,68 +721,6 @@ test('a stale lease cannot free the claim a later arming holds', async (t) => {
);
});
test('a refused arming names the tool holding the pointer and how to leave it', () => {
// Owner field test: he pressed SET A while Draw was open, nothing happened,
// and he concluded Directions was broken. Silence was the bug.
assert.equal(
pointerBlockedMessage('draw', 'a'),
'Draw is active — press Escape twice to leave Draw, then set A',
);
assert.equal(
pointerBlockedMessage('draw', 'b'),
'Draw is active — press Escape twice to leave Draw, then set B',
);
// A tool nobody has written an exit for still gets a usable sentence.
assert.equal(
pointerBlockedMessage('measure', 'a'),
'measure is active — turn measure off, then set A',
);
// A registered owner without an exit is named by its tool, not its id.
assert.equal(
pointerBlockedMessage('recent-imagery-box', 'a'),
'Recent imagery is active — turn Recent imagery off, then set A',
);
// Nothing to say when nothing is in the way, or when we are the holder.
assert.equal(pointerBlockedMessage(null, 'a'), null);
assert.equal(pointerBlockedMessage('', 'a'), null);
assert.equal(pointerBlockedMessage(' ', 'a'), null);
assert.equal(pointerBlockedMessage(DIRECTIONS_POINTER_OWNER, 'a'), null);
// Every exit the table knows names its tool and says how to leave it.
for (const [id, exit] of Object.entries(POINTER_TOOL_EXITS)) {
assert.match(
pointerBlockedMessage(id, 'a'),
new RegExp(`^${exit.name} is active — `),
);
assert.match(pointerBlockedMessage(id, 'a'), /, then set A$/);
}
});
test('the refusal reaches the app toast, and a successful arming says nothing', (t) => {
ownershipFixture(t);
const toasts = [];
directionsLayer.attachShellServices({
showToast: (text) => toasts.push(text),
});
t.after(() => directionsLayer.attachShellServices(null));
const releaseDraw = claimAs('draw');
directionsLayer.setParams({ arm: 'a' });
assert.deepEqual(toasts, [
'Draw is active — press Escape twice to leave Draw, then set A',
]);
// The row status the operator can also read is still set.
assert.match(
directionsLayer.getStats().error,
/Another map tool is using clicks/,
);
// Once Draw lets go, arming works and says nothing at all.
releaseDraw();
directionsLayer.setParams({ arm: 'a' });
assert.equal(toasts.length, 1, 'a successful arming is silent');
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
});
test('maneuvers are phrased on the page, in English word for word as the proxy does', () => {
const types = [
'depart',
+47 -12
View File
@@ -69,6 +69,15 @@ function inView(pose, point) {
);
}
/** Two colours as `fleetColor` gives them, alike (arrays element by element). */
function sameColor(a, b) {
if (a === b) return true;
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
let instances = 0;
/**
@@ -221,9 +230,8 @@ export function createFleetModelLayer({
return fromDegrees(at.lon, at.lat, at.height + lift);
}
/** The draw item for an admitted model, as the set draws it. */
function itemOf(id, record, item, show, boost) {
const at = placement(item);
/** The draw item for an admitted model, as the set draws it, at `at`. */
function itemOf(id, record, item, show, boost, at = placement(item)) {
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
return {
id,
@@ -257,16 +265,43 @@ export function createFleetModelLayer({
};
}
/** The item to write for a record, or null when nothing it draws changed. */
/**
* The item to write for a record, or null when nothing it draws changed:
* what it was last written with is compared value by value, and the item
* is built only when something did (a fleet passes every model each
* frame, and most of what it draws stays).
*/
function changed(id, record, item, show, boost) {
const next = itemOf(id, record, item, show, boost);
const p = next.pos;
const mask = next.maskColor ? String(next.maskColor) : '';
const key = `${p.x},${p.y},${p.z}|${next.orientation.heading}|${item.spec.key}|${mask}|${boost}|${show}`;
if (key === record.sent && next.meta === record.meta) return null;
record.sent = key;
record.meta = next.meta;
return next;
const at = placement(item);
const heading = item.headingDeg || 0;
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
const meta = item.pickId ?? id;
const sent = record.sent;
if (
sent !== null &&
sent.x === at.x &&
sent.y === at.y &&
sent.z === at.z &&
sent.heading === heading &&
sent.specKey === item.spec.key &&
sameColor(sent.mask, mask) &&
sent.boost === boost &&
sent.show === show &&
sent.meta === meta
)
return null;
const next = (record.sent ??= {});
next.x = at.x;
next.y = at.y;
next.z = at.z;
next.heading = heading;
next.specKey = item.spec.key;
// A colour array is kept as a copy: the layer may change its own.
next.mask = Array.isArray(mask) ? [...mask] : mask;
next.boost = boost;
next.show = show;
next.meta = meta;
return itemOf(id, record, item, show, boost, at);
}
return {
+39
View File
@@ -327,6 +327,45 @@ test('a model stands on the floor its icon is lifted above', () => {
layer.destroy();
});
test('a model that did not change is not written, nor built anew to find that out', () => {
const { layer, frame } = readyLayer({ display: { models3d: true } });
const tram = transitModelSpec(set, { mode: 'tram' });
// Reads of what only the draw item takes (its scales): a model whose item
// is built again reads them.
let shapeReads = 0;
const spec = new Proxy(tram, {
get(target, key) {
if (key === 'scale' || key === 'scaleXYZ') shapeReads += 1;
return target[key];
},
});
const tint = [1, 0, 0, 1];
const item = itemAt(10, spec, { pickId: 't', tint });
const items = new Map([['t', item]]);
const models = frame(items, 0);
const writes = models.writes;
shapeReads = 0;
for (let at = 2; at < 6; at++) layer.frame(items, at);
assert.equal(models.writes, writes, 'nothing written');
assert.equal(shapeReads, 0, 'no draw item built');
// A move, a turn and a route colour the layer changes in its own array
// are each written.
item.position = add(item.position, { x: 1, y: 0, z: 0 });
layer.frame(items, 6);
assert.equal(models.writes, writes + 1, 'a move is written');
item.headingDeg += 10;
layer.frame(items, 7);
assert.equal(models.writes, writes + 2, 'a turn is written');
tint[2] = 1;
layer.frame(items, 8);
assert.equal(models.writes, writes + 3, 'a colour changed in place');
assert.deepEqual(models.items.get('t').maskColor, [1, 0, 1, 1]);
layer.frame(items, 9);
assert.equal(models.writes, writes + 3, 'and then nothing');
layer.destroy();
});
test('under NVG/FLIR models draw unlit white, and lit again on exit, without loading again', () => {
const display = { models3d: true, irBoost: false };
const { layer, frame } = readyLayer({ display });
+84
View File
@@ -0,0 +1,84 @@
/**
* Icon motion segments packed for the GPU (`iconSegment.js`): one row per
* icon, read by `ICON_SEGMENT_GLSL` as `iconPosition` draws it.
*/
import type { Ecef } from '../render/contract/index';
/** Floats per packed row. */
export const SEGMENT_STRIDE: number;
export const SEGMENT_HOLD: number;
export const SEGMENT_LERP: number;
export const SEGMENT_ARC: number;
/** GLSL that evaluates a packed row. */
export const ICON_SEGMENT_GLSL: string;
/** Stay at `position` facing `courseDeg`. */
export function writeHoldSegment(
out: Float32Array,
row: number,
position: Ecef,
courseDeg: number,
): void;
export function writeLerpSegment(
out: Float32Array,
row: number,
segment: {
from: Ecef;
to: Ecef;
t0: number;
t1: number;
course0Deg: number;
courseSlopeDeg: number;
},
): void;
export function writeArcSegment(
out: Float32Array,
row: number,
segment: {
fix: Ecef;
t0: number;
minDt: number;
maxDt: number;
speedMps: number;
trackDeg: number;
turnRateDps: number;
climbMps?: number;
},
): void;
/**
* Glide row `row`'s drawn course from `fromCourseDeg` onto its segment's,
* at most `rateDps` from `t0` (seconds, as its times were packed).
*/
export function writeCourseGlide(
out: Float32Array,
row: number,
fromCourseDeg: number,
t0: number,
rateDps: number,
offsetDeg?: number,
): void;
/** Move a row's stored times by `deltaSec`. */
export function shiftSegmentTimes(
out: Float32Array,
row: number,
deltaSec: number,
): void;
/** The displayed course at `tau`, degrees clockwise from north. */
export function segmentCourse(
seg: Float32Array,
row: number,
tau: number,
): number;
/** The course the row glides toward at `tau`. */
export function segmentTargetCourse(
seg: Float32Array,
row: number,
tau: number,
): number;
/** Where the row is at `tau`, ECEF, into `result`. */
export function segmentPosition(
seg: Float32Array,
row: number,
tau: number,
result?: Ecef,
): Ecef;
+114 -20
View File
@@ -10,21 +10,32 @@
*
* So there is one claim, held by at most one owner at a time:
*
* - A TOOL that needs the pointer calls `claimPointer('draw')` when it turns on
* and gets back a LEASE — an opaque token. It releases with
* - A TOOL that needs the pointer calls `claimPointer('draw', {onLost})` when
* it turns on and gets back a LEASE — an opaque token. It releases with
* `releasePointer(lease)` when it turns off. It does not consult anyone;
* holding the claim is what makes it the owner.
* - An AMBIENT SELECTION HANDLER — anything that picks an entity because the
* user clicked — is not called while `isPointerFree()` is false: the input
* dispatcher skips it. It never claims.
*
* Claims do not stack and are never stolen: while one owner holds the pointer,
* a second `claimPointer` returns null rather than displacing it — and so does
* a second claim under the SAME name, because two live instances of one tool
* (an old one mid-teardown, its replacement already running) are two owners,
* not one. The lease is what tells them apart: releasing takes the token that
* was issued, so a superseded instance calling `releasePointer` with its own
* stale lease frees nothing and its successor keeps the pointer.
* The newest claim takes over, as a claim on the renderer's input port does
* (`src/render/contract/input.d.ts`): a second `claimPointer` ends the lease
* out, and its holder's `onLost` is called once, after the new lease holds the
* pointer, so that tool turns itself off as if the person had turned it off.
* That holds for a second claim under the SAME name too: an old instance
* mid-teardown and its replacement already running are two owners, and the
* replacement wins. The lease is what tells them apart: releasing takes the
* token that was issued, so a superseded instance calling `releasePointer`
* with its own stale lease frees nothing and its successor keeps the pointer.
*
* Each scene's input dispatcher bridges its renderer's input port here
* (`bridgePointer`): while a tool holds the pointer the port holds a lease
* for it, so the port is not free, and a claim made on the port itself
* takes over from the tool here like any newer claim. While such a claim is
* out the pointer is not free. The bridge's lease takes no press (its `grab`
* refuses each one): the dispatcher decides who hears each event when it
* arrives, and the renderer's own select and double-click follow run unless
* a tool holds them off (`suppressStockClicks`).
*
* Ownership is page-scoped, like the layers and handlers it arbitrates.
*/
@@ -34,19 +45,93 @@
/** @type {PointerLease|null} */
let currentLease = null;
let nextLeaseId = 1;
/** @type {WeakMap<PointerLease, () => void>} each lease's `onLost` */
const lostHandlers = new WeakMap();
/** @type {Set<{claimed: (lease: PointerLease|null) => void, isFree: () => boolean}>} */
const bridges = new Set();
/**
* Take the pointer for `owner`.
* Take the pointer for `owner`. The newest claim takes over: the lease out
* ends, and its `onLost` is called once, after this one holds the pointer.
* @param {string} owner Stable identifier for the claiming tool, e.g. 'draw'.
* @returns {PointerLease|null} The lease to release with, or null if the
* pointer is already held — including by another instance of the same tool.
* @param {{onLost?: () => void}} [options] `onLost`: called once when a newer
* claim, here or on a bridged port, ends this lease; never when it is
* released. A tool turns itself off in it.
* @returns {PointerLease|null} The lease to release with, or null for an
* owner with no name.
*/
export function claimPointer(owner) {
export function claimPointer(owner, { onLost } = {}) {
const name = normalizeOwner(owner);
if (!name) return null;
if (currentLease !== null) return null;
currentLease = Object.freeze({ owner: name, id: nextLeaseId++ });
return currentLease;
const previous = currentLease;
const lease = Object.freeze({ owner: name, id: nextLeaseId++ });
currentLease = lease;
if (typeof onLost === 'function') lostHandlers.set(lease, onLost);
announce();
if (previous) tellLost(previous);
return lease;
}
/** Each bridged port hears who holds the pointer now. */
function announce() {
for (const bridge of [...bridges]) bridge.claimed(currentLease);
}
/** Tell the holder of an ended `lease`, once. */
function tellLost(lease) {
const onLost = lostHandlers.get(lease);
lostHandlers.delete(lease);
if (!onLost) return;
try {
onLost();
} catch (error) {
console.error('Pointer owner failed to let go', error);
}
}
/**
* Hold a lease on a renderer's input port for as long as a tool holds the
* pointer here, made afresh for each claim. A claim made on the port by
* anyone else ends the tool's lease here, and its holder is told; while that
* claim is out, `isPointerFree()` is false.
* @param {import('../render/contract/input').InputPort} port
* @returns {{lease: () => import('../render/contract/input').Lease|null, off: () => void}}
* `lease` is the port lease standing for the tool's, null while no tool
* here holds the pointer; `off` gives it back and stops bridging.
*/
export function bridgePointer(port) {
let held = null;
const bridge = {
claimed(lease) {
held?.release();
held = null;
if (!lease) return;
held = port.claimPointer(lease.owner, {
// Every press goes on to the port's other listeners; the dispatcher
// decides who hears it when it arrives.
grab: () => false,
// A claim on the port that is not this bridge's.
onLost: () => {
held = null;
if (currentLease !== lease) return;
currentLease = null;
announce();
tellLost(lease);
},
});
},
isFree: () => port.isPointerFree(),
};
bridges.add(bridge);
bridge.claimed(currentLease);
return {
lease: () => (held?.current ? held : null),
off() {
if (!bridges.delete(bridge)) return;
held?.release();
held = null;
},
};
}
/**
@@ -57,7 +142,9 @@ export function claimPointer(owner) {
*/
export function releasePointer(lease) {
if (!currentLease || !lease || lease.id !== currentLease.id) return false;
lostHandlers.delete(currentLease);
currentLease = null;
announce();
return true;
}
@@ -66,9 +153,14 @@ export function pointerOwner() {
return currentLease ? currentLease.owner : null;
}
/** @returns {boolean} True when no tool holds the pointer. */
/**
* @returns {boolean} True when no tool holds the pointer, here or through a
* claim on a bridged port.
*/
export function isPointerFree() {
return currentLease === null;
if (currentLease !== null) return false;
for (const bridge of bridges) if (!bridge.isFree()) return false;
return true;
}
/**
@@ -89,13 +181,15 @@ export function isLeaseCurrent(lease) {
}
/**
* Drop any claim. For tests and for application teardown, which cannot rely on
* a half-disposed tool to release its own lease.
* Drop any claim, telling no one. For tests and for application teardown,
* which cannot rely on a half-disposed tool to release its own lease.
* @returns {string|null} The owner that was holding it, if any.
*/
export function resetPointerOwnership() {
const previous = pointerOwner();
if (currentLease) lostHandlers.delete(currentLease);
currentLease = null;
announce();
return previous;
}
+117 -15
View File
@@ -11,7 +11,9 @@ import {
pointerOwner,
releasePointer,
resetPointerOwnership,
bridgePointer,
} from './inputOwnership.js';
import { createInputRouter } from '../render/input/router.js';
const ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -35,22 +37,61 @@ test('the pointer starts free and a claim hands back a lease', () => {
assert.equal(isLeaseCurrent(lease), true);
});
test('a claim is never stolen — not even by the same tool name', () => {
const first = claimPointer('draw');
assert.ok(first);
test('the newest claim takes over and the holder it replaces is told, once', () => {
const told = [];
const first = claimPointer('draw', { onLost: () => told.push('draw') });
const second = claimPointer('directions', {
onLost: () => told.push('directions'),
});
assert.ok(second, 'a second claim is not refused');
assert.deepEqual(told, ['draw']);
assert.equal(pointerOwner(), 'directions');
assert.equal(isLeaseCurrent(first), false);
assert.equal(isLeaseCurrent(second), true);
assert.equal(
releasePointer(first),
false,
'the old late release frees nothing',
);
assert.equal(pointerOwner(), 'directions');
assert.deepEqual(told, ['draw'], 'told once');
assert.equal(releasePointer(second), true);
assert.deepEqual(told, ['draw'], 'a holder that lets go is not told');
});
assert.equal(
claimPointer('directions'),
null,
'another tool must not displace it',
);
assert.equal(
claimPointer('draw'),
null,
'a SECOND instance of the same tool is a second owner, not a no-op',
);
assert.equal(pointerOwner(), 'draw');
assert.equal(isLeaseCurrent(first), true);
test('a second instance of the same tool takes over from the first', () => {
// An old instance mid-teardown and its replacement already running are two
// owners: the replacement wins, and the old one is told to turn off.
let lost = 0;
const old = claimPointer('draw', { onLost: () => (lost += 1) });
const live = claimPointer('draw');
assert.notEqual(live.id, old.id);
assert.equal(lost, 1);
assert.equal(isLeaseCurrent(live), true);
});
test('the holder is told after the new claim holds the pointer; its error stays its own', (t) => {
const errors = [];
t.mock.method(console, 'error', (...args) => errors.push(args));
let seen = null;
const first = claimPointer('draw', {
onLost: () => {
seen = { owner: pointerOwner(), current: isLeaseCurrent(first) };
throw new Error('onLost');
},
});
const second = claimPointer('directions');
assert.deepEqual(seen, { owner: 'directions', current: false });
assert.equal(isLeaseCurrent(second), true);
assert.equal(errors.length, 1);
});
test('reset tells no one', () => {
let lost = 0;
claimPointer('draw', { onLost: () => (lost += 1) });
resetPointerOwnership();
claimPointer('directions');
assert.equal(lost, 0);
});
test('a replaced instance cannot free its successor’s claim', () => {
@@ -173,3 +214,64 @@ test('ambient selection handlers never claim the pointer themselves', () => {
);
}
});
/** A renderer's input port, as the contract's router keeps it. */
const portOf = () =>
createInputRouter({
report: (error) => {
throw error;
},
suspendCamera: () => () => {},
}).port;
test('a bridged port holds a lease for as long as a tool holds the pointer', () => {
const port = portOf();
const bridge = bridgePointer(port);
assert.equal(bridge.lease(), null);
const lease = claimPointer('draw');
assert.equal(port.isPointerFree(), false, 'the port is taken too');
assert.equal(bridge.lease().owner, 'draw');
assert.equal(bridge.lease().current, true);
const next = claimPointer('directions');
assert.equal(bridge.lease().owner, 'directions');
releasePointer(lease);
assert.equal(port.isPointerFree(), false, 'a stale release frees nothing');
releasePointer(next);
assert.equal(port.isPointerFree(), true);
assert.equal(bridge.lease(), null);
bridge.off();
});
test('a claim made on the port takes over from the page’s tool, and back', () => {
const port = portOf();
const bridge = bridgePointer(port);
const told = [];
const page = claimPointer('draw', { onLost: () => told.push('draw') });
const other = port.claimPointer('other', {
onLost: () => told.push('other'),
});
assert.deepEqual(told, ['draw'], 'the page’s tool is told');
assert.equal(isLeaseCurrent(page), false);
assert.equal(
isPointerFree(),
false,
'the port’s own claim holds the pointer',
);
assert.equal(bridge.lease(), null);
claimPointer('directions');
assert.deepEqual(told, ['draw', 'other'], 'a newer page claim takes it back');
assert.equal(other.current, false);
assert.equal(bridge.lease().owner, 'directions');
bridge.off();
});
test('a port bridged while a tool holds the pointer takes its lease at once; off gives it back', () => {
const lease = claimPointer('draw');
const port = portOf();
const bridge = bridgePointer(port);
assert.equal(port.isPointerFree(), false);
bridge.off();
assert.equal(port.isPointerFree(), true);
assert.equal(isLeaseCurrent(lease), true, 'the page claim stands');
assert.equal(isPointerFree(), false);
});
-24
View File
@@ -1,24 +0,0 @@
import { msg } from '../i18n/marker.js';
/**
* Tool name for a pointer owner. Owner ids (inputOwnership.js) never go on
* screen; callers translate the English name with translateKnown().
*/
const POINTER_OWNER_NAMES = Object.freeze({
draw: msg('Draw'),
directions: msg('Directions'),
'recent-imagery-box': msg('Recent imagery'),
});
/**
* English display name of a pointer owner. An owner without a registered name
* falls back to its id.
* @param {string|null} owner Pointer-owner id, as `pointerOwner()` returns it.
* @returns {string}
*/
export function pointerOwnerName(owner) {
const id = typeof owner === 'string' ? owner.trim() : '';
if (!id) return '';
return Object.hasOwn(POINTER_OWNER_NAMES, id) ? POINTER_OWNER_NAMES[id] : id;
}