Compare commits

..
Author SHA1 Message Date
German Khokhlov ebf2686e2f Number the changelog fragment for #1786 2026-11-18 00:51:07 +04:00
German Khokhlov ec9d5c9e06 Describe the cockpit ride fixes and add their changelog entry 2026-11-17 19:30:47 +04:00
German Khokhlov a7d966ae7e Rail cockpit rides: no height on an unknown floor, a standing train keeps its direction
- railHeightM is null while the train is drawn on the ellipsoid (floor
  quality 0) instead of -1.5 m, so a view waits for the surface.
- An arc step between two reports tells which way a train runs only above
  15 m, the layer's parked-train jitter (FOLLOW_MIN_MOVE_M). GPS jitter of
  a standing train no longer flips the direction through the playback
  segments, which turned a ride 180 degrees every poll.
- drawDirection, a copy of direction, becomes a directionPlayed flag.
2026-11-17 19:30:47 +04:00
German Khokhlov 134138931f Transit cockpit rides: hide the held icon, end a hold with the layer, no ellipsoid height
- A held vehicle's icon is hidden through the renderer (setShown, then
  flushMarkers). The icon sets draw a marker only as last pushed, so the
  direct marker.show write left a parked vehicle's icon drawn under the
  view's eye.
- disable() ends the hold: turned off and on again, the vehicle shows and
  clicks and Escape reach the layer.
- Far above the ground a vehicle with no floor is drawn on the ellipsoid.
  Its snapshot now reports groundHeightM null there, as near the ground,
  instead of -1.5 m.
- The uneven-ground test also checks the snapshot mid-segment, where a
  blend of the two reports' floors would read about 55 m instead of 10 m.
2026-11-17 19:30:47 +04:00
24 changed files with 314 additions and 378 deletions

No files matched your search

