diff --git a/changelog.d/1786-cockpit-ride-transit-rail.md b/changelog.d/1786-cockpit-ride-transit-rail.md new file mode 100644 index 0000000000..995e0b491e --- /dev/null +++ b/changelog.d/1786-cockpit-ride-transit-rail.md @@ -0,0 +1,5 @@ +- Fix application Cockpit rides on Rail trains and Transit vehicles: a held + parked vehicle no longer leaves its icon under the view, turning Transit off + ends a hold, a view waits for the ground instead of standing on the + ellipsoid, and GPS jitter at a platform no longer turns a ride around + (German, @gekh, #1786). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 879c2135fb..a712026747 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2810,10 +2810,11 @@ 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 -`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), +which way it runs (`pathBinding.js` learns it), its rail height (null while +no floor is known), 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 feed held, clicks and Escape left to the view; the held copy stays the one drawn of its train while held, another feed's copy hidden, and it keeps @@ -2826,14 +2827,23 @@ 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`, -`src/cockpitSubjectProviders.test.mjs`, `src/cockpitProgress.test.mjs`, -`src/layers/rail/cockpitSubject.test.mjs` and the Transit lifecycle tests -cover them. +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 either of +those two floors is unknown. Rail's `path.direction` is the way the drawn +train runs: once playback has told its direction, a report that runs back +turns it only when playback starts the segment to that report. A train turns +once it is more than a standing train's GPS jitter back from the last place a +longer move took it, however slowly it backs, so jitter on either side of +where it stands keeps its direction, and so does playback's jump to a +corrected position (a break, or a new clock epoch). While movement gives no +direction, the snapshot uses the operator's last reported bearing. +`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`, +`src/layers/rail/pathBinding.test.mjs` and the Transit lifecycle tests cover +them. ## Context coordination diff --git a/src/layers/rail/cockpitSubject.js b/src/layers/rail/cockpitSubject.js index 80cfc1daa6..2a66d4f28c 100644 --- a/src/layers/rail/cockpitSubject.js +++ b/src/layers/rail/cockpitSubject.js @@ -173,14 +173,15 @@ export function createRailCockpitSubject({ /** * Which way the train runs along its shape: as its binding learnt it from - * successive reports, else from its drawn course against the line's - * bearing there; 0 while neither tells. + * successive reports, else from its operator's last reported bearing + * against the line's bearing there; 0 while neither tells. Not the drawn + * course: before the binding tells, that course is GPS jitter. */ function directionOf(entry) { const binding = entry.path; if (binding.direction === 1 || binding.direction === -1) return binding.direction; - const course = finiteOrNull(entry.courseDeg); + const course = finiteOrNull(binding.bearingDeg); const point = pointAtS(binding.path, binding.drawS, scratch); if (course === null || !Number.isFinite(point?.bearingDeg)) return 0; const turn = Math.abs(((course - point.bearingDeg + 540) % 360) - 180); @@ -205,8 +206,12 @@ 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; - position.heightQuality = Number.isFinite(drawn?.q) ? drawn.q : 0; + const quality = Number.isFinite(drawn?.q) ? drawn.q : 0; + // Quality 0: no floor known here, so no height; a view waits for the + // surface. + position.railHeightM = + quality > 0 && Number.isFinite(drawn.h) ? drawn.h - liftM : null; + position.heightQuality = quality; position.atMs = finiteOrNull(drawn?.at); let path = null; diff --git a/src/layers/rail/cockpitSubject.test.mjs b/src/layers/rail/cockpitSubject.test.mjs index b439e1eecc..44043f7012 100644 --- a/src/layers/rail/cockpitSubject.test.mjs +++ b/src/layers/rail/cockpitSubject.test.mjs @@ -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,71 @@ 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 train on a known floor at sea level reports a rail height of 0 m', async (t) => { + const app = await onTheLine(t, { + ground: { ...WARM_GROUND, cachedGroundFloor: () => 0 }, + }); + app.parts().selection.selectTrain(T1); + const { position } = app.layer.getSelectedTrain(); + assert.ok(position.heightQuality > 0, 'the floor is known'); + assert.equal(position.railHeightM, 0, 'a height, not none'); +}); + +test('a train first seen standing takes no direction from its GPS jitter', async (t) => { + // Reports 13 m apart, and the course drawn between them, do not tell which + // way it runs; an operator's bearing does. + const app = harness(t, { paths: { 'mbta-rail': PACK }, at: BOSTON }); + let jitterM = 0; + app.feeds.set('mbta-rail', () => [ + train('T1', LAT, LON0 + (1000 + jitterM) / KX), + train('T2', LAT, LON0 + (3000 + jitterM) / KX, { bearing: 270 }), + ]); + await app.enable(); + const seen = []; + for (const next of [13, 0, 13, 0, 13, 0]) { + jitterM = next; + app.run(RAIL_POLL_MS); + await app.poll(); + app.parts().selection.selectTrain(T1); + const standing = app.layer.getSelectedTrain().path.direction; + app.parts().selection.selectTrain(T2); + seen.push([standing, app.layer.getSelectedTrain().path.direction]); + } + assert.deepEqual(seen, Array(6).fill([0, -1])); +}); + +test('a standing train keeps its operator’s bearing through reports that leave it out', async (t) => { + const app = harness(t, { paths: { 'mbta-rail': PACK }, at: BOSTON }); + let bearing = 270; + app.feeds.set('mbta-rail', () => [ + train('T1', LAT, LON0 + 1000 / KX, { bearing }), + ]); + await app.enable(); + const seen = []; + for (const next of [270, 270, 270, null, null, null]) { + bearing = next; + app.run(RAIL_POLL_MS); + await app.poll(); + app.parts().selection.selectTrain(T1); + seen.push(app.layer.getSelectedTrain().path.direction); + } + assert.deepEqual(seen, Array(6).fill(-1)); +}); + 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, { diff --git a/src/layers/rail/pathBinding.js b/src/layers/rail/pathBinding.js index 9eba452d37..a07cf1b20f 100644 --- a/src/layers/rail/pathBinding.js +++ b/src/layers/rail/pathBinding.js @@ -1,3 +1,4 @@ +import { FIX_FLAGS } from '../../data/contactPlayback.js'; import { pointAtS, projectOnPath } from '../../data/railPaths.js'; /** @@ -47,14 +48,23 @@ 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 a train must move before it tells which way it runs (m); a standing + * train's GPS jitter stays within it. + */ +export const DIRECTION_MIN_M = 15; -/** +1 or -1 for an arc step longer than DIRECTION_MIN_M, else `known`. */ -function directionOf(step, known) { - return Number.isFinite(step) && Math.abs(step) > DIRECTION_MIN_M - ? Math.sign(step) - : known; +/** + * The direction after one more arc position `s`: once `s` is DIRECTION_MIN_M + * or more from `turn.s`, the sign of that move, and `turn.s` moves to `s`. + */ +function steer(direction, turn, s) { + if (!Number.isFinite(s)) return direction; + if (!Number.isFinite(turn.s)) turn.s = s; + const step = s - turn.s; + if (Math.abs(step) < DIRECTION_MIN_M) return direction; + turn.s = s; + return Math.sign(step); } function createBinding(shapeIndex, path, via, s, fix) { @@ -64,14 +74,19 @@ function createBinding(shapeIndex, path, via, s, fix) { via, /** * 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. + * against it, 0 until it has moved DIRECTION_MIN_M (steer). Kept until + * 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, + /** steer() turn points: one for the reports, one for the played segments. */ + reportTurn: { s }, + playTurn: { s: NaN, epoch: NaN }, + /** The newest operator bearing its reports gave (deg), NaN before one. */ + bearingDeg: Number.isFinite(fix.bearingDeg) ? fix.bearingDeg : NaN, /** Arc and time of the newest report. */ fixS: s, fixT: fix.t, @@ -124,7 +139,7 @@ function bestRouteShape(pack, routeId, fix, accept) { * * @param {object} pack From createRailPathPack. * @param {{tripId?: string, routeId?: string}} ids - * @param {{t: number, lat: number, lon: number}} fix The newest report. + * @param {{t: number, lat: number, lon: number, bearingDeg?: number}} fix The newest report. * @returns {object|null} A binding, or null to keep straight-line motion. */ export function bindTrainPath(pack, { tripId, routeId } = {}, fix) { @@ -146,7 +161,7 @@ export function bindTrainPath(pack, { tripId, routeId } = {}, fix) { /** * Follow a new report on the bound shape. * @param {object} binding - * @param {{t: number, lat: number, lon: number}} fix + * @param {{t: number, lat: number, lon: number, bearingDeg?: number}} fix * @returns {boolean} False when the report lies off the line: the binding is wrong. */ export function followFix(binding, fix) { @@ -159,8 +174,9 @@ export function followFix(binding, fix) { pathWindowM(fix.t - binding.fixT), ); if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false; - if (!binding.drawDirection) - binding.direction = directionOf(hit.s - binding.fixS, binding.direction); + if (!binding.directionPlayed) + binding.direction = steer(binding.direction, binding.reportTurn, hit.s); + if (Number.isFinite(fix.bearingDeg)) binding.bearingDeg = fix.bearingDeg; binding.fixS = hit.s; binding.fixT = fix.t; binding.fixLat = fix.lat; @@ -211,7 +227,7 @@ function projectReport(binding, fix, hintS, hintT) { * * @param {object} binding * @param {{fromSeq: number, toSeq: number, fraction: number}} sample Playback sample. - * @param {{from: {seq:number, t:number, lat:number, lon:number}, + * @param {{from: {seq:number, t:number, lat:number, lon:number, flags?:number}, * to: {seq:number, t:number, lat:number, lon:number}}} segment The sample's two reports. * @param {{lat?: number, lon?: number, bearingDeg?: number}} out * @returns {boolean} False when the train should stay on its straight-line point. @@ -253,11 +269,15 @@ 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; + const turn = binding.playTurn; + // A break or a new epoch is a corrected position, not a move: steer + // on from there. + if (from.flags & FIX_FLAGS.BREAK || from.epoch !== turn.epoch) + turn.s = sFrom; + turn.epoch = from.epoch; + binding.direction = steer(binding.direction, turn, sFrom); + binding.direction = steer(binding.direction, turn, sTo); + if (binding.direction) binding.directionPlayed = true; } } if (!cache.ok) return false; diff --git a/src/layers/rail/pathBinding.test.mjs b/src/layers/rail/pathBinding.test.mjs index 7b9e11c0cc..7f3f9e707e 100644 --- a/src/layers/rail/pathBinding.test.mjs +++ b/src/layers/rail/pathBinding.test.mjs @@ -1,5 +1,13 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { + FIX_FLAGS, + advance, + createSample, + createTrack, + insertFix, + readFix, +} from '../../data/contactPlayback.js'; import { createRailPathPack } from '../../data/railPaths.js'; import { PATH_OFF_TRACK_M, @@ -209,8 +217,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 10 m: 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 +271,185 @@ test('a report that runs back turns the drawn train only when playback does', () ); assert.equal(binding.direction, -1); }); + +test('a jump to a corrected position in a new playback epoch is no reversal', () => { + const binding = bindTrainPath( + pack(), + { tripId: 'full', routeId: 'main' }, + fix(0, 1000, 0), + ); + const play = (seq, from, to) => { + const { sample, segment } = playback(seq, seq + 1, from, to, 0.5); + return placeOnPath(binding, sample, segment, {}); + }; + assert.ok(play(0, fix(0, 1000, 0), fix(60_000, 1600, 0))); + assert.equal(binding.direction, 1); + // The source puts it back at 1400 m: a new epoch whose first report is a + // break, and no segment is played from 1600 m to there. + const epoch = { epoch: 1 }; + assert.ok( + play( + 5, + { ...fix(70_000, 1400, 0), ...epoch, flags: FIX_FLAGS.BREAK }, + { ...fix(85_000, 1400, 0), ...epoch }, + ), + ); + assert.equal(binding.direction, 1, 'standing there, it keeps its way'); + // From there, a real move back still turns it. + assert.ok( + play( + 6, + { ...fix(85_000, 1400, 0), ...epoch }, + { ...fix(100_000, 1380, 0), ...epoch }, + ), + ); + assert.equal(binding.direction, -1); +}); + +test('a clock correction played from past its break is no reversal', () => { + const binding = bindTrainPath( + pack(), + { tripId: 'full', routeId: 'main' }, + fix(0, 600, 0), + ); + const track = createTrack(); + const sample = createSample(); + const segment = { from: {}, to: {} }; + let now = 0; + /** One report at `t`, then 15 s of frames; the direction after each. */ + const report = (t, eastM) => { + insertFix(track, fix(t, eastM, 0), { receivedAt: now, wallNowMs: now }); + return [1, 2, 3].map(() => { + now += 5000; + advance(track, { wallNowMs: now, monoNowMs: now }, sample); + if (sample.fromSeq >= 0) { + readFix(track, sample.fromSeq - track.baseSeq, segment.from); + readFix(track, sample.toSeq - track.baseSeq, segment.to); + placeOnPath(binding, sample, segment, {}); + } + return binding.direction; + }); + }; + for (const eastM of [600, 750, 900, 1050, 1200, 1200, 1200, 1200]) + report(now, eastM); + assert.equal(binding.direction, 1); + assert.ok(binding.directionPlayed); + // Its source's clock falls 120 s behind and puts it at 1000 m. The third + // such report starts a new epoch, and playback starts at the newest one, + // past the break. + const seen = [0, 1, 2].flatMap(() => report(now - 120_000, 1000)); + assert.equal(track.resetReason, 'out-of-order'); + assert.deepEqual(seen, Array(9).fill(1)); +}); + +/** The direction after each played segment, `[fromM, toM]` 15 s apart. */ +function playDirections(binding, steps) { + return steps.map(([fromM, toM], seq) => { + const { sample, segment } = playback( + seq, + seq + 1, + fix(seq * 15_000, fromM, 0), + fix((seq + 1) * 15_000, toM, 0), + 0.5, + ); + assert.ok(placeOnPath(binding, sample, segment, {})); + return binding.direction; + }); +} + +/** The direction after each report, `eastMs` 15 s apart. */ +function reportDirections(binding, eastMs) { + return eastMs.map((eastM, i) => { + assert.ok(followFix(binding, fix((i + 1) * 15_000, eastM, 0))); + return binding.direction; + }); +} + +test('a train that moves under 15 m a report still tells its direction', () => { + const p = pack(); + const ids = { tripId: 'full', routeId: 'main' }; + // It sets off slowly, runs east, then backs out 10 m a report. + const learnt = reportDirections( + bindTrainPath(p, ids, fix(0, 1000, 0)), + [1010, 1020, 1600, 1590, 1580, 1570], + ); + assert.deepEqual(learnt, [0, 1, 1, 1, -1, -1], 'from the newest reports'); + const played = bindTrainPath(p, ids, fix(0, 1000, 0)); + assert.deepEqual( + playDirections(played, [ + [1000, 1600], + [1600, 1590], + [1590, 1580], + [1580, 1570], + ]), + [1, 1, -1, -1], + 'from the played-back segments', + ); +}); + +test('a train turns 15 m back from where it ran to, not 14.9 m', () => { + const p = pack(); + const ids = { tripId: 'full', routeId: 'main' }; + for (const [backM, want, label] of [ + [1100, -1, '15 m back'], + [1100.1, 1, '14.9 m back'], + ]) { + const learnt = reportDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [ + 1115, + backM, + ]); + assert.deepEqual(learnt, [1, want], `${label}, from the newest reports`); + assert.deepEqual( + playDirections(bindTrainPath(p, ids, fix(0, 1000, 0)), [ + [1000, 1115], + [1115, backM], + ]), + [1, want], + `${label}, from the played-back segments`, + ); + } +}); + +test('GPS jitter of up to 14 m at a standing train keeps its direction', () => { + const p = pack(); + const ids = { tripId: 'full', routeId: 'main' }; + const learnt = reportDirections( + bindTrainPath(p, ids, fix(0, 1000, 0)), + [1600, 1588, 1600, 1586, 1599, 1587], + ); + assert.deepEqual(learnt, [1, 1, 1, 1, 1, 1], 'from the newest reports'); + const played = bindTrainPath(p, ids, fix(0, 1000, 0)); + assert.deepEqual( + playDirections(played, [ + [1000, 1600], + [1600, 1588], + [1588, 1600], + [1600, 1586], + [1586, 1599], + ]), + [1, 1, 1, 1, 1], + 'from the played-back segments', + ); + + // On both sides of where it stopped: 8 m either way, 16 m from end to end. + assert.deepEqual( + reportDirections( + bindTrainPath(p, ids, fix(0, 600, 0)), + [1000, 1008, 1000, 992, 1000, 1008], + ), + [1, 1, 1, 1, 1, 1], + 'both sides, from the newest reports', + ); + assert.deepEqual( + playDirections(bindTrainPath(p, ids, fix(0, 600, 0)), [ + [600, 1000], + [1000, 1008], + [1008, 1000], + [1000, 992], + [992, 1000], + [1000, 1008], + ]), + [1, 1, 1, 1, 1, 1], + 'both sides, from the played-back segments', + ); +}); diff --git a/src/layers/rail/policy.js b/src/layers/rail/policy.js index ecb3121760..f367c8f32c 100644 --- a/src/layers/rail/policy.js +++ b/src/layers/rail/policy.js @@ -16,6 +16,7 @@ import { import { displayMotion } from '../transit/movement.js'; import { FIX_FLAGS, readFix } from '../../data/contactPlayback.js'; import { roundHeadingDegrees } from '../../data/headingDegrees.js'; +import { DIRECTION_MIN_M } from './pathBinding.js'; import { stopClock, stopLateMinutes, @@ -294,9 +295,6 @@ export function playbackModeFor(railMode) { : 'rail'; } -/** Two reports closer than this are one place: a parked train's jitter (m). */ -export const FOLLOW_MIN_MOVE_M = 15; - const lastFix = {}; const priorFix = {}; @@ -333,7 +331,7 @@ export function railTrainFollowable(entry) { sample.nextMotionT > sample.displayT ) return true; - return lastReportsApartM(entry.track) >= FOLLOW_MIN_MOVE_M; + return lastReportsApartM(entry.track) >= DIRECTION_MIN_M; } /** diff --git a/src/layers/transit/cockpitSubject.js b/src/layers/transit/cockpitSubject.js index 909e4702f6..70cd6ecbfd 100644 --- a/src/layers/transit/cockpitSubject.js +++ b/src/layers/transit/cockpitSubject.js @@ -83,13 +83,16 @@ export function createTransitCockpitSubject({ state, parts, services }) { * lift: the drawn marker's height while the frame pass places it (in view, * 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. + * while either of those two floors 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. */ 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 +102,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,16 +173,32 @@ export function createTransitCockpitSubject({ state, parts, services }) { return snapshot; } - /** Show or hide a vehicle's sprite and trail for the hold. */ + /** + * Place a vehicle and show or hide its sprite and trail for the hold now: + * the icon set draws a marker as it was last pushed, not as it is. + */ function repaint(entry) { if (!entry?.marker) return; - if (entry.key === state._cockpitSubjectKey) entry.marker.show = false; - else parts.rendering.placeSample(entry); + parts.rendering.placeSample(entry); + parts.rendering.flushMarkers(); parts.rendering.schedulePlayback(entry); parts.trails.update(); state._detectRevision += 1; } + /** + * A vehicle let go of is out of play until a sweep finds it in view. It + * played on while held, so the next sweep keeps its clock if it finds it in + * view (rendering.js). + */ + function release(entry) { + if (!entry) return; + state._visible.delete(entry); + entry.releasedFromHold = true; + parts.rendering.requestVisibility(); + repaint(entry); + } + const methods = { /** The selected vehicle (see createTransitCockpitSubject), or null. */ getSelectedVehicle() { @@ -202,13 +218,7 @@ export function createTransitCockpitSubject({ state, parts, services }) { const previous = state._vehicles.get(state._cockpitSubjectKey); if (key === null || key === undefined) { state._cockpitSubjectKey = null; - // The hold kept it in play out of view: it leaves until the next - // visibility sweep finds it in view again. - if (previous) { - state._visible.delete(previous); - parts.rendering.requestVisibility(); - } - repaint(previous); + release(previous); parts.selection.refreshSelectedCard(true); return true; } @@ -217,7 +227,7 @@ export function createTransitCockpitSubject({ state, parts, services }) { if (state._selectedKey !== key) parts.selection.selectVehicle(key); state._cockpitSubjectKey = key; state._visible.add(entry); - if (previous && previous !== entry) repaint(previous); + if (previous !== entry) release(previous); repaint(entry); parts.selection.refreshSelectedCard(true); return true; diff --git a/src/layers/transit/lifecycle.js b/src/layers/transit/lifecycle.js index 5e4428f55b..0f3473ffa5 100644 --- a/src/layers/transit/lifecycle.js +++ b/src/layers/transit/lifecycle.js @@ -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(); diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs index 18760b5f5d..643aa57278 100644 --- a/src/layers/transit/lifecycle.test.mjs +++ b/src/layers/transit/lifecycle.test.mjs @@ -957,27 +957,70 @@ test('disable aborts in-flight work and a response that lands late is ignored', assert.equal(app.vehicles().length, 1); }); -test('a held vehicle with no floor yet tells its view no height', async (t) => { - // Not the ellipsoid: a first-person view waits for the surface instead. - const app = harness(t, { floorAt: () => undefined }); +/** + * Serves one bus at `place.lat` (read on every poll), enables the layer, polls + * once and settles; returns its entry. + */ +async function oneBus(app, place = { lat: 42.36 }) { app.serve('mbta', () => ({ status: 200, body: snapshot( 'mbta', 'MBTA', - [vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)], + [vehicle('bus-1', place.lat, -71.06, reported())], { fetchedAt: Date.now() }, ), })); app.layer.enable(app.viewer); await app.layer.update(); app.settle(); - const entry = app.vehicles()[0]; + return app.vehicles()[0]; +} + +test('a held vehicle with no floor yet tells its view no height', async (t) => { + // Not the ellipsoid: a first-person view waits for the surface instead. + const app = harness(t, { floorAt: () => undefined }); + const entry = await oneBus(app); assert.equal(entry.heightPending, true, 'it has nothing to stand on'); assert.ok(app.layer.setCockpitSubject(entry.key) !== false); assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null); }); +test('with the camera above the height gate, a held vehicle drawn on the ellipsoid tells its view no height', async (t) => { + const app = harness(t, { altitude: 100_000, floorAt: () => undefined }); + const entry = await oneBus(app); + 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('with the camera above the height gate, a held vehicle with one floor unknown tells its view no height', async (t) => { + // Drawn between a floor its view could stand on and none. + for (const knownLat of [42.36, 42.361]) { + await t.test(`floor known at ${knownLat}`, async (t) => { + const app = harness(t, { altitude: 100_000, floorAt: () => undefined }); + app.ground._warm.set(app.ground._key(knownLat, -71.06), 12); + const start = Date.now(); + const place = { lat: 42.36 }; + const entry = await oneBus(app, place); + place.lat = 42.361; + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + assert.equal(app.layer.setCockpitSubject(entry.key), true); + app.run(start - AGE_MS + LAG_MS + TRANSIT_POLL_MS / 2 - Date.now()); + const { from, to } = entry.segment; + assert.notEqual(Number.isFinite(from.h), Number.isFinite(to.h)); + assert.equal(entry.surfaceReady, true, 'it is drawn'); + 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 @@ -2118,13 +2161,19 @@ test('a segment climbs from the ground it left to the ground it reaches', async `its snapshot stands where it is drawn, got ${floor().toFixed(1)} m`, ); - // Halfway along the segment it is halfway up; at the end, on the high ground. + // Halfway along the segment it still follows the low ground it crosses; at + // the end, it is on the high ground. const firstFixAt = start - AGE_MS; app.run(firstFixAt + LAG_MS + TRANSIT_POLL_MS / 2 - Date.now()); assert.ok( 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, @@ -4881,3 +4930,197 @@ 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); }); + +/** A vehicle's icon in the set that draws it, still or moving. */ +function iconOf(app, key) { + return app.markers('still').get(key) ?? app.markers('moving').get(key); +} + +test('turning Transit off ends a hold; on again, the vehicle shows, a click selects it and Escape deselects it', 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(); + const [entry] = app.vehicles(); + app.frame(); + assert.equal(entry.marker.show, true, 'the vehicle is drawn, not held'); + assert.equal(iconOf(app, key)?.show, true, 'and so is its icon in the set'); + app.viewer.scene.pick = () => app.pickOf(entry); + app.input.click(new Cesium.Cartesian2(500, 400)); + assert.equal(app.state()._selectedKey, key, 'a click selects it'); + 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(); + assert.equal(iconOf(app, key)?.show, true, 'drawn before the hold'); + assert.equal(app.layer.setCockpitSubject(key), true); + assert.equal(iconOf(app, key)?.show ?? false, false, 'hidden at once'); + // 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( + iconOf(app, key)?.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(iconOf(app, key)?.show, true, 'let go: drawn again'); +}); + +test('a hold moved to another vehicle lets the first go out of view', async (t) => { + const app = harness(t); + app.serve('mbta', () => ({ + status: 200, + body: snapshot( + 'mbta', + 'MBTA', + [ + vehicle('bus-1', 42.36, -71.06, reported()), + vehicle('bus-2', 42.37, -71.05, reported()), + ], + { fetchedAt: Date.now() }, + ), + })); + app.layer.enable(app.viewer); + await app.layer.update(); + app.settle(); + const bus = (id) => app.vehicles().find((entry) => entry.key === id); + const first = bus('mbta:bus-1'); + assert.equal(app.layer.setCockpitSubject(first.key), true); + // The view looks away from both, as a view from inside the first does. + app.lookAt({ west: -70.98, south: 42.3, east: -70.9, north: 42.42 }); + app.advance(250); + app.settle(); + assert.equal(app.state()._visible.has(bus('mbta:bus-2')), false); + assert.equal(app.layer.setCockpitSubject('mbta:bus-2'), true); + assert.equal(app.state()._visible.has(first), false, 'let go, out of play'); + assert.equal(first.marker.show, false, 'and not drawn out of view'); +}); + +test('a vehicle in view let go of a hold goes on from its own clock', async (t) => { + // Held, it played on; let go, the sweep that finds it in view does not + // set its clock again, though the feed's lag has grown since. + for (const next of ['mbta:b', null]) { + await t.test(`the hold moves to ${next}`, async (t) => { + const app = harness(t, { floorAt: () => 5 }); + let fixAt = Date.now() - AGE_MS; + let north = 42.36; + app.serve('mbta', () => ({ + status: 200, + body: snapshot( + 'mbta', + 'MBTA', + [ + vehicle('a', north, -71.06, fixAt / 1000), + vehicle('b', 42.37, -71.05, reported()), + ], + { fetchedAt: Date.now() }, + ), + })); + app.layer.enable(app.viewer); + await app.layer.update(); + app.settle(); + const a = app.vehicles().find((e) => e.key === 'mbta:a'); + app.layer.setCockpitSubject(a.key); + for (let poll = 1; poll <= 5; poll += 1) { + fixAt += TRANSIT_POLL_MS; + north += 0.001; + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + } + // One late poll raises the feed's target lag. + app.run(TRANSIT_POLL_MS + 10_000); + fixAt += TRANSIT_POLL_MS; + north += 0.001; + await app.layer.update(); + app.run(3_000); + const beforeT = a.track.displayT; + const beforeLat = lat(a); + app.layer.setCockpitSubject(next); + app.advance(250); + app.settle(); + assert.equal(app.state()._visible.has(a), true, 'A is in view'); + assert.ok(a.track.displayT >= beforeT, 'its clock did not go back'); + assert.ok(lat(a) >= beforeLat, 'nor did it move back'); + }); + } +}); + +test('holding a vehicle out of view tells its view at once the floor it stands on', async (t) => { + // Out of view a vehicle plays on but its marker is not moved: the hold + // places it, so its view reads the floor it is on now, not the old one or + // null. + const app = harness(t, { floorAt: (lat) => (lat > 42.3625 ? 100 : 10) }); + for (const [lat, floorM] of [ + [42.361, 10], + [42.362, 10], + [42.363, 100], + [42.364, 100], + ]) + app.ground._warm.set(app.ground._key(lat, -71.06), floorM); + const place = { lat: 42.36 }; + const entry = await oneBus(app, place); + const drawnM = () => + Cesium.Cartographic.fromCartesian(entry.marker.position).height; + assert.ok(Math.abs(drawnM() - 11.5) < 1, 'drawn on the low ground'); + app.lookAt({ west: -70.98, south: 42.3, east: -70.9, north: 42.42 }); + app.advance(250); + app.settle(); + assert.equal(app.state()._visible.has(entry), false, 'out of view'); + // Unseen, it drives up the hill and stands there. + for (const next of [42.361, 42.362, 42.363, 42.364, 42.364, 42.364]) { + place.lat = next; + app.run(TRANSIT_POLL_MS); + await app.layer.update(); + } + app.run(LAG_MS); + app.settle(); + assert.ok(drawnM() < 30, 'its marker was left on the low ground'); + assert.equal(app.layer.setCockpitSubject(entry.key), true); + const floorM = app.layer.getCockpitSubject().position.groundHeightM; + assert.ok(Math.abs(floorM - 100) < 1.5, `up the hill, got ${floorM} m`); +}); diff --git a/src/layers/transit/rendering.js b/src/layers/transit/rendering.js index f6c22ebc81..6a6cda15f3 100644 --- a/src/layers/transit/rendering.js +++ b/src/layers/transit/rendering.js @@ -1154,13 +1154,18 @@ export function createRendering({ state, services, parts }) { visibility.noSample = noSample; const wasShown = entry.marker.show; const wasVisible = state._visible.has(entry); + // Just let go of a hold (cockpitSubject.js): it played on, so keep + // its clock. + const playedOn = entry.releasedFromHold === true; + entry.releasedFromHold = false; if (visible) state._visible.add(entry); else state._visible.delete(entry); // Turned afresh once back in view: the camera may have moved while it // was out, after the pass that would have turned it. if (visible && !wasVisible) entry.rotationCourse = undefined; if (visible && entry.track?.count) { - if (!wasVisible && !entry.qaFixture) syncPlayback(entry, now); + if (!wasVisible && !playedOn && !entry.qaFixture) + syncPlayback(entry, now); // Re-entry can advance into an unprepared corridor; loaded tiles can // also resolve a cold path without a poll or a render-loop wakeup. if (!wasVisible || entry.surfaceReady === false || entry.heightPending)