From d9e72dfc8b6d4325f40adfe9cd7b4c286061fce7 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 9 Nov 2026 10:34:53 -0800 Subject: [PATCH] World annotation renderer draws through the renderer's ports Areas, buildings, routes, arrows, pins and labels are draw-port shapes, lines and points, one set per mark, faded by upserting their colours. Pins pulse their ring and size it by camera height; arrows drape. Ground heights come from the heights service. The module leaves the Cesium allow-list. --- CHANGELOG.md | 8 + src/annotations/drawTool.test.mjs | 7 +- .../hybridAnnotationRenderer.test.mjs | 198 ++--- src/annotations/worldAnnotationRenderer.js | 825 ++++++++---------- .../worldAnnotationRenderer.test.mjs | 234 ++++- src/data/boundaryLabels.test.mjs | 45 +- src/data/sharedOsmDisplays.test.mjs | 5 +- src/render/cesium/draw.test.mjs | 95 ++ src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 3 + 10 files changed, 791 insertions(+), 630 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bca0a38e..bd9368105 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +- `gods-eye-view/annotations` no longer reaches Cesium: the world annotation + renderer draws its areas, building columns, routes, arrows, rings and + markers through the renderer's draw port (the Cesium renderer now drapes + arrows, draws clamped rings by camera height and pulses shape alpha), and + samples a building's ground through the height service. A click on a + world mark now hits its draw set (`meta: { annotation: id }`) rather than + an entity. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). - `gods-eye-view/application/layers` and `gods-eye-view/standalone/catalog` no longer reach Cesium: the weather shells and the wind layer's colour shell and flow draw through the renderer's `draw.field` (`rasterShell` and diff --git a/src/annotations/drawTool.test.mjs b/src/annotations/drawTool.test.mjs index 67ff94cfa..2d7b2a601 100644 --- a/src/annotations/drawTool.test.mjs +++ b/src/annotations/drawTool.test.mjs @@ -205,11 +205,8 @@ test('draped marks classify onto terrain as well as 3D tiles', () => { // rendered proof is in scripts/qa-draw-tool.mjs, which counts stroke pixels // against a keyless server; this stops the constant being narrowed again. const renderer = read('src/annotations/worldAnnotationRenderer.js'); - assert.match(renderer, /const CLASSIFY = Cesium\.ClassificationType\.BOTH;/); - assert.doesNotMatch( - renderer, - /classificationType: Cesium\.ClassificationType\.CESIUM_3D_TILE/, - ); + assert.match(renderer, /const CLAMP_TO = 'both';/); + assert.doesNotMatch(renderer, /clampTo: '(tiles|terrain)'/); }); test('the draw modules are registered for formatting and boundary checks', () => { diff --git a/src/annotations/hybridAnnotationRenderer.test.mjs b/src/annotations/hybridAnnotationRenderer.test.mjs index 8996c1618..ef56dea49 100644 --- a/src/annotations/hybridAnnotationRenderer.test.mjs +++ b/src/annotations/hybridAnnotationRenderer.test.mjs @@ -100,14 +100,33 @@ function withScenePorts(viewer) { const { unbind, ...ports } = bindFakeCesiumScene(viewer); unbind(); bindRenderer(viewer, { ...ports, credits: fakeCesiumCredits(viewer) }); - return viewer; + return ports.draw; +} + +/** What the world renderer draws, each item of its live sets (of `kind`). */ +function worldItems(draw, kind) { + const items = []; + for (const record of draw.sets.values()) + if ( + !record.disposed && + record.spec.id.startsWith('annotations:') && + (!kind || record.kind === kind) + ) + items.push(...record.items.values()); + return items; +} + +/** Surface heights the scene samples: `height(lon, lat)` in degrees. */ +function sampleHeights(scene, height) { + scene.sampleHeightSupported = true; + scene.sampleHeight = (carto) => + height(Cesium.Math.toDegrees(carto.longitude), Cesium.Math.toDegrees(carto.latitude)); } /** A viewer whose scene/camera is just enough for both sub-renderers. */ function fakeViewer(lon, lat) { const credits = new Set(); const camera = cameraLookingAt(lon, lat); - const dataSources = []; const frames = controlledFrames(); const scene = { camera, @@ -121,32 +140,19 @@ function fakeViewer(lon, lat) { scene.renderRequests += 1; }, }; - return { - dataSources, - frames, - viewer: withScenePorts({ - credits, - creditDisplay: { - addStaticCredit: (credit) => credits.add(credit), - removeStaticCredit: (credit) => credits.delete(credit), - }, - scene, - camera, - canvas: scene.canvas, - trackedEntity: null, - dataSources: { - add(dataSource) { - dataSources.push(dataSource); - return dataSource; - }, - remove(dataSource) { - const index = dataSources.indexOf(dataSource); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, - }, - }), + const viewer = { + credits, + creditDisplay: { + addStaticCredit: (credit) => credits.add(credit), + removeStaticCredit: (credit) => credits.delete(credit), + }, + scene, + camera, + canvas: scene.canvas, + trackedEntity: null, }; + const draw = withScenePorts(viewer); + return { draw, frames, viewer }; } function controlledFrames() { @@ -207,7 +213,6 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' }); const camera = cameraLookingAt(-99, 31); - const dataSources = []; const frames = controlledFrames(); const scene = { camera, @@ -223,20 +228,10 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' camera, canvas: scene.canvas, trackedEntity: null, - dataSources: { - add(dataSource) { - dataSources.push(dataSource); - return dataSource; - }, - remove(dataSource) { - const index = dataSources.indexOf(dataSource); - if (index >= 0) dataSources.splice(index, 1); - return index >= 0; - }, - }, }; - // The screen board projects through the renderer's camera and query. - bindFakeCesiumScene(viewer); + // The screen board projects through the renderer's camera and query; the + // world renderer draws through its draw port. + const { draw } = bindFakeCesiumScene(viewer); const { store, renderer } = hybridWithBoard(viewer); const anno = { id: 'anno-hybrid-fb3', @@ -253,8 +248,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' renderer.add(anno); const [before] = annotationGroups(store); assert.equal(childrenWithClass(before, 'gev-anno-ring').length, 2); - assert.equal(dataSources.length, 1); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); const ring = [ [-106, 25], @@ -286,10 +280,10 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' assert.equal(dot.attrs.cx, expectedWindow.x.toFixed(1)); assert.equal(dot.attrs.cy, expectedWindow.y.toFixed(1)); assert.deepEqual(centroid, { lon: -100.8, lat: 29.4, height: 0 }, 'closed-ring vertex mean stays pinned'); - assert.equal(dataSources[0].entities.values.length, 2, 'world area adds one fill and one outline'); - assert.equal(dataSources[0].entities.values.filter((entity) => entity.polygon).length, 1); - assert.equal(dataSources[0].entities.values.filter((entity) => entity.polyline).length, 1); - assert.equal(Object.hasOwn(anno, '_entities'), false, 'world entity state stays on the inherited proxy'); + assert.equal(worldItems(draw).length, 2, 'world area adds one fill and one outline'); + assert.equal(worldItems(draw, 'shapes').length, 1); + assert.equal(worldItems(draw, 'lines').length, 1); + assert.equal(Object.hasOwn(anno, '_draw'), false, 'world draw state stays on the inherited proxy'); const outer = [ [-99, 31], [-98.999, 31], @@ -316,33 +310,26 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' buildingHeight: 20, }; const completion = renderer.add(building); - assert.equal(dataSources[0].entities.values.length, 2, 'building geometry waits for all probes'); + assert.equal(worldItems(draw).length, 2, 'building geometry waits for all probes'); for (let frame = 0; frame < 8; frame += 1) frames.emit(); assert.equal((await completion).status, 'installed'); - const added = dataSources[0].entities.values.slice(2); - const fills = added.filter( - (entity) => entity.polygon && entity.polygon.fill?.getValue() !== false, - ); + const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:')); assert.equal( fills.length, 2, - 'every building part gets a classification volume', + 'every building part gets a volume', ); - assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1); - assert.equal(fills[1].polygon.hierarchy.getValue().holes.length, 0); + assert.equal(fills[0].geometry.rings.length, 2, 'the first with its hole'); + assert.equal(fills[1].geometry.rings.length, 1); + assert.deepEqual(fills[0].fill, fills[1].fill, 'parts share the fill colour'); assert.equal( - fills[0].polygon.material, - fills[1].polygon.material, - 'parts share the fill material', - ); - assert.equal( - added.filter((entity) => entity.polyline).length, + worldItems(draw, 'lines').filter((item) => item.id.startsWith('base:')).length, 3, 'all outer and hole outlines are retained', ); renderer.remove(building); assert.equal( - dataSources[0].entities.values.length, + worldItems(draw).length, 2, 'multipart removal leaves only the earlier area', ); @@ -359,7 +346,7 @@ test('hybrid outline upgrade preserves the screen group and adds world geometry' test('a sub-renderer throw mid-add leaves state the rollback can still remove', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -387,26 +374,26 @@ test('a sub-renderer throw mid-add leaves state the rollback can still remove', }; assert.throws(() => renderer.add(anno), /screen insert failed/); - assert.equal(dataSources[0].entities.values.length, 2, 'the world drape is already live'); + assert.equal(worldItems(draw).length, 2, 'the world drape is already live'); assert.equal(annotationGroups(store).length, 0, 'the half-built screen group detached itself'); // The engine's rollback path — it must reach the partial state by id. renderer.remove(anno); - assert.equal(dataSources[0].entities.values.length, 0, 'partial world state must be released'); + assert.equal(worldItems(draw).length, 0, 'partial world state must be released'); // …and the id is free again: a retry draws ONE mark, not a second one over // an orphan nothing owns. renderer.add(anno); - assert.equal(dataSources[0].entities.values.length, 2, 'the retry draws exactly one world drape'); + assert.equal(worldItems(draw).length, 2, 'the retry draws exactly one world drape'); assert.equal(annotationGroups(store).length, 1, 'and exactly one screen caption'); renderer.remove(anno); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); renderer.destroy(); }); test('a release that throws keeps the mark addressable for a retry cleanup', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -422,7 +409,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) }; renderer.add(anno); - assert.equal(dataSources[0].entities.values.length, 2); + assert.equal(worldItems(draw).length, 2); assert.equal(annotationGroups(store).length, 1); // The world route releases fine, then the screen release fails part-way @@ -430,7 +417,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) const workingSetTimeout = globalThis.window.setTimeout; globalThis.window.setTimeout = () => { throw new Error('teardown scheduling failed'); }; assert.throws(() => renderer.remove(anno), /teardown scheduling failed/); - assert.equal(dataSources[0].entities.values.length, 0, 'the world route did release'); + assert.equal(worldItems(draw).length, 0, 'the world route did release'); assert.equal(annotationGroups(store).length, 1, 'the screen route did NOT — that is the orphan'); // Dropping the routing entry here would make that orphan permanently @@ -438,7 +425,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) globalThis.window.setTimeout = workingSetTimeout; renderer.remove(anno); assert.equal(annotationGroups(store).length, 0, 'the retry cleanup must reach the orphan'); - assert.equal(dataSources[0].entities.values.length, 0, 'without double-releasing the world route'); + assert.equal(worldItems(draw).length, 0, 'without double-releasing the world route'); // Fully released now — a third call is inert. renderer.remove(anno); @@ -448,7 +435,7 @@ test('a release that throws keeps the mark addressable for a retry cleanup', (t) test('a world add that fails mid-way leaves its landed entities removable', (t) => { installBrowserGlobals(t); - const { viewer, dataSources } = fakeViewer(-99, 31); + const { viewer, draw } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]]; const anno = { @@ -464,25 +451,23 @@ test('a world add that fails mid-way leaves its landed entities removable', (t) }; // The draped fill lands; the outline throws (bad geometry / lost context). - const entities = dataSources[0].entities; - const realAdd = entities.add.bind(entities); - let addsLeft = 1; - entities.add = (options) => { - if (addsLeft <= 0) throw new Error('entity add failed'); - addsLeft -= 1; - return realAdd(options); + const realLines = draw.lines; + draw.lines = (spec) => { + const set = realLines(spec); + set.set = () => { throw new Error('draw failed'); }; + return set; }; - assert.throws(() => renderer.add(anno), /entity add failed/); - assert.equal(entities.values.length, 1, 'one entity landed before the failure'); + assert.throws(() => renderer.add(anno), /draw failed/); + assert.equal(worldItems(draw).length, 1, 'one item landed before the failure'); - entities.add = realAdd; + draw.lines = realLines; renderer.remove(anno); - assert.equal(entities.values.length, 0, - 'the rollback must see the entities that landed before the throw'); + assert.equal(worldItems(draw).length, 0, + 'the rollback must see the items that landed before the throw'); renderer.add(anno); - assert.equal(entities.values.length, 2, 'the retry draws a complete mark'); + assert.equal(worldItems(draw).length, 2, 'the retry draws a complete mark'); assert.equal(annotationGroups(store).length, 1); renderer.destroy(); }); @@ -493,7 +478,7 @@ function workTrace() { test('buildings share one probe per frame and preserve probe geometry, filtering and fallback', async (t) => { installBrowserGlobals(t); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); t.after(() => renderer.destroy()); const first = buildingAnnotation('sampled-building'); @@ -503,15 +488,12 @@ test('buildings share one probe per frame and preserve probe geometry, filtering showOsmCredit(viewer, otherOwner); const probes = []; const outcomes = [-500, 120, 30, null, new Error('tile unavailable'), 60, 9001, 90]; - viewer.scene.clampToHeight = (position) => { - const cartographic = Cesium.Cartographic.fromCartesian(position); - const lon = Cesium.Math.toDegrees(cartographic.longitude); - const lat = Cesium.Math.toDegrees(cartographic.latitude); + sampleHeights(viewer.scene, (lon, lat) => { probes.push([lon, lat]); const outcome = outcomes[probes.length - 1]; if (outcome instanceof Error) throw outcome; - return outcome == null ? undefined : Cesium.Cartesian3.fromDegrees(lon, lat, outcome); - }; + return outcome == null ? undefined : outcome; + }); // Suppress screen points: these counts concern the eight outside-building // probes, not the screen renderer's separate anchor-height sampling. const firstTrace = workTrace(); @@ -528,14 +510,14 @@ test('buildings share one probe per frame and preserve probe geometry, filtering const firstCompletion = renderer.add(first, { pendingVisible: false, workTrace: firstTrace }); const secondCompletion = renderer.add(second, { pendingVisible: false, workTrace: secondTrace }); assert.equal(probes.length, 0, 'enqueue must not probe synchronously'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1, 'pending outlines add no tile credit to the other owner'); for (let frame = 0; frame < 16; frame += 1) { const before = probes.length; frames.emit(); assert.equal(probes.length, before + 1, 'the two buildings share one total probe budget'); - if (frame < 7) assert.equal(dataSources[0].entities.values.length, 0, 'no partial world parts'); + if (frame < 7) assert.equal(worldItems(draw).length, 0, 'no partial world parts'); } const [installed, fallback] = await Promise.all([firstCompletion, secondCompletion]); assert.equal(installed.status, 'installed'); @@ -590,10 +572,10 @@ test('buildings share one probe per frame and preserve probe geometry, filtering assert.ok(Math.abs(probes[index + 8][1] - probes[index][1]) < 1e-10); } assert.equal(new Set(probes.slice(0, 8).map((point) => point.join(','))).size, 8); - const fills = dataSources[0].entities.values.filter((entity) => entity.polygon?.fill?.getValue() !== false && entity.polygon); + const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:')); assert.equal(fills.length, 2); - assert.ok(Math.abs(fills[0].polygon.height.getValue() - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3'); - assert.ok(Math.abs(fills[1].polygon.height.getValue() - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback'); + assert.ok(Math.abs(fills[0].geometry.rings[0][0].height - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3'); + assert.ok(Math.abs(fills[1].geometry.rings[0][0].height - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback'); const afterCompletion = probes.length; frames.emit(); assert.equal(probes.length, afterCompletion, 'completion releases the sampler'); @@ -616,7 +598,7 @@ test('a building queued behind others gets its full budget on a slow device', as t.mock.method(globalThis.performance, 'now', () => now); const { viewer, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); - viewer.scene.clampToHeight = (position) => position; + sampleHeights(viewer.scene, () => 0); const traces = [workTrace(), workTrace(), workTrace()]; const completions = [0, 0.01, 0.02].map((offset, index) => renderer.add(buildingAnnotation(`queued-${index}`, offset), { @@ -645,10 +627,10 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks installBrowserGlobals(t); t.mock.timers.enable({ apis: ['setTimeout'] }); t.after(() => t.mock.timers.reset()); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const renderer = createHybridAnnotationRenderer(viewer); let probeCount = 0; - viewer.scene.clampToHeight = (position) => { probeCount += 1; return position; }; + sampleHeights(viewer.scene, () => { probeCount += 1; return 0; }); const cancelled = buildingAnnotation('cancelled-building'); const cancelledTrace = workTrace(); const cancelledCompletion = renderer.add(cancelled, { pendingVisible: false, workTrace: cancelledTrace }); @@ -690,7 +672,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks assert.equal(viewer.credits.size, 0); for (const listener of savedTimeout) listener(); assert.equal(probeCount, 1, 'saved callbacks cannot revive timed-out tasks'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); const pending = buildingAnnotation('destroyed-building'); const destruction = renderer.add(pending, { pendingVisible: false }); @@ -700,7 +682,7 @@ test('building cancellation, queued deadline and destroy prevent saved callbacks for (const listener of savedDestroy) listener(); t.mock.timers.tick(2000); assert.equal(probeCount, 1); - assert.equal(dataSources.length, 0, 'destroy removes the owned data source'); + assert.ok([...draw.sets.values()].every((record) => record.disposed), 'destroy lets every set go'); assert.equal(frames.size, 0, 'destroy removes frame listeners'); assert.equal(viewer.credits.size, 0); }); @@ -709,7 +691,7 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy installBrowserGlobals(t); t.mock.timers.enable({ apis: ['setTimeout'] }); t.after(() => t.mock.timers.reset()); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const anno = { ...buildingAnnotation('pending-upgrade'), ring: null, label: 'Building' }; renderer.add(anno); @@ -722,15 +704,15 @@ test('a timed-out building upgrade keeps its existing pending screen group', asy assert.equal(after.key, before.key); assert.equal(others.length, 0); assert.ok(childrenWithClass(after, 'gev-anno-ring').length > 0, 'the honest pending point is not converted'); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); frames.emit(); - assert.equal(dataSources[0].entities.values.length, 0); + assert.equal(worldItems(draw).length, 0); renderer.destroy(); }); test('an asynchronous caption-conversion throw rolls back multipart world geometry and remains removable', async (t) => { installBrowserGlobals(t); - const { viewer, dataSources, frames } = fakeViewer(-99, 31); + const { viewer, draw, frames } = fakeViewer(-99, 31); const { store, renderer } = hybridWithBoard(viewer); const anno = { ...buildingAnnotation('caption-failure'), ring: null, label: 'Building' }; renderer.add(anno); @@ -743,7 +725,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet // Frame projection is still ordinary pending-point work. Arm the failure // only after sampling completes, before its promise converts the caption. for (let frame = 0; frame < 8; frame += 1) frames.emit(); - assert.ok(dataSources[0].entities.values.length > 0, 'multipart world geometry landed before caption conversion'); + assert.ok(worldItems(draw).length > 0, 'multipart world geometry landed before caption conversion'); assert.equal(viewer.credits.size, 2, 'credit belongs to the committed world proxy'); // The caption conversion fails when it presents the converted mark. const publish = store.publish; @@ -766,7 +748,7 @@ test('an asynchronous caption-conversion throw rolls back multipart world geomet assert.equal(captionTrace.slices.filter(s => s.phase === 'ground-step').length, 8); assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-complete').length, 1); assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-rollback').length, 1); - assert.equal(dataSources[0].entities.values.length, 0, 'all classification, cage and outline parts roll back'); + assert.equal(worldItems(draw).length, 0, 'all classification, cage and outline parts roll back'); assert.equal(viewer.credits.size, 0, 'caption rollback releases that same proxy'); assert.equal(annotationGroups(store).length, 1, 'failed screen cleanup remains addressable'); globalThis.window.setTimeout = workingSetTimeout; diff --git a/src/annotations/worldAnnotationRenderer.js b/src/annotations/worldAnnotationRenderer.js index 7cf59d02d..1d73b05b5 100644 --- a/src/annotations/worldAnnotationRenderer.js +++ b/src/annotations/worldAnnotationRenderer.js @@ -1,70 +1,87 @@ import { recordWorkSlice } from '../sources/phaseTiming.js'; import { ringCentroid } from '../sources/featureGeometry.js'; -import * as Cesium from 'cesium'; import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; -import { heightsFor } from '../render/cesium/heights.js'; -// The annotations entry's Cesium side: it loads the factories that build -// the camera, frame and query ports the engine and screen renderer ask for -// on a viewer with no renderer bound. -import '../render/cesium/camera.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { drawOf, frameOf } from '../render/rendererOf.js'; +import { heightsOf } from '../queries/heights.js'; /** * World-space annotation renderer (Direction A). * - * Draws annotations as native Cesium entities anchored to lon/lat. Because they - * live in the 3D scene they track the camera, sit at the right depth, and are - * occluded by the photoreal buildings the way a real marker would be. + * Draws annotations through the renderer's draw port, anchored to lon/lat. + * Because they live in the 3D scene they track the camera, sit at the right + * depth, and are occluded by the photoreal buildings the way a real marker + * would be. * * IMPORTANT — drawing on Google Photorealistic 3D Tiles: - * The Cesium globe is hidden, so there is no terrain to clamp to. Ground - * geometry (areas, rings, connectors) is draped onto the photoreal tiles with - * `classificationType: CESIUM_3D_TILE`; points clamp to the tile - * surface with `heightReference: CLAMP_TO_GROUND` (which requires the tileset - * to have `enableCollision = true`, set in initAnnotations). This keeps marks - * sitting ON the world instead of buried at sea level. + * The globe is hidden, so there is no terrain to clamp to. Ground geometry + * (areas, rings, connectors) is draped onto the photoreal tiles and the + * terrain alike (`clampTo: 'both'`); points clamp to the surface. This + * keeps marks sitting ON the world instead of buried at sea level. * - * Live alpha (fade in/out) and pulsing are driven by CallbackProperty so they - * animate every render without the engine touching them per frame. + * Fades follow the mark's alpha: the engine calls `sync` as it changes, and + * each mark's items take their new colours where they are. Pulsing fills + * are a declarative pulse the renderer runs; target rings follow the + * camera's height, which the renderer reads each frame. + * + * Each mark draws into sets of its own, so adding or removing one leaves + * the others' geometry alone. * * Renderer contract (shared with the screen-space renderer): * add(anno) / remove(anno) / sync(map) / destroy() */ +/** Each palette colour as `r, g, b`, 0..1. */ const PALETTE = { - primary: '#8be9ff', - amber: '#ffb547', - cyan: '#39d0ff', - green: '#5dff9f', - red: '#ff6b6b', + primary: rgb('#8be9ff'), + amber: rgb('#ffb547'), + cyan: rgb('#39d0ff'), + green: rgb('#5dff9f'), + red: rgb('#ff6b6b'), }; +const WHITE = [1, 1, 1]; /** - * What a draped mark is allowed to paint onto. - * - * This was CESIUM_3D_TILE, which is right with Google's photoreal tiles under - * the camera and wrong everywhere else: on a keyless boot (Esri or OSM imagery - * on Cesium's own globe) there are no 3D tiles to classify against, so every - * area fill, area outline, route and arrow rendered to nothing. The labels - * showed and the geometry did not, which reads as a broken feature rather than - * an unsupported surface — and it hit spoken annotations exactly as hard as - * hand-drawn ones. - * - * BOTH paints onto terrain AND onto 3D tiles, so one value covers both worlds. + * What a draped mark is allowed to paint onto: terrain AND 3D tiles, so one + * value covers a keyless boot (imagery on the globe, no tiles) and the + * photoreal world alike. Tiles alone rendered every area, route and arrow to + * nothing on a keyless boot. */ -const CLASSIFY = Cesium.ClassificationType.BOTH; -const CLAMP = Cesium.HeightReference.CLAMP_TO_GROUND; +const CLAMP_TO = 'both'; + +/** + * The pulse of a pulsing fill: its alpha swings between 60% and all of its + * own, a sine of about 0.8 Hz on the wall clock. + */ +const PULSE_MS = (2 * Math.PI) / 0.005; +const PULSE_LOW = 0.6; + +/** Target rings: 3% of the camera's height, between 14 m and 170 m. */ +const RING_RADIUS = Object.freeze({ + byCameraHeight: Object.freeze({ factor: 0.03, min: 14, max: 170 }), +}); + +/** + * Each renderer's sets have ids of their own, unique across copies of this + * module on one viewer too. + */ +let rendererSeq = 0; +const MODULE_TOKEN = Math.random().toString(36).slice(2, 8); export function createWorldAnnotationRenderer(viewer) { - const dataSource = new Cesium.CustomDataSource('gev-annotations'); - viewer.dataSources.add(dataSource); + const draw = drawOf(viewer); + const instance = `${MODULE_TOKEN}${(rendererSeq += 1)}`; + let markSeq = 0; const osmAnnotations = new Set(); - // Every mark with entities on the globe, so sync() can take a hidden one out. + // Every mark with sets on the globe, so sync() can take a hidden one out. const drawn = new Set(); const pendingGround = new Map(); const groundQueue = []; - let observingGround = false; + let offGroundFrame = null; let destroyed = false; + const requestRender = () => frameOf(viewer).requestRender('annotations'); + function sampleBuilding(anno, options) { pendingGround.get(anno)?.finish('cancelled'); return new Promise((resolve, reject) => { @@ -112,7 +129,7 @@ export function createWorldAnnotationRenderer(viewer) { // A task promoted outside a frame (its predecessor timed out or was // cancelled) still needs frames in request-render mode. try { - viewer.scene.requestRender?.(); + requestRender(); } catch { /* the enqueue path reports render failures */ } @@ -125,9 +142,9 @@ export function createWorldAnnotationRenderer(viewer) { clearTimeout(task.timer); if (position === 0) groundQueue[0]?.begin(); options.signal?.removeEventListener('abort', task.abort); - if (!groundQueue.length && observingGround) { - viewer.scene.postRender.removeEventListener(onGroundFrame); - observingGround = false; + if (!groundQueue.length && offGroundFrame) { + offGroundFrame(); + offGroundFrame = null; } timing.elapsedMs = performance.now() - (started ?? queuedAt); if (workTrace) { @@ -179,24 +196,25 @@ export function createWorldAnnotationRenderer(viewer) { const sliceStart = performance.now(); let error; try { - if (heightsFor(viewer.scene).supported().clamp) { + // Without depth support the surface answers nothing: the + // probes are skipped, and the fallback height is taken. + if (heightsOf(viewer).supported().surface) { const [lon, lat] = task.points[task.index++]; timing.probes += 1; try { - const position = Cesium.Cartesian3.fromDegrees(lon, lat, 0); - let c; + let h; note?.('clampStart'); try { - c = heightsFor(viewer.scene).clampNow(position); - if (detail) detail.clampResult = c ? 'hit' : 'missed'; + // The surface under the probe: the drawn tiles or terrain, + // never a mark (no draw set is in height queries). + h = heightsOf(viewer).now({ lon, lat }); + if (detail) + detail.clampResult = Number.isFinite(h) ? 'hit' : 'missed'; } finally { note?.('clampEnd'); } - if (c) { - const h = Cesium.Cartographic.fromCartesian(c).height; - if (Number.isFinite(h) && h > -430 && h < 9000) - task.samples.push(h); - } + if (Number.isFinite(h) && h > -430 && h < 9000) + task.samples.push(h); } catch { /* surface not ready: preserve the existing sample filter */ } @@ -241,7 +259,7 @@ export function createWorldAnnotationRenderer(viewer) { task.finish('installed'); } finally { // Commit includes sort/selection/add/deadline/finish or rollback, - // including intervening bookkeeping; it is not exclusive entity cost. + // including intervening bookkeeping; it is not exclusive draw cost. if (detail?.commitStatus === 'attempted') note('commitEnd'); if (workTrace) recordWorkSlice( @@ -258,12 +276,10 @@ export function createWorldAnnotationRenderer(viewer) { if (groundQueue[0] === task) task.begin(); options.signal?.addEventListener('abort', task.abort, { once: true }); if (!task.current()) return task.finish('cancelled'); - if (!observingGround) { - viewer.scene.postRender.addEventListener(onGroundFrame); - observingGround = true; - } try { - viewer.scene.requestRender?.(); + if (!offGroundFrame) + offGroundFrame = frameOf(viewer).on('postRender', onGroundFrame); + requestRender(); } catch (error) { task.finish('failed', error); } @@ -275,49 +291,43 @@ export function createWorldAnnotationRenderer(viewer) { const task = groundQueue[0]; try { task?.step(); - if (groundQueue.length) viewer.scene.requestRender?.(); + if (groundQueue.length) requestRender(); } catch (error) { for (const pending of [...groundQueue]) pending.finish('failed', error); } } - - // Register the GevRouteFlow fabric once so Cesium's Material.fromType() can build the - // material the route pipeline renders. The animated `time` uniform is read straight - // from performance.now() inside FlowMaterialProperty.getValue (which Cesium calls each - // rendered frame with the live uniforms object), so the dashes flow with no extra - // per-frame bookkeeping. - ensureFlowFabricRegistered(); - - function colorFor(anno) { - return Cesium.Color.fromCssColorString( - PALETTE[anno.color] || PALETTE.primary, - ); + /** + * The mark's draw sets, made on first use: shapes (fills, volumes, rings), + * lines (outlines, routes, arrows) and points (markers). + */ + function setsOf(anno) { + if (!anno._draw) { + markSeq += 1; + const prefix = `annotations:${instance}:${markSeq}`; + anno._draw = { prefix, shapes: null, lines: null, points: null }; + } + return anno._draw; } - // Target-ring radius (meters) scaled to camera height so it reads at any - // altitude. Read once per frame for BOTH ellipse axes — camera height is - // constant within a frame, so semiMajor === semiMinor always holds. - function ringRadius() { - const h = viewer.camera.positionCartographic?.height ?? 1000; - return Math.max(14, Math.min(170, h * 0.03)); - } - - // A live color that follows the annotation's fade alpha and an optional pulse. - function liveColor(anno, base, { alpha = 0.9, pulse = false } = {}) { - return new Cesium.CallbackProperty(() => { - const a = (anno.alpha ?? 1) * alpha * (pulse ? pulseFactor() : 1); - return base.withAlpha(Math.max(0, Math.min(1, a))); - }, false); + function setOf(anno, kind) { + const sets = setsOf(anno); + if (!sets[kind]) { + sets[kind] = draw[kind]({ + id: `${sets.prefix}:${kind}`, + clampTo: CLAMP_TO, + show: !anno.hidden, + }); + } + return sets[kind]; } function add(anno, options = {}) { - const base = colorFor(anno); - // Published to the mark BEFORE anything is added, and mutated in place as - // each entity lands: a mid-add failure (bad geometry, lost context) must - // leave the entities that DID land visible to remove(), or the rollback - // path cannot reach them and they stay on the globe forever. - const entities = []; - anno._entities = entities; + // A destroyed renderer draws nothing more. + if (destroyed) return; + // Published to the mark BEFORE anything is drawn: a mid-add failure (bad + // geometry, lost context) must leave the sets that DID land visible to + // remove(), or the rollback path cannot reach them and they stay on the + // globe forever. drawn.add(anno); if ( @@ -328,253 +338,33 @@ export function createWorldAnnotationRenderer(viewer) { return sampleBuilding(anno, options); } - if ( - anno.ring && - anno.ring.length >= 3 && - anno.footprintKind === 'building' - ) { - const addBuildingEntity = (definition) => { - if (!(options.isCurrent?.() ?? true)) - throw new Error('Building install cancelled'); - const entity = dataSource.entities.add(definition); - if (!(options.isCurrent?.() ?? true)) { - dataSource.entities.remove(entity); - throw new Error('Building install cancelled'); - } - return entity; - }; - // Single building → the PRIMARY highlight is an extruded CLASSIFICATION - // volume that tints the real photogrammetry mesh (dome, walls, roof — - // everything inside the column) amber and pulses. A flat footprint - // extrusion is only 2.5D and misses domes; classification colors the - // actual tiles. A faint wireframe cage rides on top as a secondary cue. - const parts = - Array.isArray(anno.polygons) && anno.polygons.length - ? anno.polygons - : [[anno.ring]]; - const groundH = - options.sampledGroundHeight ?? - (Number.isFinite(anno.anchor.height) - ? anno.anchor.height - (anno.buildingHeight || 25) - : 0); - const baseH = groundH - 3; - // Tall headroom is free: classification only colors where tiles exist, so - // empty air above the roof isn't tinted — this just guarantees we cover - // under-tagged building heights. - const topH = groundH + Math.max(18, anno.buildingHeight || 25) + 24; - const fillMaterial = new Cesium.ColorMaterialProperty( - liveColor(anno, base, { alpha: 0.45, pulse: true }), - ); - const lineMaterial = new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.25, - color: liveColor(anno, base, { alpha: 0.7 }), - }); - for (const [outer, ...holes] of parts) { - const buffered = bufferRing(outer, 3); - const positions = Cesium.Cartesian3.fromDegreesArray(buffered.flat()); - // 1) Classification volume — tints the mesh amber, pulsing. - entities.push( - addBuildingEntity({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - positions, - holes.map( - (hole) => - new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(hole.flat()), - ), - ), - ), - height: baseH, - extrudedHeight: topH, - perPositionHeight: false, - classificationType: CLASSIFY, - material: fillMaterial, - }, - }), - ); - // 2) Faint, SIMPLIFIED wireframe cage — secondary, lower opacity. Decimate - // the footprint so the extruded outline draws ~14 clean verticals, not one - // per (often 100+) ring vertex. - const cagePositions = Cesium.Cartesian3.fromDegreesArray( - decimateRing(buffered, 14).flat(), - ); - entities.push( - addBuildingEntity({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy(cagePositions), - height: baseH, - extrudedHeight: topH, - perPositionHeight: false, - fill: false, - outline: true, - outlineColor: liveColor(anno, base, { alpha: 0.32, pulse: true }), - }, - }), - ); - // 3) Crisp draped base outline so the footprint reads on the ground. - for (const ring of [outer, ...holes]) { - entities.push( - addBuildingEntity({ - polyline: { - positions: Cesium.Cartesian3.fromDegreesArray( - closedRing(ring).flat(), - ), - width: 3, - material: lineMaterial, - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } + const items = itemsOf(anno, options); + anno._drawn = { alpha: alphaOf(anno), items }; + const current = () => options.isCurrent?.() ?? true; + const building = anno.footprintKind === 'building'; + for (const kind of ['shapes', 'lines', 'points']) { + if (!items[kind].length) { + // Added again as another kind: what it drew before goes. + disposeSet(anno, kind); + continue; } - } else if (anno.ring && anno.ring.length >= 3) { - // Larger area (district / compound / park / state) → flat fill draped on - // the tiles + a glowing outline. Draping is right here: you can't extrude - // a whole neighbourhood, and the GIS overlay shows the boundary clearly. - // A multi-part outline (`anno.polygons`: Hawaii's islands, Berlin as a - // hole in Brandenburg) draws every part with its holes. All parts share - // ONE fill and ONE line material, so Cesium batches the whole mark into a - // ground primitive per kind instead of one per island. - const parts = - Array.isArray(anno.polygons) && anno.polygons.length - ? anno.polygons - : [[anno.ring]]; - const fillMaterial = new Cesium.ColorMaterialProperty( - // Synthesized (approximate) areas get a fainter fill so they don't read as solid. - liveColor(anno, base, { - alpha: anno.synthesized ? 0.1 : 0.2, - pulse: true, - }), - ); - // Synthesized → DASHED outline (signals "approximate, not an authoritative - // boundary", research §8.4/§8.6); real footprints → solid glow. - const lineMaterial = anno.synthesized - ? new Cesium.PolylineDashMaterialProperty({ - color: liveColor(anno, base, { alpha: 0.95 }), - dashLength: 24, - }) - : new Cesium.PolylineGlowMaterialProperty({ - glowPower: 0.35, - color: liveColor(anno, base, { alpha: 1 }), - }); - for (const [outer, ...holes] of parts) { - if (!Array.isArray(outer) || outer.length < 3) continue; - const rings = [outer, ...holes.filter((h) => h?.length >= 3)]; - entities.push( - dataSource.entities.add({ - polygon: { - hierarchy: new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(outer.flat()), - rings - .slice(1) - .map( - (hole) => - new Cesium.PolygonHierarchy( - Cesium.Cartesian3.fromDegreesArray(hole.flat()), - ), - ), - ), - material: fillMaterial, - classificationType: CLASSIFY, - }, - }), - ); - for (const ring of rings) { - entities.push( - dataSource.entities.add({ - polyline: { - positions: Cesium.Cartesian3.fromDegreesArray( - closedRing(ring).flat(), - ), - width: 6, - material: lineMaterial, - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } + if (building && !current()) throw new Error('Building install cancelled'); + setOf(anno, kind).set(items[kind].map((item) => item(anno._drawn.alpha))); + if (building && !current()) { + clearSets(anno); + throw new Error('Building install cancelled'); } - } else if ( - anno.type === 'route' && - Array.isArray(anno.path) && - anno.path.length >= 2 - ) { - // A real path (street-following) draped on the 3D tiles, with dashes that - // FLOW toward the destination (custom st.s + time material; works on the - // clamped/classified ground polyline). - const positions = Cesium.Cartesian3.fromDegreesArray( - anno.path.flatMap((p) => [p.lon, p.lat]), - ); - entities.push( - dataSource.entities.add({ - polyline: { - positions, - width: 9, - material: new FlowMaterialProperty( - PALETTE[anno.color] || PALETTE.primary, - () => anno.alpha ?? 1, - ), - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); + } + if (anno.type === 'route' && items.lines.length) { osmAnnotations.add(anno); showOsmCredit(viewer, anno); - } else if (anno.type === 'arrow' && anno.to) { - // Connector draped across the ground from origin to destination. - const positions = [ - Cesium.Cartesian3.fromDegrees(anno.anchor.lon, anno.anchor.lat), - Cesium.Cartesian3.fromDegrees(anno.to.lon, anno.to.lat), - ]; - entities.push( - dataSource.entities.add({ - polyline: { - positions, - width: 16, - material: new Cesium.PolylineArrowMaterialProperty( - liveColor(anno, base, { alpha: 0.95 }), - ), - clampToGround: true, - classificationType: CLASSIFY, - }, - }), - ); - } else { - // pin / highlight / label — a camera-proportional target ring + a marker. - if (anno.type !== 'label') { - // Radius scales with camera height so the ring reads at any altitude. - // semiMajor === semiMinor is required AND must hold every frame, so both - // axes read the SAME ringRadius() (camera height is constant per frame). - entities.push( - dataSource.entities.add({ - position: Cesium.Cartesian3.fromDegrees( - anno.anchor.lon, - anno.anchor.lat, - ), - ellipse: { - semiMajorAxis: new Cesium.CallbackProperty(ringRadius, false), - semiMinorAxis: new Cesium.CallbackProperty(ringRadius, false), - material: new Cesium.ColorMaterialProperty( - liveColor(anno, base, { alpha: 0.38, pulse: true }), - ), - outline: false, - classificationType: CLASSIFY, - }, - }), - ); - } - entities.push(pointMarker(anno, base)); } if ( - entities.length && + (items.shapes.length || items.lines.length || items.points.length) && anno.ring?.length >= 3 && !anno.synthesized && (anno.outlineCredit === 'tiles' || anno.outlineCredit === 'osm') && - (options.isCurrent?.() ?? true) + current() ) { // The actual world proxy owns both geometry and credit, including rollback. osmAnnotations.add(anno); @@ -584,19 +374,19 @@ export function createWorldAnnotationRenderer(viewer) { } } - // Captions belong to the hybrid renderer's screen-space callouts. - function pointMarker(anno, base) { - return dataSource.entities.add({ - position: Cesium.Cartesian3.fromDegrees(anno.anchor.lon, anno.anchor.lat), - point: { - pixelSize: anno.type === 'label' ? 8 : 14, - color: liveColor(anno, base, { alpha: 1 }), - outlineColor: liveColor(anno, Cesium.Color.WHITE, { alpha: 0.95 }), - outlineWidth: 3, - heightReference: CLAMP, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, - }); + function disposeSet(anno, kind) { + const sets = anno?._draw; + if (!sets?.[kind]) return; + try { + sets[kind].dispose(); + } catch { + /* already gone */ + } + sets[kind] = null; + } + + function clearSets(anno) { + for (const kind of ['shapes', 'lines', 'points']) disposeSet(anno, kind); } function remove(anno) { @@ -604,27 +394,32 @@ export function createWorldAnnotationRenderer(viewer) { hideOsmCredit(viewer, anno); osmAnnotations.delete(anno); drawn.delete(anno); - if (!anno?._entities) return; - for (const entity of anno._entities) { - try { - dataSource.entities.remove(entity); - } catch { - /* already gone */ - } + clearSets(anno); + if (anno) { + anno._draw = null; + anno._drawn = null; } - anno._entities = null; } /** - * CallbackProperty drives per-frame alpha and pulse. A hidden mark is taken - * out whole, so no material that keeps its own colour (the route's flow), - * ground classification or pick can still show it. + * A hidden mark is taken out whole (its sets hidden), so no fill, line or + * pick can still show it; a mark whose alpha moved (fading in or out) + * takes its new colours in place. */ function sync() { for (const anno of drawn) { + const sets = anno._draw; + if (!sets) continue; const show = !anno.hidden; - for (const entity of anno._entities || []) - if (entity.show !== show) entity.show = show; + for (const kind of ['shapes', 'lines', 'points']) + if (sets[kind] && sets[kind].show !== show) sets[kind].show = show; + const was = anno._drawn; + const alpha = alphaOf(anno); + if (!was || was.alpha === alpha) continue; + was.alpha = alpha; + for (const kind of ['shapes', 'lines', 'points']) + if (sets[kind] && was.items[kind].length) + sets[kind].upsert(was.items[kind].map((item) => item(alpha))); } } @@ -633,114 +428,228 @@ export function createWorldAnnotationRenderer(viewer) { for (const task of [...pendingGround.values()]) task.finish('cancelled'); for (const anno of osmAnnotations) hideOsmCredit(viewer, anno); osmAnnotations.clear(); - drawn.clear(); - try { - viewer.dataSources.remove(dataSource, true); - } catch { - /* scene torn down */ + for (const anno of drawn) { + clearSets(anno); + anno._draw = null; + anno._drawn = null; } + drawn.clear(); } return { add, remove, sync, destroy }; } -function pulseFactor() { - // 0.6 .. 1.0 sinusoid at ~0.8 Hz - return 0.8 + 0.2 * Math.sin(performance.now() * 0.005); -} +/** A mark's alpha as drawn, 0..1. */ +const alphaOf = (anno) => Math.max(0, Math.min(1, anno.alpha ?? 1)); -/** - * A custom Fabric polyline material whose dashes flow toward the destination. - * `materialInput.st.s` is the along-line coordinate (0 = origin, 1 = destination), - * so `fract(s*repeat - time*speed)` scrolls the pattern toward the end. Works on - * a clamped/classified ground polyline (PolylineMaterialAppearance supports it). - */ -function makeRouteFlowMaterial(colorCss) { - return new Cesium.Material({ - fabric: { - type: 'GevRouteFlow', - uniforms: { - color: Cesium.Color.fromCssColorString(colorCss).withAlpha(0.95), - time: 0.0, - repeat: 64.0, // dash cells along the whole route - duty: 0.46, // fraction of each cell that is "on" - speed: 0.55, // cells per second toward the destination - }, - source: ` - czm_material czm_getMaterial(czm_materialInput materialInput) { - czm_material m = czm_getDefaultMaterial(materialInput); - float s = materialInput.st.s; // 0 origin -> 1 dest - float flow = fract(s * repeat - time * speed); // scroll toward dest - float on = smoothstep(duty + 0.08, duty - 0.08, flow); - // keep a faint baseline so the whole route stays readable between dashes - float a = max(on, 0.18); - m.diffuse = color.rgb; - m.emission = color.rgb * on * 0.9; // glow on the lit cells - m.alpha = color.a * a; - return m; - }`, - }, - }); -} +/** `[r, g, b, a]` for a palette colour at `alpha`. */ +const colour = (base, alpha) => [base[0], base[1], base[2], alpha]; -let _flowFabricRegistered = false; -/** Register the GevRouteFlow fabric ONCE so Cesium's `Material.fromType('GevRouteFlow')` - * can build the material the render pipeline uses. Constructing one Material with the - * fabric caches it under its type name. */ -export function ensureFlowFabricRegistered() { - if (_flowFabricRegistered) return; - makeRouteFlowMaterial('#ffffff'); // side effect: registers the 'GevRouteFlow' type - _flowFabricRegistered = true; -} - -/** - * MaterialProperty for the animated route. Cesium builds the rendered Material once - * from getType() (our registered GevRouteFlow fabric), then EACH FRAME calls - * getValue(time, material.uniforms) and uses whatever we write INTO that uniforms - * object — it ignores the return value. So getValue writes color/time/repeat/duty/ - * speed straight onto `result` (the live uniforms). Writing the animated `time` here - * is what actually makes the dashes flow on the GPU. (The prior versions either - * returned a standalone Material Cesium never rendered, or treated `result` as a - * Material — both left the real uniforms untouched, so nothing animated.) - */ -export function FlowMaterialProperty(colorCss, alphaOf = () => 1) { - this._color = Cesium.Color.fromCssColorString(colorCss).withAlpha(0.95); - // The mark's live alpha (fade in and out, hidden), applied every frame. - this._alphaOf = alphaOf; - this._live = this._color.clone(); - this._definitionChanged = new Cesium.Event(); -} -Object.defineProperties(FlowMaterialProperty.prototype, { - isConstant: { - get() { - return false; - }, - }, // re-evaluated each frame → it animates - definitionChanged: { - get() { - return this._definitionChanged; - }, - }, +/** A fill or outline that pulses about `alpha`. */ +const pulse = (alpha) => ({ + property: 'alpha', + from: alpha * PULSE_LOW, + to: alpha, + periodMs: PULSE_MS, }); -FlowMaterialProperty.prototype.getType = function getType() { - return 'GevRouteFlow'; -}; -FlowMaterialProperty.prototype.getValue = function getValue(time, result) { - // `result` IS the live uniforms object Cesium renders — write into it directly. - // `time` is read straight from the wall clock so the dashes flow every rendered - // frame (the scene renders continuously; no requestRenderMode here). - if (!Cesium.defined(result)) result = {}; - this._live.alpha = this._color.alpha * this._alphaOf(); - result.color = this._live; - result.time = performance.now() / 1000; // the per-frame animated value - result.repeat = 64.0; - result.duty = 0.46; - result.speed = 0.55; - return result; -}; -FlowMaterialProperty.prototype.equals = function equals(other) { - return this === other; -}; + +/** + * What a mark draws, as item makers by kind, each taking the mark's alpha: + * built once per add, called again on each fade step. + */ +function itemsOf(anno, options) { + const base = PALETTE[anno.color] || PALETTE.primary; + const shapes = []; + const lines = []; + const points = []; + const meta = { annotation: anno.id }; + const draped = (id, positions, widthPx, style) => (alpha) => ({ + id, + positions, + widthPx, + mode: 'draped', + clampTo: CLAMP_TO, + style: style(alpha), + meta, + }); + if (anno.ring?.length >= 3 && anno.footprintKind === 'building') { + // Single building → the PRIMARY highlight is a translucent extruded + // column round the building that pulses, from just under its ground to + // well over its roof, with a faint wireframe cage on it as a secondary + // cue and a crisp draped base outline. + const parts = + Array.isArray(anno.polygons) && anno.polygons.length + ? anno.polygons + : [[anno.ring]]; + const groundH = + options.sampledGroundHeight ?? + (Number.isFinite(anno.anchor.height) + ? anno.anchor.height - (anno.buildingHeight || 25) + : 0); + const baseH = groundH - 3; + // Tall headroom so under-tagged building heights are covered too. + const topH = groundH + Math.max(18, anno.buildingHeight || 25) + 24; + const at = (ring) => + ring.map(([lon, lat]) => ({ lon, lat, height: baseH })); + parts.forEach(([outer, ...holes], p) => { + const buffered = bufferRing(outer, 3); + // Built once: a fade step only changes colours. + const volume = { kind: 'polygon', rings: [buffered, ...holes].map(at) }; + shapes.push((alpha) => ({ + id: `volume:${p}`, + geometry: volume, + fill: colour(base, 0.45 * alpha), + animate: pulse(0.45 * alpha), + extrudeHeight: topH, + height: 'absolute', + meta, + })); + // Faint, SIMPLIFIED wireframe cage: the footprint decimated so the + // extruded outline draws ~14 clean verticals, not one per (often + // 100+) ring vertex. + const cage = { + kind: 'polygon', + rings: [at(decimateRing(buffered, 14))], + }; + shapes.push((alpha) => ({ + id: `cage:${p}`, + geometry: cage, + outline: colour(base, 0.32 * alpha), + outlineOnly: true, + animate: pulse(0.32 * alpha), + extrudeHeight: topH, + height: 'absolute', + meta, + })); + [outer, ...holes].forEach((ring, r) => + lines.push( + draped(`base:${p}:${r}`, ecefOf(closedRing(ring)), 3, (alpha) => ({ + kind: 'glow', + color: colour(base, 0.7 * alpha), + power: 0.25, + })), + ), + ); + }); + } else if (anno.ring?.length >= 3) { + // Larger area (district / compound / park / state) → flat fill draped on + // the tiles + a glowing outline. Draping is right here: you can't extrude + // a whole neighbourhood, and the GIS overlay shows the boundary clearly. + // A multi-part outline (`anno.polygons`: Hawaii's islands, Berlin as a + // hole in Brandenburg) draws every part with its holes. + const parts = + Array.isArray(anno.polygons) && anno.polygons.length + ? anno.polygons + : [[anno.ring]]; + // Synthesized (approximate) areas get a fainter fill so they don't read + // as solid, and a DASHED outline (signals "approximate, not an + // authoritative boundary", research §8.4/§8.6); real footprints a solid + // glow. + const fillAlpha = anno.synthesized ? 0.1 : 0.2; + const style = anno.synthesized + ? (alpha) => ({ + kind: 'dash', + color: colour(base, 0.95 * alpha), + length: 24, + }) + : (alpha) => ({ kind: 'glow', color: colour(base, alpha), power: 0.35 }); + parts.forEach(([outer, ...holes], p) => { + if (!Array.isArray(outer) || outer.length < 3) return; + const rings = [outer, ...holes.filter((h) => h?.length >= 3)]; + const area = { + kind: 'polygon', + rings: rings.map((ring) => ring.map(([lon, lat]) => ({ lon, lat }))), + }; + shapes.push((alpha) => ({ + id: `fill:${p}`, + geometry: area, + fill: colour(base, fillAlpha * alpha), + animate: pulse(fillAlpha * alpha), + height: 'clampGround', + clampTo: CLAMP_TO, + meta, + })); + rings.forEach((ring, r) => + lines.push( + draped(`outline:${p}:${r}`, ecefOf(closedRing(ring)), 6, style), + ), + ); + }); + } else if ( + anno.type === 'route' && + Array.isArray(anno.path) && + anno.path.length >= 2 + ) { + // A real path (street-following) draped on the surface, with dashes that + // FLOW toward the destination. + lines.push( + draped( + 'route', + anno.path.map((p) => fromDegrees(p.lon, p.lat, 0)), + 9, + (alpha) => ({ + kind: 'flow', + color: colour(base, 0.95 * alpha), + repeat: 64, + duty: 0.46, + speed: 0.55, + }), + ), + ); + } else if (anno.type === 'arrow' && anno.to) { + // Connector draped across the ground from origin to destination. + lines.push( + draped( + 'arrow', + [ + fromDegrees(anno.anchor.lon, anno.anchor.lat, 0), + fromDegrees(anno.to.lon, anno.to.lat, 0), + ], + 16, + (alpha) => ({ kind: 'arrow', color: colour(base, 0.95 * alpha) }), + ), + ); + } else { + // pin / highlight / label — a camera-proportional target ring + a marker. + const pos = { lon: anno.anchor.lon, lat: anno.anchor.lat }; + if (anno.type !== 'label') + shapes.push((alpha) => ({ + id: 'ring', + geometry: { + kind: 'ellipse', + center: pos, + semiMajor: RING_RADIUS, + semiMinor: RING_RADIUS, + }, + fill: colour(base, 0.38 * alpha), + animate: pulse(0.38 * alpha), + height: 'clampGround', + clampTo: CLAMP_TO, + meta, + })); + // Captions belong to the hybrid renderer's screen-space callouts. + points.push((alpha) => ({ + id: 'marker', + pos, + height: 'clampGround', + pixelSize: anno.type === 'label' ? 8 : 14, + color: colour(base, alpha), + outlineColor: colour(WHITE, 0.95 * alpha), + outlineWidth: 3, + disableDepthTest: Number.POSITIVE_INFINITY, + meta, + })); + } + return { shapes, lines, points }; +} + +/** `[lon, lat]` pairs as ECEF positions on the ellipsoid. */ +const ecefOf = (ring) => ring.map(([lon, lat]) => fromDegrees(lon, lat, 0)); + +function rgb(css) { + const n = parseInt(css.slice(1), 16); + return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; +} /** The ring with its first vertex repeated at the end, so an outline closes. */ function closedRing(ring) { @@ -764,7 +673,7 @@ function decimateRing(ring, n) { function groundProbePositions(ring) { const { lon: clon, lat: clat } = ringCentroid(ring); const latS = 111320; - const lonS = latS * Math.cos(Cesium.Math.toRadians(clat)); + const lonS = latS * Math.cos((clat * Math.PI) / 180); let maxR = 0; for (const [lon, lat] of ring) { maxR = Math.max(maxR, Math.hypot((lon - clon) * lonS, (lat - clat) * latS)); @@ -802,7 +711,7 @@ function bufferRing(ring, meters) { clon /= ring.length; clat /= ring.length; const latScale = 111320; - const lonScale = latScale * Math.cos(Cesium.Math.toRadians(clat)); + const lonScale = latScale * Math.cos((clat * Math.PI) / 180); return ring.map(([lon, lat]) => { const dx = (lon - clon) * lonScale; const dy = (lat - clat) * latScale; diff --git a/src/annotations/worldAnnotationRenderer.test.mjs b/src/annotations/worldAnnotationRenderer.test.mjs index a05c52373..dbad95dfb 100644 --- a/src/annotations/worldAnnotationRenderer.test.mjs +++ b/src/annotations/worldAnnotationRenderer.test.mjs @@ -1,31 +1,36 @@ -// A mark hidden from Draw's list leaves the globe whole: every entity it put -// there is taken out on sync and comes back when shown, and the line's -// flowing stroke, which keeps its own colour, follows the mark's alpha. +// The world renderer draws each mark through the draw port, in sets of its +// own: a hidden mark has its sets hidden on sync and shown again; a fading +// mark takes its new colours in place; every kind draws what it drew as +// entities, draped and clamped to terrain and tiles alike. import test from 'node:test'; import assert from 'node:assert/strict'; -import * as C from 'cesium'; -import { - FlowMaterialProperty, - createWorldAnnotationRenderer, -} from './worldAnnotationRenderer.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import { createWorldAnnotationRenderer } from './worldAnnotationRenderer.js'; -const noop = () => {}; -function viewer(t) { - for (const name of ['HTMLCanvasElement', 'HTMLImageElement', 'ImageBitmap', 'OffscreenCanvas']) { - const original = globalThis[name]; - globalThis[name] = class {}; - t.after(() => { if (original === undefined) delete globalThis[name]; else globalThis[name] = original; }); - } - const before = globalThis.document; - globalThis.document = { addEventListener: noop, removeEventListener: noop }; - t.after(() => { if (before === undefined) delete globalThis.document; else globalThis.document = before; }); +/** A viewer with a fake draw port, frame and query bound. */ +function viewer(t, { heights = () => null } = {}) { + const draw = fakeDrawPort(); + const frames = new Set(); + const v = { requests: 0 }; + const frame = { + on(phase, cb) { + if (phase !== 'postRender') return () => {}; + frames.add(cb); + return () => frames.delete(cb); + }, + requestRender() { + v.requests += 1; + }, + }; + const query = { sampleHeightNow: (point) => heights(point) }; + const unbind = bindRenderer(v, { draw, frame, query }); + t.after(unbind); return { - creditDisplay: { addStaticCredit: noop, removeStaticCredit: noop }, - entities: new C.EntityCollection(), - dataSources: new C.DataSourceCollection(), - camera: { moveEnd: new C.Event(), positionCartographic: { height: 1000 } }, - scene: { requestRender: noop, canvas: { addEventListener: noop, removeEventListener: noop }, preRender: new C.Event(), - primitives: { add: (p) => p, remove: noop }, screenSpaceCameraController: { enableInputs: true } }, + v, + draw, + frames, + emit: () => [...frames].forEach((cb) => cb()), }; } @@ -35,12 +40,19 @@ const marks = () => [ { id: 'pin', type: 'pin', color: 'primary', alpha: 1, anchor: { lat: 0.02, lon: 0.02 } }, ]; -test('a hidden mark has every entity taken off on sync, and back when shown', (t) => { - const renderer = createWorldAnnotationRenderer(viewer(t)); +/** The live sets a mark draws into. */ +const setsOf = (draw, anno) => + [...draw.sets.values()].filter( + (record) => !record.disposed && record.spec.id.startsWith(`${anno._draw.prefix}:`), + ); + +test('each mark draws in sets of its own; a hidden one has them hidden on sync, and back when shown', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); const [route, area, pin] = marks(); for (const anno of [route, area, pin]) renderer.add(anno); - const shown = (anno) => anno._entities.map((entity) => entity.show); - for (const anno of [route, area, pin]) assert.ok(anno._entities.length > 0, anno.id); + for (const anno of [route, area, pin]) assert.ok(setsOf(draw, anno).length > 0, anno.id); + const shown = (anno) => setsOf(draw, anno).map((record) => record.show); route.hidden = true; area.hidden = true; @@ -52,19 +64,165 @@ test('a hidden mark has every entity taken off on sync, and back when shown', (t route.hidden = false; renderer.sync(); assert.ok(shown(route).every((show) => show === true), 'the line is back'); + const areaSets = setsOf(draw, area); renderer.remove(area); + assert.ok(areaSets.every((record) => record.disposed), 'a removed mark lets its sets go'); renderer.sync(); - assert.equal(area._entities, null, 'a removed mark is no longer synced'); + renderer.destroy(); + assert.equal([...draw.sets.values()].filter((record) => !record.disposed).length, 0); +}); + +test('a fading mark takes its new colours in place, its pulses with them', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [route, area] = marks(); + renderer.add(route); + renderer.add(area); + const line = () => [...setsOf(draw, route)[0].items.values()][0]; + const fill = () => setsOf(draw, area).find((r) => r.kind === 'shapes').items.get('fill:0'); + assert.ok(Math.abs(line().style.color[3] - 0.95) < 1e-9); + assert.ok(Math.abs(fill().fill[3] - 0.2) < 1e-9); + route.alpha = 0.5; + area.alpha = 0.5; + renderer.sync(); + assert.ok(Math.abs(line().style.color[3] - 0.475) < 1e-9, 'fading'); + assert.ok(Math.abs(fill().fill[3] - 0.1) < 1e-9); + assert.deepEqual( + [fill().animate.from, fill().animate.to].map((a) => Math.round(a * 1000)), + [60, 100], + 'its pulse swings between 60% and all of its alpha', + ); + route.alpha = 0; + renderer.sync(); + assert.equal(line().style.color[3], 0, 'faded out: nothing painted'); renderer.destroy(); }); -test('the line\'s flowing stroke follows its mark\'s alpha', () => { - let alpha = 1; - const material = new FlowMaterialProperty('#ffb547', () => alpha); - assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.95) < 1e-9); - alpha = 0; - assert.equal(material.getValue(null, {}).color.alpha, 0, 'hidden: nothing painted'); - alpha = 0.5; - assert.ok(Math.abs(material.getValue(null, {}).color.alpha - 0.475) < 1e-9, 'fading'); - assert.equal(new FlowMaterialProperty('#fff').getValue(null, {}).color.alpha, 0.95, 'no alpha source: opaque as before'); +test('every kind draws as it did: draped on terrain and tiles alike, rings by camera height, pulses', (t) => { + const { v, draw } = viewer(t); + const renderer = createWorldAnnotationRenderer(v); + const [route, area, pin] = marks(); + const synth = { ...area, id: 'synth', synthesized: true }; + const arrow = { id: 'arrow', type: 'arrow', color: 'red', alpha: 1, anchor: { lon: 0, lat: 0 }, to: { lon: 0.01, lat: 0 } }; + const label = { id: 'label', type: 'label', color: 'amber', alpha: 1, anchor: { lon: 0.03, lat: 0 } }; + for (const anno of [route, area, pin, synth, arrow, label]) renderer.add(anno); + const items = (anno, kind) => [...(setsOf(draw, anno).find((r) => r.kind === kind)?.items.values() ?? [])]; + for (const record of [...draw.sets.values()]) assert.equal(record.spec.clampTo, 'both'); + + const [flow] = items(route, 'lines'); + assert.equal(flow.mode, 'draped'); + assert.equal(flow.widthPx, 9); + assert.deepEqual({ ...flow.style, color: undefined }, { kind: 'flow', color: undefined, repeat: 64, duty: 0.46, speed: 0.55 }); + + const [areaFill] = items(area, 'shapes'); + assert.equal(areaFill.height, 'clampGround'); + assert.equal(areaFill.animate.property, 'alpha'); + assert.ok(Math.abs(areaFill.animate.periodMs - (2 * Math.PI) / 0.005) < 1e-9); + const [areaLine] = items(area, 'lines'); + assert.deepEqual([areaLine.widthPx, areaLine.style.kind, areaLine.style.power], [6, 'glow', 0.35]); + const [synthLine] = items(synth, 'lines'); + assert.deepEqual([synthLine.style.kind, synthLine.style.length], ['dash', 24]); + assert.ok(Math.abs(items(synth, 'shapes')[0].fill[3] - 0.1) < 1e-9, 'an approximate area is fainter'); + + const [arrowLine] = items(arrow, 'lines'); + assert.deepEqual([arrowLine.mode, arrowLine.widthPx, arrowLine.style.kind], ['draped', 16, 'arrow']); + + const [ring] = items(pin, 'shapes'); + assert.deepEqual(ring.geometry.semiMajor, { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }); + assert.equal(ring.geometry.semiMinor, ring.geometry.semiMajor); + const [marker] = items(pin, 'points'); + assert.deepEqual([marker.pixelSize, marker.height, marker.outlineWidth, marker.disableDepthTest], [14, 'clampGround', 3, Infinity]); + assert.equal(items(label, 'shapes').length, 0, 'a label has no ring'); + assert.equal(items(label, 'points')[0].pixelSize, 8); + renderer.destroy(); +}); + +test('a building waits for its ground probes, then draws a pulsing column, a cage and a draped base', async (t) => { + const { v, draw, emit, frames } = viewer(t, { heights: () => 150 }); + const renderer = createWorldAnnotationRenderer(v); + const ring = [[0, 0], [0.001, 0], [0.001, 0.001], [0, 0.001], [0, 0]]; + const anno = { + id: 'b', type: 'area', color: 'amber', alpha: 1, footprintKind: 'building', buildingHeight: 40, + anchor: { lon: 0.0005, lat: 0.0005, height: 200 }, ring, + }; + const done = renderer.add(anno); + assert.equal(frames.size, 1, 'probing on the frames'); + assert.equal(setsOf(draw, anno).length, 0, 'nothing until its ground is known'); + for (let i = 0; i < 8; i++) emit(); + assert.equal((await done).status, 'installed'); + assert.equal(frames.size, 0, 'done probing'); + const shapes = [...setsOf(draw, anno).find((r) => r.kind === 'shapes').items.values()]; + const volume = shapes.find((s) => s.id === 'volume:0'); + assert.equal(volume.extrudeHeight, 150 + 40 + 24); + assert.equal(volume.geometry.rings[0][0].height, 147); + assert.equal(volume.height, 'absolute'); + assert.equal(volume.classifyVolume, undefined, 'a translucent column, as before'); + const cage = shapes.find((s) => s.id === 'cage:0'); + assert.equal(cage.outlineOnly, true); + assert.ok(cage.geometry.rings[0].length <= 14); + const [base] = setsOf(draw, anno).find((r) => r.kind === 'lines').items.values(); + assert.deepEqual([base.mode, base.widthPx, base.style.kind, base.style.power], ['draped', 3, 'glow', 0.25]); + renderer.destroy(); +}); + +test('each kind paints the alphas it painted as entities, at full alpha', (t) => { + const { v, draw } = viewer(t, { heights: () => 150 }); + const renderer = createWorldAnnotationRenderer(v); + const [route, area, pin] = marks(); + const synth = { ...area, id: 'synth', synthesized: true }; + const arrow = { id: 'arrow', type: 'arrow', color: 'red', alpha: 1, anchor: { lon: 0, lat: 0 }, to: { lon: 0.01, lat: 0 } }; + const ring = Array.from({ length: 40 }, (_, i) => [ + 0.0005 + 0.0004 * Math.cos((i / 40) * 2 * Math.PI), + 0.0005 + 0.0004 * Math.sin((i / 40) * 2 * Math.PI), + ]); + const building = { + id: 'b', type: 'area', color: 'amber', alpha: 1, footprintKind: 'building', buildingHeight: 40, + anchor: { lon: 0.0005, lat: 0.0005, height: 200 }, ring, + }; + for (const anno of [route, area, pin, synth, arrow]) renderer.add(anno); + renderer.add(building, { sampledGroundHeight: 150 }); + const items = (anno, kind) => [...(setsOf(draw, anno).find((r) => r.kind === kind)?.items.values() ?? [])]; + const alpha = (c) => Math.round(c[3] * 1000) / 1000; + assert.equal(alpha(items(route, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(area, 'lines')[0].style.color), 1); + assert.equal(alpha(items(synth, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(arrow, 'lines')[0].style.color), 0.95); + assert.equal(alpha(items(pin, 'shapes')[0].fill), 0.38); + const marker = items(pin, 'points')[0]; + assert.deepEqual([alpha(marker.color), alpha(marker.outlineColor)], [1, 0.95]); + assert.deepEqual(marker.outlineColor.slice(0, 3), [1, 1, 1]); + const [volume, cage] = items(building, 'shapes'); + assert.equal(alpha(volume.fill), 0.45); + assert.equal(alpha(cage.outline), 0.32); + assert.equal(Math.round(cage.animate.from * 1000) / 1000, 0.192, 'the cage pulses too'); + assert.equal(cage.geometry.rings[0].length, 14, 'decimated to 14'); + assert.equal(alpha(items(building, 'lines')[0].style.color), 0.7); + renderer.destroy(); +}); + +test('a mark removed and added again draws afresh; two renderers on one viewer keep apart', (t) => { + const { v, draw } = viewer(t); + const first = createWorldAnnotationRenderer(v); + const second = createWorldAnnotationRenderer(v); + const [route, area] = marks(); + first.add(route); + const prefix = route._draw.prefix; + first.remove(route); + assert.doesNotThrow(() => first.add(route)); + assert.notEqual(route._draw.prefix, prefix, 'fresh sets'); + assert.doesNotThrow(() => second.add(area)); + assert.ok(!area._draw.prefix.startsWith(route._draw.prefix.split(':').slice(0, 2).join(':') + ':')); + // Added again as another kind, its old sets go. + const kinds = () => setsOf(draw, route).map((r) => r.kind).sort(); + assert.deepEqual(kinds(), ['lines']); + Object.assign(route, { type: 'pin', path: undefined }); + first.add(route); + assert.deepEqual(kinds(), ['points', 'shapes']); + assert.doesNotThrow(() => first.remove(null)); + first.destroy(); + second.destroy(); + assert.equal(route._draw, null); + first.add(route); + assert.equal(route._draw, null, 'a destroyed renderer draws nothing more'); + assert.equal([...draw.sets.values()].filter((r) => !r.disposed).length, 0); }); diff --git a/src/data/boundaryLabels.test.mjs b/src/data/boundaryLabels.test.mjs index 917bfb8ce..44d80a092 100644 --- a/src/data/boundaryLabels.test.mjs +++ b/src/data/boundaryLabels.test.mjs @@ -9,6 +9,7 @@ import * as Cesium from 'cesium'; import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js'; import { createAnnotationResolver } from '../annotations/resolver.js'; import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; import { createWorldAnnotationRenderer } from '../annotations/worldAnnotationRenderer.js'; const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8'); @@ -22,7 +23,7 @@ const DATA_MODULES = [ './local_data/wof_neighborhoods/files.js', ]; -/** Modules that use Cesium for outlines but must not draw text with it. */ +/** Modules that draw outlines but must not draw text with Cesium. */ const CESIUM_MODULES = [ '../annotations/resolver.js', '../annotations/worldAnnotationRenderer.js', @@ -110,22 +111,22 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label', featureSource, }); const primitives = []; - const dataSources = []; - // The resolver reads the camera through the renderer's camera port. - const viewer = bindFakeCesiumCamera({ - camera: { - positionCartographic: Cesium.Cartographic.fromDegrees( - -97.7431, - 30.2672, - 3000, - ), + const draw = fakeDrawPort(); + // The resolver reads the camera through the renderer's camera port; the + // world renderer draws through its draw port. + const viewer = bindFakeCesiumCamera( + { + camera: { + positionCartographic: Cesium.Cartographic.fromDegrees( + -97.7431, + 30.2672, + 3000, + ), + }, + scene: { primitives: { add: (p) => primitives.push(p) } }, }, - scene: { primitives: { add: (p) => primitives.push(p) } }, - dataSources: { - add: (ds) => dataSources.push(ds), - remove() {}, - }, - }); + { draw }, + ); const renderer = createWorldAnnotationRenderer(viewer); for (const [target, lon, lat] of [ ['Austin', -97.7431, 30.2672], @@ -157,8 +158,14 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label', }); } assert.equal(primitives.length, 0, 'no primitive collections'); - const entities = dataSources.flatMap((ds) => ds.entities.values); - assert.ok(entities.length >= 2, 'the outlines were drawn'); - for (const entity of entities) assert.equal(entity.label, undefined); + const live = [...draw.sets.values()].filter((record) => !record.disposed); + const items = live.flatMap((record) => [...record.items.values()]); + assert.ok(items.length >= 2, 'the outlines were drawn'); + // Fills and lines only: no point, text or label is drawn for a name. + assert.deepEqual([...new Set(live.map((record) => record.kind))].sort(), [ + 'lines', + 'shapes', + ]); + for (const item of items) assert.equal(item.label, undefined); renderer.destroy(); }); diff --git a/src/data/sharedOsmDisplays.test.mjs b/src/data/sharedOsmDisplays.test.mjs index 38be4d28c..da472899f 100644 --- a/src/data/sharedOsmDisplays.test.mjs +++ b/src/data/sharedOsmDisplays.test.mjs @@ -14,6 +14,9 @@ import { createDirectionsSource } from '../layers/directions/source.js'; import { createLifecycle as createCctvLifecycle } from '../layers/cctv/lifecycle.js'; import * as input from './inputOwnership.js'; import { createOverpassAlprSource } from '../layers/alpr/source.js'; +// The infrastructure layers take clicks through the input port, which their +// fake renderer leaves to the Cesium adapter's factories. +import '../render/cesium/camera.js'; const noop = () => {}; const overlayHost = { setEntries: noop, setVisible: noop, clearSource: noop }; @@ -64,7 +67,7 @@ test('Nepal locator introduces the shared OSM credit', async (t) => { }); test('voice route geometry introduces the shared OSM credit', (t) => { - const v = viewer(t), renderer = createWorldAnnotationRenderer(v); + const v = viewer(t, { draw: fakeDrawPort() }), renderer = createWorldAnnotationRenderer(v); renderer.add({ id: 'route', type: 'route', color: 'primary', anchor: { lat: 0, lon: 0 }, path: [{ lat: 0, lon: 0 }, { lat: 0.01, lon: 0.01 }] }); assertCredit(v); renderer.destroy(); assert.equal(v.credits.filter(c => c.showOnScreen).length, 0); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index c8c7b1222..446601071 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -1186,6 +1186,101 @@ test('the earthquakes layer draws its discs as ground fills on a viewer of its o assert.equal(scene.added.length, 0); }); +test('the world annotation renderer draws, fades, hides and lets go of every kind on a viewer of its own', async () => { + const { createWorldAnnotationRenderer } = + await import('../../annotations/worldAnnotationRenderer.js'); + await withImageClasses(() => + withTerrainHeights(() => { + const scene = fakeScene(); + const viewer = { scene }; + const renderer = createWorldAnnotationRenderer(viewer); + const box = (lon, d) => [ + [lon - d, -d], + [lon + d, -d], + [lon + d, d], + [lon - d, d], + ]; + const marks = [ + { + id: 'building', + type: 'area', + color: 'amber', + footprintKind: 'building', + buildingHeight: 40, + anchor: { lon: 0, lat: 0, height: 200 }, + ring: box(0, 0.0004), + }, + { + id: 'area', + type: 'area', + color: 'green', + footprintKind: 'area', + anchor: { lon: 0.01, lat: 0 }, + ring: box(0.01, 0.002), + polygons: [[box(0.01, 0.002), box(0.01, 0.0005)]], + }, + { + id: 'synth', + type: 'area', + color: 'cyan', + synthesized: true, + anchor: { lon: 0.02, lat: 0 }, + ring: box(0.02, 0.002), + }, + { + id: 'route', + type: 'route', + color: 'red', + anchor: { lon: 0, lat: 0.01 }, + path: [ + { lon: 0, lat: 0.01 }, + { lon: 0.01, lat: 0.012 }, + ], + }, + { + id: 'arrow', + type: 'arrow', + color: 'primary', + anchor: { lon: 0, lat: 0.02 }, + to: { lon: 0.01, lat: 0.02 }, + }, + { + id: 'pin', + type: 'pin', + color: 'primary', + anchor: { lon: 0.03, lat: 0 }, + }, + { + id: 'label', + type: 'label', + color: 'amber', + anchor: { lon: 0.04, lat: 0 }, + }, + ]; + for (const mark of marks) { + mark.alpha = 0.25; + renderer.add( + mark, + mark.footprintKind === 'building' ? { sampledGroundHeight: 150 } : {}, + ); + } + assert.ok(scene.added.length >= marks.length, 'every kind drew'); + for (const alpha of [0.5, 1]) { + for (const mark of marks) mark.alpha = alpha; + assert.doesNotThrow(() => renderer.sync()); + scene.preRender.raiseEvent(); + scene.postRender.raiseEvent(); + } + for (const mark of marks) mark.hidden = true; + renderer.sync(); + for (const mark of marks) mark.hidden = false; + renderer.sync(); + renderer.destroy(); + assert.equal(scene.added.length, 0, 'nothing left drawn'); + }), + ); +}); + test('the air quality layer draws its stations as ground fills on a viewer of its own', async () => { const { createAirQualityLayer } = await import('../../layers/airQuality/index.js'); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 3a7a147d0..727c91d18 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -1,6 +1,5 @@ [ "dev/conformance/main.js", - "src/annotations/worldAnnotationRenderer.js", "src/app/embed.js", "src/app/scene.js", "src/app/viewer.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 67a73aaf7..30d38452f 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -117,6 +117,9 @@ const DRAW_FROM_CALLER = new Set([ './infrastructure/geojson', // Its missions draw, pick and fly through the ports alone. './layers/launches', + // Its world marks draw through `drawOf` and probe heights through + // `heightsOf`; its screen marks project through the camera and query ports. + './annotations', // Its pins, footprints and outlines draw through `drawOf`; its horizon // cull reads the camera and frame ports. './layers/ghostmaps',