From a4a4366b131d05a3eec3f022689de6c4ac634dd3 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Wed, 11 Nov 2026 16:33:21 -0800 Subject: [PATCH] Icon sets cluster on the Cesium renderer Clustered icon sets cluster with clusterScreenPoints over the shown icons each frame drawn after the camera moves or the set changes. A cluster draws one icon (icon(count), else a count badge) at its members' mean in place of the members; a pick on it answers each member, seed first, at the cluster's position. GPU icon sets refuse clustering. The stub clusters the same way, the contract documents the semantics, and the check draw.icons.cluster covers it. --- docs/RENDERER-CONTRACT.md | 15 ++ src/render/cesium/draw.js | 187 ++++++++++++++++++++++++- src/render/cesium/draw.test.mjs | 86 ++++++++++++ src/render/cesium/gpuIcons.js | 5 +- src/render/cesium/gpuIcons.test.mjs | 15 ++ src/render/cesium/harness.js | 1 + src/render/cesium/ports.js | 2 + src/render/cesium/ports.test.mjs | 1 + src/render/cesium/query.js | 44 +++++- src/render/conformance/checks/ports.js | 105 ++++++++++++++ src/render/contract/draw.d.ts | 20 ++- src/render/stub/index.js | 113 +++++++++++++++ 12 files changed, 583 insertions(+), 11 deletions(-) diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md index 829767f68..67cfb876b 100644 --- a/docs/RENDERER-CONTRACT.md +++ b/docs/RENDERER-CONTRACT.md @@ -163,6 +163,21 @@ keyed canvas, and an atlas slot as the image it holds (an icon waits for an unregistered slot; anything else refuses it). The check `draw.icons.images` draws each kind on still and receding icons. +Icon sets with `cluster` (`ClusterSpec`) cluster the same way on every +renderer: `clusterScreenPoints` (`src/geo/screenCluster.js`) over the shown +icons in front of the eye and above the horizon, in the set's order, boxed at +their drawn size, the last pass's clusters kept. A cluster draws one icon at +the mean of its members' positions in place of its members (`icon(count)`, +else a default badge with the count, at the seed's size). A pick on it +answers one hit a member, seed first, each with the member's own `set`, `id` +and `meta` and the cluster's position, so `pick` gives the seed and +`drillPick` every member. Clusters are made again in the frames drawn after +the camera moves or the set changes, never on a timer. The Cesium port draws +a set's cluster icons in a billboard collection of their own and hides the +members' billboards; a set on the GPU (`columns`, or moving, receding, +proxy-picked or level-of-detail icons) refuses clustering. The check +`draw.icons.cluster` draws a cluster, picks it, and parts it by moving in. + The Cesium port also draws `pattern` line styles (the image repeated `repeat` times along the line, in the translucent pass; draped too), lines in the `inertial` frame (turned each frame by the set's motion clock, a depth-fail diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index c564441a4..c85ee15d0 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -34,6 +34,7 @@ import * as Cesium from 'cesium'; import { temeToPseudoFixed } from '../../geo/celestial.js'; import { alongLength } from '../../geo/polyline.js'; +import { clusterScreenPoints } from '../../geo/screenCluster.js'; import { provideUnboundDraw } from '../rendererOf.js'; import { blobUrl, listenerList, toCartesian, uncaught } from './common.js'; import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js'; @@ -549,6 +550,8 @@ export function createCesiumDraw({ requestRender(); }, setOptions(options) { + // Refused, changing nothing, where icons on the GPU cannot take it. + if (record.gpu) gpu.check([], { ...spec, ...options }); const culled = spec.horizonCull; const clampTo = spec.clampTo; const blend = spec.blend; @@ -605,6 +608,19 @@ export function createCesiumDraw({ requestRender(); }, }; + // A clustered set clusters again in the next frame drawn after a change. + for (const name of ['set', 'upsert', 'remove', 'clear', 'setOptions']) { + const call = handle[name]; + handle[name] = (...args) => { + record.clusterKey = null; + return call(...args); + }; + } + const dispose = handle.dispose; + handle.dispose = () => { + dropClusters(record); + dispose(); + }; // `columns`: column updates of an icon set, on the GPU. if (kind === 'icons' && capabilities.has('columns')) handle.setColumns = (columns) => { @@ -833,7 +849,10 @@ export function createCesiumDraw({ const horizon = horizonNow(); if (!horizon) return; for (const placed of record.placed) { - const show = placed.shown && horizon.isPointVisible(placed.position); + const show = + placed.shown && + !placed.clustered && + horizon.isPointVisible(placed.position); if (placed.primitive.show !== show) placed.primitive.show = show; } } @@ -859,6 +878,168 @@ export function createCesiumDraw({ } } + // --- Clusters (`cluster`) -------------------------------------------------- + + /** The default cluster badge: the count on a disc. */ + const clusterBadge = (count) => ({ + svg: `${count}`, + }); + + /** Whether an icon set clusters now. */ + const clusters = (record) => + record.kind === 'icons' && + Boolean(record.spec.cluster) && + capabilities.has('cluster') && + !record.gpu; + + /** Let go of a set's cluster icons, and show its members again. */ + function dropClusters(record) { + const host = record.clusterHost; + if (host && !host.isDestroyed() && live()) scene.primitives.remove(host); + record.clusterHost = null; + record.clusterState = null; + record.clusterKey = null; + for (const placed of record.placed) placed.clustered = false; + } + + const clusterScratch = new Cesium.Cartesian2(); + /** + * Each frame, before it draws: every clustered icon set clusters its + * icons again where the camera moved or the set changed since it last + * did (`ClusterSpec`), hiding the members and drawing an icon a cluster. + */ + function clusterIcons() { + let pose; + const poseNow = () => { + const eye = scene.camera?.positionWC; + const dir = scene.camera?.directionWC; + return `${eye?.x},${eye?.y},${eye?.z},${dir?.x},${dir?.y},${dir?.z},${scene.canvas?.clientWidth},${scene.canvas?.clientHeight}`; + }; + for (const record of sets.values()) { + if (!clusters(record)) { + if (record.clusterHost || record.clusterState) { + dropClusters(record); + for (const placed of record.placed) + placed.primitive.show = shownNow(record, placed); + } + continue; + } + if (!record.billboardHost || record.billboardHost.isDestroyed()) continue; + // A rebuilt collection starts afresh. + if (record.billboardHost !== record.clusteredHost) { + record.clusterState = null; + record.clusterKey = null; + record.clusteredHost = record.billboardHost; + } + pose ??= poseNow(); + if (record.clusterKey === pose) { + if (record.clusterHost) + record.clusterHost.show = record.spec.show !== false; + continue; + } + record.clusterKey = pose; + reclusterIcons(record); + } + } + + function reclusterIcons(record) { + const spec = record.spec.cluster; + const horizon = horizonNow(); + const points = []; + const entries = new Map(); + for (const [id, entry] of record.billboards) { + const item = record.items.get(id); + const placed = entry.placed; + if (!item || !placed.shown) continue; + if (horizon && !horizon.isPointVisible(placed.position)) continue; + const screen = Cesium.SceneTransforms.worldToWindowCoordinates( + scene, + placed.position, + clusterScratch, + ); + if (!screen) continue; + points.push({ + id, + position: placed.position, + screen: { x: screen.x, y: screen.y }, + pixelSize: Math.max(item.size[0], item.size[1]) * (item.scale ?? 1), + }); + entries.set(id, entry); + } + const result = clusterScreenPoints({ + points, + pixelRange: spec.pixelRange, + minimumClusterSize: spec.minimumSize, + viewHeight: scene.canvas?.clientHeight ?? 0, + eyeHeight: scene.camera.positionCartographic?.height ?? 0, + previous: record.clusterState, + project: (position) => { + const p = Cesium.SceneTransforms.worldToWindowCoordinates( + scene, + toCartesian(position), + new Cesium.Cartesian2(), + ); + return p ? { x: p.x, y: p.y } : null; + }, + isOccluded: (position) => + horizon ? !horizon.isPointVisible(toCartesian(position)) : false, + }); + record.clusterState = result.state; + const inCluster = new Set(result.clusters.flatMap((c) => c.ids)); + for (const placed of record.placed) placed.clustered = false; + for (const id of inCluster) { + const entry = entries.get(id); + if (entry) entry.placed.clustered = true; + } + for (const placed of record.placed) { + const show = shownNow(record, placed); + if (placed.primitive.show !== show) placed.primitive.show = show; + } + let host = record.clusterHost; + if (!host || host.isDestroyed()) { + host = new Cesium.BillboardCollection({ + scene, + blendOption: pointBlendOf(record.spec.blend), + }); + record.clusterHost = host; + scene.primitives.add(host); + } + host.removeAll(); + host.show = record.spec.show !== false; + for (const cluster of result.clusters) { + const seed = record.items.get(cluster.ids[0]); + const position = toCartesian(cluster.position); + const given = spec.icon?.(cluster.ids.length); + const image = + given === undefined + ? clusterBadge(cluster.ids.length) + : typeof given?.atlas === 'string' + ? atlases.get(given.atlas)?.[given.slot] + : given; + if (image === undefined) continue; + const scale = seed.scale ?? 1; + const billboard = host.add({ + position, + width: seed.size[0] * scale, + height: seed.size[1] * scale, + disableDepthTestDistance: seed.disableDepthTest ?? 0, + id: { + set: record.spec.id, + id: cluster.ids[0], + get meta() { + return record.items.get(cluster.ids[0])?.meta; + }, + cluster: { + ids: cluster.ids.slice(), + position: { x: position.x, y: position.y, z: position.z }, + }, + }, + }); + if (isKeyed(image)) billboard.setImage(image.key, image.canvas); + else billboard.image = toImage(image); + } + } + /** The horizon from the eye as it is now; null where there is none (2D). */ function horizonNow() { const eye = scene.camera?.positionWC; @@ -882,7 +1063,8 @@ export function createCesiumDraw({ * frame's cull (a frame listener that moves its items). */ function shownNow(record, placed) { - if (!placed.shown || !record.spec.horizonCull) return placed.shown; + if (!placed.shown || placed.clustered) return false; + if (!record.spec.horizonCull) return placed.shown; return horizonNow()?.isPointVisible(placed.position) ?? true; } @@ -4795,6 +4977,7 @@ export function createCesiumDraw({ beforeRender() { pulsing = runPulses(); cullHorizon(); + clusterIcons(); runFlows(); for (const record of sets.values()) if (record.inertialLines || record.inertialPieces?.length) diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 7572a2fd7..c0eac6389 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -7941,3 +7941,89 @@ test('the transit layer draws its vehicles as two icon sets, moving a marker bet assert.equal(hostOf(stillId), undefined); assert.equal(hostOf(movingId), undefined); }); + +test('a clustered icon set draws one icon a cluster in place of its members, made again as the camera moves', () => { + const scene = fakeScene(); + scene.camera.directionWC = new Cesium.Cartesian3(-1, 0, 0); + scene.camera.positionCartographic = { height: 1000 }; + scene.canvas = { clientWidth: 400, clientHeight: 300 }; + // Window positions: a degree of longitude is `spread` pixels. + let spread = 1; + const transforms = Cesium.SceneTransforms; + const project = transforms.worldToWindowCoordinates; + transforms.worldToWindowCoordinates = (_, position, result) => { + const at = Cesium.Cartographic.fromCartesian(position); + result ??= new Cesium.Cartesian2(); + result.x = 200 + Cesium.Math.toDegrees(at.longitude) * spread; + result.y = 150 - Cesium.Math.toDegrees(at.latitude) * spread; + return result; + }; + try { + const part = createCesiumDraw({ + scene, + report: (error) => { + throw error; + }, + capabilities: new Set(['cluster']), + }); + const counts = []; + const set = part.port.icons({ + id: 'clustered', + cluster: { + pixelRange: 10, + minimumSize: 2, + icon: (count) => (counts.push(count), undefined), + }, + }); + const icon = (id, lon) => ({ + id, + pos: { lon, lat: 0 }, + image: { svg: '' }, + size: [8, 8], + meta: { id }, + }); + set.set([icon('a', 0), icon('b', 2), icon('c', 4)]); + part.beforeRender(); + const members = scene.added[0]; + const clusters = scene.added.at(-1); + assert.notEqual( + clusters, + members, + 'cluster icons are a collection of their own', + ); + assert.deepEqual( + [0, 1, 2].map((i) => members.get(i).show), + [false, false, false], + 'members are not drawn', + ); + assert.equal(clusters.length, 1); + assert.deepEqual(counts, [3]); + const { id } = clusters.get(0); + assert.deepEqual([id.set, id.id, id.meta], ['clustered', 'a', { id: 'a' }]); + assert.deepEqual(id.cluster.ids, ['a', 'b', 'c'], 'seed first'); + const mean = Cesium.Cartographic.fromCartesian( + new Cesium.Cartesian3( + id.cluster.position.x, + id.cluster.position.y, + id.cluster.position.z, + ), + ); + assert.ok(Math.abs(Cesium.Math.toDegrees(mean.longitude) - 2) < 1e-6); + // Not made again while nothing moved. + part.beforeRender(); + assert.deepEqual(counts, [3]); + // The camera moved: apart, each is its own. + spread = 100; + scene.camera.positionWC = new Cesium.Cartesian3(2e7, 1, 0); + part.beforeRender(); + assert.equal(clusters.length, 0); + assert.deepEqual( + [0, 1, 2].map((i) => members.get(i).show), + [true, true, true], + ); + set.dispose(); + assert.ok(!scene.added.includes(clusters), 'let go with the set'); + } finally { + transforms.worldToWindowCoordinates = project; + } +}); diff --git a/src/render/cesium/gpuIcons.js b/src/render/cesium/gpuIcons.js index 524c80adb..2f3d1239c 100644 --- a/src/render/cesium/gpuIcons.js +++ b/src/render/cesium/gpuIcons.js @@ -13,7 +13,8 @@ * an item first needs it (or it first takes columns), and stays one. They * refuse loudly what billboards draw and they do not: clamped heights, * `fadeByDistance`, `displayRange`, pixel offsets, anchors other than the - * centre, axis and screen rotations, and opaque and additive blends. Their + * centre, axis and screen rotations, opaque and additive blends, and + * clustering. Their * images (URLs, SVG, blobs, keyed canvases and atlas slots of those) * are rasterised square into the icon atlas every GPU icon set shares, and * refused when it has no room left for them: an SVG at its own size (its @@ -205,6 +206,8 @@ export function createGpuIcons({ throw new Error( `the Cesium renderer's GPU icons have no ${spec.blend} blend`, ); + if (spec.cluster) + throw new Error("the Cesium renderer's GPU icons have no clustering"); // Atlas slots these items would take anew: they must all fit. const fresh = new Set(); for (const item of items) { diff --git a/src/render/cesium/gpuIcons.test.mjs b/src/render/cesium/gpuIcons.test.mjs index a55626644..c319ece88 100644 --- a/src/render/cesium/gpuIcons.test.mjs +++ b/src/render/cesium/gpuIcons.test.mjs @@ -349,6 +349,21 @@ test('GPU icon sets refuse what they cannot draw, changing nothing', () => { assert.equal(billboards.size(), 1); }); +test('GPU icon sets refuse clustering, changing nothing', () => { + const { part, draw } = drawOver(); + const cluster = { pixelRange: 10, minimumSize: 2 }; + const set = draw.icons({ id: 'gpu:cluster' }); + set.set([icon('a', { motion: { kind: 'hold' } })]); + assert.throws(() => set.setOptions({ cluster }), /no clustering/); + assert.equal(part.sets.get('gpu:cluster').spec.cluster, undefined); + const clustered = draw.icons({ id: 'gpu:clustered', cluster }); + assert.throws( + () => clustered.set([icon('a', { motion: { kind: 'hold' } })]), + /no clustering/, + ); + assert.equal(clustered.size(), 0); +}); + test('columns update rows by index: positions, courses, shown, scales, tints and meta', () => { const { part, draw } = drawOver(); const set = draw.icons({ id: 'gpu:columns' }); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 113269565..bdd80ea4d 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -44,6 +44,7 @@ export const CESIUM_CHECKS = new Set([ 'draw.drillPick', 'draw.field.rasterShell', 'draw.field.windStreamlines', + 'draw.icons.cluster', 'draw.icons.distance', 'draw.icons.images', 'draw.icons.update', diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 51d9e6be0..8e5e4ef0a 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -81,6 +81,8 @@ export function cesiumCapabilities(scene, only) { ? ['keepEarthFramed'] : []), ...GPU_ICON_CAPABILITIES, + // Icon sets on billboards cluster on screen (`draw.js`). + 'cluster', 'styles', 'bloom', 'sharpen', diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index 55ce0cfc7..f559fd1f9 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -17,6 +17,7 @@ test('capabilities follow what the scene supports', () => { 'columns', 'motionSegments', 'courseGlide', + 'cluster', 'styles', 'bloom', 'sharpen', diff --git a/src/render/cesium/query.js b/src/render/cesium/query.js index 4005e01d5..f38029e72 100644 --- a/src/render/cesium/query.js +++ b/src/render/cesium/query.js @@ -76,6 +76,30 @@ export function createCesiumQuery({ const hitOf = ({ id }) => drawHitOf({ id }); + /** + * The hits a picked object stands for: its item's, or for a cluster's + * icon, one a member in the cluster's order (seed first), each at the + * cluster's position (`ClusterSpec`); unpickable members left out. + */ + function hitsOf(owner) { + const cluster = owner.id.cluster; + if (!cluster) return pickable(owner) ? [hitOf(owner)] : []; + const { record } = owner; + const hits = []; + for (const id of cluster.ids) { + const item = record.items.get(id); + if (!item || !pickable({ record, item })) continue; + hits.push({ + set: record.spec.id, + id, + ...(item.meta === undefined ? {} : { meta: item.meta }), + surface: false, + position: { ...cluster.position }, + }); + } + return hits; + } + /** A query that throws answers nothing. */ const quietly = (fn) => { try { @@ -147,11 +171,18 @@ export function createCesiumQuery({ if (untilForeign) break; continue; } - const key = `${owner.id.set}\u0000${owner.id.id}`; - if (!pickable(owner) || seen.has(key)) continue; - seen.add(key); - hits.push(hitOf(owner)); - if (limit !== undefined && hits.length >= limit) break; + let full = false; + for (const hit of hitsOf(owner)) { + const key = `${hit.set}\u0000${hit.id}`; + if (seen.has(key)) continue; + seen.add(key); + hits.push(hit); + if (limit !== undefined && hits.length >= limit) { + full = true; + break; + } + } + if (full) break; } return hits; } @@ -313,7 +344,8 @@ export function createCesiumQuery({ const picked = scene.pick(screen(x, y), width, height); rememberPick(scene, x, y, width, height, picked); const owner = ownerOf(picked); - if (owner && pickable(owner)) return hitOf(owner); + const [hit] = owner ? hitsOf(owner) : []; + if (hit) return hit; // Something unpickable is on top: the first pickable item under it, // unless something else hides it. if (owner) { diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index bbf71fcde..2f0ab7ac8 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -1714,6 +1714,111 @@ export function portChecks() { for (const set of sets) set.dispose(); }, ), + check( + 'draw.icons.cluster', + 'icons close on screen draw as one cluster, picked as its members seed first at its position; apart again, each is its own', + async (h, r) => { + await overAustin(h, r, 2000); + const counts = []; + const set = r.draw.icons({ + id: 'conf:cluster', + cluster: { + pixelRange: 20, + minimumSize: 3, + icon: (count) => { + counts.push(count); + return DOT; + }, + }, + }); + const at = (dx, dy) => + h.toEcef({ + lon: AUSTIN.lon + 0.0008 + dx * 0.0003, + lat: AUSTIN.lat + 0.0006 + dy * 0.0003, + height: 0, + }); + const members = [ + ['a', at(0, 0)], + ['b', at(1, 0)], + ['c', at(0, 1)], + ['d', at(1, 1)], + ]; + const far = h.toEcef({ + lon: AUSTIN.lon - 0.003, + lat: AUSTIN.lat - 0.002, + height: 0, + }); + set.set([ + ...members.map(([id, pos]) => ({ + id, + pos, + image: DOT, + size: [16, 16], + meta: { m: id }, + })), + { id: 'far', pos: far, image: DOT, size: [16, 16] }, + ]); + await drawn(h, r); + await settled(r); + await drawn(h, r); + ok(counts.includes(4), 'the icon is drawn for its count'); + const mean = members.reduce( + (m, [, p]) => ({ + x: m.x + p.x / members.length, + y: m.y + p.y / members.length, + z: m.z + p.z / members.length, + }), + { x: 0, y: 0, z: 0 }, + ); + const s = r.query.project(mean); + ok(s, 'the cluster projects'); + const hit = r.query.pick(s.x, s.y); + deepEqual( + [hit?.set, hit?.id, hit?.meta], + ['conf:cluster', 'a', { m: 'a' }], + 'pick gives the seed, with its own meta', + ); + ok(hit?.position, 'at a position'); + nearVec(hit.position, mean, 1, 'the cluster’s position'); + const drilled = r.query + .drillPick(s.x, s.y) + .filter((x) => x.set === 'conf:cluster'); + deepEqual( + drilled.map((x) => [x.id, x.meta?.m]), + members.map(([id]) => [id, id]), + 'drillPick gives every member, seed first', + ); + const sf = r.query.project(far); + equal(r.query.pick(sf.x, sf.y)?.id, 'far', 'an icon on its own'); + + await overAustin(h, r, 300); + r.camera.setView({ + destination: { + lon: AUSTIN.lon + 0.00095, + lat: AUSTIN.lat + 0.00075, + height: 300, + }, + orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 }, + }); + await drawn(h, r); + await settled(r); + await drawn(h, r); + for (const [id, pos] of members) { + const m = r.query.project(pos); + ok(m, `${id} projects`); + deepEqual( + r.query + .drillPick(m.x, m.y) + .filter((x) => x.set === 'conf:cluster') + .map((x) => x.id), + [id], + `${id} on its own once apart`, + ); + } + set.dispose(); + }, + { capability: 'cluster' }, + ), check( 'draw.icons.update', 'an upserted icon keeps drawing, as it now is, from the next frame: picked at its new size with its new meta, even while a new image loads; a removed one is gone', diff --git a/src/render/contract/draw.d.ts b/src/render/contract/draw.d.ts index ba0b62a1a..1f990d6ca 100644 --- a/src/render/contract/draw.d.ts +++ b/src/render/contract/draw.d.ts @@ -30,8 +30,24 @@ export type HeightMode = 'absolute' | 'clampGround' | 'relativeGround'; /** What `clampGround` / `relativeGround` clamp to. */ export type ClampTarget = 'terrain' | 'tiles' | 'both'; +/** + * `cluster`: screen-space clustering of a set's icons. Which icons cluster + * is `clusterScreenPoints` (`src/geo/screenCluster.js`) over the set's shown + * icons in front of the eye and above the horizon, in the set's order, each + * boxed at its drawn size (its larger side, times its `scale`), with + * `pixelRange` and `minimumSize`, and the last pass's clusters kept as it + * keeps them: so the renderer forms exactly these clusters. A cluster draws one + * icon at the cluster's position (the mean of its members') in place of its + * members, which are not drawn: its image is `icon(count)` when given, else + * a default badge showing the count, drawn at its seed's size. A pick on a + * cluster answers one `Hit` per member, in the cluster's order (seed + * first), each with that member's own `set`, `id` and `meta` and the + * cluster's `position`: so `pick` gives the seed and `drillPick` every + * member. Clusters are recomputed in the frames drawn after the camera + * moves or the set changes, never on a timer. + */ export interface ClusterSpec { - /** Screen distance under which icons merge. */ + /** Screen distance under which icons merge, CSS pixels. */ pixelRange: number; /** Fewest icons that form a cluster. */ minimumSize: number; @@ -48,7 +64,7 @@ export interface SetSpec { id: string; /** Hide items beyond the ellipsoid's horizon, for sets drawn without depth test. */ horizonCull?: boolean; - /** `cluster`: screen-space clustering (icons only). */ + /** `cluster`: screen-space clustering (icons only; see `ClusterSpec`). */ cluster?: ClusterSpec | null; blend?: 'opaque' | 'translucent' | 'additive'; /** diff --git a/src/render/stub/index.js b/src/render/stub/index.js index 323221da8..d250c367e 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -11,6 +11,7 @@ */ import { horizonFrom } from '../../geo/horizon.js'; import { alongLength } from '../../geo/polyline.js'; +import { clusterScreenPoints } from '../../geo/screenCluster.js'; import { createInputRouter } from '../input/router.js'; import { cssColor } from '../color.js'; import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js'; @@ -288,6 +289,7 @@ export function createStubRenderer(options = {}) { step('preRender'); runPhase('preRender', t); step('render'); + for (const set of sets.values()) clusterPass(set); rendered += 1; // A frame each timed layer was asked to show is now drawn. for (const [layer, flush] of [...frameFlushes]) @@ -510,9 +512,88 @@ export function createStubRenderer(options = {}) { record.items = next; requestRender('draw'); }; + // A clustered set clusters again in the next frame drawn after a change. + record.version = 0; + for (const name of [ + 'set', + 'upsert', + 'remove', + 'clear', + 'setOptions', + 'setColumns', + ]) { + const call = handle[name]; + if (!call) continue; + handle[name] = (...args) => { + record.version += 1; + return call(...args); + }; + } return handle; } + /** + * `cluster`: a clustered icon set's clusters as the last drawn frame made + * them (`ClusterSpec`), made again where the camera moved or the set + * changed since; null for a set that does not cluster. + */ + function clusterPass(set) { + if ( + set.kind !== 'icons' || + !set.spec.cluster || + !capabilities.has('cluster') + ) { + set.clusters = null; + return; + } + const e = eye(); + const key = [ + set.version, + e.position.x, + e.position.y, + e.position.z, + e.direction.x, + e.direction.y, + e.direction.z, + viewport.width, + viewport.height, + ].join(','); + if (set.clusterKey === key) return; + set.clusterKey = key; + const points = []; + for (const item of set.items.values()) { + if (item.show === false) continue; + const position = itemPosition(set, item); + if (!position || isOccluded(position)) continue; + const screen = project(position); + if (!screen) continue; + const [w = 0, h = 0] = item.size ?? []; + points.push({ + id: item.id, + position, + screen, + pixelSize: Math.max(w, h) * (item.scale ?? 1), + }); + } + const result = clusterScreenPoints({ + points, + pixelRange: set.spec.cluster.pixelRange, + minimumClusterSize: set.spec.cluster.minimumSize, + viewHeight: viewport.height, + eyeHeight: toCartographicRadians(e.position).height, + previous: set.clusters?.state ?? null, + project, + isOccluded, + }); + // Each cluster's icon is asked for, as a renderer drawing it would. + for (const cluster of result.clusters) + set.spec.cluster.icon?.(cluster.ids.length); + set.clusters = { + ...result, + members: new Set(result.clusters.flatMap((c) => c.ids)), + }; + } + function simpleHandle(kind, spec) { const record = { kind, @@ -858,8 +939,40 @@ export function createStubRenderer(options = {}) { set.kind !== 'models' ) continue; + const clustered = set.kind === 'icons' ? set.clusters : null; + // A cluster is picked as its members, seed first, at its position. + for (const cluster of clustered?.clusters ?? []) { + const seed = set.items.get(cluster.ids[0]); + const s = project(cluster.position); + if (!seed || !s) continue; + const [w = 0, h = 0] = seed.size ?? []; + const k = seed.scale ?? 1; + if ( + Math.abs(s.x - x) > (w * k) / 2 + halfW || + Math.abs(s.y - y) > (h * k) / 2 + halfH + ) + continue; + const depth = magnitude(sub(cluster.position, eye().position)); + for (const id of cluster.ids) { + const item = set.items.get(id); + if (!item) continue; + hits.push({ + set: setId, + id, + meta: item.meta, + surface: false, + position: { ...cluster.position }, + depth, + blocked: blockedItem(item), + over: (seed.disableDepthTest ?? 0) > depth, + order: set.spec.drawOrder ?? 0, + seq: set.seq, + }); + } + } for (const item of set.items.values()) { if (item.show === false) continue; + if (clustered?.members.has(item.id)) continue; const p = itemPosition(set, item); if (!p || isOccluded(p)) continue; const distance = magnitude(sub(p, eye().position));