diff --git a/src/data/bhoteKoshiLocator.js b/src/data/bhoteKoshiLocator.js index e504375e8..81c3e3a19 100644 --- a/src/data/bhoteKoshiLocator.js +++ b/src/data/bhoteKoshiLocator.js @@ -1,10 +1,13 @@ -import * as Cesium from 'cesium'; import { clearOverlaySource, setOverlayEntries, } from '../overlays/worldOverlay.js'; import { governorRequestRender } from '../renderGovernor.js'; -import { cameraOf } from '../render/cesium/camera.js'; +import { drawOf, findCamera } from '../render/rendererOf.js'; +import { hexColor } from '../render/color.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { toRadians } from '../geo/vector.js'; +import { lengthFraction } from '../geo/polyline.js'; import { BHOTE_KOSHI_LOCATOR_CREDIT, registerDynamicCredit, @@ -145,10 +148,11 @@ const NEARBY_CITIES = Object.freeze([ placement: 'right-lower', }), ]); -const BORDER_COLOR = Cesium.Color.fromCssColorString('#20e7f2'); const BORDER_ACCENT = '#20e7f2'; const INCIDENT_ACCENT = '#ffad55'; -const INCIDENT_COLOR = Cesium.Color.fromCssColorString(INCIDENT_ACCENT); + +// Each layer's draw sets have ids of their own. +let layerSerial = 0; const DEFAULT_OVERLAY_HOST = Object.freeze({ setEntries: setOverlayEntries, @@ -195,10 +199,6 @@ function presentationUsesBoundary(value) { ); } -function presentationAnimatesBoundary(value) { - return value === BHOTE_KOSHI_REGIONAL_PRESENTATION; -} - function smoothstep(from, to, value) { if (to <= from) return value >= to ? 1 : 0; const amount = Math.max(0, Math.min(1, (value - from) / (to - from))); @@ -220,26 +220,21 @@ export function anchoredCalloutPresentation(elapsedMs) { }; } -/** Return the progressive prefix used by the animated Nepal border. */ -export function revealPolylinePositions(positions, progress) { - if (!Array.isArray(positions) || positions.length < 2) return []; +/** + * How much of a line's length is drawn when it is revealed vertex by + * vertex: `progress` of its vertices (the head between two of them), as a + * fraction of its length, for the draw port's `revealFraction`. + * @param {Array<{x: number, y: number, z: number}>} positions + * @param {number} progress 0..1 + */ +export function revealLengthFraction(positions, progress) { + if (!Array.isArray(positions) || positions.length < 2) return 0; const clamped = Math.max(0, Math.min(1, Number(progress) || 0)); - if (clamped >= 1) return positions; + if (clamped >= 1) return 1; + if (clamped <= 0) return 0; const scaled = clamped * (positions.length - 1); - const completed = Math.floor(scaled); - const revealed = positions.slice(0, completed + 1); - const next = Math.min(completed + 1, positions.length - 1); - if (next > completed) { - revealed.push( - Cesium.Cartesian3.lerp( - positions[completed], - positions[next], - scaled - completed, - new Cesium.Cartesian3(), - ), - ); - } - return revealed.length >= 2 ? revealed : [positions[0], positions[0]]; + const index = Math.floor(scaled); + return lengthFraction(positions, index, scaled - index); } /** Close a region ring without duplicating an already-closed final vertex. */ @@ -286,14 +281,27 @@ export function createBhoteKoshiLocatorLayer({ cancelDelay = (handle) => clearTimeout(handle), } = {}) { let _viewer = null; - let _dataSource = null; + const _serial = ++layerSerial; + // Whether the layer draws: from enable until it is let go. + let _drawing = false; + let _sets = null; + // What the presentation draws, each item worked out for the time now: + // pulsing halos, lines revealed as they grow, and the country fill, drawn + // once it is due. + let _halos = []; + let _lines = []; + let _fill = null; + let _fillShown = false; + // Each line's reveal and show as last drawn. + const _drawnLines = new Map(); + // Each halo's look as last drawn. + const _drawnHalos = new Map(); let _enabled = false; let _boundaryReady = false; let _boundaryResolved = false; let _boundaryRing = null; let _generation = 0; let _presentation = BHOTE_KOSHI_REGIONAL_PRESENTATION; - let _borderAnimationFrame = null; let _calloutPulseFrame = null; let _triggerApproachTimer = null; let _removeTriggerMoveStart = null; @@ -333,30 +341,164 @@ export function createBhoteKoshiLocatorLayer({ _removeTriggerMoveEnd = null; const wasInFlight = _triggerApproachInFlight; _triggerApproachInFlight = false; - if (wasInFlight) _viewer?.camera?.cancelFlight?.(); + if (wasInFlight) findCamera(_viewer)?.cancelFlight(); if (!preserveCallout) _triggerCalloutStartedAt = Number.POSITIVE_INFINITY; } function stopAnimations() { - if (_borderAnimationFrame !== null) cancelFrame(_borderAnimationFrame); if (_calloutPulseFrame !== null) cancelFrame(_calloutPulseFrame); - _borderAnimationFrame = null; _calloutPulseFrame = null; _placeRevealMoving = false; _placeRevealSettledAt = Number.POSITIVE_INFINITY; clearTriggerApproach(); } - function removeDataSource() { + function removeDrawn() { stopAnimations(); overlayHost.clearSource(BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID); - if (_dataSource && _viewer?.dataSources) - _viewer.dataSources.remove(_dataSource, true); - _dataSource = null; + if (_sets) for (const set of Object.values(_sets)) set.dispose(); + _sets = null; + _drawing = false; + resetDrawn(); + } + + function resetDrawn() { + _halos = []; + _lines = []; + _fill = null; + _fillShown = false; + _drawnLines.clear(); + _drawnHalos.clear(); + } + + /** The layer's draw sets, made on first use: fill under lines under halos. */ + function drawSets() { + if (_sets) return _sets; + const draw = drawOf(_viewer); + const prefix = `${BHOTE_KOSHI_LOCATOR_LAYER_ID}:${_serial}`; + // Presentation only: clicks go through to what is under them. + _sets = { + fill: draw.shapes({ id: `${prefix}:fill`, pickable: false }), + lines: draw.lines({ id: `${prefix}:lines`, pickable: false }), + halos: draw.points({ id: `${prefix}:halos`, pickable: false }), + }; + return _sets; + } + + /** Draw the presentation as it now stands, in place of what was drawn. */ + function commitDrawn() { + const sets = drawSets(); + _drawnLines.clear(); + _fillShown = Boolean(_fill?.visible()); + sets.fill.set(_fillShown ? [_fill.item] : []); + sets.lines.set( + _lines.map((line) => { + const item = line(); + _drawnLines.set(item.id, lineKey(item)); + return item; + }), + ); + _drawnHalos.clear(); + sets.halos.set( + _halos.map((halo) => { + const item = halo(); + _drawnHalos.set(item.id, haloKey(item)); + return item; + }), + ); + } + + const haloKey = (item) => + `${item.pixelSize}:${item.color}:${item.outlineColor}:${item.show}`; + + const lineKey = (item) => `${item.revealFraction}:${item.show !== false}`; + + /** + * Bring what is drawn to the time now: halos pulse, lines that grew or + * showed are changed in place, and the fill shows once it is due. + */ + function syncDrawn() { + if (!_drawing || !_sets) return; + if (!_fillShown && _fill?.visible()) { + _fillShown = true; + _sets.fill.set([_fill.item]); + } + const changed = []; + for (const line of _lines) { + const item = line(); + const key = lineKey(item); + if (_drawnLines.get(item.id) === key) continue; + _drawnLines.set(item.id, key); + changed.push(item); + } + if (changed.length) _sets.lines.upsert(changed); + const pulsed = []; + for (const halo of _halos) { + const item = halo(); + const key = haloKey(item); + if (_drawnHalos.get(item.id) === key) continue; + _drawnHalos.set(item.id, key); + pulsed.push(item); + } + if (pulsed.length) _sets.halos.upsert(pulsed); + } + + /** + * A pulsing halo point: `progress()` (0..1) sizes it and fades its fill + * and ring (`fillAlpha`, `ringAlpha`), shown while `visible()`. + */ + function addHalo({ + id, + subject, + color, + visible, + progress, + fillAlpha, + ringAlpha, + scaleByDistance, + }) { + const pos = { lon: subject.lon, lat: subject.lat, height: subject.heightM }; + _halos.push(() => { + const p = progress(); + return { + id, + pos, + pixelSize: CALLOUT_RING_MIN_SIZE_PX + CALLOUT_RING_SIZE_RANGE_PX * p, + color: hexColor(color, fillAlpha(p)), + outlineColor: hexColor(color, ringAlpha(p)), + outlineWidth: 2, + disableDepthTest: Number.POSITIVE_INFINITY, + scaleByDistance, + show: visible(), + }; + }); + } + + /** + * A draped line revealed vertex by vertex as `progress()` runs 0..1, + * shown while `visible()`. + */ + function addRevealedLine({ + id, + positions, + widthPx, + color, + progress, + visible, + }) { + _lines.push(() => ({ + id, + positions, + widthPx, + mode: 'draped', + clampTo: 'both', + style: { kind: 'solid', color }, + revealFraction: revealLengthFraction(positions, progress()), + show: visible(), + })); } function addCallout( - dataSource, subject, color, { @@ -366,51 +508,27 @@ export function createBhoteKoshiLocatorLayer({ showAnchor = true, } = {}, ) { - const position = Cesium.Cartesian3.fromDegrees( - subject.lon, - subject.lat, - subject.heightM, - ); + const position = fromDegrees(subject.lon, subject.lat, subject.heightM); const visibleAt = sequenceStartedAt + visibleAfterMs; const isVisible = () => now() >= visibleAt; const pulseProgress = () => { const elapsed = Math.max(0, now() - visibleAt); return (elapsed % CALLOUT_PULSE_DURATION_MS) / CALLOUT_PULSE_DURATION_MS; }; - const ringSize = new Cesium.CallbackProperty(() => { - return ( - CALLOUT_RING_MIN_SIZE_PX + CALLOUT_RING_SIZE_RANGE_PX * pulseProgress() - ); - }, false); - const ringColor = new Cesium.CallbackProperty((_time, result) => { - const dynamicColor = Cesium.Color.clone(color, result); - dynamicColor.alpha = isVisible() ? 0.14 * (1 - pulseProgress()) : 0; - return dynamicColor; - }, false); - const ringOutlineColor = new Cesium.CallbackProperty((_time, result) => { - const dynamicColor = Cesium.Color.clone(color, result); - dynamicColor.alpha = isVisible() - ? 0.08 + 0.72 * (1 - pulseProgress()) - : 0; - return dynamicColor; - }, false); if (showAnchor) { - dataSource.entities.add({ + addHalo({ id: `${subject === INCIDENT ? 'bhote-koshi-incident' : 'nepal-context'}-halo`, - position, - show: new Cesium.CallbackProperty(isVisible, false), - point: { - pixelSize: ringSize, - color: ringColor, - outlineColor: ringOutlineColor, - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar( - 250000, - 0.8, - 25000000, - 1.35, - ), + subject, + color, + visible: isVisible, + progress: pulseProgress, + fillAlpha: (p) => (isVisible() ? 0.14 * (1 - p) : 0), + ringAlpha: (p) => (isVisible() ? 0.08 + 0.72 * (1 - p) : 0), + scaleByDistance: { + near: 250000, + nearValue: 0.8, + far: 25000000, + farValue: 1.35, }, }); } @@ -499,25 +617,22 @@ export function createBhoteKoshiLocatorLayer({ _placeRevealSettledAt = Number.POSITIVE_INFINITY; publishOverlayEntries(); } + syncDrawn(); requestRender('bhote-koshi-locator-callout-pulse'); _calloutPulseFrame = scheduleFrame(pulseFrame); }; _calloutPulseFrame = scheduleFrame(pulseFrame); } - function addIncidentCallout( - dataSource, - sequenceStartedAt, - visibleAfterMs = 0, - ) { - addCallout(dataSource, INCIDENT, INCIDENT_COLOR, { + function addIncidentCallout(sequenceStartedAt, visibleAfterMs = 0) { + addCallout(INCIDENT, INCIDENT_ACCENT, { sequenceStartedAt, visibleAfterMs, }); } - function addTriggerRecordCallout(dataSource) { - const position = Cesium.Cartesian3.fromDegrees( + function addTriggerRecordCallout() { + const position = fromDegrees( TRIGGER_RECORD.lon, TRIGGER_RECORD.lat, TRIGGER_RECORD.heightM, @@ -532,30 +647,19 @@ export function createBhoteKoshiLocatorLayer({ CALLOUT_PULSE_DURATION_MS ); }; - dataSource.entities.add({ + addHalo({ id: 'bhote-koshi-trigger-record-halo', - position, - show: new Cesium.CallbackProperty(isVisible, false), - point: { - pixelSize: new Cesium.CallbackProperty( - () => - CALLOUT_RING_MIN_SIZE_PX + - CALLOUT_RING_SIZE_RANGE_PX * pulseProgress(), - false, - ), - color: new Cesium.CallbackProperty((_time, result) => { - const color = Cesium.Color.clone(INCIDENT_COLOR, result); - color.alpha = 0.16 * (1 - pulseProgress()); - return color; - }, false), - outlineColor: new Cesium.CallbackProperty((_time, result) => { - const color = Cesium.Color.clone(INCIDENT_COLOR, result); - color.alpha = isVisible() ? 0.08 + 0.78 * (1 - pulseProgress()) : 0; - return color; - }, false), - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar(3000, 1, 250000, 0.82), + subject: TRIGGER_RECORD, + color: INCIDENT_ACCENT, + visible: isVisible, + progress: pulseProgress, + fillAlpha: (p) => 0.16 * (1 - p), + ringAlpha: (p) => (isVisible() ? 0.08 + 0.78 * (1 - p) : 0), + scaleByDistance: { + near: 3000, + nearValue: 1, + far: 250000, + farValue: 0.82, }, }); queueOverlayEntry({ @@ -619,9 +723,8 @@ export function createBhoteKoshiLocatorLayer({ _removeTriggerMoveEnd = null; _triggerCalloutStartedAt = now(); requestRender('bhote-koshi-trigger-record-reveal'); - const camera = _viewer?.camera; - if (!camera?.flyTo) return; - const port = cameraOf(_viewer); + const port = findCamera(_viewer); + if (!port) return; const generation = _generation; _triggerApproachInFlight = true; const finish = () => { @@ -637,9 +740,9 @@ export function createBhoteKoshiLocatorLayer({ }, { orientation: { - heading: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.heading), - pitch: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.pitch), - roll: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.roll), + heading: toRadians(TRIGGER_APPROACH_CAMERA.heading), + pitch: toRadians(TRIGGER_APPROACH_CAMERA.pitch), + roll: toRadians(TRIGGER_APPROACH_CAMERA.roll), }, durationS: TRIGGER_APPROACH_DURATION_SEC, easing: 'cubicInOut', @@ -663,9 +766,9 @@ export function createBhoteKoshiLocatorLayer({ }, { orientation: { - heading: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.heading), - pitch: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.pitch), - roll: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.roll), + heading: toRadians(TRIGGER_ORBIT_CAMERA.heading), + pitch: toRadians(TRIGGER_ORBIT_CAMERA.pitch), + roll: toRadians(TRIGGER_ORBIT_CAMERA.roll), }, durationS: TRIGGER_ORBIT_DURATION_SEC, easing: 'sineInOut', @@ -687,40 +790,36 @@ export function createBhoteKoshiLocatorLayer({ const attempt = { phase: 'armed' }; _triggerApproachAttempt = attempt; const start = () => startTriggerApproach(attempt); - const camera = _viewer?.camera; - if ( - !camera?.moveStart?.addEventListener || - !camera?.moveEnd?.addEventListener - ) { + const camera = findCamera(_viewer); + if (!camera) { start(); return; } - _removeTriggerMoveStart = camera.moveStart.addEventListener(() => { + _removeTriggerMoveStart = camera.on('moveStart', () => { if (_triggerApproachAttempt !== attempt || attempt.phase !== 'armed') return; if (_triggerApproachTimer !== null) cancelDelay(_triggerApproachTimer); _triggerApproachTimer = null; _removeTriggerMoveStart?.(); _removeTriggerMoveStart = null; - _removeTriggerMoveEnd = camera.moveEnd.addEventListener(start); + _removeTriggerMoveEnd = camera.on('moveEnd', start); }); _triggerApproachTimer = scheduleDelay(start, TRIGGER_APPROACH_ARM_MS); } function addNepalCallout( - dataSource, sequenceStartedAt = now(), labelPlacement = 'right', { showAnchor = true } = {}, ) { - addCallout(dataSource, NEPAL, BORDER_COLOR, { + addCallout(NEPAL, BORDER_ACCENT, { labelPlacement, sequenceStartedAt, showAnchor, }); } - function addNearbyCityCallouts(dataSource, sequenceStartedAt) { + function addNearbyCityCallouts(sequenceStartedAt) { NEARBY_CITIES.forEach((city, index) => { const visibleAt = sequenceStartedAt + @@ -730,11 +829,7 @@ export function createBhoteKoshiLocatorLayer({ smoothstep(0, 1, (now() - visibleAt) / CITY_CALLOUT_REVEAL_MS); const labelOnLeft = city.placement === 'left'; const labelLower = city.placement === 'right-lower'; - const position = Cesium.Cartesian3.fromDegrees( - city.lon, - city.lat, - city.heightM, - ); + const position = fromDegrees(city.lon, city.lat, city.heightM); queueOverlayEntry({ id: `bhote-koshi-city-${city.id}`, position, @@ -771,7 +866,6 @@ export function createBhoteKoshiLocatorLayer({ } function addIncidentPlaceCallouts( - dataSource, sequenceStartedAt, { pulseHalos = false, places = INCIDENT_OVERVIEW_PLACES } = {}, ) { @@ -784,11 +878,7 @@ export function createBhoteKoshiLocatorLayer({ smoothstep(0, 1, (now() - visibleAt) / PLACE_CALLOUT_REVEAL_MS); const labelOnLeft = place.placement === 'left'; const labelLower = place.placement === 'right-lower'; - const position = Cesium.Cartesian3.fromDegrees( - place.lon, - place.lat, - place.heightM, - ); + const position = fromDegrees(place.lon, place.lat, place.heightM); if (pulseHalos) { const pulseSequenceDurationMs = PLACE_CALLOUT_STAGGER_MS * places.length; @@ -816,30 +906,19 @@ export function createBhoteKoshiLocatorLayer({ Math.min(1, pulseWindowElapsed() / PLACE_CALLOUT_STAGGER_MS), ); }; - dataSource.entities.add({ + addHalo({ id: `bhote-koshi-place-${place.id}-halo`, - position, - show: new Cesium.CallbackProperty(pulseIsActive, false), - point: { - pixelSize: new Cesium.CallbackProperty( - () => - CALLOUT_RING_MIN_SIZE_PX + - CALLOUT_RING_SIZE_RANGE_PX * pulseProgress(), - false, - ), - color: new Cesium.CallbackProperty((_time, result) => { - const color = Cesium.Color.clone(INCIDENT_COLOR, result); - color.alpha = 0.16 * (1 - pulseProgress()); - return color; - }, false), - outlineColor: new Cesium.CallbackProperty((_time, result) => { - const color = Cesium.Color.clone(INCIDENT_COLOR, result); - color.alpha = 0.08 + 0.78 * (1 - pulseProgress()); - return color; - }, false), - outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar(5000, 1, 500000, 0.82), + subject: place, + color: INCIDENT_ACCENT, + visible: pulseIsActive, + progress: pulseProgress, + fillAlpha: (p) => 0.16 * (1 - p), + ringAlpha: (p) => 0.08 + 0.78 * (1 - p), + scaleByDistance: { + near: 5000, + nearValue: 1, + far: 500000, + farValue: 0.82, }, }); } @@ -878,105 +957,67 @@ export function createBhoteKoshiLocatorLayer({ }); } - function addIncidentFloodPath(dataSource, sequenceStartedAt) { + function addIncidentFloodPath(sequenceStartedAt) { const positions = BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) => - Cesium.Cartesian3.fromDegrees(lon, lat), + fromDegrees(lon, lat), ); const drawStartedAt = sequenceStartedAt + FLOOD_PATH_START_DELAY_MS; - const animatedPositions = new Cesium.CallbackProperty( - () => - revealPolylinePositions( - positions, - (now() - drawStartedAt) / FLOOD_PATH_DRAW_DURATION_MS, - ), - false, - ); - dataSource.entities.add({ + addRevealedLine({ id: 'bhote-koshi-flood-path', - show: new Cesium.CallbackProperty(() => now() >= drawStartedAt, false), - polyline: { - positions: animatedPositions, - width: 3.5, - clampToGround: true, - material: BORDER_COLOR.withAlpha(0.96), - classificationType: Cesium.ClassificationType.BOTH, - }, + positions, + widthPx: 3.5, + color: hexColor(BORDER_ACCENT, 0.96), + progress: () => (now() - drawStartedAt) / FLOOD_PATH_DRAW_DURATION_MS, + visible: () => now() >= drawStartedAt, }); } - function addNepalBoundary(dataSource, ring, sequenceStartedAt) { + function addNepalBoundary(ring, sequenceStartedAt) { const closed = closeRegionRing(ring); if (closed.length < 4) return false; - const positions = Cesium.Cartesian3.fromDegreesArray(closed.flat()); - const hierarchy = new Cesium.PolygonHierarchy(positions.slice(0, -1)); + const positions = closed.map(([lon, lat]) => fromDegrees(lon, lat)); const drawStartedAt = sequenceStartedAt + BORDER_START_DELAY_MS; - const animatedPositions = new Cesium.CallbackProperty( - () => - revealPolylinePositions( - positions, - (now() - drawStartedAt) / BORDER_DRAW_DURATION_MS, - ), - false, - ); - dataSource.entities.add({ - id: 'nepal-border-fill', - show: new Cesium.CallbackProperty(() => now() >= drawStartedAt, false), - polygon: { - hierarchy, - material: BORDER_COLOR.withAlpha(0.055), - classificationType: Cesium.ClassificationType.BOTH, + const progress = () => (now() - drawStartedAt) / BORDER_DRAW_DURATION_MS; + _fill = { + visible: () => now() >= drawStartedAt, + item: { + id: 'nepal-border-fill', + geometry: { + kind: 'polygon', + rings: [closed.slice(0, -1).map(([lon, lat]) => ({ lon, lat }))], + }, + fill: hexColor(BORDER_ACCENT, 0.055), + height: 'clampGround', + clampTo: 'both', }, - }); - dataSource.entities.add({ - id: 'nepal-border-halo', - polyline: { - positions: animatedPositions, - width: 5, - clampToGround: true, - material: BORDER_COLOR.withAlpha(0.12), - classificationType: Cesium.ClassificationType.BOTH, - }, - }); - dataSource.entities.add({ - id: 'nepal-border-highlight', - polyline: { - positions: animatedPositions, - width: 2.5, - clampToGround: true, - material: BORDER_COLOR.withAlpha(0.96), - classificationType: Cesium.ClassificationType.BOTH, - }, - }); - const generation = _generation; - const drawFrame = () => { - if ( - !_enabled || - generation !== _generation || - !presentationAnimatesBoundary(_presentation) - ) - return; - requestRender('bhote-koshi-locator-border-draw'); - if (now() - drawStartedAt < BORDER_DRAW_DURATION_MS) { - _borderAnimationFrame = scheduleFrame(drawFrame); - } else { - _borderAnimationFrame = null; - } }; - _borderAnimationFrame = scheduleFrame(drawFrame); + for (const [id, widthPx, alpha] of [ + ['nepal-border-halo', 5, 0.12], + ['nepal-border-highlight', 2.5, 0.96], + ]) + addRevealedLine({ + id, + positions, + widthPx, + color: hexColor(BORDER_ACCENT, alpha), + progress, + visible: () => true, + }); + // The callout pulse draws each step of the reveal (`syncDrawn`). return true; } function renderPresentation() { - if (!_dataSource) return; + if (!_drawing) return; stopAnimations(); overlayHost.clearSource(BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID); _overlayEntries = []; - _dataSource.entities.removeAll(); + resetDrawn(); if (_presentation === NEPAL_CONTEXT_PRESENTATION) { - addNepalCallout(_dataSource); + addNepalCallout(); } else if (_presentation === BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION) { const sequenceStartedAt = now(); - addIncidentPlaceCallouts(_dataSource, sequenceStartedAt, { + addIncidentPlaceCallouts(sequenceStartedAt, { pulseHalos: true, places: INCIDENT_OVERVIEW_PLACES, }); @@ -993,8 +1034,8 @@ export function createBhoteKoshiLocatorLayer({ PLACE_CALLOUT_START_DELAY_MS - (INCIDENT_OVERVIEW_PLACES.length - 1) * PLACE_CALLOUT_STAGGER_MS - PLACE_CALLOUT_REVEAL_MS; - addIncidentFloodPath(_dataSource, sequenceStartedAt); - addIncidentPlaceCallouts(_dataSource, settledPlacesAt); + addIncidentFloodPath(sequenceStartedAt); + addIncidentPlaceCallouts(settledPlacesAt); } else if (_presentation === BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION) { const sequenceStartedAt = now(); const settledPathAt = @@ -1006,21 +1047,22 @@ export function createBhoteKoshiLocatorLayer({ PLACE_CALLOUT_START_DELAY_MS - (INCIDENT_OVERVIEW_PLACES.length - 1) * PLACE_CALLOUT_STAGGER_MS - PLACE_CALLOUT_REVEAL_MS; - addIncidentFloodPath(_dataSource, settledPathAt); - addIncidentPlaceCallouts(_dataSource, settledPlacesAt); + addIncidentFloodPath(settledPathAt); + addIncidentPlaceCallouts(settledPlacesAt); } else if (_presentation === BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION) { const sequenceStartedAt = now(); const settledPathAt = sequenceStartedAt - FLOOD_PATH_START_DELAY_MS - FLOOD_PATH_DRAW_DURATION_MS; - addIncidentFloodPath(_dataSource, settledPathAt); - addTriggerRecordCallout(_dataSource); + addIncidentFloodPath(settledPathAt); + addTriggerRecordCallout(); armTriggerApproach(); } else { const sequenceStartedAt = now(); - addNepalCallout(_dataSource, sequenceStartedAt, 'left'); + addNepalCallout(sequenceStartedAt, 'left'); if (!_boundaryResolved) { + commitDrawn(); publishOverlayEntries(); startCalloutAnimation(); requestRender('bhote-koshi-locator-presentation'); @@ -1029,24 +1071,20 @@ export function createBhoteKoshiLocatorLayer({ if (_presentation === BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION) { const settledAt = sequenceStartedAt - BORDER_START_DELAY_MS - BORDER_DRAW_DURATION_MS; - if (_boundaryRing) - addNepalBoundary(_dataSource, _boundaryRing, settledAt); - addIncidentCallout( - _dataSource, - sequenceStartedAt - CALLOUT_REVEAL_DURATION_MS, - ); - addNearbyCityCallouts(_dataSource, sequenceStartedAt); + if (_boundaryRing) addNepalBoundary(_boundaryRing, settledAt); + addIncidentCallout(sequenceStartedAt - CALLOUT_REVEAL_DURATION_MS); + addNearbyCityCallouts(sequenceStartedAt); } else { - if (_boundaryRing) - addNepalBoundary(_dataSource, _boundaryRing, sequenceStartedAt); + if (_boundaryRing) addNepalBoundary(_boundaryRing, sequenceStartedAt); const incidentDelayMs = _boundaryRing ? BORDER_START_DELAY_MS + BORDER_DRAW_DURATION_MS + INCIDENT_CALLOUT_GAP_MS : BORDER_START_DELAY_MS; - addIncidentCallout(_dataSource, sequenceStartedAt, incidentDelayMs); + addIncidentCallout(sequenceStartedAt, incidentDelayMs); } } + commitDrawn(); publishOverlayEntries({ moving: _placeRevealMoving }); startCalloutAnimation(); requestRender('bhote-koshi-locator-presentation'); @@ -1064,11 +1102,9 @@ export function createBhoteKoshiLocatorLayer({ _boundaryResolved = false; _boundaryRing = null; const generation = ++_generation; - removeDataSource(); - const dataSource = new Cesium.CustomDataSource('bhote-koshi-locator'); - _dataSource = dataSource; + removeDrawn(); + _drawing = true; renderPresentation(); - viewer.dataSources.add(dataSource); registerDynamicCredit(viewer, BHOTE_KOSHI_LOCATOR_CREDIT); showOsmCredit(viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID); requestRender('bhote-koshi-locator-callout'); @@ -1090,7 +1126,7 @@ export function createBhoteKoshiLocatorLayer({ return true; } catch (error) { if (error?.name === 'AbortError') { - if (generation === _generation) removeDataSource(); + if (generation === _generation) removeDrawn(); throw error; } console.warn( @@ -1112,7 +1148,7 @@ export function createBhoteKoshiLocatorLayer({ _boundaryResolved = false; _boundaryRing = null; _generation += 1; - removeDataSource(); + removeDrawn(); requestRender('bhote-koshi-locator-disable'); return true; } diff --git a/src/data/bhoteKoshiLocator.test.mjs b/src/data/bhoteKoshiLocator.test.mjs index 439d4fe7f..a24afefee 100644 --- a/src/data/bhoteKoshiLocator.test.mjs +++ b/src/data/bhoteKoshiLocator.test.mjs @@ -1,4 +1,6 @@ import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { bindRenderer } from '../render/rendererOf.js'; import assert from 'node:assert/strict'; import test from 'node:test'; import { readFile } from 'node:fs/promises'; @@ -25,32 +27,58 @@ import { createBhoteKoshiLocatorLayer, largestGeoJsonRing, NEPAL_CONTEXT_PRESENTATION, - revealPolylinePositions, + revealLengthFraction, } from './bhoteKoshiLocator.js'; -function viewerFixture() { - const added = []; - const removed = []; - return { +/** + * A viewer with a fake draw port bound; with `camera`, the Cesium camera + * port over that fake camera too. `_test` reads what is drawn: every live + * item by id (`drawn`), and `sets` of the layer. + */ +function viewerFixture({ camera } = {}) { + const draw = fakeDrawPort(); + const viewer = { creditDisplay: { addStaticCredit() {}, removeStaticCredit() {} }, - dataSources: { - add(source) { - added.push(source); - }, - remove(source) { - removed.push(source); - }, - }, - _test: { added, removed }, }; + if (camera) { + viewer.camera = camera; + bindFakeCesiumCamera(viewer, { draw }); + } else bindRenderer(viewer, { draw }); + const live = () => + [...draw.sets.values()].filter( + (set) => !set.disposed && set.spec.id.startsWith('bhote-koshi-locator:'), + ); + viewer._test = { + draw, + live, + /** Every live item, by id. */ + drawn() { + const items = new Map(); + for (const set of live()) + for (const [id, item] of set.items) items.set(id, item); + return items; + }, + ids: () => [...viewer._test.drawn().keys()], + item: (id) => viewer._test.drawn().get(id), + }; + return viewer; } +/** Frames that run only when a test ticks them. */ function nonRunningAnimation() { + let queued = []; return { - scheduleFrame() { - return 1; + scheduleFrame(callback) { + queued.push(callback); + return queued.length; }, cancelFrame() {}, + /** Run the frames asked for so far (each asks for its next). */ + tick() { + const run = queued; + queued = []; + for (const callback of run) callback(); + }, }; } @@ -133,21 +161,18 @@ test('Bhote Koshi locator selects the largest GeoJSON country exterior', () => { ); }); -test('Bhote Koshi locator reveals a border progressively', () => { +test('Bhote Koshi locator reveals a border progressively, vertex by vertex', () => { const positions = [ - new Cesium.Cartesian3(0, 0, 0), - new Cesium.Cartesian3(10, 0, 0), - new Cesium.Cartesian3(20, 0, 0), + { x: 0, y: 0, z: 0 }, + { x: 10, y: 0, z: 0 }, + { x: 40, y: 0, z: 0 }, ]; - assert.deepEqual(revealPolylinePositions(positions, 0), [ - positions[0], - positions[0], - ]); - assert.deepEqual(revealPolylinePositions(positions, 0.25), [ - positions[0], - new Cesium.Cartesian3(5, 0, 0), - ]); - assert.equal(revealPolylinePositions(positions, 1), positions); + assert.equal(revealLengthFraction(positions, 0), 0); + // A quarter of the vertices: halfway along the first, shorter segment. + assert.equal(revealLengthFraction(positions, 0.25), 5 / 40); + assert.equal(revealLengthFraction(positions, 0.75), 25 / 40); + assert.equal(revealLengthFraction(positions, 1), 1); + assert.equal(revealLengthFraction(positions.slice(0, 1), 0.5), 0); }); test('Bhote Koshi locator stages its anchored callout from dot to leader to text', () => { @@ -170,6 +195,7 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident', const overlayHost = overlayHostFixture(); const renders = []; let nowMs = 0; + const frames = nonRunningAnimation(); const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => ({ name: 'Nepal', @@ -183,24 +209,29 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident', requestRender: (reason) => renders.push(reason), overlayHost, now: () => nowMs, - ...nonRunningAnimation(), + ...frames, }); assert.equal(await layer.init(viewer), true); assert.equal(await layer.enable(viewer, { origin: 'scene' }), true); - assert.equal(viewer._test.added.length, 1); - const source = viewer._test.added[0]; - const ids = source.entities.values.map((entity) => entity.id); + const sets = viewer._test.live(); + assert.deepEqual( + sets.map(({ kind }) => kind), + ['shapes', 'lines', 'points'], + 'the fill under the lines under the halos', + ); + assert.ok(sets.every(({ spec }) => spec.pickable === false)); + // The fill is drawn once it is due, below. + const ids = viewer._test.ids(); for (const id of [ 'nepal-context-halo', - 'nepal-border-fill', 'nepal-border-highlight', 'bhote-koshi-incident-halo', ]) { assert.ok(ids.includes(id), `${id} belongs to the regional sequence`); } - const incidentHalo = source.entities.getById('bhote-koshi-incident-halo'); - const border = source.entities.getById('nepal-border-highlight'); + const incidentHalo = () => viewer._test.item('bhote-koshi-incident-halo'); + const border = () => viewer._test.item('nepal-border-highlight'); const publication = overlayHost._test.publications.at(-1); assert.equal(publication.sourceId, BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID); assert.equal(publication.entries.length, 2); @@ -226,15 +257,31 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident', assert.equal(incident.contentAlpha(), 0); assert.equal(incident.presentationScale(), 0.96); assert.equal(nepal.sourceAlpha(), 0); - assert.ok(border.polyline.positions.getValue().length < 5); - assert.equal(incidentHalo.show.getValue(), false); - assert.equal(incidentHalo.point.pixelSize.getValue(), 16); + assert.equal(border().revealFraction, 0); + assert.equal(border().mode, 'draped'); + assert.equal(border().positions.length, 5); + assert.equal(viewer._test.item('nepal-border-fill'), undefined); + assert.equal(incidentHalo().show, false); + assert.equal(incidentHalo().pixelSize, 16); + nowMs = 800; + frames.tick(); + const fill = viewer._test.item('nepal-border-fill'); + assert.equal(fill.height, 'clampGround', 'the fill, due, drapes'); + assert.equal(fill.geometry.rings[0].length, 4); + assert.ok(border().revealFraction > 0 && border().revealFraction < 0.1); nowMs = 3100; + frames.tick(); assert.equal(nepal.sourceAlpha(), 1); - assert.equal(border.polyline.positions.getValue().length, 5); - assert.equal(incidentHalo.show.getValue(), false); + assert.equal(border().revealFraction, 1); + assert.equal(incidentHalo().show, false); + const lines = sets.find(({ kind }) => kind === 'lines'); + const lineWrites = lines.writes; nowMs = 3300; - assert.equal(incidentHalo.show.getValue(), true); + frames.tick(); + frames.tick(); + assert.equal(lines.writes, lineWrites, 'settled lines are not drawn again'); + assert.equal(incidentHalo().show, true); + assert.equal(incidentHalo().disableDepthTest, Number.POSITIVE_INFINITY); assert.equal(incident.sourceAlpha(), 0); nowMs = 4500; assert.equal(incident.sourceAlpha(), 1); @@ -248,7 +295,7 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident', assert.ok(renders.includes('bhote-koshi-locator-boundary')); assert.equal(await layer.disable(), true); - assert.equal(viewer._test.removed.length, 1); + assert.equal(viewer._test.live().length, 0, 'its sets let go'); assert.equal( overlayHost._test.clears.at(-1), BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID, @@ -276,10 +323,7 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION }); await layer.enable(viewer); - assert.deepEqual( - viewer._test.added[0].entities.values.map((entity) => entity.id), - ['nepal-context-halo'], - ); + assert.deepEqual(viewer._test.ids(), ['nepal-context-halo']); const nepalLabel = overlayHost._test.publications.at(-1).entries[0]; assert.equal(nepalLabel.variant, 'label'); assert.equal(nepalLabel.placement, 'right'); @@ -299,11 +343,8 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide ); layer.setParams({ presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION }); - assert.ok(viewer._test.added[0].entities.getById('nepal-border-highlight')); - assert.equal( - viewer._test.added[0].entities.getById('bhote-koshi-city-kathmandu'), - undefined, - ); + assert.ok(viewer._test.item('nepal-border-highlight')); + assert.equal(viewer._test.item('bhote-koshi-city-kathmandu'), undefined); assert.equal( overlayHost._test.publications .at(-1) @@ -312,10 +353,7 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide ); layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION }); - assert.deepEqual( - viewer._test.added[0].entities.values.map((entity) => entity.id), - ['nepal-context-halo'], - ); + assert.deepEqual(viewer._test.ids(), ['nepal-context-halo']); await layer.destroy(); }); @@ -337,7 +375,10 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ }); layer.setParams({ presentation: BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION }); await layer.enable(viewer); - const source = viewer._test.added[0]; + const tick = () => { + const frame = pulseFrame; + frame?.(); + }; const event = JSON.parse( await readFile( new URL( @@ -349,7 +390,7 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ ); assert.equal(event.evidenceSpine.length, 16); assert.equal(event.evidenceSpine.at(-1).id, 'charaudi'); - assert.equal(source.entities.values.length, 15); + assert.equal(viewer._test.ids().length, 15); const labels = overlayHost._test.publications.at(-1).entries; assert.equal(labels.length, 15); assert.equal(overlayHost._test.publications.at(-1).options.moving, true); @@ -372,10 +413,11 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ nowMs = 349 + index * 650; assert.equal(pin.sourceAlpha(), 0); nowMs += 1; + tick(); assert.equal(pin.sourceAlpha(), 0); assert.equal( - source.entities.values.filter( - (entity) => entity.id.endsWith('-halo') && entity.show.getValue(), + [...viewer._test.drawn().values()].filter( + (item) => item.id.endsWith('-halo') && item.show, ).length, 1, ); @@ -385,10 +427,10 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ assert.ok(nowMs < INCIDENT_OVERVIEW_HOLD_SEC * 1000); // A repeat halo cycle must not erase already revealed labels. nowMs = 350 + 15 * 650; + tick(); assert.equal( - source.entities - .getById('bhote-koshi-place-immediate-collapse-viewpoint-halo') - .show.getValue(), + viewer._test.item('bhote-koshi-place-immediate-collapse-viewpoint-halo') + .show, true, ); assert.equal( @@ -406,9 +448,7 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ assert.equal(overlayHost._test.publications.at(-1).options.moving, false); layer.setParams({ presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION }); assert.equal( - source.entities.values.some((entity) => - entity.id.startsWith('bhote-koshi-place-'), - ), + viewer._test.ids().some((id) => id.startsWith('bhote-koshi-place-')), false, ); await layer.destroy(); @@ -458,18 +498,18 @@ test('Bhote Koshi flood path draws a solid cyan sourced route after the place sh const viewer = viewerFixture(); const overlayHost = overlayHostFixture(); let nowMs = 0; + const frames = nonRunningAnimation(); const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => null, requestRender() {}, overlayHost, now: () => nowMs, - ...nonRunningAnimation(), + ...frames, }); layer.setParams({ presentation: BHOTE_KOSHI_FLOOD_PATH_PRESENTATION }); await layer.enable(viewer); - const source = viewer._test.added[0]; - const path = source.entities.getById('bhote-koshi-flood-path'); + const path = () => viewer._test.item('bhote-koshi-flood-path'); const labels = overlayHost._test.publications.at(-1).entries; const trigger = labels.find( ({ id }) => id === 'bhote-koshi-place-immediate-collapse-viewpoint', @@ -478,46 +518,56 @@ test('Bhote Koshi flood path draws a solid cyan sourced route after the place sh ({ id }) => id === 'bhote-koshi-place-bidur-trishuli-bridge', ); - assert.equal(source.entities.values.length, 1); + assert.equal(viewer._test.ids().length, 1); assert.equal(labels.length, 15); assert.equal(bidur.title, '14 · BIDUR BRIDGE'); for (const place of INCIDENT_OVERVIEW_PLACES) { const pin = labels.find(({ id }) => id === `bhote-koshi-place-${place.id}`); assert.equal(pin.sourceAlpha(), 1, place.id); } - assert.equal(path.polyline.clampToGround.getValue(), true); - assert.ok(path.polyline.material instanceof Cesium.ColorMaterialProperty); + assert.equal(path().mode, 'draped'); + assert.equal(path().clampTo, 'both'); + assert.equal(path().widthPx, 3.5); + assert.equal(path().style.kind, 'solid'); + const color = Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96); assert.ok( - path.polyline.material.color - .getValue() - .equalsEpsilon( - Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96), + path().style.color.every( + (value, i) => + Math.abs(value - Cesium.Color.pack(color, [])[i]) < Cesium.Math.EPSILON7, - ), + ), ); - assert.equal(path.show.getValue(), false); + assert.equal(path().show, false); assert.equal(trigger.sourceAlpha(), 1); assert.equal(bidur.sourceAlpha(), 1); nowMs = 250; - assert.equal(path.show.getValue(), true); - assert.equal(path.polyline.positions.getValue().length, 2); + frames.tick(); + assert.equal(path().show, true); + assert.equal(path().revealFraction, 0); nowMs = 2250; - const halfwayCount = path.polyline.positions.getValue().length; - assert.ok(Math.abs(halfwayCount - BHOTE_KOSHI_FLOOD_PATH.length / 2) <= 2); + frames.tick(); + // Halfway through its vertices. + const positions = path().positions; + assert.equal(path().revealFraction, revealLengthFraction(positions, 0.5)); + assert.ok(path().revealFraction > 0.2 && path().revealFraction < 0.8); nowMs = 4250; - assert.equal( - path.polyline.positions.getValue().length, - BHOTE_KOSHI_FLOOD_PATH.length, - ); + frames.tick(); + assert.equal(path().revealFraction, 1); assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH[0], [85.48476, 28.33255]); // More observation pins must not extend or straighten the sourced route. - assert.deepEqual( - path.polyline.positions.getValue(), - BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) => - Cesium.Cartesian3.fromDegrees(lon, lat), - ), - ); + assert.equal(positions.length, BHOTE_KOSHI_FLOOD_PATH.length); + positions.forEach((position, i) => { + const [lon, lat] = BHOTE_KOSHI_FLOOD_PATH[i]; + assert.ok( + Cesium.Cartesian3.equalsEpsilon( + position, + Cesium.Cartesian3.fromDegrees(lon, lat), + 0, + 1e-6, + ), + ); + }); assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH.at(-1), [85.14943, 27.92177]); assert.equal(layer.getStats().coverage, 'Bhote Koshi · Flood path'); assert.deepEqual(layer.getParams(), { @@ -548,11 +598,10 @@ test('Bhote Koshi path-overview presentation keeps the route settled without Nep layer.setParams({ presentation: BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION }); await layer.enable(viewer); - const source = viewer._test.added[0]; - const path = source.entities.getById('bhote-koshi-flood-path'); + const path = viewer._test.item('bhote-koshi-flood-path'); const labels = overlayHost._test.publications.at(-1).entries; - assert.equal(source.entities.values.length, 1); + assert.equal(viewer._test.ids().length, 1); assert.equal(labels.length, 15); for (const [index, place] of INCIDENT_OVERVIEW_PLACES.entries()) { const pin = labels.find(({ id }) => id === `bhote-koshi-place-${place.id}`); @@ -562,23 +611,21 @@ test('Bhote Koshi path-overview presentation keeps the route settled without Nep ); assert.equal(pin.sourceAlpha(), 1); } - assert.equal(path.show.getValue(), true); - assert.equal( - path.polyline.positions.getValue().length, - BHOTE_KOSHI_FLOOD_PATH.length, - ); + assert.equal(path.show, true); + assert.equal(path.revealFraction, 1); + assert.equal(path.positions.length, BHOTE_KOSHI_FLOOD_PATH.length); assert.ok( - Cesium.Cartesian3.equals( - path.polyline.positions.getValue()[0], + Cesium.Cartesian3.equalsEpsilon( + path.positions[0], Cesium.Cartesian3.fromDegrees(85.48476, 28.33255), + 0, + 1e-6, ), ); - assert.equal(source.entities.getById('nepal-border-fill'), undefined); - assert.equal(source.entities.getById('nepal-border-highlight'), undefined); + assert.equal(viewer._test.item('nepal-border-fill'), undefined); + assert.equal(viewer._test.item('nepal-border-highlight'), undefined); assert.equal( - source.entities.getById( - 'bhote-koshi-place-immediate-collapse-viewpoint-halo', - ), + viewer._test.item('bhote-koshi-place-immediate-collapse-viewpoint-halo'), undefined, ); assert.equal(layer.getStats().coverage, 'Bhote Koshi · Path overview'); @@ -605,14 +652,13 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details', preview: true, }); await layer.enable(viewer); - const source = viewer._test.added[0]; const publication = overlayHost._test.publications.at(-1); const record = publication.entries[0]; - assert.deepEqual( - source.entities.values.map(({ id }) => id), - ['bhote-koshi-flood-path', 'bhote-koshi-trigger-record-halo'], - ); + assert.deepEqual(viewer._test.ids(), [ + 'bhote-koshi-flood-path', + 'bhote-koshi-trigger-record-halo', + ]); assert.equal(record.title, 'USGS INITIAL REPORT'); assert.deepEqual(record.details, [ '26 AUG 2026 · 08:37 NPT', @@ -625,7 +671,7 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details', assert.equal(record.sourceAlpha(), 0); nowMs = 1200; assert.equal(record.sourceAlpha(), 1); - assert.equal(source.entities.getById('nepal-border-highlight'), undefined); + assert.equal(viewer._test.item('nepal-border-highlight'), undefined); assert.equal(layer.getStats().coverage, 'Bhote Koshi · Trigger record'); assert.deepEqual(layer.getParams(), { presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION, @@ -634,21 +680,21 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details', }); test('Bhote Koshi trigger-record waits for the scene camera, zooms, then orbits', async () => { - const viewer = viewerFixture(); const overlayHost = overlayHostFixture(); const moveStart = new Cesium.Event(); const moveEnd = new Cesium.Event(); const flights = []; let armedCallback = null; - viewer.camera = { - moveStart, - moveEnd, - flyTo(options) { - flights.push(options); + const viewer = viewerFixture({ + camera: { + moveStart, + moveEnd, + flyTo(options) { + flights.push(options); + }, + cancelFlight() {}, }, - cancelFlight() {}, - }; - bindFakeCesiumCamera(viewer); + }); const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => null, requestRender() {}, @@ -690,22 +736,22 @@ test('Bhote Koshi trigger-record waits for the scene camera, zooms, then orbits' for (const phase of ['timer', 'move-end', 'approach', 'orbit']) { test(`Scene Stop revokes locator ${phase} and stale callbacks cannot own a successor`, async () => { - const viewer = viewerFixture(); const timers = new Map(); const callbacks = []; const flights = []; let nextTimer = 0; const moveStart = new Cesium.Event(); const moveEnd = new Cesium.Event(); - viewer.camera = { - moveStart, - moveEnd, - flyTo(options) { - flights.push(options); + const viewer = viewerFixture({ + camera: { + moveStart, + moveEnd, + flyTo(options) { + flights.push(options); + }, + cancelFlight() {}, }, - cancelFlight() {}, - }; - bindFakeCesiumCamera(viewer); + }); // The renderer's camera port relays these; the layer's own come on top. const portListeners = [moveStart, moveEnd].map((e) => e.numberOfListeners); const layer = createBhoteKoshiLocatorLayer({ @@ -814,8 +860,7 @@ test('Bhote Koshi locator keeps the regional context settled while nearby cities layer.setParams({ presentation: BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION }); await layer.enable(viewer); - const source = viewer._test.added[0]; - const borderFill = source.entities.getById('nepal-border-fill'); + const borderFill = viewer._test.item('nepal-border-fill'); const entries = overlayHost._test.publications.at(-1).entries; const incident = entries.find( ({ id }) => id === 'bhote-koshi-incident-callout', @@ -830,7 +875,8 @@ test('Bhote Koshi locator keeps the regional context settled while nearby cities ({ id }) => id === 'bhote-koshi-city-dhulikhel', ); - assert.equal(borderFill.show.getValue(), true); + assert.ok(borderFill, 'the settled fill is drawn at once'); + assert.equal(viewer._test.item('nepal-border-highlight').revealFraction, 1); assert.equal(incident.contentAlpha(), 1); assert.equal(kathmandu.title, 'KATHMANDU'); assert.equal(bhaktapur.title, 'BHAKTAPUR'); @@ -873,9 +919,7 @@ test('Bhote Koshi locator degrades to labels when the regional boundary is unava }); try { await layer.enable(viewer); - const ids = viewer._test.added[0].entities.values.map( - (entity) => entity.id, - ); + const ids = viewer._test.ids(); assert.ok(ids.includes('nepal-context-halo')); assert.ok(ids.includes('bhote-koshi-incident-halo')); assert.equal(ids.includes('bhote-koshi-city-kathmandu'), false); @@ -906,15 +950,9 @@ test('Bhote Koshi regional locator waits for its boundary before starting the fu }); const enabling = layer.enable(viewer); - assert.ok(viewer._test.added[0].entities.getById('nepal-context-halo')); - assert.equal( - viewer._test.added[0].entities.getById('nepal-border-highlight'), - undefined, - ); - assert.equal( - viewer._test.added[0].entities.getById('bhote-koshi-incident-halo'), - undefined, - ); + assert.ok(viewer._test.item('nepal-context-halo')); + assert.equal(viewer._test.item('nepal-border-highlight'), undefined); + assert.equal(viewer._test.item('bhote-koshi-incident-halo'), undefined); assert.equal(overlayHost._test.publications.length, 1); assert.deepEqual( overlayHost._test.publications[0].entries.map(({ id }) => id), @@ -930,14 +968,9 @@ test('Bhote Koshi regional locator waits for its boundary before starting the fu ], }); await enabling; - assert.ok( - viewer._test.added[0].entities.getById('bhote-koshi-incident-halo'), - ); - assert.ok(viewer._test.added[0].entities.getById('nepal-border-highlight')); - assert.equal( - viewer._test.added[0].entities.getById('bhote-koshi-city-kathmandu'), - undefined, - ); + assert.ok(viewer._test.item('bhote-koshi-incident-halo')); + assert.ok(viewer._test.item('nepal-border-highlight')); + assert.equal(viewer._test.item('bhote-koshi-city-kathmandu'), undefined); assert.equal(overlayHost._test.publications.length, 2); assert.deepEqual( overlayHost._test.publications.at(-1).entries.map(({ id }) => id), @@ -967,6 +1000,52 @@ test('Bhote Koshi locator cancels a stale boundary resolution and removes its su [88, 30], ], }); + assert.ok(viewer._test.live().length > 0, 'drawn while it resolves'); await assert.rejects(enabling, (error) => error?.name === 'AbortError'); - assert.equal(viewer._test.removed.length, 1); + assert.equal(viewer._test.live().length, 0, 'let go'); +}); + +test('Bhote Koshi locator layers draw sets of their own, and halos only as they change', async () => { + const viewer = viewerFixture(); + const ring = [ + [80, 26], + [88, 26], + [88, 30], + [80, 30], + ]; + let nowMs = 0; + const frames = nonRunningAnimation(); + const make = () => + createBhoteKoshiLocatorLayer({ + boundaryResolver: async () => ({ name: 'Nepal', ring }), + requestRender() {}, + overlayHost: overlayHostFixture(), + now: () => nowMs, + ...frames, + }); + const first = make(); + const second = make(); + assert.equal(await first.enable(viewer, { origin: 'scene' }), true); + assert.equal(await second.enable(viewer, { origin: 'scene' }), true); + const ids = viewer._test.live().map(({ spec }) => spec.id); + assert.equal(ids.length, 6); + assert.equal(new Set(ids).size, 6, 'no two layers share a set'); + + // Before the incident halo is due, nothing about any halo changes. + const halos = viewer._test.live().filter(({ kind }) => kind === 'points'); + nowMs = 100; + frames.tick(); + const writes = halos.map((set) => set.writes); + frames.tick(); + frames.tick(); + assert.deepEqual( + halos.map((set) => set.writes), + writes, + 'unchanged halos are not drawn again', + ); + + assert.equal(await first.disable(), true); + assert.equal(viewer._test.live().length, 3, 'the other layer keeps its sets'); + assert.equal(await second.disable(), true); + assert.equal(viewer._test.live().length, 0); }); diff --git a/src/data/sharedOsmDisplays.test.mjs b/src/data/sharedOsmDisplays.test.mjs index c2bbf716f..99a092997 100644 --- a/src/data/sharedOsmDisplays.test.mjs +++ b/src/data/sharedOsmDisplays.test.mjs @@ -51,7 +51,7 @@ for (const index of [0, 1]) test(`${index ? 'dams' : 'datacenters'} introduce th }); test('Nepal locator introduces the shared OSM credit', async (t) => { - const v = viewer(t); + const v = viewer(t, { draw: fakeDrawPort() }); const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => ({ name: 'Nepal', ring: [[80, 26], [88, 26], [88, 30], [80, 30]] }), overlayHost, requestRender: noop, scheduleFrame: () => 1, cancelFrame: noop }); await layer.init(v); await layer.enable(v, { origin: 'scene' }); assertCredit(v); await layer.destroy(v); diff --git a/src/geo/polyline.js b/src/geo/polyline.js index edd3dc924..dd9d780d0 100644 --- a/src/geo/polyline.js +++ b/src/geo/polyline.js @@ -7,6 +7,17 @@ const span = (a, b) => Math.hypot(b.x - a.x, b.y - a.y, b.z - a.z); +/** Each segment's length, and their sum. */ +function segmentLengths(positions) { + const lengths = []; + let total = 0; + for (let i = 0; i + 1 < positions.length; i++) { + lengths.push(span(positions[i], positions[i + 1])); + total += lengths[i]; + } + return { lengths, total }; +} + /** * The segment a fraction of the polyline's length ends on, and how far * along it (`t`, 0..1): fractions past 0 and up to 1 only. Null when there @@ -17,12 +28,7 @@ const span = (a, b) => Math.hypot(b.x - a.x, b.y - a.y, b.z - a.z); */ export function alongLength(positions, fraction) { if (!(fraction > 0) || fraction > 1 || positions.length < 2) return null; - const lengths = []; - let total = 0; - for (let i = 0; i + 1 < positions.length; i++) { - lengths.push(span(positions[i], positions[i + 1])); - total += lengths[i]; - } + const { lengths, total } = segmentLengths(positions); if (!(total > 0)) return null; let left = fraction * total; for (let i = 0; i < lengths.length; i++) { @@ -32,3 +38,20 @@ export function alongLength(positions, fraction) { } return { index: lengths.length - 1, t: 1 }; } + +/** + * The fraction of the polyline's length that ends `t` (0..1) along segment + * `index`: `alongLength` the other way round. Zero when there is no length. + * @param {ReadonlyArray<{x: number, y: number, z: number}>} positions + * @param {number} index + * @param {number} t + * @returns {number} + */ +export function lengthFraction(positions, index, t) { + const { lengths, total } = segmentLengths(positions); + if (!(total > 0)) return 0; + let drawn = 0; + for (let i = 0; i < lengths.length && i <= index; i++) + drawn += i < index ? lengths[i] : lengths[i] * t; + return drawn / total; +} diff --git a/src/geo/polyline.test.mjs b/src/geo/polyline.test.mjs index 225f1f28d..b0a56ed86 100644 --- a/src/geo/polyline.test.mjs +++ b/src/geo/polyline.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { alongLength } from './polyline.js'; +import { alongLength, lengthFraction } from './polyline.js'; const p = (x) => ({ x, y: 0, z: 0 }); @@ -19,3 +19,12 @@ test('alongLength has nothing to say without a length or a fraction in (0, 1]', assert.equal(alongLength([p(0), p(0)], 0.5), null); assert.equal(alongLength([p(0)], 0.5), null); }); + +test('lengthFraction is alongLength the other way round', () => { + const line = [p(0), p(1), p(4)]; + assert.equal(lengthFraction(line, 1, 1 / 3), 0.5); + assert.equal(lengthFraction(line, 0, 1), 0.25); + assert.equal(lengthFraction(line, 1, 1), 1); + assert.equal(lengthFraction(line, 0, 0), 0); + assert.equal(lengthFraction([p(0), p(0)], 0, 0.5), 0); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index b89b8b17f..ec6bd96a2 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -12,7 +12,6 @@ "src/data/aircraftModelLayer.js", "src/data/aircraftMotionRegime.js", "src/data/bhoteKoshiEvent.js", - "src/data/bhoteKoshiLocator.js", "src/data/cctvGizmo.js", "src/data/contactTrailRenderer.js", "src/data/detection.js",