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/scripts/qa-admin-outlines.mjs b/scripts/qa-admin-outlines.mjs index 114daacad..97fd10c6b 100644 --- a/scripts/qa-admin-outlines.mjs +++ b/scripts/qa-admin-outlines.mjs @@ -12,10 +12,11 @@ * and finally Brandenburg (Berlin is a hole) and Hawaii (eight islands). * * Asserts for every outline: it resolves from the bundled packs (no geocode, - * boundary or Overpass request), is drawn as a draped outline within the - * budget, and holds still — no rebuilt primitives and no new entities while - * the camera is still. The whole journey must log zero console/page errors and - * send zero requests to any Overpass host or nominatim.openstreetmap.org. + * boundary or Overpass request), shows its first frame within the budget, + * has its draped fill and outline built (their time is reported), and holds + * still — none of its primitives rebuilt while the camera is still. The whole + * journey must log zero console/page errors and send zero requests to any + * Overpass host or nominatim.openstreetmap.org. * * Evidence in qa-shots/ (gitignored): admin-outlines-.png screenshots, * admin-outlines-journey.mp4 (CDP screencast at ~24 fps, frames re-timed from @@ -210,56 +211,84 @@ try { requestAnimationFrame(step); }); }, - annotationSource() { - for (let i = 0; i < viewer.dataSources.length; i++) { - const source = viewer.dataSources.get(i); - if (source.name === 'gev-annotations') return source; - } - return null; - }, - groundPrimitives() { + /** + * The annotations' primitives in the scene, each with the marks its + * instances draw (their pick ids carry `meta.annotation`); only those + * of `mark` when given. + */ + annotationPrimitives(mark) { + const marksOf = (primitive) => { + let inner = primitive; + for (let depth = 0; inner && depth < 4; depth++) { + if (Array.isArray(inner._instanceIds)) + return inner._instanceIds + .map((id) => id?.meta?.annotation) + .filter((id) => id !== undefined); + inner = inner._primitive; + } + return []; + }; const list = []; const walk = (collection) => { for (let i = 0; i < collection.length; i++) { const item = collection.get(i); if (item?.length !== undefined && typeof item.get === 'function') walk(item); - else list.push(item); + else { + const marks = marksOf(item); + if (marks.length && (mark === undefined || marks.includes(mark))) + list.push(item); + } } }; - walk(viewer.scene.groundPrimitives); + walk(viewer.scene.primitives); return list; }, - snapshot() { - const source = this.annotationSource(); - const entities = source ? source.entities.values : []; - const primitives = this.groundPrimitives(); + /** What `mark` draws (every annotation's, without one). */ + snapshot(mark) { + const primitives = this.annotationPrimitives(mark); window.__qaPrimitiveIds ??= new WeakMap(); let next = window.__qaPrimitiveNext ?? 1; - const ids = primitives.map((primitive) => { - if (!window.__qaPrimitiveIds.has(primitive)) - window.__qaPrimitiveIds.set(primitive, next++); - return window.__qaPrimitiveIds.get(primitive); - }); + // By identity only: hosts may trade places without a rebuild. + const ids = primitives + .map((primitive) => { + if (!window.__qaPrimitiveIds.has(primitive)) + window.__qaPrimitiveIds.set(primitive, next++); + return window.__qaPrimitiveIds.get(primitive); + }) + .sort((a, b) => a - b); window.__qaPrimitiveNext = next; return { - entities: entities.length, - polygons: entities.filter((e) => e.polygon).length, - polylines: entities.filter((e) => e.polyline).length, + primitives: primitives.length, + fills: primitives.filter((p) => p instanceof Cesium.GroundPrimitive) + .length, + lines: primitives.filter( + (p) => p instanceof Cesium.GroundPolylinePrimitive, + ).length, + // Draped on terrain and tiles alike. draped: - entities.every( - (e) => - !e.polygon || - e.polygon.classificationType?.getValue() === - Cesium.ClassificationType.BOTH, - ) && - entities.every( - (e) => !e.polyline || e.polyline.clampToGround?.getValue(), + primitives.length > 0 && + primitives.every( + (p) => p.classificationType === Cesium.ClassificationType.BOTH, ), primitiveIds: ids, - ready: viewer.dataSourceDisplay.ready, + ready: primitives.every((p) => p.ready), }; }, + /** The annotations drawn under the middle of the view. */ + marksAtCentre() { + const { canvas } = viewer.scene; + const centre = new Cesium.Cartesian2( + canvas.clientWidth / 2, + canvas.clientHeight / 2, + ); + const marks = new Set(); + for (const hit of viewer.scene.drillPick(centre, 16)) { + const mark = hit?.id?.meta?.annotation; + if (mark !== undefined) marks.add(mark); + } + return [...marks]; + }, }; }); @@ -313,17 +342,31 @@ try { { flyTo }, ); const resolvedMs = performance.now() - started; - // "Drawn" = the first rendered frame after the entity visualizers have - // built the mark's primitives (each tick updates them before render). + // "Drawn" = the first rendered frame after the mark is drawn (as + // before, when it was the entities' first frame); "ready" = the first + // with its primitives all built, which may wait on Cesium's workers. const { viewer } = window.__godsEyeView; + const markId = response.ids?.[0]; + let drawnMs = null; + let readyMs = null; await new Promise((resolve) => { - const off = viewer.scene.postRender.addEventListener(() => { - if (!viewer.dataSourceDisplay.ready) return; + const giveUp = setTimeout(done, 15_000); + function done() { + clearTimeout(giveUp); off(); resolve(); + } + const off = viewer.scene.postRender.addEventListener(() => { + const now = performance.now() - started; + drawnMs ??= now; + const drawn = window.__qaOutlines.annotationPrimitives(markId); + if (drawn.length && drawn.every((p) => p.ready)) { + readyMs = now; + done(); + } }); + viewer.scene.requestRender(); }); - const drawnMs = performance.now() - started; const mark = window.__godsEyeView.annotations .list() .find((m) => m.id === response.ids?.[0]); @@ -331,6 +374,7 @@ try { response: response.results?.[0] ?? null, resolvedMs, drawnMs, + readyMs, parts: mark?.polygons?.length ?? (mark?.ring ? 1 : 0), holes: (mark?.polygons ?? []).reduce( (n, part) => n + part.length - 1, @@ -338,6 +382,7 @@ try { ), ringVertices: mark?.ring?.length ?? 0, pending: Boolean(mark?.pendingOutline), + markId, }; }, target, @@ -347,23 +392,29 @@ try { await settle(); // Hold still: the drawn mark must not rebuild or grow. marker = `still:${name}`; - const before = await page.evaluate(() => window.__qaOutlines.snapshot()); + const before = await page.evaluate( + (mark) => window.__qaOutlines.snapshot(mark), + timing.markId, + ); const stillStart = frames.length; const times = await page.evaluate( (ms) => window.__qaOutlines.frameTimes(ms), STILL_MS, ); - const after = await page.evaluate(() => window.__qaOutlines.snapshot()); + const after = await page.evaluate( + (mark) => window.__qaOutlines.snapshot(mark), + timing.markId, + ); const step = { step: `outline:${name}`, target, ...timing, - entities: after.entities, - polygons: after.polygons, - polylines: after.polylines, + primitives: after.primitives, + fills: after.fills, + lines: after.lines, draped: after.draped, stableWhileStill: - before.entities === after.entities && + after.primitives > 0 && JSON.stringify(before.primitiveIds) === JSON.stringify(after.primitiveIds), stillFrameTimes: stats(times), @@ -375,6 +426,7 @@ try { result.steps.push(step); console.log( `${name}: resolved ${timing.resolvedMs.toFixed(0)} ms, drawn ${timing.drawnMs.toFixed(0)} ms, ` + + `ready ${timing.readyMs?.toFixed(0)} ms, ` + `${timing.parts} part(s), ${timing.holes} hole(s), via ${timing.response?.resolvedVia}; ` + `still p50/p95 ${step.stillFrameTimes.p50}/${step.stillFrameTimes.p95} ms; ` + `stable=${step.stableWhileStill}`, @@ -387,6 +439,11 @@ try { timing.drawnMs < OUTLINE_BUDGET_MS, `${name}: drawn in ${timing.drawnMs} ms`, ); + assert.notEqual(timing.readyMs, null, `${name}: its primitives built`); + assert.ok( + step.fills > 0 && step.lines > 0, + `${name}: drawn as a fill and an outline`, + ); assert.equal(step.draped, true, `${name}: draped on terrain/tiles`); assert.equal(step.stableWhileStill, true, `${name}: no redraw when still`); assert.deepEqual(step.lookups, [], `${name}: no network lookups`); @@ -512,8 +569,15 @@ try { await move(name, { lat, lon, height, pitch: -90 }, 1); await outline(name, target); await shot(name); - const rendered = await page.evaluate(() => window.__qaOutlines.snapshot()); - assert.ok(rendered.polygons > 0, `${target} polygon renders`); + const rendered = await page.evaluate(() => ({ + marks: window.__godsEyeView.annotations.list().map((m) => m.id), + atCentre: window.__qaOutlines.marksAtCentre(), + })); + assert.ok( + rendered.marks.length === 1 && + rendered.atCentre.includes(rendered.marks[0]), + `${target} polygon renders`, + ); } if (recordVideo) { @@ -632,6 +696,7 @@ console.table( step: s.step, resolvedMs: s.resolvedMs?.toFixed(0), drawnMs: s.drawnMs?.toFixed(0), + readyMs: s.readyMs?.toFixed(0), parts: s.parts, stable: s.stableWhileStill, p50: (s.stillFrameTimes || s.frameTimes)?.p50, 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.js b/src/render/cesium/draw.js index 1f9e63ad2..61ac2ff59 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -239,8 +239,63 @@ function radialRimMaterial(fill) { return material; } +/** + * An ellipse radius at a camera `height`: a fixed one as it is, one by + * camera height scaled by its factor and held within its bounds. + * @param {number|{byCameraHeight: {factor: number, min: number, max: number}}} radius + * @param {number} height + */ +export function radiusAt(radius, height) { + if (typeof radius === 'number') return radius; + const { factor, min, max } = radius.byCameraHeight; + return Math.max(min, Math.min(max, height * factor)); +} + +/** + * A shape's `animate`, checked: the Cesium renderer pulses alpha, forever. + * Null for a shape that does not pulse. + */ +function pulseOf(item) { + const pulse = item.animate; + if (!pulse) return null; + if (pulse.property !== 'alpha' || pulse.repeat !== undefined) + throw new Error('the Cesium renderer pulses alpha only, forever'); + if ( + !Number.isFinite(pulse.from) || + !Number.isFinite(pulse.to) || + !(pulse.periodMs > 0 && Number.isFinite(pulse.periodMs)) + ) + throw new Error( + 'the Cesium renderer pulses between finite alphas, over a positive period', + ); + const plain = (value) => + value == null || typeof value === 'string' || Array.isArray(value); + if (!plain(item.fill) || !plain(item.outline)) + throw new Error( + 'the Cesium renderer pulses colour fills and outlines only', + ); + return pulse; +} + +/** + * A pulse's alpha now: a sine between `from` and `to` on the wall clock, + * `periodMs` a swing and back, at their middle at each whole period. + * @param {{from: number, to: number, periodMs: number}} pulse + * @param {number} now + */ +export function pulseAlpha(pulse, now) { + const turn = pulse.periodMs > 0 ? (2 * Math.PI * now) / pulse.periodMs : 0; + return pulse.from + (pulse.to - pulse.from) * (0.5 + 0.5 * Math.sin(turn)); +} + +/** Whether a shape is an ellipse with a radius by camera height. */ +const byCameraHeight = (item) => + item.geometry?.kind === 'ellipse' && + (typeof item.geometry.semiMajor !== 'number' || + typeof item.geometry.semiMinor !== 'number'); + /** The line styles the port drapes. */ -const DRAPED_STYLES = new Set(['solid', 'glow', 'dash', 'flow']); +const DRAPED_STYLES = new Set(['solid', 'glow', 'dash', 'flow', 'arrow']); // Whether Cesium's approximate terrain heights have been asked for. let terrainHeightsAsked = false; @@ -424,9 +479,17 @@ export function createCesiumDraw({ if (synced === ICONS_CHANGED) setsVersion += 1; requestRender(); }; + // A shape's pulse the renderer cannot run is refused before anything + // changes. + const checkPulses = (list) => { + if (kind !== 'shapes') return; + for (const item of list) pulseOf(item); + if (list.some((item) => item.animate)) record.mayPulse = true; + }; const handle = { id: spec.id, set(list) { + checkPulses(list); if (onGpu(record, list, true)) { items.clear(); for (const item of list) items.set(item.id, item); @@ -442,6 +505,7 @@ export function createCesiumDraw({ requestRender(); }, upsert(list) { + checkPulses(list); if (onGpu(record, list)) { for (const item of list) items.set(item.id, item); record.gpu.write(list); @@ -2110,7 +2174,7 @@ export function createCesiumDraw({ for (const item of record.items.values()) if (item.mode === 'draped' && !DRAPED_STYLES.has(item.style.kind)) throw new Error( - 'the Cesium renderer drapes solid, glow, dash and flow lines only', + 'the Cesium renderer drapes solid, glow, dash, flow and arrow lines only', ); else if ( item.frame === 'inertial' && @@ -2998,6 +3062,14 @@ export function createCesiumDraw({ showOn(part.ground, part.id, part.pendingShow); part.pendingShow = undefined; } + if ( + part.pendingColour !== undefined && + part.ground && + !part.ground.isDestroyed() + ) { + colourOn(part.ground, part.id, part.pendingColour); + part.pendingColour = undefined; + } } for (const part of record.lineParts?.values() ?? []) { if (part.batchHidden && part.batch && !part.batch.isDestroyed()) @@ -3105,7 +3177,7 @@ export function createCesiumDraw({ ? Cesium.Cartographic.fromCartesian(toCartesian(pos)).height : (pos.height ?? 0); - function shapeGeometry(item) { + function shapeGeometry(item, vertexFormat) { const g = item.geometry; const extrudedHeight = item.extrudeHeight; switch (g.kind) { @@ -3115,18 +3187,29 @@ export function createCesiumDraw({ outer, holes.map((h) => new Cesium.PolygonHierarchy(h)), ); + const polygon = { + polygonHierarchy: hierarchy, + height: g.perPositionHeight ? undefined : heightOf(g.rings[0][0]), + extrudedHeight, + perPositionHeight: g.perPositionHeight, + }; return { - fill: new Cesium.PolygonGeometry({ - polygonHierarchy: hierarchy, - height: g.perPositionHeight ? undefined : heightOf(g.rings[0][0]), - extrudedHeight, - perPositionHeight: g.perPositionHeight, - }), + fill: new Cesium.PolygonGeometry({ ...polygon, vertexFormat }), + // Extruded, its outline is the volume's edges (both faces and the + // walls' corners), as the entities' extruded polygons draw it. + outline: + item.outline && extrudedHeight !== undefined + ? new Cesium.PolygonOutlineGeometry(polygon) + : undefined, // Its holes are outlined too, as the entities' polygons outline them. rings: [outer, ...holes], }; } case 'ellipse': { + if (byCameraHeight(item)) + throw new Error( + 'the Cesium renderer takes radii by camera height on clamped ellipses only', + ); const ellipse = { center: toCartesian(g.center), semiMajorAxis: g.semiMajor, @@ -3136,7 +3219,7 @@ export function createCesiumDraw({ extrudedHeight, }; return { - fill: new Cesium.EllipseGeometry(ellipse), + fill: new Cesium.EllipseGeometry({ ...ellipse, vertexFormat }), // Its outline is an outline geometry, as the entities' ellipses draw it. outline: item.outline ? new Cesium.EllipseOutlineGeometry(ellipse) @@ -3157,6 +3240,7 @@ export function createCesiumDraw({ // An image fill turns with the rectangle, as a KML overlay's does. rotation: g.rotation ?? 0, stRotation: g.rotation ?? 0, + vertexFormat, }), }; case 'box': { @@ -3164,6 +3248,7 @@ export function createCesiumDraw({ return { fill: Cesium.BoxGeometry.fromDimensions({ dimensions: new Cesium.Cartesian3(d.x, d.y, d.z), + vertexFormat, }), modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame( toCartesian(g.center), @@ -3175,6 +3260,86 @@ export function createCesiumDraw({ } } + /** + * The camera's height for radii by camera height: above the ellipsoid, + * as Cesium places it (1000 m while it has none). + */ + const cameraHeight = () => { + const height = scene.camera?.positionCartographic?.height; + return Number.isFinite(height) ? height : 1000; + }; + + /** A clamped ellipse's radii by camera height at this frame's height, or null. */ + function radiiOf(item) { + if (!byCameraHeight(item)) return null; + const height = cameraHeight(); + return [ + radiusAt(item.geometry.semiMajor, height), + radiusAt(item.geometry.semiMinor, height), + ]; + } + + /** + * Before a frame draws: clamped ellipses with radii by camera height + * whose radii have changed with the camera are drawn at the new ones. A + * colour fill is drawn alone where it is, built in this frame + * (`moveShape`), as Cesium's entities rebuild a ground ellipse whose + * radius follows a callback, while no more than `MOVING_SHAPES` of the + * set would be drawn alone; past that, and for any other fill once its + * radii have changed by more than `REBUILD_RADII`, its set rebuilds (one + * rebuild at a time). Hidden ones wait until they show. + */ + function followCameraHeight() { + for (const record of sets.values()) { + const parts = record.shapeParts; + if (record.kind !== 'shapes' || !parts || record.spec.show === false) + continue; + try { + followIn(record, parts); + } catch (error) { + // The set draws as it did; the next frame tries again. + report(error); + } + } + } + + /** Relative change of radii past which a fill drawn in a batch rebuilds. */ + const REBUILD_RADII = 0.02; + + function followIn(record, parts) { + const changed = (radii, part, by) => + Math.abs(radii[0] - part.radii[0]) > by * part.radii[0] || + Math.abs(radii[1] - part.radii[1]) > by * part.radii[1]; + let alone = 0; + for (const part of parts.values()) if (part.solo) alone += 1; + // Those the host still retiring draws alone count too, until it goes. + if (record.retiring) + for (const part of record.retiringShapeParts?.values() ?? []) + if (part.solo && part.ground && !part.ground.isDestroyed()) alone += 1; + let rebuild = false; + for (const [id, part] of parts) { + if (!part.radii || !part.ground) continue; + const item = record.items.get(id); + if (!item || item.show === false || !byCameraHeight(item)) continue; + const radii = radiiOf(item); + if (!changed(radii, part, 1e-3)) continue; + if (part.ground.isDestroyed() || part.batch?.isDestroyed()) continue; + const movable = + colourFill(item) && + groundSyncs() && + typeof record.host?.add === 'function' && + (part.solo || alone < MOVING_SHAPES); + if (movable) { + if (!part.solo) alone += 1; + moveShape(record, part, item); + } else if (changed(radii, part, REBUILD_RADII)) rebuild = true; + } + if (rebuild && !record.pending) { + record.rebuild(); + requestRender(); + } + } + /** * A clamped shape's fill geometry, on the ellipsoid for draping; an * ellipse with a rim fill is cut finely, so its rim runs round. @@ -3191,14 +3356,19 @@ export function createCesiumDraw({ ), }); } - case 'ellipse': - if (typeof g.semiMajor !== 'number' || typeof g.semiMinor !== 'number') - throw new Error('the Cesium renderer takes fixed ellipse radii only'); + case 'ellipse': { + // Radii by camera height are the ones it has at this frame's height. + const height = cameraHeight(); + const major = radiusAt(g.semiMajor, height); + const minor = radiusAt(g.semiMinor, height); + // Radii that follow the camera apart may cross: the longer is then + // drawn as Cesium's semi-major axis, a quarter turn on. + const crossed = minor > major; return new Cesium.EllipseGeometry({ center: toCartesian(g.center), - semiMajorAxis: g.semiMajor, - semiMinorAxis: g.semiMinor, - rotation: g.rotation ?? 0, + semiMajorAxis: crossed ? minor : major, + semiMinorAxis: crossed ? major : minor, + rotation: (g.rotation ?? 0) + (crossed ? Math.PI / 2 : 0), ...(rimFill ? { granularity: RIM_GRANULARITY, @@ -3208,6 +3378,7 @@ export function createCesiumDraw({ } : {}), }); + } case 'rectangle': return new Cesium.RectangleGeometry({ rectangle: Cesium.Rectangle.fromDegrees( @@ -3279,6 +3450,10 @@ export function createCesiumDraw({ look: lookOf(item), id: pickId(record, item), ground: null, + // Radii by camera height as drawn (`followCameraHeight`). + radii: radiiOf(item), + pulse: pulseOf(item), + show: item.show !== false, }; parts.set(item.id, part); const show = new Cesium.ShowGeometryInstanceAttribute( @@ -3458,25 +3633,37 @@ export function createCesiumDraw({ */ function patchShapes(record, list) { const parts = record.shapeParts; - if (record.kind !== 'shapes' || !parts) return false; - // Each item's way in: `true` moves it (`moveShape`), else it only - // shows, hides or takes its `meta`. + const solids = record.solidParts; + if (record.kind !== 'shapes' || (!parts && !solids)) return false; + // Each item's way in: `true` moves it (`moveShape`), `'solid'` changes + // an unclamped one in place, `'recolour'` recolours a clamped one in + // place, else it only shows, hides or takes its `meta`. const moves = []; for (const item of list) { - const was = parts.get(item.id); + const solid = solids?.get(item.id); + if (solid) { + if (!solidPatchable(solid, item)) return false; + moves.push('solid'); + continue; + } + const was = parts?.get(item.id); if (!was) return false; if (was.ground?.isDestroyed() || was.batch?.isDestroyed()) return false; if (sameLook(was, item)) { moves.push(false); continue; } + if (groundRecolourable(was, item)) { + moves.push('recolour'); + continue; + } if (!movable(record, was, item)) return false; moves.push(true); } // Drawn alone after this upsert: a few at most, or the batches rebuild. const alone = new Set(); - for (const [id, part] of parts) if (part.solo) alone.add(id); - list.forEach((item, k) => moves[k] && alone.add(item.id)); + for (const [id, part] of parts ?? []) if (part.solo) alone.add(id); + list.forEach((item, k) => moves[k] === true && alone.add(item.id)); // Those the host still retiring draws alone count too, until it goes. let retiringAlone = 0; if (record.retiring) @@ -3485,11 +3672,14 @@ export function createCesiumDraw({ retiringAlone += 1; if (alone.size + retiringAlone > MOVING_SHAPES) return false; list.forEach((item, k) => { + if (moves[k] === 'solid') return patchSolid(solids.get(item.id), item); const was = parts.get(item.id); - if (moves[k]) return moveShape(record, was, item); + if (moves[k] === true) return moveShape(record, was, item); + if (moves[k] === 'recolour') recolourGround(was, item); if (!was.ground) return; was.id.meta = item.meta; const show = item.show !== false; + was.show = show; if (was.ground.ready) { showOn(was.ground, was.id, show); was.pendingShow = undefined; @@ -3501,6 +3691,194 @@ export function createCesiumDraw({ return true; } + /** Whether a fill or outline is a plain colour (or none). */ + const plainColour = (value) => + value == null || typeof value === 'string' || Array.isArray(value); + + /** + * How a shape draws but for its colours, pulse, show and `meta`, and + * whether it has a fill and an outline: shapes alike in it draw alike, + * but for their colours. + */ + const colourlessLookOf = (item) => { + const { show, meta, fill, outline, animate, ...look } = item; + return plainCopy({ + ...look, + filled: fill != null, + outlined: outline != null, + }); + }; + + /** + * Whether an upsert changes a shape's colours, its pulse, its show or its + * `meta` and nothing else, its fill and outline staying plain colours: + * those it takes in place. + */ + function colourOnly(look, item) { + if (!plainColour(item.fill) || !plainColour(item.outline)) return false; + if (!plainColour(look.fill) || !plainColour(look.outline)) return false; + return sameValues(colourlessLookOf(look), colourlessLookOf(item)); + } + + /** + * Whether a clamped colour fill's upsert recolours it (or changes its + * pulse), and changes nothing else but its show and `meta`. + */ + const groundRecolourable = (was, item) => + Boolean(was.id && was.ground) && + colourFill(item) && + colourFill(was.look) && + colourOnly(was.look, item) && + !sameValues( + plainCopy({ fill: was.look.fill, animate: was.look.animate ?? null }), + { fill: item.fill, animate: item.animate ?? null }, + ); + + /** + * Whether an unclamped shape's upsert only recolours, pulses, shows or + * hides it: a colour drawn opaque cannot become translucent in place. + */ + function solidPatchable(part, item) { + if (!colourOnly(part.look, item)) return false; + if (part.fill?.isDestroyed?.() || part.outline?.isDestroyed?.()) + return false; + // Not yet drawn: it has no colours to write, and rebuilds instead. + if ( + (part.fill && !part.fill.ready) || + (part.outline && !part.outline.ready) + ) + return false; + const pulses = Boolean(item.animate); + const fits = (translucent, colour) => + colour == null || translucent || (!pulses && toColor(colour).alpha >= 1); + // Ring outlines are polylines, whose materials take any alpha in place. + return ( + fits(part.translucent.fill, item.fill) && + fits(part.translucent.outline || !part.outline, item.outline) + ); + } + + /** An instance's colour, in a ready primitive. */ + function colourOn(primitive, id, color) { + const attributes = primitive.getGeometryInstanceAttributes(id); + attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue( + color, + attributes.color, + ); + } + + /** An unclamped shape changed in place: its colours, pulse, show and `meta`. */ + function patchSolid(part, item) { + part.look = lookOf(item); + part.pulse = pulseOf(item); + part.id.meta = item.meta; + part.show = item.show !== false; + for (const primitive of [part.fill, part.outline]) + if (primitive) primitive.show = part.show; + for (const polyline of part.rings) polyline.show = part.show; + paintSolid( + part, + part.pulse ? pulseAlpha(part.pulse, performance.now()) : null, + ); + } + + /** + * Write an unclamped shape's colours where it draws: its own, or with + * `alpha` (a pulse's) in place of theirs. A primitive not yet ready + * takes them when it is (`runPulses`, or its next patch). + */ + function paintSolid(part, alpha) { + const look = part.look; + // Primitives copy the colour they are given; polylines keep theirs. + const tint = (colour, result) => { + const base = baseColour(part, colour); + return alpha === null + ? Cesium.Color.clone(base, result) + : base.withAlpha(alpha, result); + }; + if (look.fill && part.fill?.ready && !part.fill.isDestroyed()) + colourOn(part.fill, part.id, tint(look.fill, scratchColour)); + if (look.outline) { + if (part.outline?.ready && !part.outline.isDestroyed()) + colourOn(part.outline, part.id, tint(look.outline, scratchColour)); + for (const polyline of part.rings) + polyline.material.uniforms.color = tint(look.outline); + } + } + + /** + * A clamped colour fill recoloured in place, on its ground primitive when + * it is ready, else once it is (`showPending`). + */ + function recolourGround(part, item) { + part.look = lookOf(item); + part.pulse = pulseOf(item); + const colour = toColor(item.fill); + if (part.ground.ready) { + colourOn(part.ground, part.id, colour); + part.pendingColour = undefined; + } else part.pendingColour = colour; + } + + /** + * Before a frame draws: pulsing shapes take their alpha now, where they + * draw (on primitives that are ready). Whether any pulses, so frames go + * on being asked for. + */ + function runPulses() { + const now = performance.now(); + let pulsing = false; + for (const record of sets.values()) { + if (record.kind !== 'shapes' || record.spec.show === false) continue; + if (!record.mayPulse && !record.retiring) continue; + for (const part of record.solidParts?.values() ?? []) { + if (!part.pulse || !part.show) continue; + // Only what it draws pulses: a shape with nothing drawn asks for + // no frames. + const live = (primitive) => primitive && !primitive.isDestroyed(); + if (!live(part.fill) && !live(part.outline) && !part.rings.length) + continue; + pulsing = true; + paintSolid(part, pulseAlpha(part.pulse, now)); + } + for (const parts of [record.shapeParts, record.retiringShapeParts]) + for (const part of parts?.values() ?? []) { + if (!part.pulse || !part.show || !part.ground) continue; + const ground = part.ground; + if (ground.isDestroyed()) continue; + // One still building asks for frames, to pulse once it is ready. + pulsing = true; + if (!ground.ready) continue; + colourOn( + ground, + part.id, + baseColour(part, part.look.fill).withAlpha( + pulseAlpha(part.pulse, now), + scratchColour, + ), + ); + } + } + return pulsing; + } + + const scratchColour = new Cesium.Color(); + + /** + * A part's colour as a Cesium colour, parsed once for each colour its + * look holds (a patch gives it a new look, and new values). + */ + function baseColour(part, colour) { + const cache = part.baseColours ?? (part.baseColours = new Map()); + let base = cache.get(colour); + if (!base) { + if (cache.size > 4) cache.clear(); + base = toColor(colour); + cache.set(colour, base); + } + return base; + } + /** Whether a clamped item is a plain colour fill, drawn in a batch. */ const colourFill = (item) => item.height === 'clampGround' && @@ -3525,13 +3903,7 @@ export function createCesiumDraw({ if (!was.id || !was.ground || !colourFill(item)) return false; if (!colourFill(was.look)) return false; if (!sameValues(placedLookOf(was.look), placedLookOf(item))) return false; - // Refused geometry (an ellipse radius by camera height) rebuilds, to throw. const g = item.geometry; - if ( - g?.kind === 'ellipse' && - (typeof g.semiMajor !== 'number' || typeof g.semiMinor !== 'number') - ) - return false; if (!['polygon', 'ellipse', 'rectangle'].includes(g?.kind)) return false; return groundSyncs() && typeof record.host?.add === 'function'; } @@ -3545,6 +3917,8 @@ export function createCesiumDraw({ */ function moveShape(record, part, item) { const host = record.host; + // Built first: geometry it cannot build leaves the part as it was. + const geometry = groundGeometry(item); if (part.solo) { if (part.ground && !part.ground.isDestroyed()) host.remove(part.ground); } else { @@ -3558,6 +3932,10 @@ export function createCesiumDraw({ part.solo = true; part.pendingShow = undefined; part.look = lookOf(item); + part.radii = radiiOf(item); + part.pulse = pulseOf(item); + part.show = item.show !== false; + part.pendingColour = undefined; part.id.meta = item.meta; const pickable = record.spec.pickable !== false; const Ground = pickable @@ -3566,7 +3944,7 @@ export function createCesiumDraw({ part.ground = new Ground({ geometryInstances: [ new Cesium.GeometryInstance({ - geometry: groundGeometry(item), + geometry, attributes: { color: Cesium.ColorGeometryInstanceAttribute.fromColor( toColor(item.fill), @@ -3652,10 +4030,35 @@ export function createCesiumDraw({ item.extrudeHeight === undefined && (typeof item.fill !== 'object' || Array.isArray(item.fill)); + /** + * Whether an unclamped shape classifies what is inside its volume: one + * with a volume (extruded, or a box) and a fill, on a scene that can + * classify. Where it cannot, it draws as the volume itself. + */ + function classifies(item) { + if (!item.classifyVolume || !item.fill) return false; + if (item.extrudeHeight === undefined && item.geometry.kind !== 'box') + return false; + try { + return Cesium.ClassificationPrimitive.isSupported(scene); + } catch { + return false; + } + } + function buildShapes(record) { + // Refused before anything is built: a pulse it cannot run. + record.mayPulse = false; + for (const item of record.items.values()) + if (pulseOf(item)) record.mayPulse = true; const host = new Cesium.PrimitiveCollection(); const outlines = new Cesium.PolylineCollection(); const clamped = []; + // Each unclamped item as drawn, for upserts that only recolour, show or + // hide it (`patchShapes`), and its pulse. + // Published once the build has gone through. + const solids = new Map(); + record.solidParts = null; // Image fills' materials hold their textures, which primitives leave // alone: the host destroys them as it goes. const materials = []; @@ -3688,13 +4091,61 @@ export function createCesiumDraw({ : null; if (imageFill && !imageFill.image) throw new Error('the Cesium renderer fills shapes with colours only'); - const shape = shapeGeometry(item); + // A colour fill's geometry carries what its appearance reads, as the + // entities' do. With texture coordinates too, Cesium packs them with + // the normals, which a colour appearance then misreads: a lit colour + // fill shaded darker than the same entity. + const shape = shapeGeometry( + item, + imageFill + ? Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat + : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT, + ); const id = pickId(record, item); + const pulse = pulseOf(item); + const part = { + look: lookOf(item), + id, + fill: null, + outline: null, + rings: [], + pulse, + // A pulsing colour is drawn translucent whatever its alpha now. + translucent: { fill: false, outline: false }, + show: true, + }; + solids.set(item.id, part); const solid = item.extrudeHeight !== undefined || item.geometry.kind === 'box'; // `lit`: shaded by Cesium's light, or flat; by default solids are lit. const lit = item.lit ?? solid; - if (imageFill && !item.outlineOnly) { + if (classifies(item) && !item.outlineOnly) { + if (imageFill) + throw new Error( + 'the Cesium renderer classifies volumes with colours only', + ); + // What lies inside the volume is tinted: the tiles and terrain it + // covers, as `clampTo` names them. + part.fill = host.add( + new Cesium.ClassificationPrimitive({ + geometryInstances: new Cesium.GeometryInstance({ + geometry: shape.fill, + modelMatrix: shape.modelMatrix, + attributes: { + color: Cesium.ColorGeometryInstanceAttribute.fromColor( + toColor(item.fill), + ), + }, + id, + }), + classificationType: classificationOf( + item.clampTo ?? record.spec.clampTo ?? 'both', + ), + allowPicking: record.spec.pickable !== false, + asynchronous: false, + }), + ); + } else if (imageFill && !item.outlineOnly) { const material = ownMaterial( Cesium.Material.fromType('Image', { image: toImage(imageFill.image), @@ -3721,7 +4172,8 @@ export function createCesiumDraw({ ); } else if (item.fill && !item.outlineOnly) { const color = toColor(item.fill); - host.add( + part.translucent.fill = color.alpha < 1 || Boolean(pulse); + part.fill = host.add( new Cesium.Primitive({ geometryInstances: new Cesium.GeometryInstance({ geometry: shape.fill, @@ -3732,7 +4184,7 @@ export function createCesiumDraw({ id, }), appearance: new Cesium.PerInstanceColorAppearance({ - translucent: color.alpha < 1, + translucent: part.translucent.fill, closed: solid, // Flat shapes unlit by default: lit, their faces shade by // the light (a lit box's sides differ, an unlit one's match). @@ -3745,7 +4197,8 @@ export function createCesiumDraw({ } if (item.outline && shape.outline) { const color = toColor(item.outline); - host.add( + part.translucent.outline = color.alpha < 1 || Boolean(pulse); + part.outline = host.add( new Cesium.Primitive({ geometryInstances: new Cesium.GeometryInstance({ geometry: shape.outline, @@ -3756,7 +4209,7 @@ export function createCesiumDraw({ }), appearance: new Cesium.PerInstanceColorAppearance({ flat: true, - translucent: color.alpha < 1, + translucent: part.translucent.outline, renderState: { // Clamped to what the context draws, as entities do. lineWidth: @@ -3773,17 +4226,20 @@ export function createCesiumDraw({ ); } else if (item.outline && shape.rings) for (const ring of shape.rings) - outlines.add({ - positions: [...ring, ring[0]], - width: item.outlineWidth ?? 1, - material: Cesium.Material.fromType('Color', { - color: toColor(item.outline), + part.rings.push( + outlines.add({ + positions: [...ring, ring[0]], + width: item.outlineWidth ?? 1, + material: Cesium.Material.fromType('Color', { + color: toColor(item.outline), + }), + id, }), - id, - }); + ); } host.add(outlines); const ground = groundFills(record, clamped); + record.solidParts = solids; if (!ground.length) return replaceHost(record, host); replaceHost( record, @@ -3805,6 +4261,8 @@ export function createCesiumDraw({ requestRender, }); const buildModels = (record) => modelSets.build(record); + // Whether shapes pulsed in the last frame, which draws on in the next. + let pulsing = false; const lineWidth = (px) => typeof scene.clampLineWidth === 'function' ? scene.clampLineWidth(px) @@ -3921,6 +4379,8 @@ export function createCesiumDraw({ building: () => [...sets.values()].some((record) => record.pending), /** Each frame, before it draws: the horizon cull. */ beforeRender() { + followCameraHeight(); + pulsing = runPulses(); cullHorizon(); runFlows(); for (const record of sets.values()) @@ -3953,6 +4413,7 @@ export function createCesiumDraw({ if ( [...sets.values()].some((record) => record.gpu?.animating()) || flowing() || + pulsing || playing ) requestRender(); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 95d4d7c8e..446601071 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -452,14 +452,22 @@ test('a clamped fill that only shows, hides or changes meta is changed in place' }); frame(); const moved = scene.added.at(-1); - // Anything else rebuilds: a new colour, a new item. + // A new colour is written in place too. + const colours = new Map(); + groundOf(moved).getGeometryInstanceAttributes = (id) => { + if (!colours.has(id.id)) + colours.set(id.id, { + color: new Uint8Array(4), + show: new Uint8Array([1]), + }); + return colours.get(id.id); + }; set.upsert([{ ...fill('a', true), fill: [0, 1, 0, 0.3] }]); - assert.notEqual(scene.added.at(-1), moved, 'a new look rebuilds'); - const rebuilt = scene.added.at(-1); - Object.defineProperty(groundOf(rebuilt), 'ready', { value: true }); - frame(); + assert.equal(scene.added.at(-1), moved, 'a new colour does not rebuild'); + assert.deepEqual([...colours.get('a').color], [0, 255, 0, 76]); + // A new item rebuilds. set.upsert([fill('c', true)]); - assert.notEqual(scene.added.at(-1), rebuilt, 'a new item rebuilds'); + assert.notEqual(scene.added.at(-1), moved, 'a new item rebuilds'); set.dispose(); assert.equal(scene.added.length, 0); }); @@ -503,10 +511,9 @@ test('hidden clamped fills wait for nothing, and the hidden ones it cannot build fill('c', 2, false, { fill: { preset: 'radialRim' } }), fill('d', 3, false, { geometry: { - kind: 'ellipse', + kind: 'box', center: { lon: 3, lat: 0 }, - semiMajor: { byCameraHeight: { factor: 1, min: 1, max: 2 } }, - semiMinor: 1000, + dimensions: { x: 1, y: 1, z: 1 }, }, }), ]), @@ -616,22 +623,532 @@ test('clamped shapes refuse what they cannot draw', () => { ]), /colours only/, ); + set.dispose(); + // Radii by camera height are for clamped ellipses alone. + const unclamped = draw.shapes({ id: 'refuse-unclamped' }); assert.throws( () => - set.set([ + unclamped.set([ { ...disc, + height: 'absolute', geometry: { ...disc.geometry, semiMajor: { byCameraHeight: { factor: 1, min: 1, max: 2 } }, }, }, ]), - /fixed ellipse radii/, + /radii by camera height on clamped ellipses only/, + ); + unclamped.dispose(); +}); + +test('a clamped ellipse with radii by camera height draws at the camera height and follows it', () => + withTerrainHeights(() => { + const scene = fakeScene(); + let height = 2000; + Object.defineProperty(scene.camera, 'positionCartographic', { + get: () => ({ height }), + }); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'rings' }); + const radius = { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }; + const ring = (show = true) => ({ + id: 'ring', + geometry: { + kind: 'ellipse', + center: { lon: 0, lat: 0 }, + semiMajor: radius, + semiMinor: radius, + }, + fill: [0.5, 0.9, 1, 0.38], + height: 'clampGround', + show, + }); + set.set([ring()]); + const host = scene.added[0]; + const radiusIn = (ground) => + ground.geometryInstances[0].geometry._semiMajorAxis; + const last = () => host.get(host.length - 1); + assert.equal(radiusIn(last()), 60, '3% of 2000 m'); + // The camera has not moved: nothing is built. + const built = last(); + frame(); + assert.equal(last(), built); + // It climbs: the ring is drawn wider in the frame that draws it, alone. + height = 4000; + frame(); + const wider = last(); + assert.notEqual(wider, built); + assert.equal(wider.asynchronous, false); + assert.equal(radiusIn(wider), 120); + assert.equal(wider.geometryInstances[0].id.id, 'ring', 'its own pick id'); + // Held within its bounds. + height = 1e6; + frame(); + assert.equal(radiusIn(last()), 170); + height = 10; + frame(); + assert.equal(radiusIn(last()), 14); + // Hidden, it waits; shown, it catches up. + set.upsert([ring(false)]); + const lastShown = last(); + height = 3000; + frame(); + assert.equal(last(), lastShown, 'hidden: not rebuilt'); + set.upsert([ring(true)]); + frame(); + assert.equal(radiusIn(last()), 90); + assert.equal(scene.added[0], host, 'never a rebuild of the set'); + set.dispose(); + assert.equal(scene.added.length, 0); + })); + +test('radii by camera height that cross draw the longer as the major axis; past the cap of shapes drawn alone, the set rebuilds', () => + withTerrainHeights(() => { + const scene = fakeScene(); + let height = 1000; + Object.defineProperty(scene.camera, 'positionCartographic', { + get: () => ({ height }), + }); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'crossing' }); + const ring = (id, lon) => ({ + id, + geometry: { + kind: 'ellipse', + center: { lon, lat: 0 }, + semiMajor: { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }, + semiMinor: { byCameraHeight: { factor: 0.05, min: 20, max: 100 } }, + rotation: 0.25, + }, + fill: [0.5, 0.9, 1, 0.38], + height: 'clampGround', + }); + const rings = Array.from({ length: MOVING_SHAPES + 4 }, (_, i) => + ring(`r${i}`, i * 0.1), + ); + assert.doesNotThrow(() => set.set(rings)); + const first = scene.added[0]; + const ground = (host) => { + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) return host.get(i); + return null; + }; + const geometry = ground(first).geometryInstances[0].geometry; + assert.equal(geometry._semiMajorAxis, 50, 'the longer, 5% of 1000 m'); + assert.equal(geometry._semiMinorAxis, 30); + assert.ok(Math.abs(geometry._rotation - (0.25 + Math.PI / 2)) < 1e-12); + // Its batches built. + for (let i = 0; i < first.length; i++) + if (first.get(i) instanceof Cesium.GroundPrimitive) { + Object.defineProperty(first.get(i), 'ready', { value: true }); + first.get(i).getGeometryInstanceAttributes = () => ({ + show: new Uint8Array([1]), + }); + } + frame(); + // The camera climbs: no more than the cap are drawn alone; the set + // rebuilds for the rest, and nothing throws in the frame. + height = 1500; + assert.doesNotThrow(() => frame()); + let solo = 0; + for (let i = 0; i < first.length; i++) { + const p = first.get(i); + if (p instanceof Cesium.GroundPrimitive && p.asynchronous === false) + solo += 1; + } + assert.equal(solo, MOVING_SHAPES); + assert.notEqual(scene.added.at(-1), first, 'rebuilt for the rest'); + set.dispose(); + })); + +test('rings drawn alone by a host still retiring count toward the cap when the camera moves again', () => + withTerrainHeights(() => { + const scene = fakeScene(); + let height = 1000; + Object.defineProperty(scene.camera, 'positionCartographic', { + get: () => ({ height }), + }); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'climbing' }); + const radius = { byCameraHeight: { factor: 0.03, min: 14, max: 170 } }; + const rings = Array.from({ length: MOVING_SHAPES + 4 }, (_, i) => ({ + id: `r${i}`, + geometry: { + kind: 'ellipse', + center: { lon: i * 0.1, lat: 0 }, + semiMajor: radius, + semiMinor: radius, + }, + fill: [0.5, 0.9, 1, 0.38], + height: 'clampGround', + })); + const ready = (host) => { + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) { + Object.defineProperty(host.get(i), 'ready', { value: true }); + host.get(i).getGeometryInstanceAttributes = () => ({ + show: new Uint8Array([1]), + }); + } + }; + const solo = (host) => { + let n = 0; + for (let i = 0; i < host.length; i++) { + const p = host.get(i); + if (p instanceof Cesium.GroundPrimitive && p.asynchronous === false) + n += 1; + } + return n; + }; + set.set(rings); + const first = scene.added[0]; + ready(first); + frame(); + // A climb: the cap drawn alone, and a rebuild for the rest. + height = 1500; + frame(); + assert.equal(solo(first), MOVING_SHAPES); + const second = scene.added.at(-1); + assert.notEqual(second, first, 'rebuilding, the old host retiring'); + ready(second); + // Climbing on while the old host retires: its rings drawn alone still + // count, so none more are drawn alone. + height = 2500; + frame(); + assert.equal(solo(second), 0, 'nothing more drawn alone'); + set.dispose(); + })); + +test('shapes that only change colour, pulse, show or meta change in place; a pulse runs on the frames', () => + withTerrainHeights(() => { + const scene = fakeScene(); + const asked = []; + scene.requestRender = () => asked.push(1); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'fading' }); + const ring = [ + { lon: 0, lat: 0, height: 10 }, + { lon: 0.001, lat: 0, height: 10 }, + { lon: 0.001, lat: 0.001, height: 10 }, + ]; + const pulse = (alpha) => ({ + property: 'alpha', + from: alpha * 0.6, + to: alpha, + periodMs: 1000, + }); + const column = (alpha, extra = {}) => ({ + id: 'column', + geometry: { kind: 'polygon', rings: [ring] }, + fill: [1, 0.7, 0.3, 0.45 * alpha], + animate: pulse(0.45 * alpha), + extrudeHeight: 100, + height: 'absolute', + ...extra, + }); + const cage = (alpha) => ({ + id: 'cage', + geometry: { kind: 'polygon', rings: [ring] }, + outline: [1, 0.7, 0.3, 0.32 * alpha], + outlineOnly: true, + animate: pulse(0.32 * alpha), + extrudeHeight: 100, + height: 'absolute', + }); + const fill = (alpha) => ({ + id: 'fill', + geometry: { + kind: 'polygon', + rings: [ring.map(({ lon, lat }) => ({ lon: lon + 1, lat }))], + }, + fill: [0.4, 1, 0.6, 0.2 * alpha], + animate: pulse(0.2 * alpha), + height: 'clampGround', + }); + set.set([column(0), cage(0), fill(0)]); + const host = scene.added[0]; + const solids = host.get(0); + const [columnPrimitive, cagePrimitive] = [solids.get(0), solids.get(1)]; + let ground = null; + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) ground = host.get(i); + // A pulsing colour draws translucent, whatever its alpha now. + assert.equal(columnPrimitive.appearance.translucent, true); + assert.equal(cagePrimitive.appearance.translucent, true); + // Ready, with instance attributes to write. + const colours = new Map(); + const ready = (primitive, key) => { + Object.defineProperty(primitive, 'ready', { value: true }); + primitive.getGeometryInstanceAttributes = () => { + if (!colours.has(key)) + colours.set(key, { + color: new Uint8Array(4), + show: new Uint8Array([1]), + }); + return colours.get(key); + }; + }; + ready(columnPrimitive, 'column'); + ready(cagePrimitive, 'cage'); + ready(ground, 'fill'); + frame(); + // Faded in: the same primitives take it. + set.upsert([column(1, { meta: 'm' }), cage(1), fill(1)]); + assert.equal(scene.added[0], host, 'not rebuilt'); + assert.equal(solids.get(0), columnPrimitive); + assert.equal(columnPrimitive.geometryInstances.id.meta, 'm'); + // The pulse writes each frame between 60% and all of the alpha, and asks + // for the next frame. + const seen = { column: [], cage: [], fill: [] }; + const realNow = performance.now; + let now = 0; + performance.now = () => now; + try { + for (now = 0; now < 1000; now += 50) { + asked.length = 0; + frame(); + assert.ok(asked.length > 0, 'a pulse asks for frames'); + for (const key of Object.keys(seen)) + seen[key].push(colours.get(key).color[3] / 255); + } + } finally { + performance.now = realNow; + } + const range = (values) => [Math.min(...values), Math.max(...values)]; + const near = (a, b) => Math.abs(a - b) < 0.01; + assert.ok( + near(range(seen.column)[0], 0.27) && near(range(seen.column)[1], 0.45), + `${range(seen.column)}`, + ); + assert.ok( + near(range(seen.cage)[0], 0.192) && near(range(seen.cage)[1], 0.32), + `${range(seen.cage)}`, + ); + assert.ok( + near(range(seen.fill)[0], 0.12) && near(range(seen.fill)[1], 0.2), + `${range(seen.fill)}`, + ); + // Hidden in place: its primitives hide, and stop pulsing. + set.upsert([column(1, { show: false })]); + assert.equal(scene.added[0], host); + assert.equal(columnPrimitive.show, false); + // An opaque colour drawn translucent is fine in place; a shape that + // changes more than its colours rebuilds. + set.upsert([column(1, { extrudeHeight: 200 })]); + assert.notEqual(scene.added.at(-1), host, 'rebuilt'); + set.dispose(); + })); + +test('colour fills carry what their appearance reads, as entities do', () => + withImageClasses(() => { + const { scene, draw } = drawOver(); + const set = draw.shapes({ id: 'formats' }); + const ring = [ + { lon: 0, lat: 0, height: 10 }, + { lon: 0.001, lat: 0, height: 10 }, + { lon: 0.001, lat: 0.001, height: 10 }, + ]; + set.set([ + { + id: 'column', + geometry: { kind: 'polygon', rings: [ring] }, + fill: [1, 0.7, 0.3, 0.45], + extrudeHeight: 100, + height: 'absolute', + }, + { + id: 'box', + geometry: { + kind: 'box', + center: { lon: 1, lat: 0, height: 10 }, + dimensions: { x: 10, y: 10, z: 10 }, + }, + fill: '#fff', + height: 'absolute', + }, + { + id: 'disc', + geometry: { + kind: 'ellipse', + center: { lon: 2, lat: 0, height: 10 }, + semiMajor: 50, + semiMinor: 30, + }, + fill: '#fff', + extrudeHeight: 40, + height: 'absolute', + }, + { + id: 'slab', + geometry: { + kind: 'rectangle', + rect: { west: 3, south: 0, east: 3.01, north: 0.01 }, + height: 10, + }, + fill: '#fff', + extrudeHeight: 40, + height: 'absolute', + }, + ]); + const host = scene.added[0]; + const formats = []; + const walk = (c) => { + for (let i = 0; i < c.length; i++) { + const p = c.get(i); + if (typeof p.length === 'number' && p.get) walk(p); + else if (p instanceof Cesium.Primitive && p.geometryInstances?.geometry) + formats.push(p.geometryInstances.geometry._vertexFormat); + } + }; + walk(host); + assert.equal(formats.length, 4); + // Position and normal only: with texture coordinates too, Cesium packs + // them with the normals, and the colour appearance misreads them. + for (const format of formats) { + assert.equal(format.normal, true); + assert.equal(format.st, false); + } + set.dispose(); + })); + +test('a pulse the Cesium renderer cannot run is refused before anything changes', () => { + const { scene, draw } = drawOver(); + const set = draw.shapes({ id: 'pulses' }); + const disc = (animate) => ({ + id: 'a', + geometry: { + kind: 'ellipse', + center: { lon: 0, lat: 0 }, + semiMajor: 1000, + semiMinor: 1000, + }, + fill: '#fff', + height: 'clampGround', + animate, + }); + set.set([disc(undefined)]); + const host = scene.added[0]; + assert.throws( + () => set.set([disc({ property: 'radius', from: 1, to: 2, periodMs: 1 })]), + /pulses alpha only, forever/, + ); + assert.throws( + () => + set.upsert([ + disc({ property: 'alpha', from: 0, to: 1, periodMs: 1, repeat: 2 }), + ]), + /pulses alpha only, forever/, + ); + assert.equal(scene.added[0], host, 'still drawn as it was'); + // Behind an item that would rebuild, and in a whole new list, too. + const radius = { property: 'radius', from: 1, to: 2, periodMs: 1 }; + assert.throws( + () => set.upsert([{ ...disc(undefined), id: 'b' }, disc(radius)]), + /pulses alpha only, forever/, + ); + assert.throws(() => set.set([disc(radius)]), /pulses alpha only, forever/); + assert.equal(scene.added[0], host, 'still drawn as it was'); + assert.doesNotThrow(() => set.upsert([{ ...disc(undefined), id: 'c' }])); + // Nor numbers it cannot draw, nor a fill that is not a colour. + assert.throws( + () => + set.upsert([disc({ property: 'alpha', from: 0, to: 1, periodMs: 0 })]), + /positive period/, + ); + assert.throws( + () => + set.upsert([ + { + ...disc({ property: 'alpha', from: 0, to: 1, periodMs: 1000 }), + fill: { image: 'x.png' }, + }, + ]), + /colour fills and outlines only/, ); set.dispose(); }); +test('a pulsing ring outline changes in place; a pulsing shape that draws nothing asks for no frames', () => + withImageClasses(() => { + const scene = fakeScene(); + const asked = []; + scene.requestRender = () => asked.push(1); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'rings-pulse' }); + const ring = [ + { lon: 0, lat: 0, height: 10 }, + { lon: 0.001, lat: 0, height: 10 }, + { lon: 0.001, lat: 0.001, height: 10 }, + ]; + const pulse = { property: 'alpha', from: 0.2, to: 0.5, periodMs: 1000 }; + const outlined = (extra = {}) => ({ + id: 'o', + geometry: { kind: 'polygon', rings: [ring] }, + outline: [1, 1, 1, 0.5], + outlineOnly: true, + animate: pulse, + height: 'absolute', + ...extra, + }); + set.set([outlined()]); + const host = scene.added[0]; + set.upsert([outlined({ meta: 'm' })]); + assert.equal(scene.added[0], host, 'not rebuilt'); + set.set([ + { + id: 'nothing', + geometry: { kind: 'polygon', rings: [ring] }, + animate: pulse, + height: 'absolute', + }, + ]); + frame(); + asked.length = 0; + frame(); + assert.equal(asked.length, 0, 'nothing drawn, no frames asked'); + set.dispose(); + })); + +test('an unclamped shape recoloured before it is drawn rebuilds; frames stop once nothing pulses', () => + withTerrainHeights(() => { + const scene = fakeScene(); + const asked = []; + scene.requestRender = () => asked.push(1); + const { draw, frame } = drawOver(scene); + const set = draw.shapes({ id: 'early' }); + const ring = [ + { lon: 0, lat: 0, height: 10 }, + { lon: 0.001, lat: 0, height: 10 }, + { lon: 0.001, lat: 0.001, height: 10 }, + ]; + const column = (alpha, extra = {}) => ({ + id: 'column', + geometry: { kind: 'polygon', rings: [ring] }, + fill: [1, 0.7, 0.3, alpha], + extrudeHeight: 100, + height: 'absolute', + ...extra, + }); + set.set([column(0.4)]); + const host = scene.added[0]; + set.upsert([column(0.5)]); + assert.notEqual(scene.added.at(-1), host, 'not yet drawn: rebuilt'); + // Pulsing, it asks for frames; hidden, it stops. + const pulse = { property: 'alpha', from: 0.2, to: 0.5, periodMs: 1000 }; + set.set([column(0.5, { animate: pulse })]); + asked.length = 0; + frame(); + assert.ok(asked.length > 0, 'a pulse asks for frames'); + set.set([column(0.5, { animate: pulse, show: false })]); + frame(); + asked.length = 0; + frame(); + assert.equal(asked.length, 0, 'nothing pulses, no frames asked'); + set.dispose(); + })); + test('the earthquakes layer draws its discs as ground fills on a viewer of its own', async () => { const { createEarthquakesLayer } = await import('../../layers/earthquakes/index.js'); @@ -669,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'); @@ -3543,6 +4155,66 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del unbind(); } }); +test('an extruded shape that classifies its volume tints what it covers; its outline is the volume edges', () => { + const scene = fakeScene(); + const { draw } = drawOver(scene); + const set = draw.shapes({ id: 'volumes' }); + const ring = [ + { lon: 0, lat: 0, height: 100 }, + { lon: 0.001, lat: 0, height: 100 }, + { lon: 0.001, lat: 0.001, height: 100 }, + ]; + const volume = { + id: 'volume', + geometry: { kind: 'polygon', rings: [ring] }, + fill: [1, 0.7, 0.3, 0.45], + extrudeHeight: 220, + height: 'absolute', + classifyVolume: true, + }; + const cage = { + id: 'cage', + geometry: { kind: 'polygon', rings: [ring] }, + outline: [1, 0.7, 0.3, 0.32], + outlineOnly: true, + extrudeHeight: 220, + height: 'absolute', + }; + // A scene that cannot classify draws the volume itself. + set.set([volume]); + assert.ok(scene.added[0].get(0) instanceof Cesium.Primitive); + assert.ok(!(scene.added[0].get(0) instanceof Cesium.ClassificationPrimitive)); + scene.context = { stencilBuffer: true }; + set.set([volume, cage]); + const host = scene.added[0]; + const classified = host.get(0); + assert.ok(classified instanceof Cesium.ClassificationPrimitive); + assert.equal(classified.classificationType, Cesium.ClassificationType.BOTH); + const [instance] = [classified.geometryInstances].flat(); + assert.ok(instance.geometry instanceof Cesium.PolygonGeometry); + assert.deepEqual( + [instance.geometry._extrudedHeight, instance.geometry._height].sort( + (a, b) => a - b, + ), + [100, 220], + 'from its base to its extruded face', + ); + assert.equal(instance.id.id, 'volume'); + // The cage: the extruded outline, not a ring at its base. + const edges = host.get(1); + assert.ok(edges instanceof Cesium.Primitive); + assert.ok( + [edges.geometryInstances].flat()[0].geometry instanceof + Cesium.PolygonOutlineGeometry, + ); + // An image cannot classify. + assert.throws( + () => set.set([{ ...volume, fill: { image: 'a.png' } }]), + /classifies volumes with colours only/, + ); + set.dispose(); +}); + test('an unclamped shape filled with an image draws a textured primitive and frees its material with its host', () => withImageClasses(() => { const scene = fakeScene(); @@ -3578,6 +4250,8 @@ test('an unclamped shape filled with an image draws a textured primitive and fre [true, true, true], ); assert.ok(geometryInstances.geometry instanceof Cesium.RectangleGeometry); + // Texture coordinates for the image, as its appearance reads them. + assert.equal(geometryInstances.geometry._vertexFormat.st, true); assert.equal(geometryInstances.id.id, 'image'); assert.equal( drawHitOf({ primitive, id: geometryInstances.id }).set, @@ -3927,19 +4601,19 @@ test('flow lines run their dashes toward the end, draped or not, on the frame cl asked = 0; frame(); assert.equal(asked, 0, 'an emptied set asks for none'); - // Arrows and patterns are not draped. + // Patterns are not draped. assert.throws( () => set.set([ { - id: 'arrow', + id: 'pattern', positions, widthPx: 1, mode: 'draped', - style: { kind: 'arrow', color: '#fff' }, + style: { kind: 'pattern', image: 'a.png', repeat: 2 }, }, ]), - /drapes solid, glow, dash and flow lines only/, + /drapes solid, glow, dash, flow and arrow lines only/, ); set.dispose(); })); @@ -4472,6 +5146,42 @@ test('draped glow and dash lines drape with their materials, each on a ground pr set.dispose(); })); +test('a draped arrow drapes its arrow material on a ground polyline of its own, recoloured in place', () => + withImageClasses(() => { + const { scene, draw } = drawOver(); + const set = draw.lines({ id: 'arrows' }); + const arrow = (color) => ({ + id: 'to', + positions: [ + { lon: 0, lat: 0 }, + { lon: 0.01, lat: 0.01 }, + ], + widthPx: 16, + mode: 'draped', + style: { kind: 'arrow', color }, + }); + set.set([arrow([0.5, 0.9, 1, 0.95])]); + const host = scene.added[0]; + const ground = host.get(1); + assert.ok(ground instanceof Cesium.GroundPolylinePrimitive); + assert.equal(ground.classificationType, Cesium.ClassificationType.BOTH); + assert.equal(ground.geometryInstances[0].geometry.width, 16); + const material = ground.appearance.material; + assert.equal(material.type, 'PolylineArrow'); + assert.ok( + Cesium.Color.equals( + material.uniforms.color, + new Cesium.Color(0.5, 0.9, 1, 0.95), + ), + ); + // Faded, it takes its new colour on the material it has. + set.upsert([arrow([0.5, 0.9, 1, 0.4])]); + assert.equal(scene.added[0], host, 'not rebuilt'); + assert.equal(ground.appearance.material, material); + assert.equal(material.uniforms.color.alpha, 0.4); + set.dispose(); + })); + test('a draped line drawn by its own material changes colour in place; a batched one rebuilds', () => withImageClasses(() => { const { scene, draw } = drawOver(); @@ -6384,8 +7094,8 @@ test('a clamped fill that moves or resizes is drawn where it now is in the same set.upsert([box('a', 2, { show: false })]); assert.equal(host.get(host.length - 1), again); assert.deepEqual([...shows.get('1:a').show], [0]); - // A new colour is a new look: the set rebuilds. - set.upsert([box('a', 2, { fill: [1, 0, 0, 0.5] })]); + // A new item: the set rebuilds. + set.upsert([box('a', 2), box('z', 3)]); assert.notEqual(scene.added.at(-1), host, 'rebuilt'); set.dispose(); assert.equal(scene.added.length, 0); @@ -6416,8 +7126,8 @@ test('a moved clamped fill is hidden where a rebuild in flight still draws it', frame(); const shown = { show: new Uint8Array([1]) }; old.getGeometryInstanceAttributes = () => shown; - // A new colour rebuilds; the old host draws on until the new is ready. - set.upsert([box('a', 1, [1, 0, 0, 0.5])]); + // A new item rebuilds; the old host draws on until the new is ready. + set.upsert([box('a', 1, [1, 0, 0, 0.5]), box('z', 0.5)]); const second = scene.added.find((p) => p !== first); assert.ok( second && scene.added.includes(first), @@ -6557,11 +7267,11 @@ test('a moved clamped fill shows again where the retiring host draws it when the frame(); const shown = { show: new Uint8Array([1]) }; old.getGeometryInstanceAttributes = () => shown; - set.upsert([groundBox('a', 1, { fill: [1, 0, 0, 0.5] })]); - set.upsert([groundBox('a', 2, { fill: [1, 0, 0, 0.5] })]); + set.upsert([groundBox('a', 1), groundBox('z', 0.5)]); + set.upsert([groundBox('a', 2)]); assert.deepEqual([...shown.show], [0], 'hidden while drawn alone'); // A second rebuild drops the host drawing it alone, still building. - set.upsert([groundBox('a', 2, { fill: [0, 1, 0, 0.5] })]); + set.upsert([groundBox('a', 2), groundBox('y', 0.5)]); assert.ok(scene.added.includes(first), 'the retiring host draws on'); assert.equal(scene.added.length, 2); assert.deepEqual([...shown.show], [1], 'drawn where it was, not gone'); @@ -6632,7 +7342,7 @@ test('clamped fills drawn alone by a host still retiring count toward MOVING_SHA frame(); // Half the cap moved, then a rebuild while they are drawn alone. set.upsert(ids.slice(0, MOVING_SHAPES).map((id) => groundBox(id, 1.5))); - set.upsert([groundBox(ids.at(-1), 1, { fill: [1, 0, 0, 0.5] })]); + set.upsert([groundBox('new', 1)]); assert.equal(scene.added.length, 2, 'rebuilding, the old host retiring'); const second = scene.added.find((p) => p !== first); const before = second.length; diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 7b7c5e0d4..e725b1ef6 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -64,7 +64,9 @@ export const CESIUM_CHECKS = new Set([ 'draw.points.population', 'draw.lodGroup', 'draw.sets', + 'draw.shapes.classifyVolume', 'draw.shapes.drapedRotation', + 'draw.shapes.radiusByCameraHeight', 'effects.crossfade', 'effects.defineStyle', 'effects.screenModulation', 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/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index d6c4275ec..d11a2d56a 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -1998,6 +1998,126 @@ export function portChecks() { ok(!mine(at(0)), 'gone with its set'); }, ), + check( + 'draw.shapes.radiusByCameraHeight', + 'a clamped ellipse with radii by camera height draws at the radius the camera height gives, held within its bounds, and follows the camera', + async (h, r) => { + const shapes = r.draw.shapes({ id: 'conf:rings' }); + const radius = { byCameraHeight: { factor: 0.1, min: 50, max: 600 } }; + shapes.set([ + { + id: 'ring', + geometry: { + kind: 'ellipse', + center: { lon: AUSTIN.lon, lat: AUSTIN.lat }, + semiMajor: radius, + semiMinor: radius, + }, + fill: [0.5, 0.9, 1, 0.6], + height: 'clampGround', + }, + ]); + // Metres east of the centre, at its latitude. + const east = (m) => + h.toEcef({ + lon: + AUSTIN.lon + + m / (111320 * Math.cos((AUSTIN.lat * Math.PI) / 180)), + lat: AUSTIN.lat, + }); + const covers = (m) => { + const s = r.query.project(east(m)); + return Boolean( + s && + r.query + .drillPick(s.x, s.y) + .some((hit) => hit.set === 'conf:rings' && hit.id === 'ring'), + ); + }; + const until = async (test) => { + for (let i = 0; i < 300; i++) { + await drawn(h, r, 1); + if (test()) return true; + } + return false; + }; + // 2000 m up: 200 m across its centre. + await overAustin(h, r, 2000); + ok(await until(() => covers(150)), 'at 2000 m it reaches 150 m'); + ok(!covers(260), 'and not 260 m'); + // 4000 m up: 400 m. + await overAustin(h, r, 4000); + ok( + await until(() => covers(300) && !covers(460)), + 'at 4000 m it reaches 300 m, not 460 m', + ); + // 20 km up: held at 600 m. + await overAustin(h, r, 20000); + ok( + await until(() => covers(550) && !covers(700)), + 'held at its largest', + ); + shapes.dispose(); + await drawn(h, r); + ok(!covers(0), 'gone with its set'); + }, + ), + check( + 'draw.shapes.classifyVolume', + 'an extruded shape that classifies its volume picks where it tints what it covers, and hides', + async (h, r) => { + await overAustin(h, r); + const shapes = r.draw.shapes({ id: 'conf:volume' }); + const d = 0.002; + const ring = [ + [-d, -d], + [d, -d], + [d, d], + [-d, d], + ].map(([dLon, dLat]) => ({ + lon: AUSTIN.lon + dLon, + lat: AUSTIN.lat + dLat, + height: -200, + })); + const volume = (extra = {}) => ({ + id: 'volume', + geometry: { kind: 'polygon', rings: [ring] }, + fill: [1, 0.7, 0.3, 0.45], + extrudeHeight: 300, + height: 'absolute', + classifyVolume: true, + ...extra, + }); + const mine = (dLon) => { + const s = r.query.project( + h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat }), + ); + return Boolean( + s && + r.query + .drillPick(s.x, s.y) + .some((hit) => hit.set === 'conf:volume' && hit.id === 'volume'), + ); + }; + const until = async (test) => { + for (let i = 0; i < 300; i++) { + await drawn(h, r, 1); + if (test()) return true; + } + return false; + }; + shapes.set([volume()]); + ok(await until(() => mine(0)), 'it picks inside'); + ok(!mine(0.008), 'and not outside'); + shapes.upsert([volume({ show: false })]); + ok(await until(() => !mine(0)), 'hidden'); + shapes.upsert([volume()]); + ok(await until(() => mine(0)), 'shown again'); + shapes.dispose(); + await drawn(h, r); + ok(!mine(0), 'gone with its set'); + }, + ), check( 'draw.lines.styles', 'flow lines draw draped and in space, and a line with a depth-fail colour moves every frame, without stopping the frame or picks', @@ -2069,7 +2189,7 @@ export function portChecks() { ), check( 'draw.lines.drape', - 'draped glow and dash lines draw and pick; a revealed line draws only its first part; a draped line and a clamped point that move every frame are drawn where they now are in the next frame', + 'draped glow, dash and arrow lines draw and pick; a revealed line draws only its first part; a draped line and a clamped point that move every frame are drawn where they now are in the next frame', async (h, r) => { await overAustin(h, r); const at = (dLon, dLat = 0) => @@ -2112,12 +2232,20 @@ export function portChecks() { style: { kind: 'solid', color: '#20e7f2' }, revealFraction: 0.5, }, + { + id: 'arrow', + positions: [at(-0.003, -0.004), at(0.003, -0.004)], + widthPx: 16, + mode: 'draped', + style: { kind: 'arrow', color: [0.5, 0.9, 1, 0.95] }, + }, ]); await drawn(h, r); await settled(r); await drawn(h, r); ok(mine(at(0, 0.002), 'glow'), 'a draped glow line picks'); ok(mine(at(0, -0.002), 'dash'), 'a draped dash line picks'); + ok(mine(at(-0.002, -0.004), 'arrow'), 'a draped arrow picks'); ok(mine(at(-0.0015), 'reveal'), 'revealed: its first half draws'); ok(!mine(at(0.0015), 'reveal'), 'revealed: its second half does not'); lines.upsert([ @@ -2191,7 +2319,7 @@ export function portChecks() { `moved, frame ${i}: not where it was`, ); } - equal(lines.size(), 4, 'every line held'); + equal(lines.size(), 5, 'every line held'); points.dispose(); lines.dispose(); }, diff --git a/src/render/stub/index.js b/src/render/stub/index.js index edfa96b1a..1dcf08426 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -710,6 +710,60 @@ export function createStubRenderer(options = {}) { ); } + /** The eye's height above the ellipsoid, for radii by camera height. */ + const eyeHeight = () => toCartographicRadians(eye().position)?.height ?? 0; + + /** + * Whether `lon`, `lat` (degrees) is in an ellipse geometry, its radii by + * camera height at the eye's height, measured in the plane tangent at its + * centre. + */ + function inEllipse(g, lon, lat) { + const height = eyeHeight(); + const radius = (r) => + typeof r === 'number' + ? r + : Math.max( + r.byCameraHeight.min, + Math.min(r.byCameraHeight.max, height * r.byCameraHeight.factor), + ); + const centre = toCartographicRadians(toEcef(g.center)); + const metresPerRadian = 6378137; + const east = + ((lon * Math.PI) / 180 - centre.lon) * + metresPerRadian * + Math.cos(centre.lat); + const north = ((lat * Math.PI) / 180 - centre.lat) * metresPerRadian; + // The semi-major axis is turned counter-clockwise from north. + const turn = g.rotation ?? 0; + const along = north * Math.cos(turn) - east * Math.sin(turn); + const across = north * Math.sin(turn) + east * Math.cos(turn); + return ( + (along / radius(g.semiMajor)) ** 2 + + (across / radius(g.semiMinor)) ** 2 <= + 1 + ); + } + + /** Whether `lon`, `lat` (degrees) is inside a ring of positions. */ + function inRing(ring, lon, lat) { + const points = ring.map((p) => { + const c = toCartographicRadians(toEcef(p)); + return [toDegrees(c.lon), toDegrees(c.lat)]; + }); + let inside = false; + for (let i = 0, j = points.length - 1; i < points.length; j = i++) { + const [xi, yi] = points[i]; + const [xj, yj] = points[j]; + if ( + yi > lat !== yj > lat && + lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi + ) + inside = !inside; + } + return inside; + } + /** * The pickable items under a pixel, nearest first. With a `depth`, only * the nearest `depth` things drawn there are looked through, unpickable @@ -745,18 +799,29 @@ export function createStubRenderer(options = {}) { continue; } if (set.kind === 'shapes') { - // Draped rectangles are picked where they cover the ellipsoid, turned - // as the default renderer turns them; other shapes are not picked. + // Draped rectangles and ellipses, and volumes that classify what + // they cover, are picked where they cover the ellipsoid (rectangles + // turned as the default renderer turns them); other shapes are not + // picked. const ground = rayEllipsoid(pickRay(x, y)); const at = ground && toCartographicRadians(ground); if (!at) continue; + const lon = toDegrees(at.lon); + const lat = toDegrees(at.lat); for (const item of set.items.values()) { if (item.show === false) continue; if (!item.fill || item.outlineOnly) continue; - if (item.height !== 'clampGround') continue; - if (item.geometry?.kind !== 'rectangle') continue; - if (!inRectangle(item.geometry, toDegrees(at.lon), toDegrees(at.lat))) - continue; + const g = item.geometry; + const covers = + item.height === 'clampGround' + ? (g?.kind === 'rectangle' && inRectangle(g, lon, lat)) || + (g?.kind === 'ellipse' && inEllipse(g, lon, lat)) + : item.classifyVolume === true && + item.extrudeHeight !== undefined && + g?.kind === 'polygon' && + inRing(g.rings[0], lon, lat) && + !g.rings.slice(1).some((hole) => inRing(hole, lon, lat)); + if (!covers) continue; hits.push({ set: setId, id: item.id, diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index 1b31f60c0..7dc783145 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -141,6 +141,40 @@ test('a draped rectangle across the antimeridian picks on both sides of it, turn r.destroy(); }); +test('an extruded volume that classifies picks inside its outer ring and not in its holes', () => { + const r = createStubRenderer(); + r.camera.setView({ + destination: { lon: 0, lat: 0, height: 20_000 }, + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + const shapes = r.draw.shapes({ id: 'volume' }); + const square = (d) => + [ + [-d, -d], + [d, -d], + [d, d], + [-d, d], + ].map(([lon, lat]) => ({ lon, lat, height: -50 })); + shapes.set([ + { + id: 'v', + geometry: { kind: 'polygon', rings: [square(0.02), square(0.005)] }, + fill: '#f80', + extrudeHeight: 100, + height: 'absolute', + classifyVolume: true, + }, + ]); + const picked = (lon, lat) => { + const s = r.query.project(toEcef({ lon, lat, height: 0 })); + return r.query.drillPick(s.x, s.y).some((hit) => hit.set === 'volume'); + }; + assert.ok(picked(0.012, 0), 'between its rings'); + assert.ok(!picked(0, 0), 'not in its hole'); + assert.ok(!picked(0.03, 0), 'not outside'); + r.destroy(); +}); + test('the stub says where it draws an item, for a camera that is not its own', () => { const r = createStubRenderer(); const t0 = r.frame.time(); 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',