+7 -8
View File
@@ -3,11 +3,10 @@
heading and HUD (in the page's language, via `getLocale` and
`onLocaleChange` from `./i18n`); the camera can follow it without the
ground clamp, anchored exactly on it, and a generic HUD adds source rows, a
banner, a veil (its light streaks stop under reduced motion) and a bottom
progress line. The Rail and Transit layers expose read and hold APIs so a
selected train or vehicle can be ridden, and `./layers/rail/paths` is
exported; that export and the read APIs are experimental.
`docs/APPLICATION.md` shows a minimal provider. GEV itself registers none,
and entry to the built-in aircraft, satellite and vessel views is
unchanged; a provider's subject takes entry when it was selected after them
(Denis Groshev, @ZloyS, #1686).
banner, a veil (off under reduced motion) and a bottom progress line. The
Rail and Transit layers expose read and hold APIs so a selected train or
vehicle can be ridden, and `./layers/rail/paths` is exported; that export
and the read APIs are experimental. `docs/APPLICATION.md` shows a minimal
provider. GEV itself registers none, and entry to the built-in aircraft,
satellite and vessel views is unchanged; a provider's subject takes entry
when it was selected after them (Denis Groshev, @ZloyS, #1686).
@@ -0,0 +1,8 @@
- Fix rides on a Rail train or Transit vehicle for an application's Cockpit
subjects. A held parked vehicle no longer leaves its icon drawn under the
view, and turning Transit off ends a hold, so the vehicle shows again when
the layer is back on. A train or vehicle drawn on the ellipsoid while no
floor is known reports no height, so the view waits for the ground instead
of standing on the ellipsoid. A train standing at a platform keeps the way
it runs: GPS jitter of a few metres no longer turns the ride around
(German, @gekh, #1786).
@@ -1,8 +0,0 @@
- Keep an application's Cockpit subject steady: a height its entry frame gave
holds while the floor is still cold, so the view no longer ends; the camera
keeps up when the browser draws few frames (at 5 a second it fell 700 m
behind a 30 m/s subject in a minute); a provider's Live Signals rows change
where they stand, so a changing ETA no longer pushes a steady warning off
the list; progress labels give CJK, kana and Hangul names the width they
need; and labels, entry face and look keep the words checked at
registration when a later read fails (German, @gekh, #1787).
+1 -2
View File
@@ -396,8 +396,7 @@ their `this`; one that throws or returns a promise is treated as having
failed. What a method returns may carry getters: one that throws when read
makes a candidate none, a frame malformed (the view ends) and a HUD view keep
the last; a worded member (labels, entry face, look) that throws keeps its
last good words. An entry face's `icon` must be one of the Material Symbols
`index.html` loads (`icon_names`); any other renders as its name.
last good words.
```js
import { getLocale, onLocaleChange } from 'gods-eye-view/i18n';
+18 -18
View File
@@ -2743,38 +2743,34 @@ first in that order decides alone: when its gate is shut there is no entry
rather than the next subject's.
A frame places the eye `eye.upM` above `heightM` (the shared floor where the
frame gives none, or the last height it had, the entry frame's included, while
that floor is cold; with neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for
frame gives none, or where it last stood while that floor is cold; with
neither, the camera stays where it is and the HUD reads ACQUIRING SURFACE for
at most `COCKPIT_GROUND_WAIT_TIMEOUT_MS`, after which the view ends and the
subject is released: no height stands in for a floor never read), slews toward `headingDeg` at the provider's rate, and may
turn off the floor clamps (`groundClamp: false`, for a subject inside a
structure) or keep the anchor exactly on the subject (`anchor: 'exact'`, for a
layer that already moves it smoothly; a frame with no `speedMps` is always
exact, since an inertial anchor runs on at the frame's speed); `cameraIntervalMs: 0` updates the
camera every rendered frame. Each update turns, eases and moves the view by the
time since the last one, so it keeps up when the browser draws few frames; an
update more than a second past its interval (a hidden tab) moves it as one a
second late would. A frame that is null, malformed or for another
camera every rendered frame. A frame that is null, malformed or for another
subject ends the view (`restoreTracking: false`), as an aircraft tracked
meanwhile and the provider's layer turning off do; the exit control asks the
provider to restore its subject. The generic HUD shows the provider's kicker,
title, meta line, speed with its unit and tag, readout cards, always-visible
source rows, banner, route card and Live Signals rows (each changes where it
stands, so a changing ETA never pushes a steady warning off the list), a veil that darkens the
source rows, banner, route card and Live Signals rows, a veil that darkens the
picture under the HUD (with passing light streaks, which stop under reduced
motion), arrow-key look-around when the provider asks for it, and a progress
line along the bottom edge (`src/cockpitProgress.js`: close ticks merge,
labels never overlap, a full-width CJK, kana or Hangul glyph given about 1 em). Core translates none of the provider's text: a host
labels never overlap). Core translates none of the provider's text: a host
words it for the page's language (`gods-eye-view/i18n`:
`getLocale`, `onLocaleChange`). Its entry face, labels and look may be
functions, read again when they are shown and on a change of language, as the
HUD view is; a read that throws or is malformed keeps the last good words, at
first those checked when the provider was registered.
HUD view is.
The Rail layer offers a read API for such a view: `getSelectedTrain()` and
`getCockpitSubject()` (a snapshot of the train: where it is along its line,
which way it runs (`pathBinding.js` learns it), its rail height, speed as
reported or derived, position source, feed credit and stops, and
which way it runs (`pathBinding.js` learns it), its rail height (null while
no floor is known and it is drawn on the ellipsoid), speed as reported or
derived, position source, feed credit and stops, and
`selectedAtMs`, when the user last selected it by a click or `focusTrain`,
even again; null after a deselection and for a train only a hold selected),
`setCockpitSubject(key)` (its marker, 3D model and card hidden, the selection kept, its
@@ -2789,11 +2785,15 @@ offers the same for a vehicle (`getSelectedVehicle`, `getCockpitSubject`,
`setCockpitSubject`, `focusVehicle`): a held vehicle keeps playing when it is
out of the camera's view, and its sprite, 3D model, card, trail and detection
box are hidden; released, it is out of play until a visibility sweep finds it in
view. Its snapshot's `position.groundHeightM` is the floor where playback draws
it (the drawn marker's height while it is placed, else its segment's two
reports' floors at the playback fraction), not the newest report's, and null while that floor is unknown. Rail's `path.direction` is the
way the drawn train runs: once playback has placed it, a report that runs back
turns it only when playback reaches that report. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`,
view. Turning the layer off ends the hold. Its snapshot's
`position.groundHeightM` is the floor where playback draws it (the drawn
marker's height while it is placed, else its segment's two reports' floors at
the playback fraction), not the newest report's, and null while that floor is
unknown, also far above the ground, where such a vehicle is drawn on the
ellipsoid. Rail's `path.direction` is the way the drawn train runs: once
playback has placed it, a report that runs back turns it only when playback
reaches that report, and a step of at most 15 m between two reports (a standing
train's GPS jitter) keeps the direction it had. `docs/APPLICATION.md` (Cockpit subjects) shows a minimal provider. `src/ui/cockpitSubjectView.test.mjs`,
`src/cockpitSubjectProviders.test.mjs`, `src/cockpitProgress.test.mjs`,
`src/layers/rail/cockpitSubject.test.mjs` and the Transit lifecycle tests
cover them.
+4 -11
View File
@@ -58,19 +58,12 @@ export function cockpitAnchorCorrectionStep(
return Math.min(distanceM, eased, correctionRateMps * dt);
}
/**
* How late past its interval a subject's camera update may come and still
* advance by all of it: a browser drawing a frame a second still keeps up.
*/
const COCKPIT_SUBJECT_LATE_SEC = 1;
/**
* The seconds an application subject's camera update advances its heading
* slew, ground lift and anchor by: the time since the last update, at most
* its update interval plus a second. A subject updated every 500 ms, or a
* browser drawing 5 frames a second, then turns, eases and moves at its
* configured rates, while a long stall (a hidden tab) still moves it no
* further than one late update would.
* its update interval plus 0.1 s. A subject updated every 500 ms then turns
* and eases at its configured rates, while a long stall (a hidden tab) still
* moves it no further than one late update would.
* @param {number} elapsedMs Time since the last camera update.
* @param {number} intervalMs The subject's update interval (0: every frame).
* @returns {number}
@@ -82,7 +75,7 @@ export function cockpitSubjectStepSec(elapsedMs, intervalMs) {
const intervalSec = Number.isFinite(intervalMs)
? Math.max(0, intervalMs) / 1000
: 0;
return Math.min(intervalSec + COCKPIT_SUBJECT_LATE_SEC, elapsedSec);
return Math.min(intervalSec + 0.1, elapsedSec);
}
/** Return whether a throttled cockpit presentation update is due. */
+4 -7
View File
@@ -73,15 +73,12 @@ test('an application subject steps by its interval, never by a long stall', () =
assert.equal(cockpitSubjectStepSec(16, 0), 0.016);
assert.equal(cockpitSubjectStepSec(500, 500), 0.5);
assert.equal(cockpitSubjectStepSec(520, 500), 0.52);
// Slow frames (5 a second) count in full...
assert.equal(cockpitSubjectStepSec(200, 50), 0.2);
assert.equal(cockpitSubjectStepSec(1000, 0), 1);
// ...and a hidden tab's minutes as one late update.
assert.equal(cockpitSubjectStepSec(60_000, 500), 1.5);
assert.equal(cockpitSubjectStepSec(60_000, 0), 1);
// A hidden tab's minutes count as one late update.
assert.equal(cockpitSubjectStepSec(60_000, 500), 0.6);
assert.equal(cockpitSubjectStepSec(60_000, 0), 0.1);
assert.equal(cockpitSubjectStepSec(-5, 500), 0);
assert.equal(cockpitSubjectStepSec(Number.NaN, 500), 0);
assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 1);
assert.equal(cockpitSubjectStepSec(1000, Number.NaN), 0.1);
});
test('cockpit camera clearance never falls below the rendered ground floor', () => {
+6 -22
View File
@@ -30,29 +30,13 @@ const TONE_RANK = Object.freeze([
const stronger = (a, b) =>
TONE_RANK.indexOf(b) > TONE_RANK.indexOf(a) ? b : a;
/**
* Full-width glyphs (CJK ideographs and punctuation, kana, Hangul, full-width
* forms), each about 1 em wide.
*/
const WIDE_GLYPH =
/[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꥠ-꥿가-힣豈-﫿︰-﹏＀-⦆¢-₩\u{20000}-\u{3fffd}]/u;
/** One line's width in the label's 10 px type, 0.06 em apart (px). */
function lineWidthPx(line) {
let wide = 0;
let narrow = 0;
for (const glyph of String(line ?? ''))
if (WIDE_GLYPH.test(glyph)) wide += 1;
else narrow += 1;
return wide * 10.6 + narrow * 6.4;
}
/**
* A label's width estimate (px): its longer line, a full-width glyph at
* 10.6 px and any other at 6.4 px.
*/
/** A label's width estimate (px): its longer line in small capitals. */
export function estimateProgressLabelPx(label) {
return Math.max(lineWidthPx(label?.text), lineWidthPx(label?.detail)) + 8;
const longest = Math.max(
String(label?.text ?? '').length,
String(label?.detail ?? '').length,
);
return longest * 6.4 + 8;
}
/**
+1 -18
View File
@@ -4,10 +4,7 @@
// the travelled part.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
cockpitProgressLayout,
estimateProgressLabelPx,
} from './cockpitProgress.js';
import { cockpitProgressLayout } from './cockpitProgress.js';
const tick = (at, label = null, tone = 'normal') => ({ at, tone, label });
const label = (text, priority, align = 'center', detail = '') => ({
@@ -145,17 +142,3 @@ test('a long run of calls still lays out, every one a tick or part of one', () =
assert.ok(narrow.ticks.length < wide.ticks.length);
assert.equal(wide.ticks.length, 60);
});
test('a CJK stop name gets the width its full-width glyphs need', () => {
const text = '中央駅前広場東口'; // 8 full-width glyphs
// 10 px type, 0.06 em apart.
const needPx = text.length * (10 + 0.6);
const givenPx = estimateProgressLabelPx({ text, detail: '' });
assert.ok(
givenPx >= needPx,
`${givenPx} px given, about ${needPx} px needed`,
);
// Latin, and half-width katakana, keep the narrower estimate.
assert.equal(estimateProgressLabelPx({ text: 'CENTRAL' }), 7 * 6.4 + 8);
assert.equal(estimateProgressLabelPx({ text: 'カタカナ' }), 4 * 6.4 + 8);
});
+17 -26
View File
@@ -146,12 +146,8 @@ function providerName(provider, order) {
return `#${order}`;
}
/**
* Why `provider` cannot be kept, or null. Its worded members, read once here,
* go into `words` (`face`, `labels`, `look`) to seed its copy, so one that
* fails when read again cannot undo this check.
*/
function refusal(provider, kinds, words) {
/** Why `provider` cannot be kept, or null. */
function refusal(provider, kinds) {
if (!isObject(provider)) return 'not an object';
if (typeof provider.kind !== 'string' || !KIND_PATTERN.test(provider.kind))
return 'malformed kind';
@@ -169,14 +165,11 @@ function refusal(provider, kinds, words) {
typeof provider.isEntryAllowed !== 'function'
)
return 'isEntryAllowed is not a function';
words.face = wordedNow(provider, 'entryFace', faceOf);
if (!words.face) return 'malformed entry face';
words.labels = wordedNow(provider, 'labels', labelsOf);
if (!words.labels) return 'labels need view, exit and exitText';
if (provider.look != null) {
words.look = wordedNow(provider, 'look', lookOf);
if (!words.look) return 'look needs an aheadLabel';
}
if (!wordedNow(provider, 'entryFace', faceOf)) return 'malformed entry face';
if (!wordedNow(provider, 'labels', labelsOf))
return 'labels need view, exit and exitText';
if (provider.look != null && !wordedNow(provider, 'look', lookOf))
return 'look needs an aheadLabel';
return null;
}
@@ -229,10 +222,9 @@ export function cockpitSubjectProviders(
(Array.isArray(list) ? list : []).forEach((provider, order) => {
let reason;
let copy = null;
const words = { face: null, labels: null, look: null };
try {
reason = refusal(provider, kinds, words);
if (!reason) copy = keptProvider(provider, order, words);
reason = refusal(provider, kinds);
if (!reason) copy = keptProvider(provider, order);
} catch {
reason = 'a member threw when read';
}
@@ -249,15 +241,14 @@ export function cockpitSubjectProviders(
return Object.freeze(kept);
}
/**
* The frozen copy the Cockpit keeps of a provider `refusal` passed, seeded
* with the worded members it checked.
*/
function keptProvider(provider, order, words) {
/** The frozen copy the Cockpit keeps of a provider `refusal` passed. */
function keptProvider(provider, order) {
// Worded members are read again on each use (see above); the last good
// read stands in for one that is malformed or throws.
let { face, labels, look } = words;
let face = wordedNow(provider, 'entryFace', faceOf);
let labels = wordedNow(provider, 'labels', labelsOf);
// On or off, and its rest pitch, as first read.
let look = wordedNow(provider, 'look', lookOf);
const restPitchDeg = look?.restPitchDeg ?? 0;
return Object.freeze({
kind: provider.kind,
@@ -346,9 +337,9 @@ function candidateOf(raw) {
* A `heightM` that is not finite or lies outside
* COCKPIT_SUBJECT_MIN_HEIGHT_M..COCKPIT_SUBJECT_MAX_HEIGHT_M reads as null:
* the eye then stands on the shared floor, or where it last stood while that
* is cold. The anchor is `'inertial'` by default for a frame with a valid
* speed, and `'exact'` when asked for or with no speed. An id is compared
* with `heldId` trimmed, as `cockpitSubjectCandidate` trims it.
* is cold. The anchor is `'inertial'` only when asked for and the frame
* gives a speed; otherwise it is `'exact'`. An id is compared with `heldId`
* trimmed, as `cockpitSubjectCandidate` trims it.
* @param {unknown} raw What `read()` returned.
* @param {string} heldId The subject the view holds.
* @returns {object|null} `{id, name, latitude, longitude, heightM, headingDeg,
+4 -1
View File
@@ -205,7 +205,10 @@ export function createRailCockpitSubject({
finiteOrNull(drawn?.lat) ?? finiteOrNull(sample?.lat) ?? record.lat;
position.longitude =
finiteOrNull(drawn?.lon) ?? finiteOrNull(sample?.lon) ?? record.lon;
position.railHeightM = Number.isFinite(drawn?.h) ? drawn.h - liftM : null;
// Quality 0 is the ellipsoid a train is drawn on while no floor is
// known: no height, so a view waits for the surface.
position.railHeightM =
Number.isFinite(drawn?.h) && drawn.q > 0 ? drawn.h - liftM : null;
position.heightQuality = Number.isFinite(drawn?.q) ? drawn.q : 0;
position.atMs = finiteOrNull(drawn?.at);
+23 -1
View File
@@ -44,6 +44,13 @@ const PACK = Object.freeze({
routes: { R1: [0] },
});
/** A floor service that knows the ground everywhere, at 12 m. */
const WARM_GROUND = Object.freeze({
GROUND_FLOOR_LIFT_M: 1.5,
cachedGroundFloor: () => 12,
warmGroundFloor() {},
});
/** Two trains on the line, T1 running east and T2 west, a step a poll. */
async function onTheLine(t, options = {}) {
const app = harness(t, {
@@ -76,7 +83,7 @@ const T1 = railTrainKey('mbta-rail', 'T1');
const T2 = railTrainKey('mbta-rail', 'T2');
test('the selected train reads as a snapshot of its place, motion and sources', async (t) => {
const app = await onTheLine(t);
const app = await onTheLine(t, { ground: WARM_GROUND });
assert.equal(app.layer.getSelectedTrain(), null, 'nothing selected');
app.parts().selection.selectTrain(T1);
const view = app.layer.getSelectedTrain();
@@ -105,6 +112,7 @@ test('the selected train reads as a snapshot of its place, motion and sources',
assert.equal(view.provenance.positionSource, 'gps');
assert.equal(view.provenance.timestampSource, 'vehicle');
const drawn = app.entry(T1).drawnHeight;
assert.ok(view.position.heightQuality > 0, 'on a known floor');
assert.equal(view.position.railHeightM, drawn.h - 1.5);
assert.ok(Number.isFinite(view.position.latitude));
assert.ok(Array.isArray(view.stops));
@@ -129,6 +137,20 @@ const stopList = (...names) =>
state: 'upcoming',
}));
test('a train drawn on an unknown floor reports no rail height', async (t) => {
// The harness's floor service is always cold: the train is drawn on the
// ellipsoid, which is no floor for a view to stand on.
const app = await onTheLine(t);
app.parts().selection.selectTrain(T1);
const view = app.layer.getSelectedTrain();
assert.equal(view.position.heightQuality, 0, 'no floor is known');
assert.equal(
view.position.railHeightM,
null,
'an unknown floor is no height',
);
});
test('a snapshot read again while nothing changed is the one read before', async (t) => {
let list = stopList('Alpha', 'Bravo', 'Charlie');
const app = await onTheLine(t, {
+15 -13
View File
@@ -47,8 +47,13 @@ export function pathWindowM(dtMs) {
return window > PATH_WINDOW_MAX_M ? NaN : window;
}
/** Arc moved between two reports before it says which way a train runs (m). */
const DIRECTION_MIN_M = 1;
/**
* Arc moved between two reports before it says which way a train runs (m).
* A standing train's GPS jitter, a few metres back and forth, stays under it
* (the same parked-train jitter as FOLLOW_MIN_MOVE_M, policy.js) and keeps
* the direction learnt.
*/
const DIRECTION_MIN_M = 15;
/** +1 or -1 for an arc step longer than DIRECTION_MIN_M, else `known`. */
function directionOf(step, known) {
@@ -65,13 +70,13 @@ function createBinding(shapeIndex, path, via, s, fix) {
/**
* Which way the drawn train runs along the shape: +1 along it, -1
* against it, 0 until two reports or a playback segment tell. Kept until
* a rebind. Once playback has placed the train, only playback changes
* it: the newest reports run ahead of the drawn train, so a reversal
* they show turns it when playback reaches it.
* a rebind, and while the train stands. Once a playback segment has told
* it (`directionPlayed`), only playback changes it: the newest reports
* run ahead of the drawn train, so a reversal they show turns it when
* playback reaches it.
*/
direction: 0,
/** The direction the last placed playback segment ran, 0 before one. */
drawDirection: 0,
directionPlayed: false,
/** Arc and time of the newest report. */
fixS: s,
fixT: fix.t,
@@ -159,7 +164,7 @@ export function followFix(binding, fix) {
pathWindowM(fix.t - binding.fixT),
);
if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false;
if (!binding.drawDirection)
if (!binding.directionPlayed)
binding.direction = directionOf(hit.s - binding.fixS, binding.direction);
binding.fixS = hit.s;
binding.fixT = fix.t;
@@ -253,11 +258,8 @@ export function placeOnPath(binding, sample, segment, out) {
cache.sTo = sTo;
cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo);
if (cache.ok) {
binding.drawDirection = directionOf(
sTo - sFrom,
binding.drawDirection || binding.direction || 0,
);
binding.direction = binding.drawDirection;
binding.direction = directionOf(sTo - sFrom, binding.direction);
if (binding.direction) binding.directionPlayed = true;
}
}
if (!cache.ok) return false;
+63 -2
View File
@@ -209,8 +209,9 @@ test('a binding learns which way its train runs, and keeps it through a stop', (
assert.equal(along.direction, 0, 'one report tells no direction');
assert.ok(followFix(along, fix(10_000, 700, 0)));
assert.equal(along.direction, 1);
// Standing still (under a metre) keeps what it learnt.
assert.ok(followFix(along, fix(20_000, 700.4, 0)));
// Standing at a stop, its reports jitter back a few metres: it keeps what
// it learnt.
assert.ok(followFix(along, fix(20_000, 690, 0)));
assert.equal(along.direction, 1);
const against = bindTrainPath(p, ids, fix(0, 1500, 0));
assert.ok(followFix(against, fix(10_000, 1200, 0)));
@@ -262,3 +263,63 @@ test('a report that runs back turns the drawn train only when playback does', ()
);
assert.equal(binding.direction, -1);
});
test('jitter segments played back at a standing train keep the direction it learnt', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const binding = bindTrainPath(p, ids, fix(0, 1000, 0));
assert.ok(followFix(binding, fix(15_000, 1600, 0)));
// Playback runs the train east, 1000 m -> 1600 m: direction +1.
const out = {};
let seq = 0;
const play = (fromM, toM, t0) => {
const segment = {
from: { seq, ...fix(t0, fromM, 0) },
to: { seq: seq + 1, ...fix(t0 + 15_000, toM, 0) },
};
assert.ok(
placeOnPath(
binding,
{ fromSeq: seq, toSeq: seq + 1, fraction: 0.5 },
segment,
out,
),
);
seq += 1;
return binding.direction;
};
assert.equal(play(1000, 1600, 0), 1);
assert.equal(
binding.directionPlayed,
true,
'playback owns the direction now',
);
// At the platform: reports 3-5 m apart, back and forth, polled and played.
const learnt = [];
let t0 = 15_000;
for (const [fromM, toM] of [
[1600, 1597],
[1597, 1600],
[1600, 1596],
[1596, 1601],
]) {
assert.ok(followFix(binding, fix(t0 + 15_000, toM, 0)));
learnt.push(play(fromM, toM, t0));
t0 += 15_000;
}
assert.deepEqual(learnt, [1, 1, 1, 1], 'from the played-back segments');
});
test('GPS jitter in the newest reports before playback keeps the direction', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const binding = bindTrainPath(p, ids, fix(0, 1000, 0));
assert.ok(followFix(binding, fix(15_000, 1600, 0)));
assert.equal(binding.direction, 1);
const learnt = [];
[1597, 1600, 1596, 1601].forEach((eastM, i) => {
assert.ok(followFix(binding, fix(30_000 + i * 15_000, eastM, 0)));
learnt.push(binding.direction);
});
assert.deepEqual(learnt, [1, 1, 1, 1], 'from the newest reports');
});
+14 -7
View File
@@ -84,12 +84,16 @@ export function createTransitCockpitSubject({ state, parts, services }) {
* or held), which near the ground follows the terrain between reports;
* else its segment's two reports' floors at the playback fraction. Null
* while either floor is unknown, as on cold terrain, so a view waits for
* the surface. Not `entry.heightM`, the floor at the newest report, which
* playback has not reached yet.
* the surface: far above the ground such a marker is drawn on the
* ellipsoid, which is no floor. Not `entry.heightM`, the floor at the
* newest report, which playback has not reached yet.
*/
function drawnFloorOf(entry) {
const segment = entry.segment;
if (!segment || entry.heightPending) return null;
const from = segment.from?.h;
const to = segment.to?.h;
if (!Number.isFinite(from) || !Number.isFinite(to)) return null;
const placed =
entry.surfaceReady === true &&
entry.hasRendered &&
@@ -99,9 +103,6 @@ export function createTransitCockpitSubject({ state, parts, services }) {
const drawn = toCartographicRadians(entry.marker.position);
if (drawn) return drawn.height - liftM;
}
const from = segment.from?.h;
const to = segment.to?.h;
if (!Number.isFinite(from) || !Number.isFinite(to)) return null;
const f = Number.isFinite(segment.fraction)
? Math.max(0, Math.min(1, segment.fraction))
: 1;
@@ -173,11 +174,17 @@ export function createTransitCockpitSubject({ state, parts, services }) {
return snapshot;
}
/** Show or hide a vehicle's sprite and trail for the hold. */
/**
* Show or hide a vehicle's sprite and trail for the hold. The sprite goes
* through the renderer (setShown, flushMarkers): its set draws a marker
* only as last pushed.
*/
function repaint(entry) {
if (!entry?.marker) return;
if (entry.key === state._cockpitSubjectKey) entry.marker.show = false;
if (entry.key === state._cockpitSubjectKey)
parts.rendering.setShown(entry, false);
else parts.rendering.placeSample(entry);
parts.rendering.flushMarkers();
parts.rendering.schedulePlayback(entry);
parts.trails.update();
state._detectRevision += 1;
+2
View File
@@ -165,6 +165,8 @@ export function createLifecycle({ state, services, parts }) {
state._visible.clear();
clearTimeout(state._cameraDebounceTimer);
state._cameraDebounceTimer = null;
// A hold ends with the layer (cockpitSubject.js).
state._cockpitSubjectKey = null;
parts.selection.clearSelection();
state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false);
parts.selection.removeClickHandler();
+106
View File
@@ -978,6 +978,34 @@ test('a held vehicle with no floor yet tells its view no height', async (t) => {
assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null);
});
test('far above the ground, a held vehicle drawn on the ellipsoid tells its view no height', async (t) => {
// Above the height gate a vehicle with no floor is drawn on the ellipsoid
// at once, not held back; the ellipsoid is still no floor to stand a view
// on.
const app = harness(t, { altitude: 100_000, floorAt: () => undefined });
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
const [entry] = app.vehicles();
assert.ok(app.layer.setCockpitSubject(entry.key) !== false);
app.frame();
assert.equal(entry.surfaceReady, true, 'it is drawn');
const drawnM = Cesium.Cartographic.fromCartesian(
entry.marker.position,
).height;
assert.ok(Math.abs(drawnM) < 1e-3, `on the ellipsoid, got ${drawnM} m`);
assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null);
});
test('a vehicle waits for its floor rather than standing on the ellipsoid', async (t) => {
// The shared ground-floor system answers from the rendered mesh cell or the
// real DEM cell; until one of them is warm there is no honest height to draw
@@ -2125,6 +2153,11 @@ test('a segment climbs from the ground it left to the ground it reaches', async
Math.abs(height() - 11.5) < 3,
`at the corridor floor, got ${height().toFixed(1)} m`,
);
// The two reports' floors blended at the fraction would say about 55 m.
assert.ok(
Math.abs(floor() + 1.5 - height()) < 1,
`its snapshot stands on that floor too, got ${floor().toFixed(1)} m`,
);
app.run(TRANSIT_POLL_MS);
assert.ok(
Math.abs(height() - 101.5) < 1.5,
@@ -4880,3 +4913,76 @@ test('a held vehicle hides, keeps moving out of view, and lets go when it goes',
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
test('turning Transit off ends a hold; on again, Escape deselects and the vehicle shows', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
assert.equal(app.layer.setCockpitSubject(key), true);
app.layer.disable(app.viewer);
assert.equal(
app.state()._cockpitSubjectKey,
null,
'the hold ended with the layer',
);
// On again, without a release: the same bus is listed again.
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
assert.equal(app.layer.focusVehicle(key), true);
const [entry] = app.vehicles();
app.frame();
assert.equal(entry.marker.show, true, 'the vehicle is drawn, not held');
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, null, 'Escape deselects');
});
test('a held parked vehicle draws no icon; let go, it draws its icon again', async (t) => {
// A parked bus with no course: nothing moves or turns its icon, so only the
// hold itself can take the icon out of the set that draws it.
const app = harness(t);
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[vehicle('bus-1', 42.36, -71.06, reported(), { stopId: 'place-1' })],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
for (let i = 0; i < 3; i += 1) {
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
}
const key = 'mbta:bus-1';
const [entry] = app.vehicles();
const icon = () =>
app.markers('still').get(key) ?? app.markers('moving').get(key);
assert.equal(icon()?.show, true, 'drawn before the hold');
assert.equal(app.layer.setCockpitSubject(key), true);
// The view rides it for a while: frames, a sweep, a poll.
app.run(2_000, 16);
app.settle();
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
assert.equal(entry.marker.show, false, 'its marker is hidden');
assert.equal(
icon()?.show ?? false,
false,
'and so is the icon the set draws',
);
assert.equal(app.layer.setCockpitSubject(null), true);
app.advance(250);
app.settle();
assert.equal(icon()?.show, true, 'let go: drawn again');
});
+1
View File
@@ -1225,6 +1225,7 @@ export function createRendering({ state, services, parts }) {
setNameOf,
markerShown,
markDirty,
setShown,
flushMarkers,
removeMarker,
watchCamera,
+2 -2
View File
@@ -336,7 +336,7 @@ function updateVessel(nowMs) {
* gives none) and slew toward its heading. A frame that is null, malformed or
* for another subject ends the view, as an aircraft tracked meanwhile does.
* The update runs on the provider's `cameraIntervalMs` (0: every frame), and
* its rates advance by the time since the last update (cockpitSubjectStepSec).
* its rates advance by the time that interval spans (cockpitSubjectStepSec).
*/
function updateSubject(nowMs) {
const provider = this.subjectProvider;
@@ -366,7 +366,7 @@ function updateSubject(nowMs) {
frame.longitude,
);
// A frame with no height stands on the shared floor; while that is cold
// it keeps the last height it had, the entry frame's included.
// it keeps the height it last stood at.
heightM = Number.isFinite(floorM) ? floorM : this.subjectHeightM;
}
if (!Number.isFinite(heightM)) {
+2 -10
View File
@@ -735,16 +735,8 @@ export class CockpitViewController {
publishCockpitSignals() {
return publishCockpitSignals.call(this);
}
pushCockpitSignal(key, tone, title, detail, target, options) {
return pushCockpitSignal.call(
this,
key,
tone,
title,
detail,
target,
options,
);
pushCockpitSignal(key, tone, title, detail, target) {
return pushCockpitSignal.call(this, key, tone, title, detail, target);
}
dropCockpitSignal(key) {
return dropCockpitSignal.call(this, key);
-4
View File
@@ -257,8 +257,6 @@ function updateSubjectHud(info, nowMs, forceContext) {
this.maybeRefreshRegionalBrief(info);
this.showContextCard(false);
const keys = new Set();
// The view's rows are its current signals: each changes where it stands,
// so a changing one (an ETA) never pushes a steady one off the list.
for (const signal of hud.signals) {
const key = `subject:${signal.id}`;
keys.add(key);
@@ -267,8 +265,6 @@ function updateSubjectHud(info, nowMs, forceContext) {
SUBJECT_SIGNAL_TONES[signal.tone] ?? 'info',
signal.title,
signal.detail || signal.title,
null,
{ inPlace: true },
);
}
for (const key of this.subjectSignalKeys ?? [])
+7 -22
View File
@@ -39,32 +39,17 @@ export function publishCockpitSignals() {
this.scheduleContextLayout();
}
/**
* Log a signal as the newest row, unless its key last said the same.
* @param {{inPlace?: boolean}} [options] `inPlace`: a status row, such as a
* provider's, that changes where it stands rather than log a new row, and
* comes back if newer rows pushed it off the list.
*/
export function pushCockpitSignal(
key,
tone,
title,
detail,
target = null,
{ inPlace = false } = {},
) {
export function pushCockpitSignal(key, tone, title, detail, target = null) {
if (!title || !detail) return;
const signature = `${title}|${detail}|${target?.layerId || ''}|${target?.id || ''}`;
// A locale change words the signal again where it stands.
const shown =
this.rewordingSignals || inPlace
? this.signalItems.find((item) => item.key === key)
: null;
if (this.signalSignatures.get(key) === signature && (!inPlace || shown))
return;
if (this.signalSignatures.get(key) === signature) return;
this.signalSignatures.set(key, signature);
// A locale change words the signal again where it stands.
const shown = this.rewordingSignals
? this.signalItems.find((item) => item.key === key)
: null;
if (shown) {
Object.assign(shown, { tone, title, detail });
Object.assign(shown, { title, detail });
this.publishCockpitSignals();
return;
}
+8 -193
View File
@@ -585,44 +585,7 @@ test('a subject updated every 500 ms turns, eases and closes on its target at it
// A long stall (a hidden tab) moves it as one late update would.
clock.advance(60_000);
cockpit.update();
assert.ok(Math.abs(cockpit.heading - 110) < 1e-6, 'at most 1.5 s');
});
test('an inertial subject drawn at 5 frames a second stays near its target', async (t) => {
const clock = manualClock(t, 10_000);
const ride = subjectProvider();
const SPEED_MPS = 30;
const startMs = 10_000;
const eastOf = (ms) =>
LON +
(SPEED_MPS * (ms - startMs)) /
1000 /
(111_320 * Math.cos((LAT * Math.PI) / 180));
let nowMs = startMs;
ride.subject.frame = () => ({
...subjectProvider().subject.frame,
longitude: eastOf(nowMs),
speedMps: SPEED_MPS,
anchor: 'inertial',
});
const { cockpit, shots } = fixture(t, { providers: [ride] });
cockpit.syncEntry();
assert.equal(cockpit.enter(), true);
for (let i = 0; i < 300; i += 1) {
clock.advance(200);
nowMs += 200;
cockpit.update();
}
const target = Cesium.Cartesian3.fromDegrees(
eastOf(nowMs),
LAT,
FLOOR_M + 3.5,
);
const gapM = Cesium.Cartesian3.distance(shots.at(-1).destination, target);
assert.ok(
gapM < 50,
`after 60 s the camera is ${gapM.toFixed(0)} m from the subject`,
);
assert.ok(Math.abs(cockpit.heading - 101) < 1e-6, 'at most 0.6 s');
});
test('an exact anchor sits on the subject, wherever the frame moves it', async (t) => {
@@ -900,32 +863,6 @@ test('a floor that never comes ends the view after the bounded wait, releasing t
assert.deepEqual(lastRelease(ride.calls), ['release', 'a1', false]);
});
test('a height the entry frame gave holds while later frames give none and the floor is cold', async (t) => {
const clock = manualClock(t, 10_000);
const ride = subjectProvider();
const { cockpit, shots, setFloor } = fixture(t, { providers: [ride] });
setFloor(undefined);
cockpit.syncEntry();
// The entry frame stands at FLOOR_M (heightM 400).
assert.equal(cockpit.enter(), true);
ride.subject.frame = { ...ride.subject.frame, heightM: null };
for (
let elapsed = 0;
elapsed < COCKPIT_GROUND_WAIT_TIMEOUT_MS + 1000;
elapsed += 100
) {
clock.advance(100);
cockpit.update();
}
assert.equal(
cockpit.active,
true,
'the view keeps the height its entry frame gave',
);
assert.ok(shots.length > 0, 'the camera is placed');
assert.ok(Math.abs(shotHeight(shots) - (FLOOR_M + 3.5)) < 0.01);
});
test('an asynchronous hold that lands after entry was refused is released again', async (t) => {
let heldId = null;
const releases = [];
@@ -1005,41 +942,6 @@ test('a provider’s labels, entry face and look follow a change of language', a
);
});
/** Labels that read well once, when the provider is checked, then throw. */
const GOOD_LABELS = Object.freeze({
view: 'Ride view',
exit: 'Exit ride view',
exitText: 'EXIT RIDE',
kicker: 'RIDE',
});
const labelsOnce = () => {
let reads = 0;
return function labels() {
reads += 1;
if (reads > 1) throw new Error('word bundle unloaded');
return GOOD_LABELS;
};
};
test('labels that start throwing after the first read keep the first good words', () => {
const warned = [];
const [kept] = cockpitSubjectProviders(
[{ ...subjectProvider().definition, labels: labelsOnce() }],
{ warn: (message) => warned.push(message) },
);
assert.ok(kept, 'the provider is kept');
assert.deepEqual({ ...kept.labels }, GOOD_LABELS);
});
test('entering such a provider with no HUD kicker does not throw', async (t) => {
manualClock(t, 10_000);
const ride = subjectProvider({ labels: labelsOnce() });
ride.subject.hud = { title: 'Example 12' };
const { cockpit } = fixture(t, { providers: [ride] });
cockpit.syncEntry();
assert.doesNotThrow(() => cockpit.enter());
});
test('a read that throws ends the view once; a hud that throws keeps the last', async (t) => {
const clock = manualClock(t, 10_000);
const ride = subjectProvider();
@@ -1220,57 +1122,26 @@ test('a subject first seen together with a built-in one comes after it', async (
assert.equal(store.presence.entryKind, 'vessel');
});
/**
* Every world position projects to (x, y): the scene query port projects
* through Cesium.SceneTransforms.
*/
function everythingAt(t, x, y) {
t.mock.method(
Cesium.SceneTransforms,
'worldToWindowCoordinates',
(_scene, _position, result = new Cesium.Cartesian2()) =>
Object.assign(result, { x, y }),
);
}
test("a double-click on the selected vessel does not enter an application's subject", async (t) => {
const clock = manualClock(t, 10_000);
const ride = subjectProvider();
ride.subject.candidate = null;
const { cockpit, store } = fixture(t, {
const { cockpit, store, viewer } = fixture(t, {
providers: [ride],
vessel: VESSEL,
});
everythingAt(t, 100, 100);
cockpit.syncEntry();
assert.equal(store.presence.entryKind, 'vessel');
// The application's subject is selected after the vessel: it takes entry.
clock.advance(500);
ride.subject.candidate = { id: 'a1', name: 'Example 12', selectedAt: 1 };
cockpit.syncEntry();
assert.equal(store.presence.entryKind, 'example-kind');
// The user double-clicks the vessel, still selected.
assert.equal(cockpit.onSceneDoubleClick({ x: 100, y: 100 }), false);
assert.equal(cockpit.resolveEntryKind(), 'example-kind');
// Every world position lands under the pointer, the vessel's sprite too.
viewer.scene.cartesianToCanvasCoordinates = (_position, result = {}) =>
Object.assign(result, { x: 400, y: 300 });
assert.equal(cockpit.onSceneDoubleClick({ x: 400, y: 300 }), false);
await settle();
assert.equal(
cockpit.subjectProvider ?? null,
null,
'no provider view entered from a double-click on the vessel',
);
assert.equal(
ride.calls.some(([name]) => name === 'hold'),
false,
'the provider subject was not held',
);
});
test('the same double-click on the vessel alone enters its bridge', async (t) => {
manualClock(t, 10_000);
const { cockpit, store } = fixture(t, { vessel: VESSEL });
everythingAt(t, 100, 100);
cockpit.syncEntry();
assert.equal(store.presence.entryKind, 'vessel');
assert.equal(cockpit.onSceneDoubleClick({ x: 100, y: 100 }), true);
assert.notEqual(store.presence.active, true);
});
test('a provider view with look turns with the arrow keys and words its readout', async (t) => {
@@ -1317,59 +1188,3 @@ test('rows a HUD view no longer lists leave Live Signals', async (t) => {
cockpit.update();
assert.ok(dropped.includes('subject:note'));
});
test('a signal still listed stays in Live Signals while another one changes', async (t) => {
const clock = manualClock(t, 10_000);
const ride = subjectProvider();
const { cockpit } = fixture(t, { providers: [ride] });
// The real Live Signals rows, not the fixture's recorder.
delete cockpit.pushCockpitSignal;
delete cockpit.dropCockpitSignal;
const hudWith = (minutes) => ({
...HUD,
signals: [
{
id: 'doors',
tone: 'warning',
title: 'DOORS',
detail: 'door fault, car 2',
},
{ id: 'eta', title: 'NEXT', detail: `Central in ${minutes} min` },
],
});
ride.subject.hud = hudWith(10);
cockpit.syncEntry();
assert.equal(cockpit.enter(), true);
for (let minutes = 9; minutes >= 2; minutes -= 1) {
ride.subject.hud = hudWith(minutes);
clock.advance(1000);
cockpit.update();
}
const keys = cockpit.signalItems.map((row) => row.key);
assert.ok(
keys.includes('subject:doors'),
`the warning the HUD still lists is shown (rows: ${keys.join(', ')})`,
);
// The changing one is one row, worded as it reads now.
const etas = cockpit.signalItems.filter((row) => row.key === 'subject:eta');
assert.deepEqual(
etas.map((row) => row.detail),
['Central in 2 min'],
);
// Rows pushed off the list by newer ones come back while still listed.
for (let i = 0; i < 5; i += 1)
cockpit.pushCockpitSignal(`other-${i}`, 'info', 'OTHER', `row ${i}`);
assert.equal(
cockpit.signalItems.some((row) => row.key.startsWith('subject:')),
false,
);
clock.advance(1000);
cockpit.update();
assert.deepEqual(
cockpit.signalItems
.map((row) => row.key)
.filter((key) => key.startsWith('subject:'))
.sort(),
['subject:doors', 'subject:eta'],
);
});
+1 -3
View File
@@ -516,9 +516,7 @@ function enterSubject(provider) {
this.surfaceAcquiring = false;
this.surfaceFallback = false;
this.cockpitAnchorValid = false;
// A height the entry frame gave is where the eye stands until a later frame
// or the warmed floor gives another.
this.subjectHeightM = frame.heightM;
this.subjectHeightM = null;
this.lookRestPitchDeg = provider.look?.restPitchDeg ?? null;
this.resetLook({ immediate: true });
this.active = true;