mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Draw the traffic heat-lines through the draw port, batching alike draped glow lines in the Cesium draw port
This commit is contained in:
1 parent
bbd6049e21
commit
5715bf9df3
11 files changed
+608
-193
No files matched your search
@@ -2352,6 +2352,7 @@
|
||||
"src/layers/traffic/policy.js",
|
||||
"src/render/color.js",
|
||||
"src/layers/traffic/rendering.js",
|
||||
"src/render/cesium/surfaceState.js",
|
||||
"src/layers/traffic/retention.js",
|
||||
"src/layers/traffic/source.js",
|
||||
"src/layers/traffic/state.js",
|
||||
@@ -3589,6 +3590,7 @@
|
||||
"src/layers/traffic/model.js",
|
||||
"src/layers/traffic/policy.js",
|
||||
"src/layers/traffic/rendering.js",
|
||||
"src/render/cesium/surfaceState.js",
|
||||
"src/layers/traffic/retention.js",
|
||||
"src/layers/traffic/source.js",
|
||||
"src/layers/traffic/state.js",
|
||||
@@ -4547,6 +4549,7 @@
|
||||
"src/layers/traffic/model.js",
|
||||
"src/layers/traffic/policy.js",
|
||||
"src/layers/traffic/rendering.js",
|
||||
"src/render/cesium/surfaceState.js",
|
||||
"src/layers/traffic/retention.js",
|
||||
"src/layers/traffic/source.js",
|
||||
"src/layers/traffic/state.js",
|
||||
|
||||
@@ -257,9 +257,10 @@ test('traffic timing pairs real ordering to the scheduling change and guards re-
|
||||
return { west: degrees(r.west), south: degrees(r.south), east: degrees(r.east), north: degrees(r.north) };
|
||||
},
|
||||
},
|
||||
// The dots' draw set: timing reads none of what it draws.
|
||||
// The dots' and heat-lines' draw sets: timing reads none of what they draw.
|
||||
draw: {
|
||||
points: () => ({ show: false, upsert() {}, remove() {}, clear() {}, dispose() {} }),
|
||||
lines: () => ({ show: true, set() {}, upsert() {}, clear() {}, dispose() {} }),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import {
|
||||
HEAT_JAM_BASE_ALPHA,
|
||||
HEAT_JAM_COLOR,
|
||||
HEAT_JAM_PULSE_ALPHA,
|
||||
HEAT_LINE_CAP,
|
||||
HEAT_LINE_JAM_WIDTH,
|
||||
HEAT_LINE_SLOW_WIDTH,
|
||||
HEAT_SLOW_COLOR,
|
||||
} from './policy.js';
|
||||
|
||||
/** A road of `length` metres along x, in the flow bucket `level` gives. */
|
||||
const road = (level, length = 100, x = 0) => ({
|
||||
flow: { level },
|
||||
segmentDist: [length],
|
||||
waypoints: [
|
||||
{ x, y: 6378137, z: 0 },
|
||||
{ x: x + length, y: 6378137, z: 0 },
|
||||
],
|
||||
});
|
||||
|
||||
function setup({
|
||||
live = true,
|
||||
heatline = true,
|
||||
preset = 'normal',
|
||||
supported = true,
|
||||
} = {}) {
|
||||
const draw = fakeDrawPort();
|
||||
const demand = [];
|
||||
const state = {
|
||||
_viewer: {},
|
||||
_liveMode: live,
|
||||
_presetDots: 'on',
|
||||
_stylePreset: preset,
|
||||
_heatJam: [],
|
||||
_heatLineCount: 0,
|
||||
_heatSupported: supported,
|
||||
_heatSet: draw.lines({ id: 'traffic:1:heat', clampTo: 'tiles' }),
|
||||
};
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: {},
|
||||
parts: {
|
||||
style: { heatlineOn: () => heatline },
|
||||
animation: { syncRenderDemand: () => demand.push(state._heatLineCount) },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
const items = () => [...draw.set('traffic:1:heat').items.values()];
|
||||
return {
|
||||
state,
|
||||
rendering,
|
||||
items,
|
||||
demand,
|
||||
record: draw.set('traffic:1:heat'),
|
||||
};
|
||||
}
|
||||
|
||||
test('congested roads drape heat-lines on the tiles: jam glowing, slow flat', () => {
|
||||
const { state, rendering, items, demand } = setup();
|
||||
rendering.rebuildHeatLines([
|
||||
road(0.9), // free: none
|
||||
road(0.2, 50, 1), // jam
|
||||
road(0.6, 80, 2), // slow
|
||||
{ ...road(0.2), flow: { level: 0.2, closure: true } }, // closed: none
|
||||
]);
|
||||
const lines = items();
|
||||
assert.equal(lines.length, 2);
|
||||
const [jam, slow] = lines;
|
||||
assert.equal(jam.mode, 'draped');
|
||||
assert.equal(jam.clampTo, 'tiles');
|
||||
assert.equal(jam.widthPx, HEAT_LINE_JAM_WIDTH);
|
||||
assert.deepEqual(jam.style, {
|
||||
kind: 'glow',
|
||||
color: [...HEAT_JAM_COLOR.slice(0, 3), HEAT_JAM_BASE_ALPHA],
|
||||
power: 0.25,
|
||||
});
|
||||
assert.deepEqual(jam.positions, [
|
||||
{ x: 1, y: 6378137, z: 0 },
|
||||
{ x: 51, y: 6378137, z: 0 },
|
||||
]);
|
||||
assert.equal(slow.widthPx, HEAT_LINE_SLOW_WIDTH);
|
||||
assert.deepEqual(slow.style, { kind: 'solid', color: HEAT_SLOW_COLOR });
|
||||
assert.equal(state._heatLineCount, 2);
|
||||
assert.equal(rendering.heatPulsing(), true);
|
||||
assert.deepEqual(demand, [2]);
|
||||
});
|
||||
|
||||
test('the jam heat-lines pulse together, recoloured where they are', () => {
|
||||
const { rendering, items, record } = setup();
|
||||
rendering.rebuildHeatLines([road(0.2), road(0.25, 50), road(0.6)]);
|
||||
const writes = record.writes;
|
||||
rendering.pulseHeatLines(260 * (Math.PI / 2));
|
||||
assert.equal(record.writes, writes + 1, 'one upsert a frame');
|
||||
const alpha = HEAT_JAM_BASE_ALPHA + HEAT_JAM_PULSE_ALPHA;
|
||||
const [a, b, slow] = items();
|
||||
assert.ok(Math.abs(a.style.color[3] - alpha) < 1e-12);
|
||||
assert.equal(b.style, a.style);
|
||||
assert.equal(slow.style.kind, 'solid', 'slow lines do not pulse');
|
||||
});
|
||||
|
||||
test('heat-lines are capped jam first, longest first', () => {
|
||||
const { items } = (() => {
|
||||
const s = setup();
|
||||
const roads = [];
|
||||
for (let i = 0; i < HEAT_LINE_CAP; i++) roads.push(road(0.6, 10 + i));
|
||||
roads.push(road(0.2, 5));
|
||||
s.rendering.rebuildHeatLines(roads);
|
||||
return s;
|
||||
})();
|
||||
const lines = items();
|
||||
assert.equal(lines.length, HEAT_LINE_CAP);
|
||||
assert.equal(lines[0].style.kind, 'glow', 'the jam line kept first');
|
||||
assert.equal(lines[1].widthPx, HEAT_LINE_SLOW_WIDTH);
|
||||
assert.equal(lines[1].positions[1].x, 10 + HEAT_LINE_CAP - 1);
|
||||
});
|
||||
|
||||
test('mono presets draw heat-lines in luminance', () => {
|
||||
const { rendering, items } = setup({ preset: 'surveillance' });
|
||||
rendering.rebuildHeatLines([road(0.2), road(0.6)]);
|
||||
const [jam, slow] = items();
|
||||
assert.deepEqual(jam.style.color, [1, 1, 1, HEAT_JAM_BASE_ALPHA]);
|
||||
assert.deepEqual(slow.style.color, [0.7, 0.7, 0.7, HEAT_SLOW_COLOR[3]]);
|
||||
});
|
||||
|
||||
test('no heat-lines in simulation or with the mode off, and removal empties the set', () => {
|
||||
for (const options of [{ live: false }, { heatline: false }]) {
|
||||
const { rendering, items, record } = setup(options);
|
||||
rendering.rebuildHeatLines([road(0.2)]);
|
||||
assert.equal(items().length, 0);
|
||||
assert.equal(record.writes, 0, 'an empty set is left alone');
|
||||
assert.equal(rendering.heatPulsing(), false);
|
||||
}
|
||||
const { state, rendering, items } = setup();
|
||||
rendering.rebuildHeatLines([road(0.2)]);
|
||||
rendering.removeHeatLines();
|
||||
assert.equal(items().length, 0);
|
||||
assert.equal(state._heatLineCount, 0);
|
||||
assert.equal(rendering.heatPulsing(), false);
|
||||
rendering.pulseHeatLines(0);
|
||||
assert.equal(items().length, 0, 'nothing to pulse');
|
||||
});
|
||||
|
||||
test('where lines cannot drape, no heat-lines are drawn and that is said once', (t) => {
|
||||
const warn = t.mock.method(console, 'warn', () => {});
|
||||
const { state, rendering, items } = setup({ supported: null });
|
||||
state._viewer = { scene: {} };
|
||||
rendering.rebuildHeatLines([road(0.2)]);
|
||||
rendering.rebuildHeatLines([road(0.2)]);
|
||||
assert.equal(items().length, 0);
|
||||
assert.equal(state._heatSupported, false);
|
||||
assert.equal(warn.mock.callCount(), 1);
|
||||
assert.equal(rendering.heatPulsing(), false);
|
||||
});
|
||||
@@ -24,19 +24,30 @@ export function createLifecycle({
|
||||
|
||||
const methods = {
|
||||
/**
|
||||
* One-time initialisation. Makes the dots' draw set (hidden); it is
|
||||
* shown and hidden with the layer, and let go on destroy.
|
||||
* One-time initialisation. Makes the dots' draw set (hidden; it is
|
||||
* shown and hidden with the layer) and the heat-lines' (emptied when
|
||||
* the layer is disabled); both are let go on destroy.
|
||||
*
|
||||
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
|
||||
*/
|
||||
init(viewer) {
|
||||
layerState._viewer = viewer;
|
||||
layerState._dotSet?.dispose();
|
||||
layerState._dotSet = drawOf(viewer).points({
|
||||
id: `traffic:${++instances}:dots`,
|
||||
layerState._heatSet?.dispose();
|
||||
const instance = ++instances;
|
||||
const draw = drawOf(viewer);
|
||||
layerState._dotSet = draw.points({
|
||||
id: `traffic:${instance}:dots`,
|
||||
blend: 'translucent',
|
||||
show: false,
|
||||
});
|
||||
// Draped on the 3D tiles only, as the dots' roads are sampled there.
|
||||
layerState._heatSet = draw.lines({
|
||||
id: `traffic:${instance}:heat`,
|
||||
clampTo: 'tiles',
|
||||
});
|
||||
layerState._heatJam = [];
|
||||
layerState._heatLineCount = 0;
|
||||
layerState._dots = [];
|
||||
layerState._roads = [];
|
||||
layerState._count = 0;
|
||||
@@ -194,16 +205,18 @@ export function createLifecycle({
|
||||
},
|
||||
|
||||
/**
|
||||
* Permanently tear down the layer. Disables it, lets the dots' draw set
|
||||
* go, and clears the tile cache.
|
||||
* Permanently tear down the layer. Disables it, lets the dots' and
|
||||
* heat-lines' draw sets go, and clears the tile cache.
|
||||
*
|
||||
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
|
||||
*/
|
||||
destroy(viewer) {
|
||||
this.disable(viewer);
|
||||
parts.rendering.removeHeatLines();
|
||||
layerState._dotSet?.dispose();
|
||||
layerState._dotSet = null;
|
||||
parts.rendering.removeHeatLines();
|
||||
layerState._heatSet?.dispose();
|
||||
layerState._heatSet = null;
|
||||
layerState._tileCache.clear();
|
||||
resetFlowTileCache();
|
||||
layerState._count = 0;
|
||||
|
||||
@@ -591,7 +591,7 @@ test('a closure that empties the population mid-correction settles heights and c
|
||||
corrected[0].flow = { level: 0, closure: true };
|
||||
for (let i = 0; i < 20 && h.state._dots.length; i++) h.frame();
|
||||
assert.equal(h.state._dots.length, 0);
|
||||
assert.equal(h.state._heatJamPrim, null);
|
||||
assert.equal(h.state._heatLineCount, 0);
|
||||
assert.equal(h.state._renderHeld, false);
|
||||
assert.equal(h.state._heightPending, false);
|
||||
assert.equal(h.state._populationPending, false);
|
||||
|
||||
@@ -16,9 +16,9 @@ test('traffic render demand follows animated population and jam lines across emp
|
||||
parts: {
|
||||
retention: { clear() {} },
|
||||
rendering: {
|
||||
heatPulsing: () => Boolean(state._heatJamPrim),
|
||||
heatPulsing: () => Boolean(state._heatJam?.length),
|
||||
removeHeatLines() {
|
||||
state._heatJamPrim = null;
|
||||
state._heatJam = [];
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -31,7 +31,7 @@ test('traffic render demand follows animated population and jam lines across emp
|
||||
assert.deepEqual(calls, [['hold', 'traffic']]);
|
||||
animation.clearDots();
|
||||
assert.deepEqual(calls.at(-1), ['release', 'traffic']);
|
||||
state._heatJamPrim = {};
|
||||
state._heatJam = [{}];
|
||||
animation.syncRenderDemand();
|
||||
assert.deepEqual(calls.at(-1), ['hold', 'traffic']);
|
||||
state._enabled = false;
|
||||
|
||||
+73
-167
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { flowBucket } from '../../data/trafficFlowStyle.js';
|
||||
import { trafficStyleProfile } from '../../data/trafficPresetStyle.js';
|
||||
import {
|
||||
@@ -11,83 +10,17 @@ import {
|
||||
HEAT_LINE_SLOW_WIDTH,
|
||||
TRAFFIC_TIMING_ENABLED,
|
||||
} from './policy.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { findCamera } from '../../render/rendererOf.js';
|
||||
// What the dots' surface is, and whether it has loaded, the renderer
|
||||
// contract cannot say: the Cesium adapter reads it off the scene.
|
||||
import {
|
||||
drapesLines,
|
||||
surfaceTilesReady,
|
||||
surfaceKey as trafficSurfaceKey,
|
||||
} from '../../render/cesium/surfaceState.js';
|
||||
|
||||
/**
|
||||
* Whether the surface the dots sit on has loaded what is in view: the
|
||||
* globe's tiles while it is shown, otherwise every shown 3D tileset (and
|
||||
* there is one). The globe port's settle states cannot say whether any
|
||||
* tileset is drawn at all, so this reads the scene.
|
||||
* @param {object|undefined} viewer
|
||||
*/
|
||||
export function surfaceTilesReady(viewer) {
|
||||
const scene = viewer?.scene;
|
||||
if (!scene) return false;
|
||||
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
|
||||
let found = false;
|
||||
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
|
||||
const primitive = scene.primitives.get(i);
|
||||
if (!primitive.show || typeof primitive.tilesLoaded !== 'boolean') continue;
|
||||
found = true;
|
||||
if (!primitive.tilesLoaded) return false;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// Stable ids for the objects heights are sampled from (tilesets, terrain).
|
||||
const surfaceIds = new WeakMap();
|
||||
let nextSurfaceId = 1;
|
||||
const surfaceId = (object) => {
|
||||
if (!object || typeof object !== 'object') return 0;
|
||||
if (!surfaceIds.has(object)) surfaceIds.set(object, nextSurfaceId++);
|
||||
return surfaceIds.get(object);
|
||||
};
|
||||
|
||||
/**
|
||||
* Name what heights are sampled against: the terrain provider when the globe
|
||||
* is shown, otherwise the set of visible 3D tilesets. A map-provider switch
|
||||
* changes it and invalidates every cached height. The renderer contract
|
||||
* names no surface identity, so this reads the scene.
|
||||
* @param {object|undefined} viewer
|
||||
*/
|
||||
const surfaceKeys = new WeakMap();
|
||||
export function trafficSurfaceKey(viewer) {
|
||||
const scene = viewer?.scene;
|
||||
if (!scene) return '';
|
||||
let state = surfaceKeys.get(scene);
|
||||
if (!state) {
|
||||
state = { globe: null, terrain: null, tiles: [], key: '' };
|
||||
surfaceKeys.set(scene, state);
|
||||
}
|
||||
const globe = Boolean(scene.globe?.show);
|
||||
const terrain = globe ? scene.globe.terrainProvider : null;
|
||||
let changed = state.globe !== globe || state.terrain !== terrain;
|
||||
let count = 0;
|
||||
if (!globe) {
|
||||
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
|
||||
const primitive = scene.primitives.get(i);
|
||||
if (!primitive?.show || typeof primitive.tilesLoaded !== 'boolean')
|
||||
continue;
|
||||
if (state.tiles[count] !== primitive) {
|
||||
state.tiles[count] = primitive;
|
||||
changed = true;
|
||||
}
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count !== state.tiles.length) {
|
||||
state.tiles.length = count;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
state.globe = globe;
|
||||
state.terrain = terrain;
|
||||
// Allocate only when the actual map surface changes, never per frame.
|
||||
state.key = globe
|
||||
? `globe:${surfaceId(terrain)}`
|
||||
: `tiles:${state.tiles.map(surfaceId).join(',')}`;
|
||||
}
|
||||
return state.key;
|
||||
}
|
||||
export { surfaceTilesReady, trafficSurfaceKey };
|
||||
|
||||
export function createRendering({
|
||||
state: layerState,
|
||||
@@ -112,21 +45,11 @@ export function createRendering({
|
||||
: roads;
|
||||
}
|
||||
|
||||
/** Remove both heat-line ground primitives from the scene. */
|
||||
/** Take every heat-line down. */
|
||||
|
||||
function removeHeatLines() {
|
||||
if (layerState._heatJamPrim) {
|
||||
layerState._viewer?.scene.groundPrimitives.remove(
|
||||
layerState._heatJamPrim,
|
||||
);
|
||||
layerState._heatJamPrim = null;
|
||||
}
|
||||
if (layerState._heatSlowPrim) {
|
||||
layerState._viewer?.scene.groundPrimitives.remove(
|
||||
layerState._heatSlowPrim,
|
||||
);
|
||||
layerState._heatSlowPrim = null;
|
||||
}
|
||||
if (layerState._heatLineCount) layerState._heatSet?.clear();
|
||||
layerState._heatJam = [];
|
||||
layerState._heatLineCount = 0;
|
||||
parts.animation.syncRenderDemand?.();
|
||||
}
|
||||
@@ -135,32 +58,35 @@ export function createRendering({
|
||||
* Rebuild the congestion heat-line underlay (jam-viz heatline prototype):
|
||||
* slow/jam roads drape a corridor line onto the rendered 3D tiles — glowing
|
||||
* pulsing red for jam, faint flat amber for slow — with the dots animating
|
||||
* on top. Two batched GroundPolylinePrimitives (one per bucket) so the jam
|
||||
* batch pulses through one shared material. Capped at HEAT_LINE_CAP (jam
|
||||
* first, longest first); overflow is logged. No-op in sim mode, when the
|
||||
* heatline mode is off, or without ground-primitive support.
|
||||
* on top. Lines of the layer's heat-line draw set, draped on the tiles;
|
||||
* the jam lines pulse together (`pulseHeatLines`). Capped at
|
||||
* HEAT_LINE_CAP (jam first, longest first); overflow is logged. No-op in
|
||||
* sim mode, when the heatline mode is off, or where lines cannot drape.
|
||||
*
|
||||
* @param {Array} roads - Road objects visible in the current render.
|
||||
*/
|
||||
|
||||
function rebuildHeatLines(roads) {
|
||||
removeHeatLines();
|
||||
if (
|
||||
!layerState._viewer ||
|
||||
!layerState._heatSet ||
|
||||
!layerState._liveMode ||
|
||||
!parts.style.heatlineOn()
|
||||
)
|
||||
) {
|
||||
removeHeatLines();
|
||||
return;
|
||||
}
|
||||
if (layerState._heatSupported === null) {
|
||||
layerState._heatSupported = Cesium.GroundPolylinePrimitive.isSupported(
|
||||
layerState._viewer.scene,
|
||||
);
|
||||
layerState._heatSupported = drapesLines(layerState._viewer);
|
||||
if (!layerState._heatSupported)
|
||||
console.warn(
|
||||
'[Data:Traffic] GroundPolylinePrimitive unsupported — heat-lines disabled',
|
||||
'[Data:Traffic] Draped lines unsupported — heat-lines disabled',
|
||||
);
|
||||
}
|
||||
if (!layerState._heatSupported) return;
|
||||
if (!layerState._heatSupported) {
|
||||
removeHeatLines();
|
||||
return;
|
||||
}
|
||||
|
||||
const candidates = [];
|
||||
for (const road of roads) {
|
||||
@@ -177,63 +103,37 @@ export function createRendering({
|
||||
);
|
||||
const kept = candidates.slice(0, HEAT_LINE_CAP);
|
||||
|
||||
const instancesFor = (bucket, width) =>
|
||||
kept
|
||||
.filter((c) => c.bucket === bucket)
|
||||
.map(
|
||||
(c) =>
|
||||
new Cesium.GeometryInstance({
|
||||
geometry: new Cesium.GroundPolylineGeometry({
|
||||
// A snapshot of the waypoints, as the renderer's points.
|
||||
positions: c.road.waypoints.map((p) =>
|
||||
Cesium.Cartesian3.clone(p),
|
||||
),
|
||||
width,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
// Mono presets (NVG/FLIR/noir) discard hue — heat-lines re-encode in
|
||||
// luminance like the dots: jam = white glow, slow = faint gray.
|
||||
const monoHeat =
|
||||
layerState._presetDots === 'on' &&
|
||||
trafficStyleProfile(layerState._stylePreset) === 'mono';
|
||||
const jamLineColor = monoHeat
|
||||
? Cesium.Color.WHITE
|
||||
: new Cesium.Color(...HEAT_JAM_COLOR);
|
||||
const slowLineColor = monoHeat
|
||||
? new Cesium.Color(0.7, 0.7, 0.7, HEAT_SLOW_COLOR[3])
|
||||
: new Cesium.Color(...HEAT_SLOW_COLOR);
|
||||
layerState._heatJamRgb = monoHeat ? [1, 1, 1] : HEAT_JAM_COLOR.slice(0, 3);
|
||||
const jamStyle = jamLineStyle(HEAT_JAM_BASE_ALPHA);
|
||||
const slowStyle = {
|
||||
kind: 'solid',
|
||||
color: monoHeat ? [0.7, 0.7, 0.7, HEAT_SLOW_COLOR[3]] : HEAT_SLOW_COLOR,
|
||||
};
|
||||
|
||||
const jamInstances = instancesFor('jam', HEAT_LINE_JAM_WIDTH);
|
||||
if (jamInstances.length) {
|
||||
layerState._heatJamPrim = layerState._viewer.scene.groundPrimitives.add(
|
||||
new Cesium.GroundPolylinePrimitive({
|
||||
geometryInstances: jamInstances,
|
||||
classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
|
||||
appearance: new Cesium.PolylineMaterialAppearance({
|
||||
material: Cesium.Material.fromType('PolylineGlow', {
|
||||
color: jamLineColor.withAlpha(HEAT_JAM_BASE_ALPHA),
|
||||
glowPower: 0.25,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
const slowInstances = instancesFor('slow', HEAT_LINE_SLOW_WIDTH);
|
||||
if (slowInstances.length) {
|
||||
layerState._heatSlowPrim = layerState._viewer.scene.groundPrimitives.add(
|
||||
new Cesium.GroundPolylinePrimitive({
|
||||
geometryInstances: slowInstances,
|
||||
classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
|
||||
appearance: new Cesium.PolylineMaterialAppearance({
|
||||
material: Cesium.Material.fromType('Color', {
|
||||
color: slowLineColor,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const items = [];
|
||||
const jam = [];
|
||||
for (let i = 0; i < kept.length; i++) {
|
||||
const { road, bucket } = kept[i];
|
||||
const item = {
|
||||
id: `heat:${i}`,
|
||||
// A snapshot of the waypoints, as the renderer's points.
|
||||
positions: road.waypoints.map((p) => ({ x: p.x, y: p.y, z: p.z })),
|
||||
widthPx: bucket === 'jam' ? HEAT_LINE_JAM_WIDTH : HEAT_LINE_SLOW_WIDTH,
|
||||
mode: 'draped',
|
||||
clampTo: 'tiles',
|
||||
style: bucket === 'jam' ? jamStyle : slowStyle,
|
||||
};
|
||||
items.push(item);
|
||||
if (bucket === 'jam') jam.push(item);
|
||||
}
|
||||
if (items.length || layerState._heatLineCount)
|
||||
layerState._heatSet.set(items);
|
||||
layerState._heatJam = jam;
|
||||
|
||||
layerState._heatLineCount = kept.length;
|
||||
parts.animation.syncRenderDemand?.();
|
||||
@@ -244,19 +144,29 @@ export function createRendering({
|
||||
}
|
||||
}
|
||||
|
||||
/** The jam heat-lines' glow at `alpha`. */
|
||||
const jamLineStyle = (alpha) => ({
|
||||
kind: 'glow',
|
||||
color: [...layerState._heatJamRgb, alpha],
|
||||
power: 0.25,
|
||||
});
|
||||
|
||||
/** Whether jam heat-lines are drawn, which pulse every frame. */
|
||||
const heatPulsing = () => Boolean(layerState._heatJamPrim);
|
||||
const heatPulsing = () => Boolean(layerState._heatJam?.length);
|
||||
|
||||
/**
|
||||
* Throb the jam heat-lines (~1.6 s period): one shared material uniform
|
||||
* for the whole jam batch, no geometry rebuild.
|
||||
* Throb the jam heat-lines (~1.6 s period): one colour for them all,
|
||||
* each line recoloured where it is, no geometry rebuilt.
|
||||
* @param {number} now - Epoch ms.
|
||||
*/
|
||||
function pulseHeatLines(now) {
|
||||
if (layerState._heatJamPrim?.appearance) {
|
||||
layerState._heatJamPrim.appearance.material.uniforms.color.alpha =
|
||||
HEAT_JAM_BASE_ALPHA + HEAT_JAM_PULSE_ALPHA * Math.sin(now / 260);
|
||||
}
|
||||
const jam = layerState._heatJam;
|
||||
if (!jam?.length || !layerState._heatSet) return;
|
||||
const style = jamLineStyle(
|
||||
HEAT_JAM_BASE_ALPHA + HEAT_JAM_PULSE_ALPHA * Math.sin(now / 260),
|
||||
);
|
||||
for (const item of jam) item.style = style;
|
||||
layerState._heatSet.upsert(jam);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -300,7 +210,10 @@ export function createRendering({
|
||||
// nadir view: oblique pitches put the loaded roads many km away even at
|
||||
// low altitude. Probe three roads and stretch the curves accordingly.
|
||||
let areaDist = altitude;
|
||||
if (layerState._viewer && filteredRoads.length) {
|
||||
const eye = filteredRoads.length
|
||||
? findCamera(layerState._viewer)?.pose()?.position
|
||||
: null;
|
||||
if (eye) {
|
||||
const probes = [
|
||||
filteredRoads[0],
|
||||
filteredRoads[Math.floor(filteredRoads.length / 2)],
|
||||
@@ -308,14 +221,7 @@ export function createRendering({
|
||||
];
|
||||
for (const probe of probes) {
|
||||
const wp = probe?.waypoints?.[0];
|
||||
if (wp)
|
||||
areaDist = Math.max(
|
||||
areaDist,
|
||||
Cesium.Cartesian3.distance(
|
||||
layerState._viewer.camera.positionWC,
|
||||
wp,
|
||||
),
|
||||
);
|
||||
if (wp) areaDist = Math.max(areaDist, distance(eye, wp));
|
||||
}
|
||||
}
|
||||
layerState._fadeScaleFar = Math.max(8000, areaDist * 1.5);
|
||||
|
||||
@@ -167,24 +167,26 @@ export function createState({ services }) {
|
||||
layerState._jamViz = 'density';
|
||||
|
||||
/**
|
||||
* Congestion heat-lines are GroundPolylinePrimitive batches draped onto the
|
||||
* rendered 3D tiles (ClassificationType.CESIUM_3D_TILE). One
|
||||
* primitive per bucket so the jam batch can pulse via a single shared
|
||||
* material uniform.
|
||||
* Congestion heat-lines: a lines draw set draped onto the rendered 3D
|
||||
* tiles, made at init.
|
||||
* @type {object|null}
|
||||
*/
|
||||
|
||||
layerState._heatJamPrim = null;
|
||||
layerState._heatSet = null;
|
||||
|
||||
/** @type {object|null} Slow-bucket heat-line batch. */
|
||||
/** @type {Array} The jam heat-line items, recoloured as they pulse. */
|
||||
|
||||
layerState._heatSlowPrim = null;
|
||||
layerState._heatJam = [];
|
||||
|
||||
/** @type {number[]} The jam heat-lines' colour, without its alpha. */
|
||||
|
||||
layerState._heatJamRgb = [1, 1, 1];
|
||||
|
||||
/** @type {number} Heat-lines in the current render (stats). */
|
||||
|
||||
layerState._heatLineCount = 0;
|
||||
|
||||
/** @type {boolean|null} GroundPolylinePrimitive.isSupported, checked once. */
|
||||
/** @type {boolean|null} Whether lines can drape here, checked once. */
|
||||
|
||||
layerState._heatSupported = null;
|
||||
|
||||
|
||||
+115
-6
@@ -1612,6 +1612,9 @@ export function createCesiumDraw({
|
||||
);
|
||||
const polylines = new Cesium.PolylineCollection();
|
||||
const draped = new Map();
|
||||
// Draped glow lines that look alike: one ground primitive and one
|
||||
// material for them all, so they recolour together in place.
|
||||
const glows = new Map();
|
||||
// Draped lines a batch cannot draw, each with a primitive of its own.
|
||||
const alone = [];
|
||||
// Each line as drawn, for upserts that change it in place.
|
||||
@@ -1652,6 +1655,11 @@ export function createCesiumDraw({
|
||||
draped.get(clampTo).push(...instances);
|
||||
continue;
|
||||
}
|
||||
if (item.style.kind === 'glow' && !revealed(item)) {
|
||||
if (!glows.has(part.look)) glows.set(part.look, []);
|
||||
glows.get(part.look).push({ item, part });
|
||||
continue;
|
||||
}
|
||||
if (!batchable(item)) {
|
||||
alone.push({ item, part });
|
||||
continue;
|
||||
@@ -1693,7 +1701,7 @@ export function createCesiumDraw({
|
||||
own.add(deep);
|
||||
}
|
||||
record.deepLines = deep;
|
||||
if (!draped.size && !alone.length) {
|
||||
if (!draped.size && !glows.size && !alone.length) {
|
||||
noteFlows(record);
|
||||
return replaceHost(record, own);
|
||||
}
|
||||
@@ -1714,6 +1722,26 @@ export function createCesiumDraw({
|
||||
part.ground = byClamp.get(part.clampTo);
|
||||
part.batch = part.ground;
|
||||
}
|
||||
for (const lines of glows.values()) {
|
||||
const [{ item, part: first }] = lines;
|
||||
const material = lineMaterial(record, item.style);
|
||||
const primitive = new Cesium.GroundPolylinePrimitive({
|
||||
geometryInstances: lines.map(({ item, part }) =>
|
||||
drapedInstance(item, part, false),
|
||||
),
|
||||
appearance: new Cesium.PolylineMaterialAppearance({ material }),
|
||||
classificationType: classificationOf(first.clampTo),
|
||||
allowPicking: record.spec.pickable !== false,
|
||||
});
|
||||
// A batch as the solid ones are: a line moved leaves it, hidden.
|
||||
for (const { part } of lines) {
|
||||
part.ground = primitive;
|
||||
part.batch = primitive;
|
||||
part.material = material;
|
||||
part.shared = true;
|
||||
}
|
||||
ground.push(primitive);
|
||||
}
|
||||
for (const { item, part } of alone) {
|
||||
part.ground = drapedPrimitive(record, item, part, false);
|
||||
ground.push(part.ground);
|
||||
@@ -1744,6 +1772,48 @@ export function createCesiumDraw({
|
||||
item.frame,
|
||||
]);
|
||||
|
||||
/**
|
||||
* Whether two lines have the same `lineLook` by the identity of what it
|
||||
* is drawn from, read without stringifying either.
|
||||
*/
|
||||
const sameLookFrom = (a, b) =>
|
||||
a.mode === b.mode &&
|
||||
Object.is(a.widthPx, b.widthPx) &&
|
||||
a.clampTo === b.clampTo &&
|
||||
a.style === b.style &&
|
||||
a.depthFailColor === b.depthFailColor &&
|
||||
(a.segmentColors != null) === (b.segmentColors != null) &&
|
||||
(a.segmentShow != null) === (b.segmentShow != null) &&
|
||||
revealed(a) === revealed(b) &&
|
||||
a.frame === b.frame;
|
||||
|
||||
/**
|
||||
* `lineLook`, kept for the last item asked for: within one upsert, lines
|
||||
* sent with one style object (lines pulsing together) are stringified
|
||||
* once. Not across upserts, where a caller may have changed the style
|
||||
* object it sends again.
|
||||
*/
|
||||
function lineLooks() {
|
||||
let last = null;
|
||||
let look = '';
|
||||
let shape = '';
|
||||
return {
|
||||
look(item) {
|
||||
if (!last || !sameLookFrom(last, item)) {
|
||||
last = item;
|
||||
look = lineLook(item);
|
||||
shape = '';
|
||||
}
|
||||
return look;
|
||||
},
|
||||
shape(item) {
|
||||
this.look(item);
|
||||
shape ||= lineLook(item, true);
|
||||
return shape;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A line's positions as one flat array of numbers, to compare. */
|
||||
function flatPositions(positions) {
|
||||
if (positions instanceof Float64Array) return Array.from(positions);
|
||||
@@ -1797,10 +1867,40 @@ export function createCesiumDraw({
|
||||
* nor revealed or in segments) changes only its colour: its material
|
||||
* takes the new one in place.
|
||||
*/
|
||||
const recolourable = (was, item) =>
|
||||
const recolourable = (was, item, looks) =>
|
||||
Boolean(was.clampTo && was.material && !was.segments) &&
|
||||
!revealed(item) &&
|
||||
was.shape === lineLook(item, true);
|
||||
was.shape === (looks ? looks.shape(item) : lineLook(item, true));
|
||||
|
||||
/**
|
||||
* The colours the glow lines sharing a material that `list` recolours
|
||||
* are given together: each such material and the item whose colour it
|
||||
* takes, when every line it draws ends the upsert with one look (its
|
||||
* last in `list`); null when they would not, as the material draws them
|
||||
* all. Lines that move then draw on a material of their own.
|
||||
*/
|
||||
function sharedRecolours(parts, list, looks) {
|
||||
const recolours = new Map();
|
||||
// Each shared line's last look in `list`, and the item it is from.
|
||||
let final = null;
|
||||
for (let k = 0; k < list.length; k++) {
|
||||
const was = parts.get(list[k].id);
|
||||
if (was.shared && !was.solo) (final ??= new Map()).set(list[k].id, k);
|
||||
}
|
||||
if (!final) return recolours;
|
||||
const lookOf = new Map();
|
||||
for (const [id, k] of final) {
|
||||
const was = parts.get(id);
|
||||
if (looks[k] === was.look) continue;
|
||||
recolours.set(was.material, list[k]);
|
||||
lookOf.set(was.material, looks[k]);
|
||||
}
|
||||
for (const [id, part] of parts) {
|
||||
if (!part.shared || part.solo || !lookOf.has(part.material)) continue;
|
||||
if (looks[final.get(id)] !== lookOf.get(part.material)) return null;
|
||||
}
|
||||
return recolours;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a draped line's upsert can change it in place: its ground
|
||||
@@ -1832,12 +1932,13 @@ export function createCesiumDraw({
|
||||
const flats = new Map();
|
||||
// Each item's look, in order: an item sent twice is changed twice.
|
||||
const looks = [];
|
||||
const lookOf = lineLooks();
|
||||
for (const item of list) {
|
||||
const was = parts.get(item.id);
|
||||
if (!was) return false;
|
||||
const look = lineLook(item);
|
||||
const look = lookOf.look(item);
|
||||
// Only its colour may change: its material takes it in place.
|
||||
if (was.look !== look && !recolourable(was, item)) return false;
|
||||
if (was.look !== look && !recolourable(was, item, lookOf)) return false;
|
||||
looks.push(look);
|
||||
if (was.deep !== undefined && record.deepLines?.isDestroyed())
|
||||
return false;
|
||||
@@ -1854,12 +1955,20 @@ export function createCesiumDraw({
|
||||
if (!drapedPatchable(record, was, flat)) return false;
|
||||
flats.set(item.id, flat);
|
||||
}
|
||||
const shared = sharedRecolours(parts, list, looks);
|
||||
if (!shared) return false;
|
||||
// Shared materials take their one colour once, before lines move off
|
||||
// them.
|
||||
for (const [material, item] of shared)
|
||||
material.uniforms.color = toColor(item.style.color);
|
||||
for (let k = 0; k < list.length; k++) {
|
||||
const item = list[k];
|
||||
const was = parts.get(item.id);
|
||||
const show = item.show !== false;
|
||||
if (was.look !== looks[k]) {
|
||||
was.material.uniforms.color = toColor(item.style.color);
|
||||
// A line drawing on a shared material took its colour above.
|
||||
if (!was.shared || was.solo)
|
||||
was.material.uniforms.color = toColor(item.style.color);
|
||||
was.look = looks[k];
|
||||
}
|
||||
if (was.polyline) {
|
||||
|
||||
@@ -3705,6 +3705,12 @@ test('a draped line drawn by its own material changes colour in place; a batched
|
||||
assert.equal(glow.appearance.material.uniforms.color.alpha, 0.7);
|
||||
set.upsert([jam(0.3)]);
|
||||
assert.equal(glow.appearance.material.uniforms.color.alpha, 0.3);
|
||||
// A style object the caller changes and sends again is read anew.
|
||||
const again = jam(0.4);
|
||||
set.upsert([again]);
|
||||
again.style.color[3] = 0.6;
|
||||
set.upsert([again]);
|
||||
assert.equal(glow.appearance.material.uniforms.color.alpha, 0.6);
|
||||
// Another width is another line: rebuilt.
|
||||
set.upsert([{ ...jam(0.7), widthPx: 10 }]);
|
||||
assert.notEqual(scene.added[0], host, 'a new width rebuilds');
|
||||
@@ -3714,6 +3720,126 @@ test('a draped line drawn by its own material changes colour in place; a batched
|
||||
set.dispose();
|
||||
}));
|
||||
|
||||
test('draped glow lines that look alike share one ground primitive and recolour together in place', () =>
|
||||
withImageClasses(() => {
|
||||
const { scene, draw } = drawOver();
|
||||
const set = draw.lines({ id: 'glows', clampTo: 'tiles' });
|
||||
const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0);
|
||||
const glow = (id, lon, alpha, extra = {}) => ({
|
||||
id,
|
||||
positions: [at(lon), at(lon + 0.01)],
|
||||
widthPx: 9,
|
||||
mode: 'draped',
|
||||
style: { kind: 'glow', color: [0.9, 0.3, 0.3, alpha], power: 0.25 },
|
||||
...extra,
|
||||
});
|
||||
const grounds = () => {
|
||||
const host = scene.added[0];
|
||||
return [...Array(host.length).keys()]
|
||||
.map((i) => host.get(i))
|
||||
.filter((p) => p instanceof Cesium.GroundPolylinePrimitive);
|
||||
};
|
||||
set.set([glow('a', 0, 0.5), glow('b', 1, 0.5), glow('c', 2, 0.5)]);
|
||||
const host = scene.added[0];
|
||||
const [batch] = grounds();
|
||||
assert.equal(grounds().length, 1, 'one primitive for the three');
|
||||
assert.equal(batch.geometryInstances.length, 3);
|
||||
const uniforms = batch.appearance.material.uniforms;
|
||||
// All recoloured alike: in place, on the one material.
|
||||
set.upsert([glow('a', 0, 0.7), glow('b', 1, 0.7), glow('c', 2, 0.7)]);
|
||||
assert.equal(scene.added[0], host, 'in place');
|
||||
assert.ok(!batch.isDestroyed());
|
||||
assert.equal(uniforms.color.alpha, 0.7);
|
||||
// A line moved off the batch, sent twice in one upsert, takes its last
|
||||
// colour on a material of its own; its peers keep theirs.
|
||||
const moved = (alpha) =>
|
||||
glow('a', 0, alpha, { positions: [at(0.5), at(0.51)] });
|
||||
withTerrainHeights(() => set.upsert([moved(0.2), moved(0.7)]));
|
||||
assert.equal(scene.added[0], host, 'moved in place');
|
||||
assert.equal(uniforms.color.alpha, 0.7, 'the peers keep their colour');
|
||||
// Two recoloured and one not: it would change colour with them, so
|
||||
// the set is rebuilt.
|
||||
set.upsert([glow('a', 0, 0.2), glow('b', 1, 0.2)]);
|
||||
assert.notEqual(scene.added[0], host, 'rebuilt');
|
||||
assert.equal(grounds().length, 2, 'one for each look');
|
||||
const rebuilt = scene.added[0];
|
||||
// Another width is another look: drawn apart.
|
||||
set.upsert([glow('c', 2, 0.7, { widthPx: 4 })]);
|
||||
assert.notEqual(scene.added[0], rebuilt);
|
||||
assert.equal(grounds().length, 2);
|
||||
set.dispose();
|
||||
}));
|
||||
|
||||
test('the traffic layer drapes its heat-lines on the tiles and pulses the jam ones in place', async () => {
|
||||
const { createRendering } = await import('../../layers/traffic/rendering.js');
|
||||
const policy = await import('../../layers/traffic/policy.js');
|
||||
await withImageClasses(() => {
|
||||
const { scene, draw } = drawOver();
|
||||
const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 30.26);
|
||||
const road = (level, lon) => ({
|
||||
flow: { level },
|
||||
segmentDist: [100],
|
||||
waypoints: [at(lon), at(lon + 0.001)],
|
||||
});
|
||||
const state = {
|
||||
_viewer: {},
|
||||
_liveMode: true,
|
||||
_presetDots: 'off',
|
||||
_heatJam: [],
|
||||
_heatLineCount: 0,
|
||||
_heatSupported: true,
|
||||
_heatSet: draw.lines({ id: 'traffic:1:heat', clampTo: 'tiles' }),
|
||||
};
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: {},
|
||||
parts: {
|
||||
style: { heatlineOn: () => true },
|
||||
animation: { syncRenderDemand() {} },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
rendering.rebuildHeatLines([
|
||||
road(0.2, -97.74),
|
||||
road(0.25, -97.735),
|
||||
road(0.6, -97.73),
|
||||
]);
|
||||
const host = scene.added[0];
|
||||
const grounds = [...Array(host.length).keys()]
|
||||
.map((i) => host.get(i))
|
||||
.filter((p) => p instanceof Cesium.GroundPolylinePrimitive);
|
||||
assert.equal(grounds.length, 2, 'the jam lines glowing, the slow ones');
|
||||
assert.ok(
|
||||
grounds.every(
|
||||
(p) =>
|
||||
p.classificationType === Cesium.ClassificationType.CESIUM_3D_TILE,
|
||||
),
|
||||
'draped on the tiles alone',
|
||||
);
|
||||
const glow = grounds.find(
|
||||
(p) => p.appearance?.material?.type === 'PolylineGlow',
|
||||
);
|
||||
assert.ok(glow, 'the jam line glows');
|
||||
assert.equal(
|
||||
glow.appearance.material.uniforms.color.alpha,
|
||||
policy.HEAT_JAM_BASE_ALPHA,
|
||||
);
|
||||
rendering.pulseHeatLines(260 * (Math.PI / 2));
|
||||
assert.equal(scene.added[0], host, 'pulsed where it is');
|
||||
assert.ok(!glow.isDestroyed());
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
glow.appearance.material.uniforms.color.alpha -
|
||||
(policy.HEAT_JAM_BASE_ALPHA + policy.HEAT_JAM_PULSE_ALPHA),
|
||||
) < 1e-6,
|
||||
);
|
||||
rendering.removeHeatLines();
|
||||
assert.equal(state._heatSet.size(), 0);
|
||||
state._heatSet.dispose();
|
||||
assert.equal(scene.added.length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
test('revealFraction draws a line up to that fraction of its length, and changes in place', () =>
|
||||
withImageClasses(() => {
|
||||
const { scene, draw } = drawOver();
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* @module render/cesium/surfaceState
|
||||
*
|
||||
* What a layer that samples heights off the drawn surface, or drapes lines
|
||||
* on it, needs to know of it and the renderer contract cannot say: whether
|
||||
* any 3D tileset is drawn (the globe port's settle states hold for none),
|
||||
* which surface it is (the contract names no surface identity), and
|
||||
* whether lines can be draped at all. Read off the Cesium scene.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/**
|
||||
* Whether the scene can drape lines on the surface: Cesium's ground
|
||||
* polylines need depth textures.
|
||||
* @param {object|undefined} viewer
|
||||
*/
|
||||
export function drapesLines(viewer) {
|
||||
const scene = viewer?.scene;
|
||||
return (
|
||||
Boolean(scene?.frameState) &&
|
||||
Cesium.GroundPolylinePrimitive.isSupported(scene)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the drawn surface has loaded what is in view: the
|
||||
* globe's tiles while it is shown, otherwise every shown 3D tileset (and
|
||||
* there is one).
|
||||
* @param {object|undefined} viewer
|
||||
*/
|
||||
export function surfaceTilesReady(viewer) {
|
||||
const scene = viewer?.scene;
|
||||
if (!scene) return false;
|
||||
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
|
||||
let found = false;
|
||||
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
|
||||
const primitive = scene.primitives.get(i);
|
||||
if (!primitive.show || typeof primitive.tilesLoaded !== 'boolean') continue;
|
||||
found = true;
|
||||
if (!primitive.tilesLoaded) return false;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// Stable ids for the objects heights are sampled from (tilesets, terrain).
|
||||
const surfaceIds = new WeakMap();
|
||||
let nextSurfaceId = 1;
|
||||
const surfaceId = (object) => {
|
||||
if (!object || typeof object !== 'object') return 0;
|
||||
if (!surfaceIds.has(object)) surfaceIds.set(object, nextSurfaceId++);
|
||||
return surfaceIds.get(object);
|
||||
};
|
||||
|
||||
/**
|
||||
* Name what heights are sampled against: the terrain provider when the globe
|
||||
* is shown, otherwise the set of visible 3D tilesets. A map-provider switch
|
||||
* changes it and invalidates every cached height.
|
||||
* @param {object|undefined} viewer
|
||||
*/
|
||||
const surfaceKeys = new WeakMap();
|
||||
export function surfaceKey(viewer) {
|
||||
const scene = viewer?.scene;
|
||||
if (!scene) return '';
|
||||
let state = surfaceKeys.get(scene);
|
||||
if (!state) {
|
||||
state = { globe: null, terrain: null, tiles: [], key: '' };
|
||||
surfaceKeys.set(scene, state);
|
||||
}
|
||||
const globe = Boolean(scene.globe?.show);
|
||||
const terrain = globe ? scene.globe.terrainProvider : null;
|
||||
let changed = state.globe !== globe || state.terrain !== terrain;
|
||||
let count = 0;
|
||||
if (!globe) {
|
||||
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
|
||||
const primitive = scene.primitives.get(i);
|
||||
if (!primitive?.show || typeof primitive.tilesLoaded !== 'boolean')
|
||||
continue;
|
||||
if (state.tiles[count] !== primitive) {
|
||||
state.tiles[count] = primitive;
|
||||
changed = true;
|
||||
}
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count !== state.tiles.length) {
|
||||
state.tiles.length = count;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
state.globe = globe;
|
||||
state.terrain = terrain;
|
||||
// Allocate only when the actual map surface changes, never per frame.
|
||||
state.key = globe
|
||||
? `globe:${surfaceId(terrain)}`
|
||||
: `tiles:${state.tiles.map(surfaceId).join(',')}`;
|
||||
}
|
||||
return state.key;
|
||||
}
|
||||
Reference in new issue
Block a user