diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 1893045f8..205512676 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1335,6 +1335,14 @@ owners. Tuner calculations have a pure entry, with existing layer exports preserved. Destruction removes listeners and state subscriptions before ending tuning; a delayed Enable result cannot reveal or refocus removed controls. +The stations, their clusters and the selected marker draw through the +renderer's draw port, and the layer no longer reaches Cesium. Stations drawn +too close together on screen stand behind one cluster dot, grouped as the +default renderer's entity clustering grouped them (`geo/screenCluster.js`, +42 px, three or more), reclustered as the camera moves and when the filter +changes. A caller handing the layer a Cesium viewer, with no +renderer bound, loads the `./render/cesium/unbound` export once first. + ## NYC DOT TMC CCTV source pack The CCTV catalog can add New York City traffic cameras from the NYC DOT diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 72f7c1f94..967edb508 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2848,6 +2848,8 @@ "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", + "src/render/color.js", "src/render/cesium/iconOrientation.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", @@ -3570,6 +3572,7 @@ "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", "src/layers/radio/state.js", @@ -4534,6 +4537,7 @@ "src/layers/radio/presentation.js", "src/layers/radio/queries.js", "src/layers/radio/rendering.js", + "src/geo/screenCluster.js", "src/layers/radio/selection.js", "src/layers/radio/source.js", "src/layers/radio/state.js", diff --git a/scripts/qa-radio.mjs b/scripts/qa-radio.mjs index 957144a50..bec07d25c 100644 --- a/scripts/qa-radio.mjs +++ b/scripts/qa-radio.mjs @@ -184,6 +184,50 @@ async function main() { queueMicrotask(() => this.dispatchEvent(new Event('playing'))); return Promise.resolve(); }; + // What Radio draws, read from the renderer's draw-port sets: the + // station dots (`stations`), cluster dots (`clusters`), and the + // selected station's dot (`selected`) and bracket + // (`selected-bracket`). Each row is a drawn point or billboard whose + // pick id is the draw port's `{set, id, meta}`; `show` is whether it + // draws, its set's host included. + window.__qaRadioRows = (kind) => { + const pattern = new RegExp(`^radio:\\d+:${kind}$`); + const out = []; + const visit = (node, shown) => { + if (!node || typeof node.get !== 'function' || typeof node.length !== 'number') return; + const here = shown && node.show !== false; + for (let index = 0; index < node.length; index += 1) { + const child = node.get(index); + const id = child?.id; + if (id && typeof id === 'object' && !Array.isArray(id) && typeof id.set === 'string') { + if (pattern.test(id.set)) { + out.push({ + primitive: child, + id: id.id, + meta: id.meta, + show: here && child.show !== false, + setShown: here, + }); + } + } else visit(child, here); + } + }; + visit(window.__godsEyeView.viewer.scene.primitives, true); + return out; + }; + // The selected station's drawn dot and bracket, with its pick id. + window.__qaRadioSelected = () => { + const dot = window.__qaRadioRows('selected')[0] || null; + if (!dot) return null; + const bracket = window.__qaRadioRows('selected-bracket')[0] || null; + return { + id: dot.id, + show: dot.show, + position: dot.primitive.position, + dot, + bracket, + }; + }; }); await page.setRequestInterception(true); let catalogDegraded = false; @@ -420,7 +464,7 @@ async function main() { await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); const result = { presentationActive: module.getUIState().presentationActive, - markerSourceVisible: gev.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), tunerHidden: document.getElementById('radio-tuner').hidden, filterDisabled: document.getElementById('radio-filter').disabled, prevDisabled: document.getElementById('radio-prev-btn').disabled, @@ -514,7 +558,7 @@ async function main() { const disablingPresentation = await page.evaluate(() => ({ manager: window.__godsEyeView.dataManager.getLayerLifecycleState('radio'), presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive, - markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), full: document.getElementById('radio-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, message: document.getElementById('radio-playback-state').textContent, @@ -583,7 +627,7 @@ async function main() { const enablingPresentation = await page.evaluate(() => ({ manager: window.__godsEyeView.dataManager.getLayerLifecycleState('radio'), presentationActive: window.__godsEyeView.dataManager.layers.get('radio').module.getUIState().presentationActive, - markerSourceVisible: window.__godsEyeView.viewer.dataSources.getByName('Radio stations')[0]?.show, + markerSourceVisible: (window.__qaRadioRows('stations')[0]?.setShown ?? false), full: document.getElementById('radio-enable-btn').textContent, layerState: document.getElementById('radio-layer-state').textContent, message: document.getElementById('radio-playback-state').textContent, @@ -687,8 +731,6 @@ async function main() { const sample = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; - const dataSource = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const { radioStationIdFromPick } = await import('/src/data/radio.js'); return new Promise((resolve) => { @@ -710,7 +752,9 @@ async function main() { host: getWorldOverlayDiagnostics(), paintedSingletonIds, pickableSingletonIds, - nativeLabelCount: dataSource.entities.values.filter((entity) => Boolean(entity.label)).length, + // The station dots are a draw-port point set, which draws no + // labels of its own; a label primitive would be a row here. + nativeLabelCount: window.__qaRadioRows('stations').filter((row) => row.primitive.text !== undefined).length, }); }; const timeout = setTimeout(finish, 500); @@ -1255,12 +1299,10 @@ async function main() { }); await page.select('#radio-filter', 'all'); const allPalette = await page.evaluate(() => { - const source = Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => ( - window.__godsEyeView.viewer.dataSources.get(index) - )).find((item) => item.name === 'Radio stations'); + const rows = new Map(window.__qaRadioRows('stations').map((row) => [row.id, row])); const colorFor = (index) => { const id = `radio:00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}`; - const color = source?.entities.getById(id)?.point?.color?.getValue?.(); + const color = rows.get(id)?.primitive.color; return color ? [color.red, color.green, color.blue].map((value) => Math.round(value * 255)) : null; }; return { news: colorFor(0), talk: colorFor(1), music: colorFor(7) }; @@ -1277,8 +1319,6 @@ async function main() { const viewer = window.__godsEyeView.viewer; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const baselineSolveRevision = getWorldOverlayDiagnostics().solveRevision; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); const ellipsoid = viewer.scene.globe.ellipsoid; viewer.camera.cancelFlight(); viewer.camera.setView({ @@ -1289,26 +1329,25 @@ async function main() { }), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - source.clustering.enabled = false; viewer.scene.requestRender(); - await new Promise((resolve) => setTimeout(resolve, 100)); + // The camera's move clusters the stations again: wait for a cluster dot. return new Promise((resolve) => { - const originalPixelRange = source.clustering.pixelRange; - const timeout = setTimeout(() => { - remove(); - resolve(null); - }, 2_000); - const remove = source.clustering.clusterEvent.addEventListener(async (entities, cluster) => { - clearTimeout(timeout); - remove(); + const started = performance.now(); + const poll = async () => { + const cluster = window.__qaRadioRows('clusters').find((row) => row.show); + if (!cluster) { + if (performance.now() - started > 2_000) resolve(null); + else setTimeout(poll, 50); + return; + } + // The cluster's dot is a draw-port point, which draws no label. const native = { - count: entities.length, - labelShow: cluster.label.show, - labelText: cluster.label.text, - pointSize: cluster.point.pixelSize, - pointMaxDistance: cluster.point.distanceDisplayCondition?.far ?? null, + count: cluster.meta.stationIds.length, + labelShow: cluster.primitive.text !== undefined, + labelText: cluster.primitive.text ?? '', + pointSize: cluster.primitive.pixelSize, + pointMaxDistance: cluster.primitive.distanceDisplayCondition?.far ?? null, }; - source.clustering.pixelRange = originalPixelRange; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; await new Promise((done) => setTimeout(done, 0)); let painted = null; @@ -1345,9 +1384,8 @@ async function main() { source: radio.getOverlayDiagnostics(), host: painted?.host || getWorldOverlayDiagnostics(), }); - }); - source.clustering.enabled = true; - viewer.scene.requestRender(); + }; + poll(); }); }); check( @@ -1393,15 +1431,13 @@ async function main() { 0, cameraRadius * cameraRadius - ellipsoid.maximumRadius * ellipsoid.maximumRadius, )); - const points = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations')?.clustering?._clusterPointCollection; let clusterPoint = null; - // Pool order is not visibility order after a camera change. Choose an - // on-screen point independently of the native pick result being tested. + // Choose an on-screen cluster dot independently of the native pick + // result being tested. const visiblePoints = []; - for (let index = 0; index < (points?.length || 0); index += 1) { - const point = points.get(index); - if (!point?.show || !Array.isArray(point.id) || !point.id.length) continue; + for (const row of window.__qaRadioRows('clusters')) { + const point = row.primitive; + if (!row.show || !row.meta?.stationIds?.length) continue; const anchor = viewer.scene.cartesianToCanvasCoordinates(point.position); if (!anchor) continue; if (anchor.x < 0 || anchor.y < 0 || anchor.x > viewer.canvas.clientWidth || anchor.y > viewer.canvas.clientHeight) continue; @@ -2432,26 +2468,23 @@ async function main() { await sleep(700); const newsClusterTarget = await page.evaluate(() => { const gev = window.__godsEyeView; - const source = Array.from({ length: gev.viewer.dataSources.length }, (_, index) => gev.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - const points = source.clustering._clusterPointCollection; - for (let index = 0; index < (points?.length || 0); index += 1) { - const point = points.get(index); - if (!point.show || !Array.isArray(point.id) || !point.id.length) continue; - const canvasPoint = gev.viewer.scene.cartesianToCanvasCoordinates(point.position); + const rows = window.__qaRadioRows('clusters'); + for (const row of rows) { + if (!row.show || !row.meta?.stationIds?.length) continue; + const canvasPoint = gev.viewer.scene.cartesianToCanvasCoordinates(row.primitive.position); if (!canvasPoint) continue; return { x: canvasPoint.x, y: canvasPoint.y, - firstId: String(point.id[0]?.id || '').replace(/^radio:/, ''), - pointIds: point.id.map((entity) => entity.id), + firstId: row.meta.stationIds[0], + pointIds: row.meta.stationIds.map((id) => `radio:${id}`), }; } return { missing: true, - points: Array.from({ length: points?.length || 0 }, (_, index) => ({ - show: points.get(index).show, - pointIds: Array.isArray(points.get(index)?.id) ? points.get(index).id.length : 0, + points: rows.map((row) => ({ + show: row.show, + pointIds: row.meta?.stationIds?.length || 0, })), }; }); @@ -2654,9 +2687,13 @@ async function main() { const horizon = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const ellipsoid = viewer.scene.globe.ellipsoid; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - const visibleIds = () => source.entities.values.filter((entity) => entity.show).map((entity) => entity.id); + // A station dot standing in a cluster is hidden too; the cluster's + // dot draws its stations' ids. + const visibleIds = () => [ + ...window.__qaRadioRows('stations').filter((row) => row.show).map((row) => row.id), + ...window.__qaRadioRows('clusters').filter((row) => row.show) + .flatMap((row) => row.meta.stationIds.map((id) => `radio:${id}`)), + ]; const setView = (lon, lat = 0) => { viewer.camera.cancelFlight(); viewer.camera.setView({ @@ -2702,8 +2739,7 @@ async function main() { buttons: type === 'pointerup' || type === 'pointercancel' ? 0 : 1, })); const snapshot = () => { - const markerId = gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const markerId = window.__qaRadioSelected()?.id || null; return { slot: Number(slider.value), markerId, @@ -2823,8 +2859,7 @@ async function main() { // The tuner renders from the Radio store; let Vue patch before reading. await Promise.resolve(); const shiftedSlot = Number(slider.value); - const previewBeforeCancel = gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const previewBeforeCancel = window.__qaRadioSelected()?.id || null; const flyToCallsBeforeCancel = flyToCalls.length; pointer('pointercancel', targetIndex); await Promise.resolve(); @@ -2840,8 +2875,7 @@ async function main() { tuningActive: afterState.tuningActive, }; const flyToCallsAfterCancel = flyToCalls.length; - const selectedEntity = () => gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:')) || null; + const selectedEntity = () => window.__qaRadioSelected(); const restoredEntity = selectedEntity(); const previewId = restoredEntity?.id || null; after.previewId = previewId; @@ -2858,7 +2892,7 @@ async function main() { filter: changedFilterState.filter, restoredStationId: changedFilterState.tuningRestoredStationId, selectedId: changedFilterState.selected?.id || null, - entityRebuilt: Boolean(changedFilterEntity && changedFilterEntity !== restoredEntity), + entityRebuilt: Boolean(changedFilterEntity && changedFilterEntity.dot.primitive !== restoredEntity?.dot.primitive), entityId: changedFilterEntity?.id || null, snapshotPreserved: radio.getAcceptedCatalogSnapshot() === changedFilterSnapshot, playDelta: window.__qaRadioPlayCalls.length - changedFilterPlays, @@ -2882,7 +2916,7 @@ async function main() { restoredAfter: sameFilterState.tuningRestoredStationId, filter: sameFilterState.filter, selectedId: sameFilterState.selected?.id || null, - entityRebuilt: Boolean(sameFilterEntity && sameFilterEntity !== sameFilterRestoredEntity), + entityRebuilt: Boolean(sameFilterEntity && sameFilterEntity.dot.primitive !== sameFilterRestoredEntity?.dot.primitive), entityId: sameFilterEntity?.id || null, snapshotPreserved: radio.getAcceptedCatalogSnapshot() === sameFilterSnapshot, playDelta: window.__qaRadioPlayCalls.length - sameFilterPlays, @@ -3327,8 +3361,7 @@ async function main() { cancelable: true, key: value, })); - const markerId = () => gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null; + const markerId = () => window.__qaRadioSelected()?.id || null; const startIndex = Number(slider.value); const expectedIndex = Math.min(style._radioControls._radioTunerStations.length - 1, startIndex + 1); const expectedId = style._radioControls._radioTunerStations[expectedIndex]?.id || null; @@ -3428,8 +3461,7 @@ async function main() { centerIndex, slot: Number(slider.value), ratio: Number(document.getElementById('radio-tuner').style.getPropertyValue('--radio-tuner-ratio')), - markerId: gev.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:'))?.id || null, + markerId: window.__qaRadioSelected()?.id || null, expectedId: style._radioControls._radioTunerStations[centerIndex]?.id || null, }; slider.dispatchEvent(new PointerEvent('pointercancel', { @@ -3554,9 +3586,6 @@ async function main() { const markerTarget = await page.evaluate(async () => { const viewer = window.__godsEyeView.viewer; const radio = window.__godsEyeView.dataManager.layers.get('radio').module; - const source = Array.from({ length: viewer.dataSources.length }, (_, index) => viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations'); - source.clustering.enabled = false; const selectedId = radio.getUIState().selected?.id || null; if (selectedId) { radio.selectStation(selectedId, { @@ -3583,9 +3612,6 @@ async function main() { }); viewer.scene.requestRender(); }); - // Cesium clears its private cluster collections during the rendered - // disabled-state update. Publish the same-filter singleton overlay only - // after that frame so this harness mutation cannot leak stale clusters. radio.setFilter('news'); viewer.scene.requestRender(); await new Promise((resolve) => setTimeout(resolve, 500)); @@ -3614,14 +3640,14 @@ async function main() { let visibleEntityCount = 0; let singletonEntityCount = 0; let paintedSingletonCount = 0; - for (const entity of source.entities.values) { - if (!entity.show) continue; + for (const row of window.__qaRadioRows('stations')) { + if (!row.show) continue; visibleEntityCount += 1; - const id = String(entity.id).slice('radio:'.length); + const id = String(row.id).slice('radio:'.length); const overlayId = `station:${id}`; if (!singletonIds.has(overlayId)) continue; singletonEntityCount += 1; - const position = entity.position?.getValue(viewer.clock.currentTime); + const position = row.primitive.position; const canvas = position && viewer.scene.cartesianToCanvasCoordinates(position); const paintRect = getOverlayPaintRect('radio', overlayId); if (paintRect) paintedSingletonCount += 1; @@ -3631,7 +3657,7 @@ async function main() { id, x: canvas.x, y: canvas.y, - ownsNativeLabel: Boolean(entity.label), + ownsNativeLabel: row.primitive.text !== undefined, labelPainted: true, singletonTexts: diagnostics.singletonTexts, }); @@ -3700,8 +3726,6 @@ async function main() { orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); radio.stopPlayback(); - Array.from({ length: gev.viewer.dataSources.length }, (_, index) => gev.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations').clustering.enabled = true; // Next plays only while a stream is active, so start from a playing station. radio.selectStation('00000000-0000-4000-8000-000000000001', { autoplay: true, focus: false }); }); @@ -3757,8 +3781,7 @@ async function main() { const playing = await page.evaluate(async () => { const radio = window.__godsEyeView.dataManager.layers.get('radio').module; const viewer = window.__godsEyeView.viewer; - const selectedEntity = window.__godsEyeView.viewer.entities.values - .find((entity) => String(entity.id).startsWith('radio:selected:')); + const selectedEntity = window.__qaRadioSelected(); const { getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const flightTargets = window.__qaRadioFlyToCalls.map(({ destination }) => { const position = viewer.scene.globe.ellipsoid.cartesianToCartographic(destination); @@ -3775,11 +3798,10 @@ async function main() { flightTargets, cameraHeight: window.__qaRadioCameraHeight, playLabel: document.getElementById('radio-play-btn').getAttribute('aria-label'), - regularMarkerSize: Array.from({ length: window.__godsEyeView.viewer.dataSources.length }, (_, index) => window.__godsEyeView.viewer.dataSources.get(index)) - .find((item) => item.name === 'Radio stations')?.entities.values[0]?.point?.pixelSize?.getValue(), - selectedMarkerSize: selectedEntity?.point?.pixelSize?.getValue(), - selectedBracketWidth: selectedEntity?.billboard?.width?.getValue(), - selectedOwnsNativeLabel: Boolean(selectedEntity?.label), + regularMarkerSize: window.__qaRadioRows('stations')[0]?.primitive.pixelSize, + selectedMarkerSize: selectedEntity?.dot.primitive.pixelSize, + selectedBracketWidth: selectedEntity?.bracket?.primitive.width, + selectedOwnsNativeLabel: Boolean(window.__qaRadioRows('selected-label').length), overlay: radio.getOverlayDiagnostics(), host: getWorldOverlayDiagnostics(), expectedPrimary: window.__qaRadioExpectedPrimary, @@ -3940,8 +3962,12 @@ async function main() { destination, orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - const selectedEntity = viewer.entities.values - .find((entity) => String(entity.id) === `radio:selected:${selected.id}`); + // The selected station's drawn dot and bracket, read afresh: Radio's + // horizon pass shows them on its own timer. + const selectedEntity = () => { + const drawn = window.__qaRadioSelected(); + return drawn?.id === `radio:selected:${selected.id}` ? drawn : null; + }; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const expectedEntryId = `selected:${selected.id}`; let painted = null; @@ -3949,7 +3975,7 @@ async function main() { // after the camera jump, so a stationary view waits for both to settle. for ( let attempt = 0; - attempt < 20 && !(painted?.rect && selectedEntity?.show === true); + attempt < 20 && !(painted?.rect && selectedEntity()?.show === true); attempt += 1 ) { painted = await new Promise((resolve) => { @@ -3974,7 +4000,7 @@ async function main() { expectedEntryId, rect: painted?.rect || null, host: painted?.host || getWorldOverlayDiagnostics(), - selectedEntityShow: selectedEntity?.show, + selectedEntityShow: selectedEntity()?.show, cameraHeight: viewer.camera.positionCartographic.height, }; }); @@ -3999,8 +4025,12 @@ async function main() { }), orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, }); - const selectedEntity = viewer.entities.values - .find((entity) => String(entity.id) === `radio:selected:${selected.id}`); + // The selected station's drawn dot and bracket, read afresh: Radio's + // horizon pass shows them on its own timer. + const selectedEntity = () => { + const drawn = window.__qaRadioSelected(); + return drawn?.id === `radio:selected:${selected.id}` ? drawn : null; + }; const { getOverlayPaintRect, getWorldOverlayDiagnostics } = await import('/src/overlays/worldOverlay.js'); const expectedEntryId = `selected:${selected.id}`; let rect = null; @@ -4025,7 +4055,8 @@ async function main() { viewer.scene.requestRender(); }); } - const entityPosition = selectedEntity?.position?.getValue?.(); + const selectedDrawn = selectedEntity(); + const entityPosition = selectedDrawn?.position; const entityAnchor = entityPosition && viewer.scene.cartesianToCanvasCoordinates(entityPosition); let selectedNativePick = null; @@ -4035,13 +4066,16 @@ async function main() { // billboard satisfy the loop while the point anchor was still missing. for (let attempt = 0; entityAnchor && attempt < 8 && !selectedPointPick; attempt += 1) { const picks = viewer.scene.drillPick(entityAnchor, 16) || []; - selectedNativePick = picks.find((picked) => picked?.id === selectedEntity); + selectedNativePick = picks.find((picked) => ( + picked?.primitive === selectedDrawn.dot.primitive + || picked?.primitive === selectedDrawn.bracket?.primitive + )); selectedPointPick = picks.find((picked) => ( - picked?.id === selectedEntity + picked?.primitive === selectedDrawn.dot.primitive && String(picked?.primitive?.constructor?.name || '').includes('PointPrimitive') )); selectedBillboardPick = picks.find((picked) => ( - picked?.id === selectedEntity + picked?.primitive === selectedDrawn.bracket?.primitive && String(picked?.primitive?.constructor?.name || '').includes('Billboard') )); if (!selectedPointPick) { @@ -4054,18 +4088,15 @@ async function main() { }); } } - const selectedPointDistance = selectedEntity?.point?.distanceDisplayCondition?.getValue?.(); + const selectedPointDistance = selectedDrawn?.dot.primitive.distanceDisplayCondition; return { rect, selectedNativePickable: Boolean(selectedNativePick), selectedPointPickable: Boolean(selectedPointPick), selectedBillboardPickable: Boolean(selectedBillboardPick), selectedPointMaxDistance: selectedPointDistance?.far ?? null, - selectedEntityShow: selectedEntity?.show, - selectedBracketVisible: Boolean( - selectedEntity?.billboard - && selectedEntity.billboard.show?.getValue?.() !== false - ), + selectedEntityShow: selectedDrawn?.show, + selectedBracketVisible: Boolean(selectedDrawn?.bracket?.show), entityAnchor: entityAnchor ? { x: entityAnchor.x, y: entityAnchor.y } : null, entityDistance: entityPosition ? Math.hypot( diff --git a/src/data/radio.test.mjs b/src/data/radio.test.mjs index 46f238c4d..e00538685 100644 --- a/src/data/radio.test.mjs +++ b/src/data/radio.test.mjs @@ -5,6 +5,7 @@ import { fakeCameraPort, } from '../testSupport/fakeCameraPort.mjs'; import { bindRenderer } from '../render/rendererOf.js'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; import { buildRadioTunerBand, buildRadioTunerTicks, @@ -405,7 +406,7 @@ test('destroy and re-init reset Radio audio ownership, volume, filter, and telem radioLayer.destroy(); try { - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); radioLayer.enable(); radioLayer.setLifecyclePresentation({ lifecycleState: 'enabled', enabled: true, uncertain: false, @@ -430,7 +431,7 @@ test('destroy and re-init reset Radio audio ownership, volume, filter, and telem assert.equal(getRadioUIState().volume, 0.8); assert.equal(getRadioUIState().effectiveVolume, 0.8); - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); assert.equal(audioInstances.length, 2, 're-init creates a clean Audio session'); const nextState = getRadioUIState(); for (const eventName of ['playing', 'pause', 'waiting', 'error']) { @@ -524,7 +525,7 @@ test('late media errors after replacement or Pause cannot mutate the active stat radioLayer.destroy(); try { - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); radioLayer.enable(); await radioLayer.update(); radioLayer.setLifecyclePresentation({ @@ -654,7 +655,7 @@ test('unusable directory responses preserve warm client state atomically', async }; radioLayer.destroy(); try { - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); globalThis.fetch = async () => new Response(JSON.stringify({ stations: [station], stale: false, @@ -768,7 +769,7 @@ test('unusable directory responses preserve warm client state atomically', async assert.equal(getRadioUIState().stale, true); assert.equal(getRadioUIState().rejectedStationCount, 10_000); radioLayer.destroy(); - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); assert.equal(getRadioUIState().rejectedStationCount, 0); assert.equal(getRadioUIState().degraded, false); } finally { @@ -826,7 +827,7 @@ test('tuner drag keeps one immutable catalog resolution through refresh and rele radioLayer.destroy(); try { - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); radioLayer.enable(); await publish(stationA, 1); assert.equal(radioLayer.beginTuning(), true); @@ -933,7 +934,20 @@ test('failed exact tuner release cannot consume a stale playback fallback', asyn test('tuner cancellation restores the frozen start marker after catalog removal', async () => { const originalFetch = globalThis.fetch; const originalAudio = globalThis.Audio; - const selectedEntities = new Map(); + const draw = fakeDrawPort(); + // The selected station's dot, from the layer's selected-marker set. + const selectedEntities = { + record: () => + [...draw.sets.values()].find( + (set) => !set.disposed && set.spec.id.endsWith(':selected'), + ), + get(id) { + return this.record()?.items.get(id); + }, + has(id) { + return Boolean(this.get(id)); + }, + }; let playCalls = 0; let flyToCalls = 0; globalThis.Audio = class FakeAudio { @@ -956,11 +970,6 @@ test('tuner cancellation restores the frozen start marker after catalog removal' canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} }, requestRender() {}, }, - dataSources: { add() {}, remove() {} }, - entities: { - add(entity) { selectedEntities.set(entity.id, entity); return entity; }, - remove(entity) { return selectedEntities.delete(entity?.id); }, - }, }; const stationA = { id: '00000000-0000-4000-8000-000000000051', @@ -1000,7 +1009,7 @@ test('tuner cancellation restores the frozen start marker after catalog removal' radioLayer.destroy(); try { - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw })); radioLayer.enable(); radioLayer.setLifecyclePresentation({ lifecycleState: 'enabled', enabled: true, uncertain: false, @@ -1020,7 +1029,7 @@ test('tuner cancellation restores the frozen start marker after catalog removal' assert.equal(radioLayer.cancelTuning(), true); const restoredMarker = selectedEntities.get(`radio:selected:${stationA.id}`); assert.ok(restoredMarker, 'the frozen start marker remains visible after cancellation'); - assert.deepEqual(restoredMarker.position, startMarker.position); + assert.deepEqual(restoredMarker.pos, startMarker.pos); assert.equal(getRadioUIState().tuningRestoredStationId, stationA.id); assert.equal(getRadioUIState().tuningActive, false); assert.equal(getRadioUIState().selected, null, 'stale marker never becomes playback authority'); @@ -1109,7 +1118,7 @@ test('Radio public tuner, filter, and resume mutations require certain enabled l radioLayer.destroy(); try { - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); radioLayer.enable(); await radioLayer.update(); radioLayer.setLifecyclePresentation({ @@ -1184,7 +1193,7 @@ test('tuner refuses a degraded fallback that has no accepted catalog generation' acceptedGeneration: null, updatedAt: new Date().toISOString(), }), { status: 200, headers: { 'Content-Type': 'application/json' } }); - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); radioLayer.enable(); await radioLayer.update(); @@ -1239,7 +1248,7 @@ test('accepted snapshots allowlist station fields and never regress generation i radioLayer.destroy(); try { - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); serve([station], 1); radioLayer.enable(); await radioLayer.update(); @@ -1350,7 +1359,7 @@ test('update abort, destroy, and re-init invalidate the prior session and reset requestSignal = options.signal; return new Promise((resolve) => { resolveFetch = resolve; }); }; - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); radioLayer.enable(); const pending = radioLayer.update(); assert.equal(getRadioUIState().loading, true); @@ -1359,7 +1368,7 @@ test('update abort, destroy, and re-init invalidate the prior session and reset assert.equal(getRadioUIState().loading, false); radioLayer.destroy(); - radioLayer.init(bindFakeCesiumCamera(viewer)); + radioLayer.init(bindFakeCesiumCamera(viewer, { draw: fakeDrawPort() })); const cleanState = getRadioUIState(); assert.deepEqual({ enabled: cleanState.enabled, diff --git a/src/data/radioProxy.test.mjs b/src/data/radioProxy.test.mjs index e9df10678..b2a1694c6 100644 --- a/src/data/radioProxy.test.mjs +++ b/src/data/radioProxy.test.mjs @@ -3,6 +3,7 @@ import { EventEmitter } from 'node:events'; import https from 'node:https'; import { Readable } from 'node:stream'; import test from 'node:test'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { fetchPinnedRadioResponse } from '../../server/providers/radio/transport.js'; import { createRadioProxyMiddleware, @@ -575,9 +576,9 @@ test('server structural rejections reach the client diagnostic without discardin const viewer = { camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } }, scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } }, - dataSources: { add() {}, remove() {} }, - entities: { add(entity) { return entity; }, remove() {} }, }; + // The stations draw through the renderer's draw port. + const { unbind } = bindFakeDraw(viewer); radioLayer.destroy(); try { globalThis.fetch = async () => new Response(response.body, { @@ -597,5 +598,6 @@ test('server structural rejections reach the client diagnostic without discardin } finally { globalThis.fetch = originalFetch; radioLayer.destroy(); + unbind(); } }); diff --git a/src/geo/screenCluster.js b/src/geo/screenCluster.js new file mode 100644 index 000000000..c21ca1705 --- /dev/null +++ b/src/geo/screenCluster.js @@ -0,0 +1,206 @@ +/** + * @module geo/screenCluster + * @description Screen-space clustering of points, as the default renderer's + * entity clustering groups them: each point not yet in a cluster, in order, + * takes every unclustered point whose screen position falls inside its own + * box (its pixel size grown by `pixelRange` on every side) into a cluster at + * the mean of their world positions, when they number at least + * `minimumClusterSize`. On a pass made closer to the ground than the last + * one, each cluster of the last pass that is still above the horizon first + * keeps the points inside its box, shrunk by how much closer the eye came + * (never below the box it was seeded with); only then are new ones seeded. + * + * The coordinates follow that renderer's choices so that the clusters are + * the same ones: points are boxed in window coordinates measured from the + * bottom (`height - y`), a last pass's clusters from the top, and a kept + * cluster's box reaches half its width left and up but its whole width + * right and down. + */ + +/** + * @typedef {object} ScreenClusterPoint + * @property {string} id + * @property {{x: number, y: number, z: number}} position World position. + * @property {{x: number, y: number}} screen CSS pixels from the top left. + * @property {number} pixelSize Its drawn size, CSS pixels. + */ + +/** + * @typedef {object} ScreenClusterState What a pass leaves for the next. + * @property {Array<{position: {x: number, y: number, z: number}, + * width: number, height: number, minimumWidth: number, + * minimumHeight: number}>} clusters + * @property {number} height The eye's height above the ground at that pass. + */ + +/** + * Cluster `points` (those shown, above the horizon and in front of the eye, + * in their drawing order). + * @param {object} options + * @param {ScreenClusterPoint[]} options.points + * @param {number} options.pixelRange + * @param {number} options.minimumClusterSize + * @param {number} options.viewHeight The view's height, CSS pixels. + * @param {number} options.eyeHeight The eye's height above the ground, m. + * @param {ScreenClusterState|null} [options.previous] The last pass's state. + * @param {(position: object) => ({x: number, y: number}|null)} options.project + * Window position of a world position, CSS pixels from the top left + * (null behind the eye). + * @param {(position: object) => boolean} options.isOccluded Whether the + * ellipsoid's horizon hides a world position. + * @returns {{clusters: Array<{position: {x: number, y: number, z: number}, + * ids: string[]}>, single: string[], state: ScreenClusterState}} + * The clusters (each with its points' ids, its seed first), the ids of the + * points left on their own, and the state for the next pass. + */ +export function clusterScreenPoints({ + points, + pixelRange, + minimumClusterSize, + viewHeight, + eyeHeight, + previous = null, + project, + isOccluded, +}) { + const n = points.length; + const xs = new Float64Array(n); + const ys = new Float64Array(n); + for (let i = 0; i < n; i++) { + xs[i] = points[i].screen.x; + ys[i] = viewHeight - points[i].screen.y; + } + const clustered = new Uint8Array(n); + const index = createGridIndex(xs, ys, Math.max(1, pixelRange * 2)); + const clusters = []; + const kept = []; + + if (n > 0 && previous && eyeHeight < previous.height) { + const factor = 1 - eyeHeight / previous.height; + for (const cluster of previous.clusters) { + if (isOccluded(cluster.position)) continue; + const coord = project(cluster.position); + if (!coord) continue; + cluster.width *= factor; + cluster.height *= factor; + const width = Math.max(cluster.width, cluster.minimumWidth); + const height = Math.max(cluster.height, cluster.minimumHeight); + const neighbors = index.range( + coord.x - width * 0.5, + coord.y - height * 0.5, + coord.x + width, + coord.y + height, + ); + const ids = []; + for (const j of neighbors) if (!clustered[j]) ids.push(points[j].id); + if (ids.length >= minimumClusterSize) { + clusters.push({ position: { ...cluster.position }, ids }); + kept.push(cluster); + for (const j of neighbors) clustered[j] = 1; + } + } + } + + const single = []; + for (let i = 0; i < n; i++) { + if (clustered[i]) continue; + clustered[i] = 1; + const seed = points[i]; + const box = pointBox(xs[i], ys[i], seed.pixelSize, pixelRange); + let minX = box.x; + let minY = box.y; + let maxX = box.x + box.width; + let maxY = box.y + box.height; + const neighbors = index.range( + box.x, + box.y, + box.x + box.width, + box.y + box.height, + ); + const sum = { x: seed.position.x, y: seed.position.y, z: seed.position.z }; + const ids = [seed.id]; + for (const j of neighbors) { + if (clustered[j]) continue; + const other = points[j]; + const near = pointBox(xs[j], ys[j], other.pixelSize, pixelRange); + sum.x += other.position.x; + sum.y += other.position.y; + sum.z += other.position.z; + minX = Math.min(minX, near.x); + minY = Math.min(minY, near.y); + maxX = Math.max(maxX, near.x + near.width); + maxY = Math.max(maxY, near.y + near.height); + ids.push(other.id); + } + if (ids.length >= minimumClusterSize) { + const position = { + x: sum.x / ids.length, + y: sum.y / ids.length, + z: sum.z / ids.length, + }; + clusters.push({ position, ids }); + kept.push({ + position, + width: maxX - minX, + height: maxY - minY, + minimumWidth: box.width, + minimumHeight: box.height, + }); + for (const j of neighbors) clustered[j] = 1; + } else single.push(seed.id); + } + + return { clusters, single, state: { clusters: kept, height: eyeHeight } }; +} + +/** A point's box: its drawn square grown by `pixelRange` on every side. */ +function pointBox(x, y, size, pixelRange) { + return { + x: x - size * 0.5 - pixelRange, + y: y - size * 0.5 - pixelRange, + width: size + pixelRange * 2, + height: size + pixelRange * 2, + }; +} + +/** + * A uniform grid over packed coordinates, answering which points lie in a + * box (bounds included), in ascending index order. + */ +function createGridIndex(xs, ys, cell) { + const buckets = new Map(); + const key = (cx, cy) => `${cx}:${cy}`; + for (let i = 0; i < xs.length; i++) { + const k = key(Math.floor(xs[i] / cell), Math.floor(ys[i] / cell)); + let bucket = buckets.get(k); + if (!bucket) buckets.set(k, (bucket = [])); + bucket.push(i); + } + return { + range(minX, minY, maxX, maxY) { + const found = []; + if (!(maxX >= minX && maxY >= minY)) return found; + const x0 = Math.floor(minX / cell); + const x1 = Math.floor(maxX / cell); + const y0 = Math.floor(minY / cell); + const y1 = Math.floor(maxY / cell); + if ((x1 - x0 + 1) * (y1 - y0 + 1) > buckets.size) { + for (let i = 0; i < xs.length; i++) + if (xs[i] >= minX && xs[i] <= maxX && ys[i] >= minY && ys[i] <= maxY) + found.push(i); + return found; + } + for (let cx = x0; cx <= x1; cx++) + for (let cy = y0; cy <= y1; cy++) + for (const i of buckets.get(key(cx, cy)) ?? []) + if ( + xs[i] >= minX && + xs[i] <= maxX && + ys[i] >= minY && + ys[i] <= maxY + ) + found.push(i); + return found.sort((a, b) => a - b); + }, + }; +} diff --git a/src/geo/screenCluster.test.mjs b/src/geo/screenCluster.test.mjs new file mode 100644 index 000000000..2c535311a --- /dev/null +++ b/src/geo/screenCluster.test.mjs @@ -0,0 +1,136 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { clusterScreenPoints } from './screenCluster.js'; + +/** A point at screen `x, y` whose world position is `x, y, 0` too. */ +const at = (id, x, y, pixelSize = 13) => ({ + id, + position: { x, y, z: 0 }, + screen: { x, y }, + pixelSize, +}); + +const run = (points, extra = {}) => + clusterScreenPoints({ + points, + pixelRange: 42, + minimumClusterSize: 3, + viewHeight: 1000, + eyeHeight: 1_000_000, + project: (p) => ({ x: p.x, y: p.y }), + isOccluded: () => false, + ...extra, + }); + +test('points inside a seed’s grown box cluster at their mean, the seed first', () => { + const result = run([ + at('a', 100, 100), + at('b', 140, 100), + at('c', 100, 140), + at('far', 600, 600), + ]); + assert.equal(result.clusters.length, 1); + assert.deepEqual(result.clusters[0].ids, ['a', 'b', 'c']); + assert.deepEqual(result.clusters[0].position, { + x: 340 / 3, + y: 340 / 3, + z: 0, + }); + assert.deepEqual(result.single, ['far']); +}); + +test('fewer than the minimum stay on their own, and a box reaches half the size plus the range', () => { + // 6.5 + 42 = 48.5 px each way from the seed. + const edge = run([ + at('a', 100, 100), + at('b', 148.5, 100), + at('c', 100, 51.5), + ]); + assert.deepEqual(edge.clusters[0].ids, ['a', 'b', 'c']); + const out = run([at('a', 100, 100), at('b', 148.6, 100), at('c', 100, 51.5)]); + assert.deepEqual(out.clusters, []); + assert.deepEqual(out.single, ['a', 'b', 'c']); +}); + +test('a point already clustered is not taken again by a later seed', () => { + const result = run([ + at('a', 100, 100), + at('b', 120, 100), + at('c', 140, 100), + at('d', 160, 100), + at('e', 180, 100), + ]); + assert.deepEqual( + result.clusters.map((c) => c.ids), + [['a', 'b', 'c']], + ); + assert.deepEqual(result.single, ['d', 'e']); +}); + +test('zooming in keeps last pass’s clusters still in view before seeding anew', () => { + const points = [at('a', 100, 100), at('b', 140, 100), at('c', 100, 140)]; + const first = run(points); + const [kept] = first.state.clusters; + assert.equal(kept.minimumWidth, 97); + // Closer, with the points spread past a fresh seed's box but inside the + // kept cluster's (its box is measured from the top, the points' from the + // bottom, as the default renderer measures them). + const spread = [at('a', 70, 930), at('b', 200, 800), at('c', 70, 800)]; + const again = run(spread, { + eyeHeight: 900_000, + previous: first.state, + project: () => ({ x: 113, y: 113 }), + }); + assert.equal(again.clusters.length, 1); + assert.deepEqual(again.clusters[0].position, first.clusters[0].position); + assert.deepEqual([...again.clusters[0].ids].sort(), ['a', 'b', 'c']); + + // From higher up, the last pass is not consulted. + const higher = run(spread, { + eyeHeight: 1_100_000, + previous: first.state, + project: () => ({ x: 113, y: 113 }), + }); + assert.deepEqual(higher.clusters, []); + + // Nor a cluster now behind the horizon. + const hidden = run(spread, { + eyeHeight: 900_000, + previous: run(points).state, + project: () => ({ x: 113, y: 113 }), + isOccluded: () => true, + }); + assert.deepEqual(hidden.clusters, []); +}); + +test('many points cluster as a scan of every point would', () => { + let seed = 7; + const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + const points = Array.from({ length: 600 }, (_, i) => + at(`p${i}`, random() * 1600, random() * 1000), + ); + const result = run(points); + const all = [...result.single, ...result.clusters.flatMap((c) => c.ids)]; + assert.equal(all.length, 600); + assert.equal(new Set(all).size, 600, 'each point once'); + // Brute force, as the renderer does it. + const done = new Set(); + const expected = []; + const inBox = (s, o) => + Math.abs(o.screen.x - s.screen.x) <= 48.5 && + Math.abs(o.screen.y - s.screen.y) <= 48.5; + for (const s of points) { + if (done.has(s.id)) continue; + done.add(s.id); + const ids = [s.id]; + for (const o of points) if (!done.has(o.id) && inBox(s, o)) ids.push(o.id); + if (ids.length >= 3) { + expected.push(ids); + ids.forEach((id) => done.add(id)); + } + } + assert.deepEqual( + result.clusters.map((c) => c.ids), + expected, + ); +}); diff --git a/src/layers/radio/lifecycle.test.mjs b/src/layers/radio/lifecycle.test.mjs index d2e08d350..594893bd4 100644 --- a/src/layers/radio/lifecycle.test.mjs +++ b/src/layers/radio/lifecycle.test.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { createLifecycle } from './lifecycle.js'; import { createRendering } from './rendering.js'; import { createState } from './state.js'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; const overlays = () => ({ clearOverlaySource() {}, @@ -10,7 +11,7 @@ const overlays = () => ({ setOverlayEntries() {}, }); -/** A viewer whose data sources and entities record what was done to them. */ +/** A viewer whose data sources and entities would record what was done to them. */ function recordingViewer() { const calls = []; return { @@ -24,7 +25,7 @@ function recordingViewer() { }; } -test('the stations data source is added once, clustered, and removed with its listener', () => { +test('the stations draw sets are made once, cluster on camera moves, and go with their listener', () => { const services = { ground: { cachedGroundFloor: () => null }, overlays: overlays(), @@ -33,28 +34,52 @@ test('the stations data source is added once, clustered, and removed with its li const state = createState({ services }); const rendering = createRendering({ state, services, parts: {} }); const viewer = recordingViewer(); - state._viewer = viewer; + const changed = new Set(); + const camera = { + pose: () => null, + on(event, cb) { + assert.equal(event, 'changed'); + changed.add(cb); + return () => changed.delete(cb); + }, + }; + const { draw, unbind } = bindFakeDraw(viewer, { camera }); + try { + state._viewer = viewer; - rendering.installDataSource(viewer); - const source = state._dataSource; - assert.ok(source, 'a data source is made'); - assert.equal(source.name, 'Radio stations'); - assert.equal(source.clustering.enabled, true); - assert.equal(typeof state._removeClusterListener, 'function'); - rendering.installDataSource(viewer); - assert.deepEqual(viewer.calls, [['add', source]], 'added once'); + rendering.installDataSource(viewer); + const ids = () => + [...draw.sets.values()] + .filter((set) => !set.disposed) + .map((set) => `${set.kind}:${set.spec.id.replace(/^radio:\d+:/, '')}`); + assert.deepEqual(ids(), [ + 'points:stations', + 'points:clusters', + 'points:selected', + 'icons:selected-bracket', + ]); + assert.equal(changed.size, 1, 'clusters again as the camera moves'); + rendering.installDataSource(viewer); + assert.equal(ids().length, 4, 'made once'); - rendering.setStationsShown(false); - assert.equal(source.show, false); + rendering.setStationsShown(false); + assert.equal(draw.find('radio:').show, false); + assert.equal( + [...draw.sets.values()].find((set) => set.spec.id.endsWith(':clusters')) + .show, + false, + ); - rendering.removeDataSource(); - assert.deepEqual(viewer.calls.at(-1), ['remove', source, true]); - assert.equal(state._dataSource, null); - assert.equal(state._removeClusterListener, null); - assert.equal(source.clustering.clusterEvent.numberOfListeners, 0); + rendering.removeDataSource(); + assert.deepEqual(ids(), [], 'every set goes'); + assert.equal(changed.size, 0, 'and its camera listener'); + assert.deepEqual(viewer.calls, [], 'no Cesium data source or entity'); + } finally { + unbind(); + } }); -test('the lifecycle leaves the Cesium data source and entities to the rendering part', () => { +test("the lifecycle leaves the stations' draw sets to the rendering part", () => { const services = { overlays: overlays() }; const state = createState({ services }); const done = []; diff --git a/src/layers/radio/rendering.js b/src/layers/radio/rendering.js index 9d77ce5cc..5ce7fd73d 100644 --- a/src/layers/radio/rendering.js +++ b/src/layers/radio/rendering.js @@ -1,9 +1,14 @@ -import * as Cesium from 'cesium'; -// The Cesium camera factory: given a viewer of a caller's own, with no -// renderer bound, the layer's flights and camera reads find a camera port. -import '../../render/cesium/camera.js'; -import { clusterPointCollection as clusterPointsOf } from '../../render/cesium/internals.js'; -import { horizonOccluder } from '../../render/cesium/iconOrientation.js'; +import { cssColor } from '../../render/color.js'; +import { + canvasOf, + drawOf, + findCamera, + findQuery, +} from '../../render/rendererOf.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { distance } from '../../geo/vector.js'; +import { clusterScreenPoints } from '../../geo/screenCluster.js'; import { MARKER_LIFT_M, RADIO_PREFIX, @@ -15,8 +20,42 @@ import { DEFAULT_RADIO_FILTER, } from './policy.js'; +/** Draw sets made so far, by every Radio layer: set ids unique to each. */ +let instances = 0; + +/** Where a station's dot shows: from the ground out to the globe view. */ +const DISPLAY_RANGE = Object.freeze([ + 0, + RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M, +]); +const STATION_SCALE_BY_DISTANCE = Object.freeze({ + near: 100_000, + nearValue: 1.15, + far: 12_000_000, + farValue: 1, +}); +const BRACKET_SCALE_BY_DISTANCE = Object.freeze({ + near: 100_000, + nearValue: 1, + far: 12_000_000, + farValue: 0.72, +}); +const STATION_PIXEL_SIZE = 13; +const STATION_OUTLINE = cssColor('#071b25'); +const BLACK = Object.freeze([0, 0, 0, 1]); +/** Stations' screen clustering, as the stations' data source clustered them. */ +const CLUSTER_PIXEL_RANGE = 42; +const CLUSTER_MINIMUM_SIZE = 3; + +/** A CSS colour with another alpha. */ +function withAlpha(css, alpha) { + const [r, g, b] = cssColor(css) ?? [1, 1, 1]; + return [r, g, b, alpha]; +} + /** - * A station id from ordinary, selected, or Cesium cluster pick shapes. + * A station id from ordinary, selected, or cluster pick shapes: a pick id, + * a renderer pick's `{set, id}`, or a list of them. * @param {object|null|undefined} picked A scene pick result. * @returns {string|null} */ @@ -54,23 +93,92 @@ export function createRendering({ services.overlays; const { governorRequestRender } = services.render; + /** + * The layer's draw sets (made with `installDataSource`): the station + * dots, the cluster dots that stand in for stations drawn too close + * together, and the selected station's dot and bracket. + */ + let sets = null; + /** The camera subscription that clusters the stations again as it moves. */ + let offCameraChanged = null; + /** What the last clustering pass leaves for the next. */ + let clusterState = null; + /** + * The clusters drawn now, each `{position, stationIds}` with its seed + * station first, and the stations they hold. + */ + let clusters = []; + let clusteredIds = new Set(); + /** + * The stations the last clustering pass left on their own, or null before + * one: a station it passed over (past the horizon or behind the eye) is + * hidden until the next, as the default renderer's clustering hid it. + */ + let singleIds = null; + /** Each station dot's drawn show, by station id. */ + const drawnShow = new Map(); + /** The selected station's items while it has them, and whether shown. */ + let selection = null; + function markerPosition(station, liftM = MARKER_LIFT_M) { const floor = cachedGroundFloor(station.lat, station.lon); - return Cesium.Cartesian3.fromDegrees( + return fromDegrees( station.lon, station.lat, (Number.isFinite(floor) ? floor : 0) + liftM, ); } + /** The eye's pose, or null without a camera. */ + const pose = () => findCamera(layerState._viewer)?.pose() ?? null; + + /** A station's dot item, shown or not. */ + function stationItem(record, show) { + const markerColor = parts.model.radioCategoryColor( + parts.model.radioStationCategoryId(record.station), + ); + return { + id: `${RADIO_PREFIX}${record.station.id}`, + pos: record.position, + pixelSize: STATION_PIXEL_SIZE, + color: withAlpha(markerColor, 0.86), + outlineColor: STATION_OUTLINE, + outlineWidth: 1, + disableDepthTest: Infinity, + scaleByDistance: STATION_SCALE_BY_DISTANCE, + displayRange: DISPLAY_RANGE, + show, + }; + } + + /** + * Draw each station dot that is visible and not standing in a cluster, + * writing only the dots whose show changed. + */ + function syncStationShows() { + if (!sets) return false; + const changed = []; + for (const record of layerState._renderById.values()) { + const show = + record.visible && + (singleIds + ? singleIds.has(record.station.id) + : !clusteredIds.has(record.station.id)); + if (drawnShow.get(record.station.id) === show) continue; + drawnShow.set(record.station.id, show); + changed.push(stationItem(record, show)); + } + if (changed.length) sets.stations.upsert(changed); + return changed.length > 0; + } + function updateSelectionEntity() { - if (layerState._selectedEntity && layerState._viewer) - layerState._viewer.entities.remove(layerState._selectedEntity); - layerState._selectedEntity = null; + removeSelectionEntity(); const station = parts.queries.selectedPresentationStation(); if ( !parts.interaction.radioPresentationAllowed() || !layerState._viewer || + !sets || !station ) { scheduleRadioOverlayPublish(); @@ -79,41 +187,122 @@ export function createRendering({ const selectionColor = parts.model.radioCategoryColor( parts.model.radioStationCategoryId(station), ); - const bracketImage = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(parts.labels.radioSelectionBracketSvg(selectionColor))}`; - - layerState._selectedEntity = layerState._viewer.entities.add({ - id: `${RADIO_PREFIX}selected:${station.id}`, - position: markerPosition(station, SELECTED_LIFT_M), - point: { + const id = `${RADIO_PREFIX}selected:${station.id}`; + const position = markerPosition(station, SELECTED_LIFT_M); + selection = { + position, + shown: true, + dot: { + id, + pos: position, pixelSize: 14, - color: Cesium.Color.fromCssColorString(selectionColor), - outlineColor: Cesium.Color.BLACK, + color: cssColor(selectionColor), + outlineColor: BLACK, outlineWidth: 2, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - distanceDisplayCondition: new Cesium.DistanceDisplayCondition( - 0, - RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M, - ), + disableDepthTest: Infinity, + displayRange: DISPLAY_RANGE, }, - billboard: { - image: bracketImage, - width: 40, - height: 40, - horizontalOrigin: Cesium.HorizontalOrigin.CENTER, - verticalOrigin: Cesium.VerticalOrigin.CENTER, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - distanceDisplayCondition: new Cesium.DistanceDisplayCondition( - 0, - RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M, - ), - scaleByDistance: new Cesium.NearFarScalar(100_000, 1, 12_000_000, 0.72), + bracket: { + id, + pos: position, + image: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(parts.labels.radioSelectionBracketSvg(selectionColor))}`, + size: [40, 40], + disableDepthTest: Infinity, + displayRange: DISPLAY_RANGE, + scaleByDistance: BRACKET_SCALE_BY_DISTANCE, }, - }); + }; + sets.selectedDot.set([selection.dot]); + sets.selectedBracket.set([selection.bracket]); scheduleRadioOverlayPublish(); } - function clusterPointCollection() { - return clusterPointsOf(layerState._dataSource?.clustering); + /** Show or hide the selected station's dot and bracket. */ + function showSelection(shown) { + if (!selection || selection.shown === shown) return false; + selection.shown = shown; + sets.selectedDot.upsert([{ ...selection.dot, show: shown }]); + sets.selectedBracket.upsert([{ ...selection.bracket, show: shown }]); + return true; + } + + /** + * Cluster the visible stations on screen, as the stations' data source + * clustered them (`geo/screenCluster.js`), draw each cluster as a dot + * sized by its count and coloured by its stations' category, and hide the + * stations it holds. + */ + function clusterStations() { + if (!sets) return; + const query = findQuery(layerState._viewer); + const eye = pose(); + const points = []; + if (query && eye) { + const horizon = horizonFrom(eye.position); + for (const record of layerState._renderById.values()) { + if (!record.visible || !horizon.isPointVisible(record.position)) + continue; + const screen = query.project(record.position); + if (!screen) continue; + points.push({ + id: record.station.id, + position: record.position, + screen, + pixelSize: STATION_PIXEL_SIZE, + }); + } + } + const viewHeight = canvasOf(layerState._viewer)?.clientHeight ?? 0; + const result = clusterScreenPoints({ + points, + pixelRange: CLUSTER_PIXEL_RANGE, + minimumClusterSize: CLUSTER_MINIMUM_SIZE, + viewHeight, + eyeHeight: eye?.height ?? Number.POSITIVE_INFINITY, + previous: clusterState, + project: (position) => query.project(position), + isOccluded: (position) => + !horizonFrom(eye.position).isPointVisible(position), + }); + clusterState = result.state; + clusters = result.clusters.map(({ position, ids }) => ({ + position, + stationIds: ids, + })); + clusteredIds = new Set(clusters.flatMap((cluster) => cluster.stationIds)); + singleIds = query && eye ? new Set(result.single) : null; + sets.clusters.set(clusters.map(clusterItem)); + syncStationShows(); + scheduleRadioOverlayPublish(); + } + + /** A cluster's dot: its seed station's id, so a click plays that one. */ + function clusterItem(cluster) { + const clusteredStations = []; + for (const stationId of cluster.stationIds) { + const station = layerState._renderById.get(stationId)?.station; + if (station) clusteredStations.push(station); + } + const clusterCategory = parts.model.radioClusterCategoryId( + clusteredStations, + layerState._filter, + ); + return { + id: `${RADIO_PREFIX}${cluster.stationIds[0]}`, + pos: cluster.position, + pixelSize: Math.min(26, 12 + Math.log2(cluster.stationIds.length) * 1.6), + color: withAlpha(parts.model.radioCategoryColor(clusterCategory), 0.9), + outlineColor: BLACK, + outlineWidth: 2, + disableDepthTest: Infinity, + displayRange: DISPLAY_RANGE, + meta: { stationIds: cluster.stationIds }, + }; + } + + /** The clusters drawn now: `{position, stationIds}`, seed first. */ + function stationClusters() { + return clusters; } function publishRadioOverlayEntries() { @@ -139,18 +328,9 @@ export function createRendering({ const clusterCandidates = []; const clusteredStationIds = new Set(); - const points = clusterPointCollection(); - for (let index = 0; index < (points?.length || 0); index += 1) { - const point = points.get(index); - if ( - !point?.show || - !point.position || - !Array.isArray(point.id) || - point.id.length < 3 - ) - continue; - const stationIds = point.id - .map((entity) => String(entity?.id || '').slice(RADIO_PREFIX.length)) + for (const cluster of clusters) { + if (cluster.stationIds.length < 3) continue; + const stationIds = cluster.stationIds .filter((id) => { const station = layerState._stationById.get(id); return ( @@ -174,7 +354,7 @@ export function createRendering({ clusterCandidates.push({ id: `${stationIds[0]}:${stationIds.at(-1)}:${stationIds.length}`, stationIds, - point, + point: cluster, text: parts.model.radioClusterBadgeText(category, stationIds.length), accent: parts.model.radioCategoryColor(category), stationCount: stationIds.length, @@ -196,11 +376,10 @@ export function createRendering({ if (clusterEntry) entries.push(clusterEntry); } - const cameraPosition = layerState._viewer?.camera?.positionWC; + const eye = pose(); + const cameraPosition = eye?.position ?? null; const singletonAllowance = Math.min( - parts.clustering.radioSingletonLabelLimit( - layerState._viewer?.camera?.positionCartographic?.height, - ), + parts.clustering.radioSingletonLabelLimit(eye?.height), Math.max( 0, RADIO_OVERLAY_COHORT_LIMIT - selectedClusterCandidates.length, @@ -210,14 +389,14 @@ export function createRendering({ [...layerState._renderById.values()] .filter( (record) => - record.entity?.show && + record.visible && record.station?.id !== station?.id && !clusteredStationIds.has(record.station?.id), ) .map((record) => ({ ...record, distanceM: cameraPosition - ? Cesium.Cartesian3.distance(cameraPosition, record.position) + ? distance(cameraPosition, record.position) : Number.POSITIVE_INFINITY, })), singletonAllowance, @@ -275,8 +454,9 @@ export function createRendering({ } function updateRenderVisibility({ force = true } = {}) { - if (!layerState._viewer || !layerState._dataSource) return; - const cameraPosition = layerState._viewer.camera?.positionWC; + if (!layerState._viewer || !sets) return; + const eye = pose(); + const cameraPosition = eye?.position ?? null; if ( !force && !parts.navigation.radioCameraPositionChanged( @@ -289,26 +469,31 @@ export function createRendering({ ? { x: cameraPosition.x, y: cameraPosition.y, z: cameraPosition.z } : null; layerState._horizonScanCount += 1; - const occluder = horizonOccluder(layerState._viewer.camera); - let visibilityChanged = false; + // With no eye, as with no camera before, nothing is hidden by a horizon. + const visibleFrom = cameraPosition + ? horizonFrom(cameraPosition) + : { isPointVisible: () => true }; + let shownChanged = false; for (const record of layerState._renderById.values()) { const matches = parts.categories.stationMatchesRadioCategory( record.station, layerState._filter, ); - const visible = matches && occluder.isPointVisible(record.position); - if (record.entity.show !== visible) visibilityChanged = true; - record.entity.show = visible; - } - if (layerState._selectedEntity) { - const position = layerState._selectedEntity.position?.getValue?.( - Cesium.JulianDate.now(), - ); - const selectedVisible = !position || occluder.isPointVisible(position); - if (layerState._selectedEntity.show !== selectedVisible) - visibilityChanged = true; - layerState._selectedEntity.show = selectedVisible; + const visible = matches && visibleFrom.isPointVisible(record.position); + if (visible !== record.visible) shownChanged = true; + record.visible = visible; } + // A station shown or hidden clusters the stations again, as the default + // renderer's clustering did whenever one of its entities came or went. + let visibilityChanged = false; + if (shownChanged && sets.stations.show) { + clusterStations(); + visibilityChanged = true; + } else visibilityChanged = syncStationShows(); + if (selection) + visibilityChanged = + showSelection(visibleFrom.isPointVisible(selection.position)) || + visibilityChanged; scheduleRadioOverlayPublish(); // The horizon timer can commit AFTER the camera settles and the governor // parks the scene — a changed show flag needs one frame. (perf wave 2 fix) @@ -344,132 +529,88 @@ export function createRendering({ layerState._selectedId = null; } - if (layerState._dataSource) layerState._dataSource.entities.removeAll(); layerState._renderById.clear(); + drawnShow.clear(); + clusteredIds = new Set(); + singleIds = null; + const items = []; for (const station of stations) { - const position = markerPosition(station); - const markerColor = parts.model.radioCategoryColor( - parts.model.radioStationCategoryId(station), - ); - const entity = layerState._dataSource.entities.add({ - id: `${RADIO_PREFIX}${station.id}`, - position, - point: { - pixelSize: 13, - color: Cesium.Color.fromCssColorString(markerColor).withAlpha(0.86), - outlineColor: Cesium.Color.fromCssColorString('#071b25'), - outlineWidth: 1, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - scaleByDistance: new Cesium.NearFarScalar( - 100_000, - 1.15, - 12_000_000, - 1, - ), - distanceDisplayCondition: new Cesium.DistanceDisplayCondition( - 0, - RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M, - ), - }, - }); - layerState._renderById.set(station.id, { station, entity, position }); + const record = { station, position: markerPosition(station) }; + // Shown until the horizon pass below says otherwise. + record.visible = true; + layerState._renderById.set(station.id, record); + drawnShow.set(station.id, true); + items.push(stationItem(record, true)); } + sets?.stations.set(items); updateSelectionEntity(); updateRenderVisibility(); + clusterStations(); } - function installClusterStyling() { - if (!layerState._dataSource || layerState._removeClusterListener) return; - const clustering = layerState._dataSource.clustering; - clustering.enabled = true; - clustering.pixelRange = 42; - clustering.minimumClusterSize = 3; - clustering.clusterPoints = true; - clustering.clusterLabels = false; - clustering.clusterBillboards = false; - layerState._removeClusterListener = - clustering.clusterEvent.addEventListener((clusteredEntities, cluster) => { - const clusteredStations = []; - for (const entity of clusteredEntities) { - const stationId = String(entity.id || '').slice(RADIO_PREFIX.length); - const station = layerState._renderById.get(stationId)?.station; - if (station) clusteredStations.push(station); - } - const clusterCategory = parts.model.radioClusterCategoryId( - clusteredStations, - layerState._filter, - ); - const clusterColor = Cesium.Color.fromCssColorString( - parts.model.radioCategoryColor(clusterCategory), - ); - // Cesium assigns the entity-id array only to the generated cluster label. - // Mirror it to the visible point so clicking either part of the callout - // resolves the first station and remains a direct playback gesture. - cluster.point.id = clusteredEntities; - cluster.billboard.id = clusteredEntities; - cluster.label.show = false; - cluster.label.text = ''; - cluster.point.show = true; - cluster.point.pixelSize = Math.min( - 26, - 12 + Math.log2(clusteredEntities.length) * 1.6, - ); - cluster.point.color = clusterColor.withAlpha(0.9); - cluster.point.outlineColor = Cesium.Color.BLACK; - cluster.point.outlineWidth = 2; - cluster.point.disableDepthTestDistance = Number.POSITIVE_INFINITY; - cluster.point.distanceDisplayCondition = - new Cesium.DistanceDisplayCondition( - 0, - RADIO_GLOBE_INTERACTION_MAX_DISTANCE_M, - ); - scheduleRadioOverlayPublish(); - }); - } /** - * Add the stations' data source to the viewer, once, with its clustering. + * Make the stations' draw sets on the viewer's renderer (`drawOf`), once, + * and cluster the stations again whenever the camera moves enough. * @param {object} viewer */ function installDataSource(viewer) { - if (layerState._dataSource) return; - layerState._dataSource = new Cesium.CustomDataSource('Radio stations'); - viewer.dataSources.add(layerState._dataSource); - installClusterStyling(); + if (sets) return; + const draw = drawOf(viewer); + const prefix = `radio:${++instances}`; + sets = { + stations: draw.points({ id: `${prefix}:stations` }), + clusters: draw.points({ id: `${prefix}:clusters` }), + selectedDot: draw.points({ id: `${prefix}:selected` }), + selectedBracket: draw.icons({ id: `${prefix}:selected-bracket` }), + }; + offCameraChanged = + findCamera(viewer)?.on('changed', () => { + if (sets?.stations.show) clusterStations(); + }) ?? null; } - /** Stop styling clusters and take the data source off the viewer. */ + /** Stop clustering and let the stations' draw sets go. */ function removeDataSource() { - layerState._removeClusterListener?.(); - layerState._removeClusterListener = null; - if (layerState._dataSource && layerState._viewer) - layerState._viewer.dataSources.remove(layerState._dataSource, true); - layerState._dataSource = null; + offCameraChanged?.(); + offCameraChanged = null; + if (sets) for (const set of Object.values(sets)) set.dispose(); + sets = null; + selection = null; + clusterState = null; + clusters = []; + clusteredIds = new Set(); + singleIds = null; + drawnShow.clear(); } - /** Show or hide the stations' entities. */ + /** Show or hide the stations and their clusters. */ function setStationsShown(shown) { - if (layerState._dataSource) layerState._dataSource.show = shown; + if (!sets) return; + const was = sets.stations.show; + sets.stations.show = shown; + sets.clusters.show = shown; + // Hidden, the stations leave nothing for a later pass to keep, as the + // default renderer's clustering kept nothing of a hidden source. + if (!shown) clusterState = null; + if (shown && !was) clusterStations(); } - /** Remove the selected station's entity, if there is one. */ + /** Take the selected station's dot and bracket down, if it has them. */ function removeSelectionEntity() { - if (layerState._selectedEntity && layerState._viewer) - layerState._viewer.entities.remove(layerState._selectedEntity); - layerState._selectedEntity = null; + if (!selection) return; + selection = null; + sets?.selectedDot.clear(); + sets?.selectedBracket.clear(); } /** - * Entity visibility changes do not invalidate Cesium's existing cluster - * primitives. Toggle a public clustering input twice to mark the current - * cluster set dirty without changing its effective configuration. + * Cluster the stations again now: a filter change hides or shows + * stations, which the camera's next move would otherwise wait for. */ function reclusterStations() { - if (!layerState._dataSource?.clustering?.enabled) return; - const clustering = layerState._dataSource.clustering; - const clusterPoints = clustering.clusterPoints; - clustering.clusterPoints = !clusterPoints; - clustering.clusterPoints = clusterPoints; - layerState._viewer?.scene?.requestRender(); + if (!sets) return; + clusterStations(); + governorRequestRender('radio-recluster'); } return { @@ -481,11 +622,10 @@ export function createRendering({ reclusterStations, markerPosition, updateSelectionEntity, - clusterPointCollection, + stationClusters, publishRadioOverlayEntries, scheduleRadioOverlayPublish, updateRenderVisibility, reconcileStations, - installClusterStyling, }; } diff --git a/src/layers/radio/rendering.test.mjs b/src/layers/radio/rendering.test.mjs new file mode 100644 index 000000000..7f9c59529 --- /dev/null +++ b/src/layers/radio/rendering.test.mjs @@ -0,0 +1,141 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { fromDegrees, toLonLatH, WGS84 } from '../../geo/ellipsoid.js'; +import { radioStationIdFromPick } from './rendering.js'; +import { + radioStationRow, + withRadioLayer, +} from '../../testSupport/radioLayerHarness.mjs'; +import { radioLayer } from '../../data/radio.js'; + +const station = (n, lon, lat, tags = ['news']) => + radioStationRow({ + id: `00000000-0000-4000-8000-0000000000${String(n).padStart(2, '0')}`, + name: `Station ${n}`, + lon, + lat, + tags, + streamUrl: `https://radio.example.com/${n}.mp3`, + }); + +/** + * Camera and query ports over a flat projection, `pxPerDegree` CSS pixels a + * degree from (-98, 31) at the top left, with an eye over Austin. + */ +function flatRenderer() { + const listeners = new Set(); + const view = { pxPerDegree: 1000, height: 1_000_000 }; + const eye = () => fromDegrees(-97, 30, view.height); + return { + view, + listeners, + renderer: { + canvas: { clientWidth: 2000, clientHeight: 1000 }, + camera: { + pose: () => ({ position: eye(), height: view.height }), + on(event, cb) { + if (event !== 'changed') return () => {}; + listeners.add(cb); + return () => listeners.delete(cb); + }, + }, + query: { + project(p) { + const { lon, lat } = toLonLatH(p, WGS84); + return { + x: (lon + 98) * view.pxPerDegree, + y: (31 - lat) * view.pxPerDegree, + }; + }, + }, + }, + }; +} + +test('stations drawn close together on screen stand behind one cluster dot', async () => { + const flat = flatRenderer(); + const stations = [ + station(1, -97.0, 30.0), + station(2, -96.98, 30.0), + station(3, -97.0, 29.98), + station(4, -96.5, 30.0), + ]; + await withRadioLayer( + { stations, renderer: flat.renderer }, + async ({ draw }) => { + const set = (suffix) => + [...draw.sets.values()].find( + (record) => !record.disposed && record.spec.id.endsWith(suffix), + ); + const shown = () => + [...set(':stations').items.values()] + .filter((item) => item.show) + .map((item) => item.id); + const clusters = set(':clusters'); + assert.equal(clusters.items.size, 1, 'one cluster'); + const [cluster] = clusters.items.values(); + assert.equal(cluster.id, `radio:${stations[0].id}`, 'named by its seed'); + assert.deepEqual( + cluster.meta.stationIds, + stations.slice(0, 3).map((s) => s.id), + ); + // At the mean of its stations, sized by its count, news blue. + const { lon, lat } = toLonLatH(cluster.pos, WGS84); + assert.ok( + Math.abs(lon + 96.9933) < 1e-3 && Math.abs(lat - 29.9933) < 1e-3, + ); + assert.equal(cluster.pixelSize, 12 + Math.log2(3) * 1.6); + assert.equal(cluster.outlineWidth, 2); + assert.deepEqual( + shown(), + [`radio:${stations[3].id}`], + 'only the lone one', + ); + // A click on the cluster plays its seed station. + assert.equal( + radioStationIdFromPick({ + id: { set: clusters.spec.id, id: cluster.id }, + }), + stations[0].id, + ); + // Its badge is published with it. + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.equal(radioLayer.getOverlayDiagnostics().clusterTexts.length, 1); + + // Closer in, the stations spread apart: the camera's move clusters + // them again, and every station shows on its own. + flat.view.pxPerDegree = 20_000; + flat.view.height = 200_000; + for (const cb of flat.listeners) cb(); + assert.equal(clusters.items.size, 0); + assert.equal(shown().length, 4); + }, + ); +}); + +test('a filter that hides stations clusters them again at once', async () => { + const flat = flatRenderer(); + const stations = [ + station(1, -97.0, 30.0, ['news']), + station(2, -96.98, 30.0, ['news']), + station(3, -97.0, 29.98, ['jazz']), + ]; + await withRadioLayer( + { stations, renderer: flat.renderer }, + async ({ draw }) => { + const set = (suffix) => + [...draw.sets.values()].find( + (record) => !record.disposed && record.spec.id.endsWith(suffix), + ); + radioLayer.setFilter('all'); + assert.equal(set(':clusters').items.size, 1); + radioLayer.setFilter('news'); + assert.equal(set(':clusters').items.size, 0, 'two left: no cluster'); + const shown = [...set(':stations').items.values()].filter((i) => i.show); + assert.deepEqual( + shown.map((item) => item.id), + stations.slice(0, 2).map((s) => `radio:${s.id}`), + ); + }, + ); +}); diff --git a/src/layers/radio/state.js b/src/layers/radio/state.js index 9166210bc..fb1342640 100644 --- a/src/layers/radio/state.js +++ b/src/layers/radio/state.js @@ -14,8 +14,6 @@ export function createState({ services }) { layerState._viewer = null; - layerState._dataSource = null; - layerState._enabled = false; layerState._managerLifecyclePresentation = null; @@ -46,8 +44,6 @@ export function createState({ services }) { layerState._selectedId = null; - layerState._selectedEntity = null; - layerState._selectionGeneration = 0; layerState._selectionTimer = null; @@ -136,8 +132,6 @@ export function createState({ services }) { layerState._sessionGeneration = 0; - layerState._removeClusterListener = null; - layerState._overlayPublishTimer = null; layerState._clusterOverlayIdentitySequence = 0; diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 818320bf8..afead0d81 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -3009,6 +3009,99 @@ test('the FIRMS layer draws its fire glows as one GPU icon set on a viewer of it assert.equal(scene.added.length, 0); }); +test('the Radio layer draws its stations, clusters and selected marker as point and billboard sets', async () => { + const { withRadioLayer, radioStationRow } = + await import('../../testSupport/radioLayerHarness.mjs'); + const { radioLayer, radioStationIdFromPick } = + await import('../../data/radio.js'); + const { fromDegrees, toLonLatH, WGS84 } = + await import('../../geo/ellipsoid.js'); + const scene = fakeScene(); + const part = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }); + // A flat projection, 1000 CSS px a degree from (-98, 31) at the top left. + const renderer = { + draw: part.port, + canvas: { clientWidth: 2000, clientHeight: 1000 }, + camera: { + pose: () => ({ position: fromDegrees(-97, 30, 1e6), height: 1e6 }), + on: () => () => {}, + }, + query: { + project(p) { + const { lon, lat } = toLonLatH(p, WGS84); + return { x: (lon + 98) * 1000, y: (31 - lat) * 1000 }; + }, + }, + }; + const station = (n, lon, lat) => + radioStationRow({ + id: `00000000-0000-4000-8000-0000000000${String(n).padStart(2, '0')}`, + name: `Station ${n}`, + lon, + lat, + tags: ['news'], + streamUrl: `https://radio.example.com/${n}.mp3`, + }); + const stations = [ + station(1, -97.0, 30.0), + station(2, -96.98, 30.0), + station(3, -97.0, 29.98), + station(4, -96.5, 30.0), + ]; + await withRadioLayer({ stations, renderer }, async () => { + const rows = (pattern) => { + const out = []; + for (const host of scene.added) { + const collections = + host instanceof Cesium.PrimitiveCollection + ? [host.get(0), host.get(1)] + : [host]; + for (const collection of collections) + for (let i = 0; i < (collection?.length ?? 0); i += 1) { + const primitive = collection.get(i); + if (pattern.test(primitive.id?.set)) out.push(primitive); + } + } + return out; + }; + const dots = rows(/^radio:\d+:stations$/); + assert.equal(dots.length, 4); + assert.ok(dots.every((dot) => dot instanceof Cesium.PointPrimitive)); + const lone = dots.find((dot) => dot.show); + assert.equal(lone.id.id, `radio:${stations[3].id}`, 'the others are in a cluster'); + assert.equal(lone.pixelSize, 13); + assert.equal(lone.outlineWidth, 1); + assert.ok(Math.abs(lone.color.alpha - 0.86) < 1e-6); + assert.equal(lone.disableDepthTestDistance, Number.POSITIVE_INFINITY); + assert.equal(lone.distanceDisplayCondition.far, 50_000_000); + assert.equal(lone.scaleByDistance.nearValue, 1.15); + assert.equal(radioStationIdFromPick({ primitive: lone, id: lone.id }), stations[3].id); + + const [cluster] = rows(/^radio:\d+:clusters$/); + assert.deepEqual( + cluster.id.meta.stationIds, + stations.slice(0, 3).map((s) => s.id), + ); + assert.equal(cluster.pixelSize, 12 + Math.log2(3) * 1.6); + assert.equal(cluster.outlineWidth, 2); + assert.equal(radioStationIdFromPick({ primitive: cluster, id: cluster.id }), stations[0].id); + + radioLayer.selectStation(stations[3].id, { autoplay: false, focus: false }); + const [selected] = rows(/^radio:\d+:selected$/); + const [bracket] = rows(/^radio:\d+:selected-bracket$/); + assert.equal(selected.pixelSize, 14); + assert.equal(selected.id.id, `radio:selected:${stations[3].id}`); + assert.ok(bracket instanceof Cesium.Billboard); + assert.equal(bracket.width, 40); + assert.equal(bracket.scaleByDistance.farValue, 0.72); + assert.equal(radioStationIdFromPick({ primitive: bracket, id: bracket.id }), stations[3].id); + }); + assert.equal(scene.added.length, 0, 'gone with the layer'); +}); + test('vessels on a host with no sprite-set registry still draw, and say so once', async (t) => { const warnings = []; t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' '))); diff --git a/src/render/cesium/internals.js b/src/render/cesium/internals.js index e9530293d..80a33f8b4 100644 --- a/src/render/cesium/internals.js +++ b/src/render/cesium/internals.js @@ -46,15 +46,6 @@ export function billboardCollectionOf(billboard) { return billboard?._billboardCollection; } -/** - * The point collection an `EntityCluster` draws its cluster markers into. - * @param {object} clustering Cesium EntityCluster. - * @returns {object|null} Cesium PointPrimitiveCollection. - */ -export function clusterPointCollection(clustering) { - return clustering?._clusterPointCollection || null; -} - /** * Close the widget's pending render-loop latch after `useDefaultRenderLoop` * is set false, so a callback already queued sees the loop as stopped and diff --git a/src/render/cesium/internals.test.mjs b/src/render/cesium/internals.test.mjs index 75c152766..d454272aa 100644 --- a/src/render/cesium/internals.test.mjs +++ b/src/render/cesium/internals.test.mjs @@ -10,7 +10,6 @@ import { billboardLoadError, cameraFlightActive, closeRenderLoopLatch, - clusterPointCollection, commandExtents, creditDisplayContents, defaultView, @@ -43,7 +42,6 @@ test('every private field the app reaches is still declared by the installed Ces [ENGINE, 'Scene/Picking.js', '_pickOffscreenView'], [ENGINE, 'Scene/View.js', '_commandExtents'], [ENGINE, 'Scene/Billboard.js', '_billboardCollection'], - [ENGINE, 'DataSources/EntityCluster.js', '_clusterPointCollection'], [ENGINE, 'Widget/CesiumWidget.js', '_renderLoopRunning'], [WIDGETS, 'Viewer/Viewer.js', '_cesiumWidget'], [ENGINE, 'Renderer/Context.js', '_gl'], @@ -125,11 +123,6 @@ test('the helpers read and write exactly those fields', () => { billboardCollectionOf({ _billboardCollection: collection }), collection, ); - assert.equal( - clusterPointCollection({ _clusterPointCollection: collection }), - collection, - ); - assert.equal(clusterPointCollection(undefined), null); const widget = { _renderLoopRunning: true }; closeRenderLoopLatch({ _cesiumWidget: widget }); assert.equal(widget._renderLoopRunning, false); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 8986b6868..cddeacc54 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -15,7 +15,6 @@ "src/layers/launches/launchPad.js", "src/layers/launches/orbitRendering.js", "src/layers/launches/rendering.js", - "src/layers/radio/rendering.js", "src/layers/recentImagery/rendering.js", "src/layers/satellites/rendering.js", "src/layers/traffic/rendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 783693ed1..e277cd85a 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -92,6 +92,9 @@ const DRAW_FROM_CALLER = new Set([ // Its heat cells and fire glows draw through `drawOf`; its cards and LOD // watcher read the eye, projection and frames through the ports. './layers/firms', + // Its station dots, clusters and selected marker draw through `drawOf`; + // it clusters them on screen through the camera and query ports. + './layers/radio', // Its data packs draw through `drawOf`; its flights ask `cameraOf`, which // throws until then too. './scenes', diff --git a/src/testSupport/radioLayerHarness.mjs b/src/testSupport/radioLayerHarness.mjs index 45493357c..3aadedc10 100644 --- a/src/testSupport/radioLayerHarness.mjs +++ b/src/testSupport/radioLayerHarness.mjs @@ -1,4 +1,6 @@ import { radioLayer } from '../data/radio.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { bindFakeDraw } from './fakeDrawPort.mjs'; export function radioStationRow(overrides = {}) { return { @@ -21,11 +23,17 @@ export function radioStationRow(overrides = {}) { } /** - * Run `body` against an enabled `radioLayer` that serves `stations`. + * Run `body` against an enabled `radioLayer` that serves `stations`, drawing + * through `renderer.draw`, or a fake draw port (with `renderer`'s other + * ports, if given). * Streams listed in `failingUrls` (mutable) reject play(); `body` receives the - * played URLs and the catalog, whose rows and generation the next update() serves. + * played URLs, the catalog, whose rows and generation the next update() + * serves, and the fake draw port. */ -export async function withRadioLayer({ stations, failingUrls = [] }, body) { +export async function withRadioLayer( + { stations, failingUrls = [], renderer = {} }, + body, +) { const originalFetch = globalThis.fetch; const originalAudio = globalThis.Audio; const playUrls = []; @@ -76,24 +84,23 @@ export async function withRadioLayer({ stations, failingUrls = [] }, body) { removeEventListener() {}, }, }, - dataSources: { add() {}, remove() {} }, - entities: { - add(entity) { - return entity; - }, - remove() {}, - }, }; + // The stations draw through the renderer's draw port: `renderer.draw` + // when given, else a fake one. + const { draw, unbind } = renderer.draw + ? { draw: renderer.draw, unbind: bindRenderer(viewer, renderer) } + : bindFakeDraw(viewer, renderer); radioLayer.destroy(); try { radioLayer.init(viewer); radioLayer.enable(); await radioLayer.update(); - await body({ playUrls, catalog }); + await body({ playUrls, catalog, draw }); } finally { globalThis.fetch = originalFetch; if (originalAudio === undefined) delete globalThis.Audio; else globalThis.Audio = originalAudio; radioLayer.destroy(); + unbind(); } }