From 9de93b8d31c3e091e046202ef476ce847d3d0fdb Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 05:42:02 -0800 Subject: [PATCH] Draw directions through the draw port The directions layer draws its endpoint markers, its flowing route and its maneuver dots through draw-port sets, takes clicks from the draw hit and ground picks from the click's ground position, and leaves the Cesium allow-list. The route keeps the annotation's flowing dashes, draped on terrain and tiles; the maneuver dots keep their place in the sprite order through the steps set. --- scripts/package-boundaries.json | 4 + src/data/directions.js | 14 +- src/data/directions.test.mjs | 31 +-- src/data/sharedOsmDisplays.test.mjs | 12 +- src/layers/directions/index.js | 335 ++++++++++++++++------------ src/render/cesium/draw.test.mjs | 143 ++++++++++++ src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 1 + 8 files changed, 361 insertions(+), 180 deletions(-) diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 5aa2eab4b..9d90a27d8 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -5163,6 +5163,10 @@ "src/data/distanceFormat.js", "src/i18n/marker.js", "src/layers/directions/index.js", + "src/geo/ellipsoid.js", + "src/render/rendererOf.js", + "src/geo/vector.js", + "src/render/color.js", "src/data/pointerOwnerNames.js", "src/layers/directions/source.js", "src/data/routeSteps.js", diff --git a/src/data/directions.js b/src/data/directions.js index d9a6afe0d..6179b3950 100644 --- a/src/data/directions.js +++ b/src/data/directions.js @@ -4,20 +4,18 @@ import { createDirectionsSource } from '../layers/directions/source.js'; * @description Service bundle for the Directions layer. * * The layer itself lives in `src/layers/directions/`, which imports nothing - * but Cesium and the pure step formatter. This module is the one place that - * names the application's shared services — the render governor, sprite order, - * the pick registry, the world overlay, the annotation material, the camera - * verbs, the shared ground floor and the pointer arbiter — and it re-exports - * the layer's pure helpers for the tests and the share-link code. + * but the renderer's draw port, geodesy and the pure step formatter. This + * module is the one place that names the application's shared services — + * the render governor, sprite order, the pick registry, the world overlay, + * the camera verbs, the shared ground floor and the pointer arbiter — and it + * re-exports the layer's pure helpers for the tests and the share-link code. */ import * as credits from './dataCredits.js'; import * as render from '../renderGovernor.js'; import * as sprites from './spriteOrder.js'; import * as picking from './pickRegistry.js'; -import * as scenePick from './scenePick.js'; import * as overlays from '../overlays/worldOverlay.js'; -import * as annotations from '../annotations/worldAnnotationRenderer.js'; import * as camera from '../cameraVerbs.js'; import * as ground from './groundFloor.js'; import * as input from './inputOwnership.js'; @@ -29,9 +27,7 @@ const directionsServices = Object.freeze({ render, sprites, picking, - scenePick, overlays, - annotations, camera, ground, input, diff --git a/src/data/directions.test.mjs b/src/data/directions.test.mjs index 9d7aea50e..4a18fd60f 100644 --- a/src/data/directions.test.mjs +++ b/src/data/directions.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { DEFAULT_DIRECTIONS_MODE, DIRECTIONS_MODES, @@ -969,7 +970,6 @@ test('a placed endpoint draws its letter through the overlay, not as entity text const published = []; const cleared = []; const visibility = []; - const entities = []; const markerVisibility = () => visibility .filter(([source]) => source === DIRECTIONS_MARKER_OVERLAY_SOURCE_ID) @@ -983,23 +983,11 @@ test('a placed endpoint draws its letter through the overlay, not as entity text resetPointerOwnership(); const viewer = { isDestroyed: () => false, - entities: { - add: (spec) => (entities.push(spec), spec), - remove() {}, - }, - scene: { - requestRender() {}, - primitives: { - add: (primitive) => primitive, - remove() {}, - raiseToTop() {}, - lowerToBottom() {}, - contains: () => true, - length: 0, - }, - }, + scene: { requestRender() {} }, }; + const { draw, unbind } = bindFakeDraw(viewer); t.after(() => { + unbind(); directionsLayer.destroy(viewer); directionsLayer._setOverlayHostForTest(null); resetPointerOwnership(); @@ -1008,9 +996,13 @@ test('a placed endpoint draws its letter through the overlay, not as entity text assert.equal(markerVisibility(), false, 'hidden until enabled'); directionsLayer.placeEndpoint('a', { lat: 37.7955, lon: -122.3937 }); - assert.equal(entities.length, 1); - assert.equal(entities[0].label, undefined, 'no Cesium label on the marker'); - assert.ok(entities[0].point, 'the marker keeps its point'); + const markers = [...draw.sets.values()].find( + (set) => !set.disposed && set.spec.id.endsWith(':markers'), + ); + assert.deepEqual([...markers.items.keys()], ['directions:marker:A']); + const marker = markers.items.get('directions:marker:A'); + assert.equal(marker.label, undefined, 'no renderer label on the marker'); + assert.equal(marker.height, 'clampGround', 'a dot on the ground'); const [source, entries] = published.at(-1); assert.equal(source, DIRECTIONS_MARKER_OVERLAY_SOURCE_ID); assert.deepEqual( @@ -1027,6 +1019,7 @@ test('a placed endpoint draws its letter through the overlay, not as entity text assert.ok(Math.abs(Cesium.Math.toDegrees(anchor.latitude) - 37.7955) < 1e-9); directionsLayer.setParams({ clear: true }); + assert.equal(markers.items.size, 0, 'CLEAR takes the markers'); assert.ok(cleared.includes(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID)); cleared.length = 0; directionsLayer.destroy(viewer); diff --git a/src/data/sharedOsmDisplays.test.mjs b/src/data/sharedOsmDisplays.test.mjs index ef0472443..c2bbf716f 100644 --- a/src/data/sharedOsmDisplays.test.mjs +++ b/src/data/sharedOsmDisplays.test.mjs @@ -2,11 +2,12 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as C from 'cesium'; import { showOsmCredit, hideOsmCredit } from './dataCredits.js'; -import { bindFakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs'; +import { bindFakeCesiumCredits, fakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { bindRenderer } from '../render/rendererOf.js'; import { createInfrastructureLayers } from './infrastructure.js'; import { createBhoteKoshiLocatorLayer } from './bhoteKoshiLocator.js'; import { createWorldAnnotationRenderer } from '../annotations/worldAnnotationRenderer.js'; -import * as annotations from '../annotations/worldAnnotationRenderer.js'; import { createDirectionsLayer } from '../layers/directions/index.js'; import { createDirectionsSource } from '../layers/directions/source.js'; import { createLifecycle as createCctvLifecycle } from '../layers/cctv/lifecycle.js'; @@ -15,7 +16,7 @@ import { createOverpassAlprSource } from '../layers/alpr/source.js'; const noop = () => {}; const overlayHost = { setEntries: noop, setVisible: noop, clearSource: noop }; -function viewer(t) { +function viewer(t, ports = null) { t.mock.timers.enable({ apis: ['setTimeout'] }); for (const name of ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']) { const original = globalThis[name]; @@ -32,6 +33,7 @@ function viewer(t) { scene: { requestRender: noop, canvas: { addEventListener: noop, removeEventListener: noop }, preRender: new C.Event(), primitives: { add: (p) => p, remove: noop }, screenSpaceCameraController: { enableInputs: true } }, }; + if (ports) bindRenderer(v, { credits: fakeCesiumCredits(v), ...ports }); return bindFakeCesiumCredits(v); } function assertCredit(v) { @@ -64,10 +66,10 @@ test('voice route geometry introduces the shared OSM credit', (t) => { }); test('Directions introduces the shared OSM credit when the requested route draws', async (t) => { - const v = viewer(t); + const v = viewer(t, { draw: fakeDrawPort() }); t.mock.method(globalThis, 'fetch', async () => Response.json({ ok: true, geometry: [[0, 0], [0.01, 0.01]], steps: [] })); const layer = createDirectionsLayer({ source: createDirectionsSource(), services: { - credits: { showOsmCredit, hideOsmCredit }, annotations, input, scenePick: {}, camera: {}, + credits: { showOsmCredit, hideOsmCredit }, input, camera: {}, overlays: { setOverlayEntries: noop, setOverlaySourceVisible: noop, clearOverlaySource: noop }, render: { governorRequestRender: noop, holdContinuousRender: noop, releaseContinuousRender: noop }, sprites: { registerSpriteCollection: noop, unregisterSpriteCollection: noop, restoreSpriteOrder: noop }, diff --git a/src/layers/directions/index.js b/src/layers/directions/index.js index cc7eb7875..556d44433 100644 --- a/src/layers/directions/index.js +++ b/src/layers/directions/index.js @@ -16,8 +16,10 @@ * route. */ -import * as Cesium from 'cesium'; import { roadLabel } from '../../data/routeSteps.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { hexColor } from '../../render/color.js'; +import { drawOf } from '../../render/rendererOf.js'; import { t, msg, @@ -78,10 +80,24 @@ export function presentRoutingFailure(error) { export const DIRECTIONS_ROUTE_COLOR = '#39d0ff'; const MARKER_A_CSS = '#5dff9f'; const MARKER_B_CSS = '#ff6b6b'; -const MARKER_A_COLOR = Cesium.Color.fromCssColorString(MARKER_A_CSS); -const MARKER_B_COLOR = Cesium.Color.fromCssColorString(MARKER_B_CSS); -const STEP_COLOR = Cesium.Color.WHITE.withAlpha(0.95); -const STEP_OUTLINE = Cesium.Color.fromCssColorString(DIRECTIONS_ROUTE_COLOR); +const MARKER_A_COLOR = hexColor(MARKER_A_CSS); +const MARKER_B_COLOR = hexColor(MARKER_B_CSS); +const MARKER_OUTLINE = [0, 0, 0, 1]; +const STEP_COLOR = [1, 1, 1, 0.95]; +const STEP_OUTLINE = hexColor(DIRECTIONS_ROUTE_COLOR); +/** + * The route's flowing dashes, as the voice route annotation draws them: + * 64 cells along the whole route, each lit for its first 46%, running + * toward B at 0.55 cells a second. + */ +const ROUTE_STYLE = Object.freeze({ + kind: 'flow', + color: hexColor(DIRECTIONS_ROUTE_COLOR, 0.95), + repeat: 64, + duty: 0.46, + speed: 0.55, +}); +const ROUTE_WIDTH_PX = 9; const STEP_PIXEL_SIZE = 8; const STEP_SELECTED_PIXEL_SIZE = 13; /** Route request timeout (ms) — the proxy itself gives OSRM 12 s. */ @@ -776,7 +792,7 @@ export function directionsStepCopy(steps, index) { /** * Shared-host card for the selected maneuver. * @param {number} index - * @param {Cesium.Cartesian3} position + * @param {{x: number, y: number, z: number}} position * @param {{title:string, details:string[]}} copy * @returns {object|null} */ @@ -809,7 +825,7 @@ export function createDirectionsStepOverlayEntry(index, position, copy) { * The letter above one endpoint marker, as a world-overlay label. It is * protected, like the step card, so it never yields to ambient labels. * @param {'A'|'B'} letter - * @param {Cesium.Cartesian3|(() => Cesium.Cartesian3)} position + * @param {{x: number, y: number, z: number}|(() => {x: number, y: number, z: number}|null)} position * @param {string} accent CSS colour of the marker. */ export function createDirectionsMarkerOverlayEntry(letter, position, accent) { @@ -885,13 +901,16 @@ export function normalizeRoutePayload(payload, mode) { }; } +/** Directions layers made, so each one's draw sets have ids of their own. */ +let _instances = 0; + /** * Construct one Directions layer over the application scene owners. * * Each catalog builds its own, so two applications on a page never share the * route, the markers, the pointer claim or the flight this layer owns. The * shared services are injected, which is what keeps this module's own imports - * down to Cesium and the pure step formatter. + * down to the renderer's draw port, geodesy and the pure step formatter. * @param {{services: object, source: {getRoute: Function}}} options * @returns {object} The layer module the data manager registers. */ @@ -932,10 +951,22 @@ export function createDirectionsLayer({ services, source }) { let _routeSeq = 0; let _routeAbort = null; let _lastUpdate = null; - let _markerA = null; - let _markerB = null; - let _routeEntity = null; - let _stepPoints = null; + /** + * The layer's draw sets on its viewer's renderer (`drawOf`), made at + * `init`: the A and B markers, the maneuver dots and the route. + * @type {{markers: object, steps: object, route: object}|null} + */ + let _sets = null; + /** The registration of the dots in the shared sprite order. */ + let _spriteEntry = null; + /** Whether a route is drawn. */ + let _routeDrawn = false; + /** + * Each maneuver dot drawn, by step index: where it stands (once its ground + * cell has answered) and whether it shows. + * @type {Map} + */ + const _stepDots = new Map(); let _selectedStep = null; let _clickSubscription = null; let _renderHeld = false; @@ -969,6 +1000,18 @@ export function createDirectionsLayer({ services, source }) { // Internals // --------------------------------------------------------------------------- + /** Let the layer's draw sets go. */ + function detachSets() { + if (_spriteEntry) + services.sprites.unregisterSpriteCollection?.('directions', _spriteEntry); + _spriteEntry = null; + if (!_sets) return; + for (const set of Object.values(_sets)) set.dispose(); + _sets = null; + _routeDrawn = false; + _stepDots.clear(); + } + function state() { return { enabled: _enabled, @@ -996,7 +1039,7 @@ export function createDirectionsLayer({ services, source }) { } function syncRenderHold() { - const shouldHold = _enabled && Boolean(_routeEntity); + const shouldHold = _enabled && _routeDrawn; if (shouldHold && !_renderHeld) { services.render.holdContinuousRender('directions'); _renderHeld = true; @@ -1006,37 +1049,35 @@ export function createDirectionsLayer({ services, source }) { } } - function pickGround(screenPosition) { - const cartesian = services.scenePick.pickGroundPosition( - _viewer, - screenPosition, - ); - if (!cartesian) return null; - const carto = Cesium.Cartographic.fromCartesian(cartesian); + /** + * Where a click lands on the ground, from the click's own ground pick (the + * rendered surface, else the ellipsoid; null over the sky). + * @param {{ground: () => ({x: number, y: number, z: number}|null)}} event + */ + function pickGround(event) { + const ecef = event.ground?.(); + if (!ecef) return null; + const carto = toLonLatH(ecef); if (!carto) return null; - const point = { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), - }; + const point = { lat: carto.lat, lon: carto.lon }; // A pick at the ellipsoid itself is the fallback when the drawn surface // gave no position; the floor path places that letter instead. if (Math.abs(carto.height) > 0.01) _surfaceHeights.set(point, carto.height); return point; } - function markerEntity(letter, point, color) { - return _viewer.entities.add({ + /** An endpoint marker: a dot on the ground, drawn over everything. */ + function markerItem(letter, point, color) { + return { id: `directions:marker:${letter}`, - position: Cesium.Cartesian3.fromDegrees(point.lon, point.lat, 0), - point: { - pixelSize: 14, - color, - outlineColor: Cesium.Color.BLACK, - outlineWidth: 2, - heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + pos: { lon: point.lon, lat: point.lat, height: 0 }, + height: 'clampGround', + pixelSize: 14, + color, + outlineColor: MARKER_OUTLINE, + outlineWidth: 2, + disableDepthTest: Number.POSITIVE_INFINITY, + }; } /** @@ -1054,7 +1095,7 @@ export function createDirectionsLayer({ services, source }) { _surfaceHeights.get(point) ?? services.ground.cachedGroundFloor(point.lat, point.lon); if (!Number.isFinite(height) && !_floorSettled.has(point)) return null; - position = Cesium.Cartesian3.fromDegrees( + position = fromDegrees( point.lon, point.lat, Number.isFinite(height) ? height : 0, @@ -1085,20 +1126,13 @@ export function createDirectionsLayer({ services, source }) { ); } - function removeEntity(entity) { - if (entity && _viewer && !_viewer.isDestroyed?.()) - _viewer.entities.remove(entity); - } - function placeMarker(letter, point) { - if (!_viewer) return; - if (letter === 'a') { - removeEntity(_markerA); - _markerA = markerEntity('A', point, MARKER_A_COLOR); - } else { - removeEntity(_markerB); - _markerB = markerEntity('B', point, MARKER_B_COLOR); - } + if (!_viewer || !_sets) return; + _sets.markers.upsert([ + letter === 'a' + ? markerItem('A', point, MARKER_A_COLOR) + : markerItem('B', point, MARKER_B_COLOR), + ]); publishMarkerLabels(); if (_surfaceHeights.has(point)) return; // The letter appears when its floor cell lands, even under a still camera. @@ -1116,9 +1150,10 @@ export function createDirectionsLayer({ services, source }) { services.credits?.hideOsmCredit?.(_viewer, 'directions'); _clearStepSelection(); stopStepAnchoring(); - removeEntity(_routeEntity); - _routeEntity = null; - _stepPoints?.removeAll(); + _sets?.route.clear(); + _routeDrawn = false; + _stepDots.clear(); + _sets?.steps.clear(); syncRenderHold(); } @@ -1137,31 +1172,28 @@ export function createDirectionsLayer({ services, source }) { */ function anchorStepPoints() { _anchorTimer = null; - if (!_stepPoints || !_route || !_enabled) return; + if (!_sets || !_route || !_enabled) return; const steps = _route.steps; const pending = []; let unresolved = 0; for (const index of stepMarkerIndices(steps)) { const step = steps[index]; - const point = findStepPoint(index); - if (!point) continue; + const dot = _stepDots.get(index); + if (!dot) continue; const height = stepMarkerHeightM( services.ground.cachedGroundFloor(step.lat, step.lon), services.ground.GROUND_FLOOR_LIFT_M, ); if (height === null) { unresolved += 1; - point.show = false; + dot.show = false; pending.push({ lat: step.lat, lon: step.lon }); continue; } - point.position = Cesium.Cartesian3.fromDegrees( - step.lon, - step.lat, - height, - ); - point.show = true; + dot.pos = fromDegrees(step.lon, step.lat, height); + dot.show = true; } + drawStepDots(); // A card already open on a step that has just been anchored moves with it. if (_selectedStep !== null) refreshStepCard(_selectedStep); services.render.governorRequestRender('directions-anchor'); @@ -1180,45 +1212,63 @@ export function createDirectionsLayer({ services, source }) { _anchorTimer = setTimeout(anchorStepPoints, delay); } + /** One maneuver dot as the steps set draws it. */ + function stepDotItem(index, dot) { + return { + id: `directions:step:${index}`, + pos: dot.pos, + color: STEP_COLOR, + pixelSize: + index === _selectedStep ? STEP_SELECTED_PIXEL_SIZE : STEP_PIXEL_SIZE, + outlineColor: STEP_OUTLINE, + outlineWidth: 2, + show: dot.show, + // The shared ground floor is a coarse cell, and on the photoreal stack + // the rendered mesh can stand above it. Keeping the dot always visible + // is the same choice every other anchored sprite in the app makes. + disableDepthTest: Number.POSITIVE_INFINITY, + }; + } + + /** Draw the maneuver dots as they now are (moved and restyled in place). */ + function drawStepDots(indices = _stepDots.keys()) { + if (!_sets) return; + const items = []; + for (const index of indices) { + const dot = _stepDots.get(index); + if (dot) items.push(stepDotItem(index, dot)); + } + if (items.length) _sets.steps.upsert(items); + } + function drawRoute(route) { clearRouteGraphics(); - if (!_viewer) return; - services.annotations.ensureFlowFabricRegistered(); - const positions = Cesium.Cartesian3.fromDegreesArray(route.geometry.flat()); - _routeEntity = _viewer.entities.add({ - id: 'directions:route', - polyline: { - positions, - width: 9, - material: new services.annotations.FlowMaterialProperty( - DIRECTIONS_ROUTE_COLOR, - ), - clampToGround: true, - // BOTH: drape on 3D tiles when they are up and on terrain when they are + if (!_viewer || !_sets) return; + _sets.route.set([ + { + id: 'directions:route', + positions: route.geometry.map(([lon, lat]) => fromDegrees(lon, lat, 0)), + widthPx: ROUTE_WIDTH_PX, + mode: 'draped', + // Draped on 3D tiles when they are up and on terrain when they are // not, so the keyless globe shows the route too. - classificationType: Cesium.ClassificationType.BOTH, + clampTo: 'both', + style: ROUTE_STYLE, }, - }); + ]); + _routeDrawn = true; // One dot per decision; A and B already mark departure and arrival. The dots // start hidden and appear as anchorStepPoints resolves each ground cell. const cells = []; + const dots = []; for (const index of stepMarkerIndices(route.steps)) { const step = route.steps[index]; cells.push({ lat: step.lat, lon: step.lon }); - _stepPoints.add({ - id: `directions:step:${index}`, - position: Cesium.Cartesian3.fromDegrees(step.lon, step.lat, 0), - color: STEP_COLOR, - pixelSize: STEP_PIXEL_SIZE, - outlineColor: STEP_OUTLINE, - outlineWidth: 2, - show: false, - // The shared ground floor is a coarse cell, and on the photoreal stack - // the rendered mesh can stand above it. Keeping the dot always visible - // is the same choice every other anchored sprite in the app makes. - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }); + const dot = { pos: fromDegrees(step.lon, step.lat, 0), show: false }; + _stepDots.set(index, dot); + dots.push(stepDotItem(index, dot)); } + _sets.steps.set(dots); services.credits?.showOsmCredit?.(_viewer, 'directions'); services.ground.warmGroundFloor(cells); _anchorAttempts = 0; @@ -1411,10 +1461,7 @@ export function createDirectionsLayer({ services, source }) { _route = null; _status = 'idle'; _error = null; - removeEntity(_markerA); - removeEntity(_markerB); - _markerA = null; - _markerB = null; + _sets?.markers.clear(); _overlayHost.clearSource(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID); clearRouteGraphics(); services.render.governorRequestRender('directions-clear'); @@ -1506,24 +1553,12 @@ export function createDirectionsLayer({ services, source }) { // --- Step selection --- function _clearStepSelection() { - if (_selectedStep !== null && _stepPoints) { - const point = findStepPoint(_selectedStep); - if (point) point.pixelSize = STEP_PIXEL_SIZE; - } + const was = _selectedStep; _selectedStep = null; + if (was !== null) drawStepDots([was]); _overlayHost.clearSource(DIRECTIONS_STEP_OVERLAY_SOURCE_ID); } - function findStepPoint(index) { - if (!_stepPoints) return null; - const id = `directions:step:${index}`; - for (let i = 0; i < _stepPoints.length; i += 1) { - const point = _stepPoints.get(i); - if (point.id === id) return point; - } - return null; - } - /** * Where a step's card should hang, or null while that is not yet known. * @@ -1533,13 +1568,13 @@ export function createDirectionsLayer({ services, source }) { * the same shared floor, and a step whose cell is still cold has no anchor at * all rather than one at sea level. * @param {number} index Step index. - * @returns {Cesium.Cartesian3|null} + * @returns {{x: number, y: number, z: number}|null} */ function stepAnchorPosition(index) { const step = _route?.steps?.[index]; if (!step) return null; - const point = findStepPoint(index); - if (point?.show) return Cesium.Cartesian3.clone(point.position); + const dot = _stepDots.get(index); + if (dot?.show) return { ...dot.pos }; const height = stepMarkerHeightM( services.ground.cachedGroundFloor(step.lat, step.lon), services.ground.GROUND_FLOOR_LIFT_M, @@ -1548,7 +1583,7 @@ export function createDirectionsLayer({ services, source }) { services.ground.warmGroundFloor([{ lat: step.lat, lon: step.lon }]); return null; } - return Cesium.Cartesian3.fromDegrees(step.lon, step.lat, height); + return fromDegrees(step.lon, step.lat, height); } function refreshStepCard(index) { @@ -1585,20 +1620,17 @@ export function createDirectionsLayer({ services, source }) { return false; } _selectedStep = index; - const point = findStepPoint(index); - if (point) point.pixelSize = STEP_SELECTED_PIXEL_SIZE; + drawStepDots([index]); services.render.governorRequestRender('directions-select'); return true; } - function stepIndexFromPick(picked) { - const candidates = [picked?.primitive?.id, picked?.id]; - for (const candidate of candidates) { - if (typeof candidate !== 'string') continue; - const match = /^directions:step:(\d+)$/.exec(candidate); - if (match) return Number(match[1]); - } - return null; + /** The step of a maneuver dot this layer draws under a click, or null. */ + function stepIndexFromHit(hit) { + if (!hit || !_sets || hit.set !== _sets.steps.id) return null; + const match = /^directions:step:(\d+)$/.exec(hit.id); + const index = match ? Number(match[1]) : null; + return index !== null && _stepDots.has(index) ? index : null; } function _onKeyDown(event) { @@ -1621,7 +1653,7 @@ export function createDirectionsLayer({ services, source }) { 'click', (event) => { if (!_enabled || !_armed) return; - const point = pickGround(event.position); + const point = pickGround(event); if (!point) return; placeDirectionsEndpoint(_armed, point); }, @@ -1631,13 +1663,13 @@ export function createDirectionsLayer({ services, source }) { // yields the moment a tool (this one included) owns the click. const offSelect = input.onClick((event) => { if (!_enabled) return; - let picked = null; + let hit = null; try { - picked = event.pick; + hit = event.drawHit; } catch { - picked = null; + hit = null; } - const index = stepIndexFromPick(picked); + const index = stepIndexFromHit(hit); if (index !== null) { _selectStep(index); return; @@ -1672,17 +1704,31 @@ export function createDirectionsLayer({ services, source }) { updateInterval: 0, /** - * Create the maneuver-dot collection. Called once at bootstrap. - * @param {Cesium.Viewer} viewer + * Make the layer's draw sets on the viewer's renderer. Called once at + * bootstrap. + * @param {object} viewer */ init(viewer) { _viewer = viewer; - _stepPoints = new Cesium.PointPrimitiveCollection({ - blendOption: Cesium.BlendOption.TRANSLUCENT, - }); - viewer.scene.primitives.add(_stepPoints); - services.sprites.registerSpriteCollection('directions', _stepPoints); - _stepPoints.show = false; + detachSets(); + const draw = drawOf(viewer); + const prefix = `directions:${++_instances}`; + _sets = { + markers: draw.points({ id: `${prefix}:markers` }), + steps: draw.points({ + id: `${prefix}:steps`, + blend: 'translucent', + show: false, + }), + route: draw.lines({ id: `${prefix}:route` }), + }; + // Drawn from the start, empty, so the dots take their place in the + // scene now, as their collection did; their place among the other + // sprite layers is the sprite order's. + _sets.steps.set([]); + _spriteEntry = + services.sprites.registerSpriteSet?.('directions', _sets.steps.id) ?? + null; _enabled = false; _mode = DEFAULT_DIRECTIONS_MODE; disarm(); @@ -1700,12 +1746,12 @@ export function createDirectionsLayer({ services, source }) { /** * Show the row chips and listen for placement clicks. - * @param {Cesium.Viewer} viewer + * @param {object} viewer */ enable(viewer) { _enabled = true; _pointerBlocked = false; - _stepPoints.show = true; + if (_sets) _sets.steps.show = true; _overlayHost.setVisible(DIRECTIONS_STEP_OVERLAY_SOURCE_ID, true); _overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, true); _installClickHandler(viewer); @@ -1720,7 +1766,7 @@ export function createDirectionsLayer({ services, source }) { /** * Remove the route, markers and listeners. - * @param {Cesium.Viewer} viewer + * @param {object} viewer */ disable(viewer) { _enabled = false; @@ -1729,7 +1775,7 @@ export function createDirectionsLayer({ services, source }) { _overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, false); _removeClickHandler(); services.picking.unregisterPickOwner('directions'); - if (_stepPoints) _stepPoints.show = false; + if (_sets) _sets.steps.show = false; syncRenderHold(); void viewer; }, @@ -1814,7 +1860,7 @@ export function createDirectionsLayer({ services, source }) { /** * Tear down entirely. - * @param {Cesium.Viewer} viewer + * @param {object} viewer */ destroy(viewer) { if (_enabled) this.disable(viewer); @@ -1827,11 +1873,8 @@ export function createDirectionsLayer({ services, source }) { _shellSeams = null; _dataManager = null; _rowControlsListener = null; - if (_stepPoints) { - services.sprites.unregisterSpriteCollection('directions', _stepPoints); - viewer.scene.primitives.remove(_stepPoints); - _stepPoints = null; - } + detachSets(); + void viewer; _overlayHost.clearSource(DIRECTIONS_STEP_OVERLAY_SOURCE_ID); _overlayHost.clearSource(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID); _viewer = null; diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 5df748b8d..666339049 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -2524,3 +2524,146 @@ test('a draped flow line still drawing while its rebuilds build keeps flowing', assert.ok(material.uniforms.time >= 0, 'and keeps its clock'); set.dispose(); })); + +test('the directions layer draws its markers, flowing route and maneuver dots on a viewer of its own', async (t) => { + // Materials check their uniforms against the DOM's image classes. + const names = ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']; + const real = names.map((name) => globalThis[name]); + for (const name of names) globalThis[name] ??= class {}; + t.after(() => names.forEach((name, i) => (globalThis[name] = real[i]))); + { + const { createDirectionsLayer } = + await import('../../layers/directions/index.js'); + const { fakeInput } = await import('../../input/testDoubles.mjs'); + const ownership = await import('../../data/inputOwnership.js'); + const scene = fakeScene(); + scene.pickResult = undefined; + scene.pick = () => scene.pickResult; + scene.drillPick = () => []; + const viewer = { scene, isDestroyed: () => false }; + const clicks = fakeInput(viewer); + const noop = () => {}; + const sprites = []; + const overlays = []; + const layer = createDirectionsLayer({ + source: { + getRoute: async () => ({ + ok: true, + distanceM: 2000, + durationS: 200, + geometry: [ + [-97.74, 30.26], + [-97.73, 30.27], + [-97.72, 30.27], + ], + steps: [ + { instruction: 'Depart', lat: 30.26, lon: -97.74 }, + { instruction: 'Turn left', lat: 30.27, lon: -97.73 }, + { instruction: 'Arrive', lat: 30.27, lon: -97.72 }, + ], + }), + }, + services: { + render: { + governorRequestRender: noop, + holdContinuousRender: noop, + releaseContinuousRender: noop, + }, + sprites: { + registerSpriteSet: (layerId, setId) => { + sprites.push([layerId, setId]); + return { drawSetId: setId }; + }, + unregisterSpriteCollection: noop, + restoreSpriteOrder: noop, + }, + picking: { registerPickOwner: noop, unregisterPickOwner: noop }, + overlays: { + setOverlayEntries: (source, entries) => + overlays.push([source, entries]), + setOverlaySourceVisible: noop, + clearOverlaySource: noop, + }, + ground: { + GROUND_FLOOR_LIFT_M: 2, + cachedGroundFloor: () => 150, + warmGroundFloor: noop, + resolveGroundFloorCells: async () => {}, + }, + input: ownership, + camera: {}, + }, + }); + ownership.resetPointerOwnership(); + // Let go even when an assertion fails, so nothing leaks into later tests. + t.after(() => { + layer.destroy(viewer); + clicks.destroy(); + ownership.resetPointerOwnership(); + }); + layer.init(viewer); + layer.enable(viewer); + layer.placeEndpoint('a', { lat: 30.26, lon: -97.74 }); + layer.placeEndpoint('b', { lat: 30.27, lon: -97.72 }); + + const hostOf = (suffix) => + scene.added.find((host) => host.drawSetId?.endsWith(suffix)); + // The route is asked for, then drawn. + const deadline = Date.now() + 5000; + while (!(hostOf(':route')?.length > 0) && Date.now() < deadline) + await new Promise((resolve) => setTimeout(resolve, 5)); + // A and B: dots on the ground, drawn over everything. + const markers = hostOf(':markers'); + assert.ok(markers instanceof Cesium.BillboardCollection); + assert.equal(markers.length, 2); + const a = markers.get(0); + assert.equal(a.id.id, 'directions:marker:A'); + assert.equal(a.disableDepthTestDistance, Infinity); + assert.equal(a.heightReference, Cesium.HeightReference.CLAMP_TO_GROUND); + // The route: the annotation's flowing dashes, draped on everything. + const route = hostOf(':route'); + const ground = route.get(1); + assert.ok(ground instanceof Cesium.GroundPolylinePrimitive); + assert.equal(ground.classificationType, Cesium.ClassificationType.BOTH); + assert.equal(ground.geometryInstances[0].geometry.width, 9); + assert.equal(ground.geometryInstances[0].id.id, 'directions:route'); + const flow = ground.appearance.material.uniforms; + assert.deepEqual( + [flow.repeat, flow.duty, flow.speed, flow.color.alpha], + [64, 0.46, 0.55, 0.95], + ); + // One maneuver dot, at its junction on the ground floor, in the sprite + // order. + const steps = hostOf(':steps'); + assert.ok(steps instanceof Cesium.PointPrimitiveCollection); + assert.equal(steps.blendOption, Cesium.BlendOption.TRANSLUCENT); + assert.deepEqual(sprites, [['directions', steps.drawSetId]]); + assert.equal(steps.length, 1); + const dot = steps.get(0); + assert.equal(dot.id.id, 'directions:step:1'); + assert.equal(dot.show, true); + assert.equal(dot.pixelSize, 8); + assert.equal(dot.disableDepthTestDistance, Infinity); + const at = Cesium.Cartographic.fromCartesian(dot.position); + assert.ok(Math.abs(at.height - 152) < 1e-6, 'floor plus its lift'); + + // A click on the dot opens its card and enlarges it, in place. + scene.pickResult = { primitive: dot, id: dot.id }; + clicks.click({ x: 10, y: 10 }); + assert.equal(steps.get(0), dot, 'the same point'); + assert.equal(dot.pixelSize, 13); + const card = overlays.findLast(([source]) => source === 'directions-step'); + assert.equal(card[1][0].id, 'directions-step-1'); + // Empty map closes it. + scene.pickResult = undefined; + clicks.click({ x: 10, y: 10 }); + assert.equal(dot.pixelSize, 8); + + layer.disable(viewer); + assert.equal(hostOf(':markers').length, 0, 'markers cleared'); + layer.destroy(viewer); + clicks.destroy(); + ownership.resetPointerOwnership(); + assert.equal(scene.added.length, 0, 'every set let go'); + } +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 5f0298ed0..ccf441c8e 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -34,7 +34,6 @@ "src/input/sensorPick.js", "src/layers/cctv/projection.js", "src/layers/cctv/rendering.js", - "src/layers/directions/index.js", "src/layers/firms/rendering.js", "src/layers/flights/enrichment.js", "src/layers/flights/evidence.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index efea3be0a..e3429cf6d 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -84,6 +84,7 @@ const DRAW_FROM_CALLER = new Set([ './layers/street-level/kartaview', './layers/street-level/panoramax', './layers/air-quality', + './layers/directions', // Its data packs draw through `drawOf`; its flights ask `cameraOf`, which // throws until then too. './scenes',