Merge branch 'sameh/renderer-transit' into sameh/renderer-seam

# Conflicts:
#	src/render/cesium/draw.test.mjs
This commit is contained in:
Sameh Khamis committed 2026-11-09 01:00:43 -08:00
commit 9d4e438e63
27 files changed
+2016 -465

No files matched your search

+90
View File
@@ -747,3 +747,93 @@ test('the perspective helper is continuous through the sub-pixel band, not a 23
`exact alone at ${s.separation.toFixed(2)} px`,
);
});
test('the port-side perspective rotation matches the Cesium one through the whole band', async () => {
// The transit layer turns its icons with `perspectiveCourseRotation`, which
// projects through the query port and blends with the camera-port basis;
// given the same projection and basis it must answer as the scene helper.
const { perspectiveCourseRotation } = await import('./screenRotation.js');
let compared = 0;
for (let altitude = 500; altitude <= 600_000; altitude *= 1.05) {
const scene = obliqueScene(altitude, 45);
const project = (p) => {
const s = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
new Cesium.Cartesian3(p.x, p.y, p.z),
);
return s ? { x: s.x, y: s.y } : null;
};
const basis = { right: scene.camera.rightWC, up: scene.camera.upWC };
for (const [east, north] of [
[0.7, 1.2],
[-0.4, 0.9],
[0, 0.5],
[0, -2],
])
for (const course of [0, 37, 90, 181, 300]) {
const contact = Cesium.Cartesian3.fromDegrees(
(east * altitude) / 111_320,
(north * altitude) / 111_320,
0,
);
for (const previous of [null, 0.25]) {
const expected = perspectiveProjectedRotation(
scene,
contact,
course,
previous,
);
const actual = perspectiveCourseRotation(
project,
basis,
{ x: contact.x, y: contact.y, z: contact.z },
course,
previous,
);
if (expected === null || actual === null)
assert.equal(actual, expected);
else
assert.ok(
Math.abs(actual - expected) < 1e-9,
`${altitude.toFixed(0)} m, course ${course}: ${actual} vs ${expected}`,
);
compared += 1;
}
}
}
assert.ok(compared > 1000);
assert.equal(perspectiveCourseRotation(null, null, null, 0, 0.5), 0.5);
});
test('the port-side perspective rotation probes along the east-north frame, poles included', async () => {
const { perspectiveCourseRotation, PERSPECTIVE_PROBE_M: probeM } =
await import('./screenRotation.js');
const { eastNorthUp, frameVector } = await import('../geo/frames.js');
const { fromDegrees } = await import('../geo/ellipsoid.js');
for (const position of [
fromDegrees(-71.06, 42.36, 12),
fromDegrees(150, -60, 0),
{ x: 0, y: 0, z: 6_356_752.314245 },
])
for (const course of [0, 45, 200]) {
const seen = [];
perspectiveCourseRotation(
(p) => (seen.push({ x: p.x, y: p.y, z: p.z }), { x: 0, y: 0 }),
null,
position,
course,
);
const rad = (course * Math.PI) / 180;
const forward = frameVector(eastNorthUp(position), {
x: Math.sin(rad) * probeM,
y: Math.cos(rad) * probeM,
z: 0,
});
const [, ahead] = seen;
for (const axis of ['x', 'y', 'z'])
assert.ok(
Math.abs(ahead[axis] - (position[axis] + forward[axis])) < 1e-6,
`${axis} at course ${course}`,
);
}
});
+70 -1
View File
@@ -25,7 +25,7 @@ import { bindRenderer } from '../render/rendererOf.js';
import { resolveEllipsoidalGround } from './terrainHeights.js';
import {
cachedGroundFloor, cachedMeshFloor, setMeshFloorPreferred,
_clearMeshFloorCellsForTest,
_clearMeshFloorCellsForTest, reportValidatedMeshFloorCell,
} from './groundFloor.js';
/** Distinct site per test — terrainHeights' cache is module-global and warm
@@ -183,3 +183,72 @@ test('sampler: with `sets` the probe asks the query port, naming those sets', as
assert.ok(Math.abs(asked[0].point.lat - cell.lat) < 0.05);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), 138.0);
});
test('sampler: the probe goes where the point is, not to the cell centre', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
const asked = [];
const scene = fakeScene((carto) => {
asked.push(Cesium.Math.toDegrees(carto.longitude));
return 122.0;
});
const point = { lat: cell.lat + 0.0003, lon: cell.lon + 0.0004 };
sampleMeshFloorCells(scene, [point], { viewerLat: cell.lat, viewerLon: cell.lon });
assert.equal(asked.length, 1);
assert.ok(Math.abs(asked[0] - point.lon) < 1e-9, `probed at ${asked[0]}, not ${point.lon}`);
});
test('sampler: a viaduct and the street beside it in one cell keep their own heights', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
// A viaduct deck 9 m up along one line of the cell, the street elsewhere.
const deckLat = cell.lat + 0.0003;
let calls = 0;
const scene = fakeScene((carto) => {
calls += 1;
return Math.abs(Cesium.Math.toDegrees(carto.latitude) - deckLat) < 1e-7 ? 129.0 : 121.0;
});
const opts = { viewerLat: cell.lat, viewerLon: cell.lon };
const onDeck = { lat: deckLat, lon: cell.lon };
const street = { lat: cell.lat - 0.0003, lon: cell.lon };
sampleMeshFloorCells(scene, [onDeck], opts);
sampleMeshFloorCells(scene, [street], opts);
assert.equal(calls, 2);
assert.equal(cachedMeshFloor(onDeck.lat, onDeck.lon + 0.0001), 129.0, 'the train stays on the deck');
assert.equal(cachedMeshFloor(street.lat, street.lon - 0.0001), 121.0, 'the bus stays on the street');
assert.equal(cachedGroundFloor(street.lat, street.lon), 121.0);
sampleMeshFloorCells(scene, [{ lat: deckLat, lon: cell.lon + 0.00001 }], opts);
assert.equal(calls, 2, 'a point next to one already probed is not probed again');
});
test('sampler: a second reading at the same spot keeps the lower one', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
assert.equal(reportValidatedMeshFloorCell(cell.lat, cell.lon, 131.0), true);
assert.equal(reportValidatedMeshFloorCell(cell.lat + 0.00002, cell.lon, 122.0), true);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), 122.0);
assert.equal(reportValidatedMeshFloorCell(cell.lat, cell.lon + 0.00002, 140.0), true);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), 122.0, 'a higher one never raises it');
});
test('sampler: a latched cell is read a few times at most', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
let calls = 0;
const scene = fakeScene(() => {
calls += 1;
return 121.0;
});
const opts = { viewerLat: cell.lat, viewerLon: cell.lon };
for (let i = 0; i < 20; i++)
sampleMeshFloorCells(
scene,
[{ lat: cell.lat - 0.0004 + (i % 5) * 0.0002, lon: cell.lon - 0.00045 + Math.floor(i / 5) * 0.0003 }],
opts,
);
assert.equal(calls, 8);
});
+115
View File
@@ -6,6 +6,7 @@
* render noise. See `iconOrientation.js` for why the course is projected
* onto the camera basis. No engine.
*/
import { WGS84 } from '../geo/ellipsoid.js';
import { eastNorthUp, frameVector } from '../geo/frames.js';
import { dot, toRadians, vec } from '../geo/vector.js';
@@ -79,3 +80,117 @@ export function stabilizeScreenRotation(
);
return Math.abs(delta) < Math.max(0, deadbandRad) ? previous : next;
}
/**
* Metres ahead `perspectiveCourseRotation` probes: short, so the projection
* is local to the contact (a two kilometre probe on a bus seen from six
* hundred metres would sample a part of the view the bus is nowhere near).
*/
export const PERSPECTIVE_PROBE_M = 30;
/**
* Probe separations (CSS px) across which the exact and camera-basis
* answers are blended: at or below the floor the camera-basis answer alone,
* at or above the ceiling the exact one.
*/
export const PERSPECTIVE_BLEND_MIN_PX = 0.5;
export const PERSPECTIVE_BLEND_MAX_PX = 3;
/**
* The icon rotation (as `courseScreenRotation`'s) that points a SURFACE
* contact along `courseDeg`, projected exactly, perspective division
* included: the contact and a point `PERSPECTIVE_PROBE_M` ahead of it are
* projected through `project` (a query port's `project`) and the angle
* between them read on screen. The camera-basis answer is orthographic,
* exact at the view's centre and wrong by twenty-odd degrees for a
* street-level contact away from it in an oblique view. Where either point
* cannot be projected it falls back to the camera-basis answer; below a few
* pixels of separation, where projection noise rules the exact one, the
* two are blended the short way round, so the rotation is continuous.
* @param {(p: {x: number, y: number, z: number}) => ({x: number, y: number}|null)} project
* @param {{right?: object, up?: object}|null} basis The camera's axes.
* @param {{x: number, y: number, z: number}|null} position ECEF.
* @param {number} courseDeg Degrees clockwise from north.
* @param {number|null} [previous] Kept when the rotation is unknown.
* @returns {number|null}
*/
export function perspectiveCourseRotation(
project,
basis,
position,
courseDeg,
previous = null,
) {
if (!project || !position || !Number.isFinite(courseDeg)) return previous;
if (!courseProbeInto(position, courseDeg, probeScratch)) {
// At a pole, through the frame `eastNorthUp` defines there.
const courseRad = toRadians(courseDeg);
const forward = frameVector(
eastNorthUp(position),
vec(
Math.sin(courseRad) * PERSPECTIVE_PROBE_M,
Math.cos(courseRad) * PERSPECTIVE_PROBE_M,
0,
),
);
probeScratch.x = position.x + forward.x;
probeScratch.y = position.y + forward.y;
probeScratch.z = position.z + forward.z;
}
const at = project(position);
const atX = at?.x;
const atY = at?.y;
const ahead = at ? project(probeScratch) : null;
if (!at || !ahead)
return courseScreenRotation(basis, position, courseDeg, previous);
const dx = ahead.x - atX;
const dy = ahead.y - atY;
const separation = Math.hypot(dx, dy);
// Window y grows downward; rotation 0 points the icon screen-up.
const exact = Math.atan2(-dx, -dy);
if (separation >= PERSPECTIVE_BLEND_MAX_PX) return exact;
const camera = courseScreenRotation(basis, position, courseDeg, previous);
if (!Number.isFinite(camera)) return exact;
if (separation <= PERSPECTIVE_BLEND_MIN_PX) return camera;
const weight =
(separation - PERSPECTIVE_BLEND_MIN_PX) /
(PERSPECTIVE_BLEND_MAX_PX - PERSPECTIVE_BLEND_MIN_PX);
const delta = Math.atan2(Math.sin(exact - camera), Math.cos(exact - camera));
return camera + delta * weight;
}
// The probe point, reused: the rotation pass visits every visible contact.
const probeScratch = { x: 0, y: 0, z: 0 };
/**
* The point `PERSPECTIVE_PROBE_M` ahead of `position` along `courseDeg` on
* its east-north plane (as `eastNorthUp` and `frameVector` give it), into
* `out`, allocating nothing. False at a pole, where `eastNorthUp` picks
* its own east.
*/
function courseProbeInto(position, courseDeg, out) {
const { x, y, z } = position;
// `eastNorthUp`'s own test for a pole.
if (Math.abs(x) <= 1e-14 && Math.abs(y) <= 1e-14) return false;
const eastLength = Math.hypot(x, y);
const o = WGS84.oneOverRadiiSquared;
let ux = x * o.x,
uy = y * o.y,
uz = z * o.z;
const upLength = Math.sqrt(ux * ux + uy * uy + uz * uz);
ux /= upLength;
uy /= upLength;
uz /= upLength;
const ex = -y / eastLength,
ey = x / eastLength;
// North is up × east (east has no z).
const nx = -uz * ey,
ny = uz * ex,
nz = ux * ey - uy * ex;
const courseRad = toRadians(courseDeg);
const e = Math.sin(courseRad) * PERSPECTIVE_PROBE_M;
const n = Math.cos(courseRad) * PERSPECTIVE_PROBE_M;
out.x = x + ex * e + nx * n;
out.y = y + ey * e + ny * n;
out.z = z + nz * n;
return true;
}
+1 -1
View File
@@ -185,7 +185,7 @@ export function createHeight({ state, services, parts }) {
meshUsed += mesh.length;
for (let i = 0; i < dem.length; i += 8)
warmGroundFloor(dem.slice(i, i + 8));
parts.rendering.sampleMeshFloors(mesh, entries);
parts.rendering.sampleMeshFloors(mesh);
// Cached completions can be adopted now; asynchronous completions are
// adopted by the next bounded reread.
for (const entry of entries) parts.trails.prepareEntry(entry);
+3 -1
View File
@@ -72,7 +72,7 @@ export function createIngestion({ state, services, parts, source }) {
const entry = state._vehicles.get(key);
if (!entry) return;
if (state._selectedKey === key) parts.selection.clearSelection();
if (entry.marker) entry.markerCollection?.remove(entry.marker);
parts.rendering.removeMarker(entry);
entry.marker = null;
entry.detectContact = null;
state._visible.delete(entry);
@@ -414,6 +414,8 @@ export function createIngestion({ state, services, parts, source }) {
// trip and must never sit on the render path.
parts.height.anchorFloors();
state._detectRevision++;
// New markers are drawn now, hidden until the visibility sweep shows them.
parts.rendering.flushMarkers();
parts.rendering.requestVisibility();
parts.rendering.syncRenderHold();
governorRequestRender('transit-poll');
+330 -88
View File
@@ -40,7 +40,7 @@ import {
import { fakeInput } from '../../input/testDoubles.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
import { bindRenderer, rendererOf } from '../../render/rendererOf.js';
import { fakeSceneQuery } from '../../testSupport/fakeCesiumScene.mjs';
import { framePortFor } from '../../testSupport/fakeFramePort.mjs';
import { registerStyleStages } from '../../styles/styleStages.js';
@@ -148,6 +148,60 @@ function groundStub(floorAt) {
};
}
/** A number per terrain the fake viewer has had, as `surfaceVersion` is. */
const surfaceVersions = new WeakMap();
let surfaceVersionSeq = 0;
function surfaceVersion(terrain) {
if (!terrain) return 0;
if (!surfaceVersions.has(terrain))
surfaceVersions.set(terrain, (surfaceVersionSeq += 1));
return surfaceVersions.get(terrain);
}
// A marker record's colour (a 0..1 tuple or a CSS string) as a Cesium colour.
function colourOf(c) {
return typeof c === 'string'
? Cesium.Color.fromCssColorString(c)
: new Cesium.Color(c[0], c[1], c[2], c[3]);
}
// A camera `height` metres above a place, looking straight down at it or,
// with `away`, straight out to space.
function viewFrom(lon, lat, height, away = false) {
const ground = Cesium.Cartesian3.fromDegrees(lon, lat, 0);
const n = Cesium.Cartesian3.normalize(ground, new Cesium.Cartesian3());
const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
const east = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(
Cesium.Cartesian3.UNIT_Z,
n,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const north = Cesium.Cartesian3.cross(n, east, new Cesium.Cartesian3());
const v = (c) => ({ x: c.x, y: c.y, z: c.z });
const down = Cesium.Cartesian3.negate(n, new Cesium.Cartesian3());
return {
position: v(position),
direction: v(away ? n : down),
up: v(north),
right: v(
away ? Cesium.Cartesian3.negate(east, new Cesium.Cartesian3()) : east,
),
heading: 0,
pitch: away ? Math.PI / 2 : -Math.PI / 2,
roll: 0,
fovy: Math.PI / 3,
aspectRatio: 1,
near: 1,
far: 5e8,
};
}
// A camera above Boston's antipode looking out to space: Boston is behind it.
const lookingAway = () => viewFrom(BOSTON.lon + 180, -BOSTON.lat, 1e6, true);
function harness(
t,
{
@@ -206,6 +260,11 @@ function harness(
const cameraChanged = new Cesium.Event();
const cameraListeners = new Set();
const preUpdates = new Set();
const preRenders = new Set();
// The scene's preRender is the frame port's, as the Cesium port's is.
preRender.addEventListener(() => {
for (const cb of [...preRenders]) cb({ frame: 0 });
});
const viewer = {
camera: {
changed: cameraChanged,
@@ -243,6 +302,10 @@ function harness(
return index >= 0;
},
contains: (primitive) => primitives.includes(primitive),
get: (index) => primitives[index],
get length() {
return primitives.length;
},
raiseToTop() {},
},
},
@@ -283,6 +346,11 @@ function harness(
sprites: {
registerSpriteCollection: (id, collection) =>
sprites.set(id, collection),
registerSpriteSet: (id, setId) => {
const entry = { drawSetId: setId };
sprites.set(id, entry);
return entry;
},
unregisterSpriteCollection: (id) => sprites.delete(id),
restoreSpriteOrder() {},
},
@@ -313,13 +381,71 @@ function harness(
const draw = fakeDrawPort();
const unbindCamera = bindRenderer(viewer, {
draw,
query: fakeSceneQuery(viewer),
// Only the tick the layer's camera listener waits on.
query: {
...fakeSceneQuery(viewer),
// A 1000 px square pinhole through the test's `view`; none without.
project(p) {
const view = viewer.camera.view;
if (!view) return null;
const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const v = {
x: p.x - view.position.x,
y: p.y - view.position.y,
z: p.z - view.position.z,
};
const z = dot(v, view.direction);
if (!(z > 0)) return null;
const f = 500 / Math.tan(view.fovy / 2);
return {
x: 500 + (f * dot(v, view.right)) / z,
y: 500 - (f * dot(v, view.up)) / z,
};
},
// The horizon from the fake camera's eye, as the Cesium port reads it
// from a real camera's.
isOccluded(position) {
const eye = Cesium.Ellipsoid.WGS84.cartographicToCartesian(
viewer.camera.positionCartographic,
);
return !new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
eye,
).isPointVisible(
new Cesium.Cartesian3(position.x, position.y, position.z),
);
},
// Terrain heights as the fake globe has them, told apart from the
// bare ellipsoid as the Cesium port tells them.
async sampleHeight(points, { against } = {}) {
if (against !== 'terrain') return points.map(() => null);
const flat =
viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider;
return points.map(() => ({
height: 0,
confidence: 1,
source: flat ? 'ellipsoid' : 'terrain',
lod: 'visible',
}));
},
},
// Whether the fake globe is shown, and a version that changes with its
// terrain, as the Cesium globe port reads them.
globe: {
isGlobeVisible: () => viewer.scene.globe.show === true,
surfaceVersion: () => surfaceVersion(viewer.terrainProvider),
},
// The tick the layer's camera listener waits on, and its frames.
frame: {
on(phase, cb) {
if (phase !== 'preUpdate') return () => {};
preUpdates.add(cb);
return () => preUpdates.delete(cb);
const listeners =
phase === 'preUpdate'
? preUpdates
: phase === 'preRender'
? preRenders
: null;
if (!listeners) return () => {};
listeners.add(cb);
return () => listeners.delete(cb);
},
requestRender() {},
},
@@ -342,6 +468,9 @@ function harness(
lon: carto ? Cesium.Math.toDegrees(carto.longitude) : NaN,
lat: carto ? Cesium.Math.toDegrees(carto.latitude) : NaN,
height: carto ? carto.height : NaN,
// A test sets `view` (position, direction, up, right and the
// frustum's fovy, aspectRatio and near) to cull by the frustum.
...viewer.camera.view,
};
},
viewRectangle() {
@@ -407,6 +536,27 @@ function harness(
responders.delete(feedId);
},
state: () => layer._transitStateForTest(),
/**
* The items of the markers' draw set, `still` or `moving`, as the draw
* port holds them (none once the set is gone).
*/
markers(name = 'still') {
const state = layer._transitStateForTest();
const set = name === 'moving' ? state._movingIcons : state._stillIcons;
return set ? (draw.set(set.id)?.items ?? new Map()) : new Map();
},
/**
* What a Cesium pick of a vehicle's marker returns: the draw port's pick
* id for its item in the set that draws it now.
*/
pickOf(entry) {
const state = layer._transitStateForTest();
const set = entry.animated ? state._movingIcons : state._stillIcons;
return {
primitive: {},
id: { set: set.id, id: entry.key, meta: { layer: 'transit' } },
};
},
vehicles: () => [...layer._transitStateForTest()._vehicles.values()],
frame() {
preRender.raiseEvent();
@@ -551,8 +701,7 @@ test('a vehicle the feed stops reporting is removed, and its primitive with it',
app.layer.enable(app.viewer);
await app.layer.update();
assert.equal(app.vehicles().length, 2);
const collection = app.sprites.get('transit');
assert.equal(collection.length, 2);
assert.equal(app.markers('still').size, 2);
app.serve('mbta', () => ({
status: 200,
@@ -576,7 +725,7 @@ test('a vehicle the feed stops reporting is removed, and its primitive with it',
['bus-1'],
);
assert.equal(
collection.length + app.sprites.get('transit-motion').length,
app.markers('still').size + app.markers('moving').size,
1,
'the removed vehicle released its point primitive',
);
@@ -646,7 +795,7 @@ test('a feed that goes silent has its vehicles evicted instead of frozen on the
app.advance(FEED_EVICT_AFTER_MS + 1_000);
await app.layer.update();
assert.equal(app.vehicles().length, 0, 'the last fleet is not left standing');
assert.equal(app.sprites.get('transit').length, 0);
assert.equal(app.markers('still').size, 0);
const stats = app.layer.getStats();
assert.equal(stats.count, 0);
assert.equal(stats.stale, true);
@@ -730,7 +879,7 @@ test('a snapshot the proxy replayed from its own cache for six minutes is refuse
0,
'the replayed fleet is gone, not frozen',
);
assert.equal(app.sprites.get('transit').length, 0);
assert.equal(app.markers('still').size, 0);
const stats = app.layer.getStats();
assert.equal(stats.count, 0);
assert.equal(stats.stale, true);
@@ -961,7 +1110,12 @@ test('destroy releases every shared registration this layer took', async (t) =>
await app.layer.update();
assert.ok(app.sprites.has('transit'));
assert.ok(app.pickOwners.has('transit'));
assert.equal(app.primitives.length, 2);
const ids = app.layer._transitSetIdsForTest();
assert.deepEqual(
ids.map((id) => app.draw.set(id)?.spec.id),
ids,
'two marker sets are live',
);
app.layer.destroy(app.viewer);
assert.deepEqual(app.cameraThresholds(), [], 'the camera listener goes');
@@ -975,10 +1129,10 @@ test('destroy releases every shared registration this layer took', async (t) =>
false,
'the pick owner is released',
);
assert.equal(
app.primitives.length,
0,
'the primitive collection leaves the scene',
assert.deepEqual(
ids.map((id) => app.draw.set(id)),
[undefined, undefined],
'both marker sets are let go',
);
assert.equal(app.holds().includes('transit'), false);
assert.equal(app.state()._viewer, null);
@@ -2217,12 +2371,12 @@ test('under FLIR and NVG every sprite is white-hot with a dark halo, and selecti
const bus = byRoute.get('742');
const plainImage = bus.marker.image;
const plainWidth = bus.marker.width;
const modeColour = bus.marker.color.clone();
const modeColour = colourOf(bus.marker.color);
app.style('thermal');
for (const entry of app.vehicles()) {
assert.ok(
Cesium.Color.equals(entry.marker.color, Cesium.Color.WHITE),
Cesium.Color.equals(colourOf(entry.marker.color), Cesium.Color.WHITE),
`${entry.record.routeId} is white-hot`,
);
assert.notEqual(entry.marker.image, plainImage, 'a haloed raster');
@@ -2236,7 +2390,7 @@ test('under FLIR and NVG every sprite is white-hot with a dark halo, and selecti
// Selecting under FLIR grows the sprite and keeps it white — cyan would dim it.
app.layer._transitPartsForTest().selection.selectVehicle(bus.key);
assert.ok(
Cesium.Color.equals(bus.marker.color, Cesium.Color.WHITE),
Cesium.Color.equals(colourOf(bus.marker.color), Cesium.Color.WHITE),
'still white when selected',
);
assert.ok(
@@ -2245,7 +2399,7 @@ test('under FLIR and NVG every sprite is white-hot with a dark halo, and selecti
);
app.layer._transitPartsForTest().selection.clearSelection();
assert.ok(
Cesium.Color.equals(bus.marker.color, Cesium.Color.WHITE),
Cesium.Color.equals(colourOf(bus.marker.color), Cesium.Color.WHITE),
'and white when deselected',
);
assert.equal(bus.marker.width, byRoute.get('Red').marker.width);
@@ -2253,7 +2407,7 @@ test('under FLIR and NVG every sprite is white-hot with a dark halo, and selecti
// Back to normal: the shipped look, exactly.
app.style('normal');
assert.ok(
Cesium.Color.equals(bus.marker.color, modeColour),
Cesium.Color.equals(colourOf(bus.marker.color), modeColour),
'mode colour restored',
);
assert.equal(bus.marker.image, plainImage, 'plain raster restored');
@@ -2278,12 +2432,12 @@ test('a cockpit vision override wins over the map style while it lasts, and dest
const plain = entry.marker.image;
app.vision('nvg', true);
assert.ok(
Cesium.Color.equals(entry.marker.color, Cesium.Color.WHITE),
Cesium.Color.equals(colourOf(entry.marker.color), Cesium.Color.WHITE),
'cockpit NVG restyles',
);
app.style('normal');
assert.ok(
Cesium.Color.equals(entry.marker.color, Cesium.Color.WHITE),
Cesium.Color.equals(colourOf(entry.marker.color), Cesium.Color.WHITE),
'the map style cannot undo a live cockpit override',
);
app.vision('normal', false);
@@ -2356,16 +2510,16 @@ test('the floor cycle samples the rendered mesh for the cells it warms, with its
'the sampler was asked after the floor resolved',
);
const call = app.meshCalls[0];
assert.equal(call.scene, app.viewer.scene);
assert.equal(call.scene, app.viewer);
assert.deepEqual(
call.points.map((p) => p.lat).sort(),
[42.36, 42.37],
'the in-view cells, and not the one off screen',
);
assert.equal(
call.options.excludeObjects.length,
2,
'both in-view billboards excluded',
assert.deepEqual(
call.options.sets,
app.layer._transitPartsForTest().rendering.setIds(),
'both marker sets excluded',
);
assert.ok(
Math.abs(call.options.viewerLat - BOSTON.lat) < 1e-6,
@@ -2801,11 +2955,7 @@ test('missing rectangle still rejects the far side, and frustum rejection wins',
[...app.state()._visible].map((e) => e.record.id),
['near'],
);
app.viewer.camera.frustum = {
computeCullingVolume: () => ({
computeVisibility: () => Cesium.Intersect.OUTSIDE,
}),
};
app.viewer.camera.view = lookingAway();
app.advance(250);
app.layer._transitPartsForTest().rendering.refreshVisibility();
assert.equal(app.state()._visible.size, 0);
@@ -2835,11 +2985,15 @@ test('motion transitions migrate billboards and update cached positions; disable
latitude += 0.001;
await app.layer.update();
app.run(8000, 16);
assert.equal(entry.markerCollection, app.state()._animatedMarkers);
assert.notEqual(entry.marker, old);
assert.equal(entry.animated, true);
assert.ok(app.markers('moving').has(entry.key));
assert.equal(app.markers('still').has(entry.key), false);
assert.equal(entry.marker, old, 'the record stays; only its draw set moves');
assert.equal(entry.detectContact.position, entry.marker.position);
app.run(30000, 16);
assert.equal(entry.markerCollection, app.state()._markers);
assert.equal(entry.animated, false);
assert.ok(app.markers('still').has(entry.key));
assert.equal(app.markers('moving').has(entry.key), false);
const parts = app.layer._transitPartsForTest();
const contacts = app.layer.getDetectableObjects();
const metric = contacts[0].metric;
@@ -2876,7 +3030,10 @@ test('every styling path retains the mode palette and exact unpadded size', asyn
const entry = app.vehicles()[0],
parts = app.layer._transitPartsForTest();
const check = (hex, display) => {
assert.equal(entry.marker.color.toCssHexString().toUpperCase(), hex);
assert.equal(
colourOf(entry.marker.color).toCssHexString().toUpperCase(),
hex,
);
const svg = Buffer.from(
entry.marker.image.split(',')[1],
'base64',
@@ -2926,11 +3083,7 @@ test('visible motion is recullable without a camera event and releases its hold
await app.layer.update();
app.layer._loadTransitFleetForTest(1, BOSTON, 1);
assert.equal(app.state()._moving.size, 1);
app.viewer.camera.frustum = {
computeCullingVolume: () => ({
computeVisibility: () => Cesium.Intersect.OUTSIDE,
}),
};
app.viewer.camera.view = lookingAway();
app.layer._transitPartsForTest().rendering.maintainPresentation();
app.advance(250);
assert.equal(app.state()._moving.size, 0);
@@ -3095,11 +3248,8 @@ test('tab visibility synchronizes playback before the returning frame and remove
for (const bounds of ['null', 'stale']) {
test(`browser visibility starts an injected fleet with ${bounds} bounds and an unsampled hidden marker`, async (t) => {
const app = harness(t);
app.viewer.camera.frustum = {
computeCullingVolume: () => ({
computeVisibility: () => Cesium.Intersect.INSIDE,
}),
};
// A real view over the fleet: the frustum, not the bounds, admits it.
app.viewer.camera.view = viewFrom(BOSTON.lon, BOSTON.lat, 4000);
app.layer.enable(app.viewer);
const loaded = app.layer._loadTransitFleetForTest(4, BOSTON, 70, [
'Red',
@@ -3158,7 +3308,7 @@ test('keyless loaded terrain resolves a pending surface without needing a frame
assert.equal(entry.marker.show, true);
});
test('the terrain under a vehicle is asked through the query port, and a flat globe stands at the ellipsoid', (t) => {
test('the terrain under a vehicle is asked through the query port, and a flat globe stands at the ellipsoid', async (t) => {
const app = harness(t, { floorAt: () => undefined });
const parts = app.layer._transitPartsForTest();
const lift = parts.height.requestHeight(0, 0).height;
@@ -3174,12 +3324,65 @@ test('the terrain under a vehicle is asked through the query port, and a flat gl
assert.equal(parts.rendering.globeSurface(), 'terrain');
app.viewer.scene.globe.getHeight = () => undefined;
app.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider();
// The surface is read once in a task, as a terrain swap comes in a task
// of its own.
await new Promise((resolve) => setImmediate(resolve));
// The new surface is asked about through the height service; until the
// answer arrives the last one holds.
assert.equal(parts.rendering.globeSurface(), 'terrain');
await new Promise((resolve) => setImmediate(resolve));
assert.equal(parts.rendering.globeSurface(), 'flat');
const flat = parts.height.requestHeight(42.36, -71.06);
assert.equal(terrain.height - flat.height, 30, 'flat terrain is height 0');
assert.equal(flat.prior, null);
});
test('a flat-globe answer that flips starts one fresh floor cycle, and a failed one is asked again', async (t) => {
const app = harness(t, { floorAt: () => undefined });
app.viewer.scene.globe.show = true;
app.layer.enable(app.viewer);
const parts = app.layer._transitPartsForTest();
const anchored = [];
const anchorFloors = parts.height.anchorFloors;
parts.height.anchorFloors = () => {
anchored.push(app.state()._floorTimer);
anchorFloors();
};
const tick = () => new Promise((resolve) => setImmediate(resolve));
assert.equal(parts.rendering.globeSurface(), 'terrain');
await tick();
assert.equal(anchored.length, 0, 'the same answer starts nothing');
app.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider();
await tick();
parts.rendering.globeSurface();
await tick();
assert.equal(parts.rendering.globeSurface(), 'flat');
assert.equal(anchored.length, 1, 'one fresh cycle on the flip');
// A probe that fails is asked again at the next read.
const query = rendererOf(app.viewer).query;
const sampleHeight = query.sampleHeight;
let asked = 0;
query.sampleHeight = async () => {
asked += 1;
throw new Error('terrain request failed');
};
app.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider();
await tick();
parts.rendering.globeSurface();
await tick();
assert.ok(asked > 0);
let askedAgain = 0;
query.sampleHeight = (...args) => {
askedAgain += 1;
return sampleHeight(...args);
};
await tick();
assert.equal(parts.rendering.globeSurface(), 'flat', 'the last answer holds');
assert.ok(askedAgain > 0, 'and the same surface is asked about again');
await tick();
assert.equal(anchored.length, 1, 'the same answer starts nothing');
});
test('scripted keyless fleet keeps its known floor through selection and floor rereads', async (t) => {
const app = harness(t, { floorAt: () => undefined });
app.viewer.scene.globe.show = true;
@@ -3200,27 +3403,13 @@ for (const count of [800, 3000]) {
test(`real perspective frustum admits all ${count} moving budget fixtures`, async (t) => {
const altitude = count === 800 ? 600 : 30000;
const app = harness(t, { altitude, floorAt: () => undefined });
const camera = app.viewer.camera;
camera.positionWC = Cesium.Cartesian3.fromDegrees(
BOSTON.lon,
BOSTON.lat,
altitude,
);
camera.directionWC = Cesium.Cartesian3.negate(
Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(
camera.positionWC,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(camera.positionWC);
camera.upWC = Cesium.Matrix4.getColumn(enu, 1, new Cesium.Cartesian3());
camera.frustum = new Cesium.PerspectiveFrustum({
fov: Math.PI / 3,
// Straight down from the altitude, through the frustum the camera port
// describes.
app.viewer.camera.view = {
...viewFrom(BOSTON.lon, BOSTON.lat, altitude),
aspectRatio: 1920 / 1080,
near: 1,
far: 100000,
});
};
app.layer.enable(app.viewer);
const loaded = app.layer._loadTransitFleetForTest(
count,
@@ -3229,6 +3418,10 @@ for (const count of [800, 3000]) {
);
assert.equal(loaded.moving, count);
assert.equal(app.state()._visible.size, count);
assert.ok(
app.vehicles().every((e) => e.visibility?.boundsApplied === false),
'the frustum, not the view rectangle, admitted them',
);
const entry = app.vehicles()[0],
before = Cesium.Cartesian3.clone(entry.marker.position);
app.run(1000, 16);
@@ -3242,8 +3435,8 @@ test('click handler selects a migrated scripted billboard and prepares its drape
app.layer.enable(app.viewer);
app.layer._loadTransitFleetForTest(4, BOSTON, 70);
const entry = app.vehicles()[0];
assert.equal(entry.markerCollection, app.state()._animatedMarkers);
app.viewer.scene.pick = () => ({ primitive: entry.marker, id: entry.key });
assert.equal(entry.animated, true);
app.viewer.scene.pick = () => app.pickOf(entry);
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, entry.key);
const body = app.layer._transitPartsForTest().trails.diagnostics().body;
@@ -3445,7 +3638,7 @@ test('selected anchor rejects nonfinite marker coordinates before sampling and d
assert.equal(card.position(), null);
});
test('preset clicks preserve both pick id paths through moving and stationary collection migration', async (t) => {
test('preset clicks pick the marker in whichever set draws it, moving or still', async (t) => {
const app = harness(t, { floorAt: () => undefined });
app.layer.enable(app.viewer);
app.layer._loadTransitFleetForTest(4, BOSTON, 70);
@@ -3459,17 +3652,17 @@ test('preset clicks preserve both pick id paths through moving and stationary co
entry.sample.nextWakeMonoMs = Infinity;
entry.sample.segmentCourseDeg = entry.courseDeg;
parts.rendering.schedulePlayback(entry);
parts.rendering.flushMarkers();
assert.equal(entry.animated, animated);
assert.ok(app.markers(animated ? 'moving' : 'still').has(entry.key));
app.viewer.scene.pick = () => app.pickOf(entry);
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, entry.key);
assert.equal(
entry.markerCollection,
animated ? app.state()._animatedMarkers : app.state()._markers,
app.state()._lastPickForTest.collection,
animated ? 'animated' : 'stationary',
);
assert.equal(entry.marker.id, entry.key);
for (const pick of [{ id: entry.key }, { primitive: entry.marker }]) {
app.viewer.scene.pick = () => pick;
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, entry.key);
parts.selection.clearSelection();
}
parts.selection.clearSelection();
}
});
@@ -3501,7 +3694,7 @@ test('sensor clicks map displayed pixels into the pre-shader pick buffer', async
let actual;
scene.pick = (p) => {
actual = { x: p.x, y: p.y };
return { id: entry.key };
return app.pickOf(entry);
};
scene.canvas = {
width: 1920,
@@ -3765,7 +3958,12 @@ test('moving and stationary transit stay adjacent above CCTV and Bikeshare durin
const cctv = {},
bike = {},
flights = {};
app.primitives.push(cctv, bike, flights);
// The marker sets' hosts, named by their set ids as the draw port names
// them, between the others.
const [stillId, movingId] = app.layer._transitSetIdsForTest();
const still = { drawSetId: stillId },
moving = { drawSetId: movingId };
app.primitives.push(cctv, still, bike, moving, flights);
app.viewer.scene.primitives.raiseToTop = (c) => {
app.primitives.splice(app.primitives.indexOf(c), 1);
app.primitives.push(c);
@@ -3783,24 +3981,24 @@ test('moving and stationary transit stay adjacent above CCTV and Bikeshare durin
});
const entry = app.vehicles()[0],
parts = app.layer._transitPartsForTest();
const stillHost = still,
movingHost = moving;
for (const moving of [true, false, true]) {
entry.sample.phase = moving ? 'playing' : 'held';
entry.sample.segmentSpeedMps = moving ? 1 : 0;
entry.sample.segmentCourseDeg = NaN;
parts.rendering.schedulePlayback(entry);
restoreSpriteOrder(app.viewer);
const active = app.primitives.indexOf(entry.markerCollection);
parts.rendering.flushMarkers();
assert.ok(app.markers(moving ? 'moving' : 'still').has(entry.key));
const active = app.primitives.indexOf(moving ? movingHost : stillHost);
assert.ok(active > app.primitives.indexOf(cctv));
assert.ok(active > app.primitives.indexOf(bike));
assert.ok(active < app.primitives.indexOf(flights));
assert.equal(
Math.abs(
app.primitives.indexOf(app.state()._markers) -
app.primitives.indexOf(app.state()._animatedMarkers),
),
app.primitives.indexOf(movingHost) - app.primitives.indexOf(stillHost),
1,
);
assert.equal(entry.marker.id, entry.key);
}
});
@@ -4003,6 +4201,50 @@ test('parked transit reprojects held and reported courses at the bounded camera
);
};
pose(0);
// The camera port reads the camera above; the query port projects through
// it as a pinhole the size of the canvas.
const viewer = { scene };
const plainOf = (c) => ({ x: c.x, y: c.y, z: c.z });
const direction = { x: -1, y: 0, z: 0 };
const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({
lon: 0,
lat: 0,
height: 1000,
heading: scene.camera.heading,
pitch: scene.camera.pitch,
roll: scene.camera.roll,
position: plainOf(cameraPosition),
direction,
up: plainOf(scene.camera.upWC),
right: plainOf(scene.camera.rightWC),
fovy: scene.camera.frustum.fovy,
aspectRatio: 1.6,
near: 1,
far: 1e7,
}),
},
query: {
project(p) {
const v = {
x: p.x - cameraPosition.x,
y: p.y - cameraPosition.y,
z: p.z - cameraPosition.z,
};
const z = dot(v, direction);
if (!(z > 0)) return null;
const f = 400 / Math.tan(scene.camera.frustum.fovy / 2);
return {
x: 640 + (f * dot(v, scene.camera.rightWC)) / z,
y: 400 - (f * dot(v, scene.camera.upWC)) / z,
};
},
isOccluded: () => false,
},
});
t.after(unbind);
const make = (key, courseDeg, bearing) => ({
key,
courseDeg,
@@ -4015,7 +4257,7 @@ test('parked transit reprojects held and reported courses at the bounded camera
const unknown = make('unknown', null, null);
const hidden = make('hidden', 90, 90);
const state = {
_viewer: { scene },
_viewer: viewer,
_enabled: true,
_vehicles: new Map(
[held, reportedOnly, unknown, hidden].map((e) => [e.key, e]),
+1 -1
View File
@@ -84,7 +84,7 @@ export function createQueries({ state, parts }) {
* @returns {Array<object>}
*/
function collectDetectableVehicles(options = defaults) {
if (!state._enabled || !state._markers?.show) return empty;
if (!state._enabled || !state._markersShown) return empty;
if (state._vehicles.size === 0) return empty;
const maxCount = Number.isFinite(options.maxCount)
? Math.max(1, Math.floor(options.maxCount))
+452 -231
View File
@@ -1,14 +1,16 @@
import * as Cesium from 'cesium';
// The Cesium camera factory: given a viewer of a caller's own, with no
// renderer bound, the layer's camera reads find a camera port.
import '../../render/cesium/camera.js';
import '../../render/cesium/frame.js';
import { webglContext } from '../../render/cesium/internals.js';
import { findCamera, findFrame } from '../../render/rendererOf.js';
import {
cameraPoseSignature,
perspectiveProjectedRotation,
} from '../../render/cesium/iconOrientation.js';
canvasOf,
drawOf,
findCamera,
findFrame,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { poseSignature } from '../../render/camera/poseSignature.js';
import { heightsOf } from '../../queries/heights.js';
import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { frustumPlanes } from '../../geo/frustum.js';
import { perspectiveCourseRotation } from '../../data/screenRotation.js';
import {
updatePlayback,
applyDisplayCourse,
@@ -35,15 +37,22 @@ import {
vehicleNearView,
} from './policy.js';
export const MODE_CESIUM_COLORS = Object.fromEntries(
Object.entries(TRANSIT_MODE_COLORS).map(([mode, css]) => [
mode,
Cesium.Color.fromCssColorString(css),
]),
);
/** Layers built so far, so each one's draw sets have ids of their own. */
let instances = 0;
/** Radius, metres, of the sphere a vehicle is culled by. */
const CULL_RADIUS_M = 5;
/**
* Billboards and the per-frame glide.
* Markers and the per-frame glide.
*
* Each vehicle's marker is a plain record (`entry.marker`: its position,
* whether it shows, its image, size, colour and screen rotation) drawn as
* an icon in one of two draw sets: the still one, or the moving one while
* it glides or turns, so a fleet at rest is not rewritten with the few
* that move. Changed markers are pushed to their sets once per frame (and
* once per visibility sweep), each with the one item object it keeps:
* a frame pass over a moving fleet allocates nothing per vehicle.
* @param {object} context
* @returns {object}
*/
@@ -56,69 +65,211 @@ export function createRendering({ state, services, parts }) {
// The application's rendered-mesh sampler. Optional so a layer built on a
// bare floor stub still runs; the application always supplies it.
const sampleMeshFloorCells = services.mesh?.sampleMeshFloorCells || null;
const instance = (instances += 1);
/** Markers changed since they were last pushed to their sets. */
const dirty = new Set();
// Kept between pushes, so a push allocates no lists.
const stillUpserts = [];
const movingUpserts = [];
const stillRemovals = [];
const movingRemovals = [];
/**
* The two billboard collections, still and moving, added to the scene and
* to the shared sprite order, hidden.
* The two icon sets, still and moving, hidden, in the scene now (with no
* items) and in the shared sprite order. A viewer of the layer's own
* draws through `./render/cesium/unbound`, which its owner loads.
* @param {object} viewer
*/
function createMarkers(viewer) {
state._markers = new Cesium.BillboardCollection({
blendOption: Cesium.BlendOption.TRANSLUCENT,
destroyMarkers(viewer);
const draw = drawOf(viewer);
state._stillIcons = draw.icons({
id: `transit:${instance}:still`,
blend: 'translucent',
show: false,
});
viewer.scene.primitives.add(state._markers);
services.sprites.registerSpriteCollection('transit', state._markers);
state._animatedMarkers = new Cesium.BillboardCollection({
blendOption: Cesium.BlendOption.TRANSLUCENT,
state._movingIcons = draw.icons({
id: `transit:${instance}:moving`,
blend: 'translucent',
show: false,
});
viewer.scene.primitives.add(state._animatedMarkers);
services.sprites.registerSpriteCollection(
// Emptied, they are drawn now: the sprite order finds them at once.
state._stillIcons.set([]);
state._movingIcons.set([]);
const { registerSpriteSet } = services.sprites;
state._stillSprite = registerSpriteSet?.('transit', state._stillIcons.id);
state._movingSprite = registerSpriteSet?.(
'transit-motion',
state._animatedMarkers,
state._movingIcons.id,
);
state._animatedMarkers.show = false;
state._markers.show = false;
state._markersShown = false;
}
/** Show both collections. */
/** Show both sets. */
function showMarkers() {
state._markers.show = true;
state._animatedMarkers.show = true;
if (!state._stillIcons) return;
state._stillIcons.show = true;
state._movingIcons.show = true;
state._markersShown = true;
}
/** Drop every billboard and hide both collections. */
/** Drop every marker and hide both sets. */
function clearMarkers() {
state._markers?.removeAll();
state._animatedMarkers?.removeAll();
if (state._animatedMarkers) state._animatedMarkers.show = false;
if (state._markers) state._markers.show = false;
dirty.clear();
stillRemovals.length = 0;
movingRemovals.length = 0;
state._stillIcons?.clear();
state._movingIcons?.clear();
if (state._movingIcons) state._movingIcons.show = false;
if (state._stillIcons) state._stillIcons.show = false;
state._markersShown = false;
}
/**
* Take both collections off the scene and out of the sprite order.
* @param {object|null|undefined} viewer
* Let both sets go and take them out of the sprite order.
* @param {object|null|undefined} _viewer
*/
function destroyMarkers(viewer) {
if (state._markers) {
services.sprites.unregisterSpriteCollection('transit', state._markers);
viewer?.scene?.primitives?.remove(state._markers);
state._markers = null;
function destroyMarkers(_viewer) {
dirty.clear();
stillRemovals.length = 0;
movingRemovals.length = 0;
const { unregisterSpriteCollection } = services.sprites;
if (state._stillIcons) {
if (state._stillSprite)
unregisterSpriteCollection?.('transit', state._stillSprite);
state._stillIcons.dispose();
state._stillIcons = null;
state._stillSprite = null;
}
if (state._animatedMarkers) {
services.sprites.unregisterSpriteCollection(
'transit-motion',
state._animatedMarkers,
);
viewer?.scene?.primitives?.remove(state._animatedMarkers);
state._animatedMarkers = null;
if (state._movingIcons) {
if (state._movingSprite)
unregisterSpriteCollection?.('transit-motion', state._movingSprite);
state._movingIcons.dispose();
state._movingIcons = null;
state._movingSprite = null;
}
state._markersShown = false;
}
/** Whether a vehicle's billboard is shown. */
/** The ids of both sets (for the frame probe and floor sampling). */
function setIds() {
return [state._stillIcons?.id, state._movingIcons?.id].filter(Boolean);
}
/** Whether `setId` is one of this layer's sets. */
function ownsSet(setId) {
return (
typeof setId === 'string' &&
(setId === state._stillIcons?.id || setId === state._movingIcons?.id)
);
}
/** Which of the sets a draw set id is: `'moving'`, `'still'` or null. */
function setNameOf(setId) {
if (setId && setId === state._movingIcons?.id) return 'moving';
if (setId && setId === state._stillIcons?.id) return 'still';
return null;
}
/** Whether a vehicle's marker is shown. */
function markerShown(entry) {
return entry.marker?.show === true;
}
/** Note that a marker changed, for the next push. */
function markDirty(entry) {
if (entry.marker) dirty.add(entry);
}
/** Show or hide a marker. */
function setShown(entry, shown) {
if (entry.marker.show === shown) return;
entry.marker.show = shown;
dirty.add(entry);
}
/**
* The icon item a marker draws as: the one item object the vehicle
* keeps, brought up to date. Its position is the marker's own, which the
* frame pass moves in place; the renderer reads positions as they are
* when pushed.
*/
function itemOf(entry) {
const marker = entry.marker;
const item = (entry.iconItem ||= {
id: entry.key,
pos: marker.position,
image: marker.image,
size: [0, 0],
color: marker.color,
rotationMode: 'screen',
rotation: 0,
show: false,
disableDepthTest: Infinity,
meta: { layer: 'transit', key: entry.key },
});
item.pos = marker.position;
item.image = marker.image;
item.size[0] = marker.width;
item.size[1] = marker.height;
item.color = marker.color;
item.rotation = marker.rotation;
item.show = marker.show;
return item;
}
/**
* Push the markers changed since the last push to their sets: a marker
* that changed set leaves the one it was in first.
*/
function flushMarkers() {
const still = state._stillIcons;
const moving = state._movingIcons;
if (!still || !moving) return;
if (!dirty.size && !stillRemovals.length && !movingRemovals.length) return;
for (const entry of dirty) {
if (!entry.marker) continue;
const target = entry.animated ? moving : still;
if (entry.drawnIn && entry.drawnIn !== target)
(entry.drawnIn === still ? stillRemovals : movingRemovals).push(
entry.key,
);
entry.drawnIn = target;
(target === still ? stillUpserts : movingUpserts).push(itemOf(entry));
}
dirty.clear();
if (stillRemovals.length) still.remove(stillRemovals);
if (movingRemovals.length) moving.remove(movingRemovals);
if (stillUpserts.length) still.upsert(stillUpserts);
if (movingUpserts.length) moving.upsert(movingUpserts);
stillRemovals.length = 0;
movingRemovals.length = 0;
stillUpserts.length = 0;
movingUpserts.length = 0;
}
/**
* Take a vehicle's marker out of the set it is drawn in: with the others
* taken out in this task, in one removal (a sweep drops many at once).
*/
let flushQueued = false;
function removeMarker(entry) {
dirty.delete(entry);
const set = entry.drawnIn;
entry.drawnIn = null;
if (!set) return;
if (set === state._stillIcons) stillRemovals.push(entry.key);
else if (set === state._movingIcons) movingRemovals.push(entry.key);
else return;
if (flushQueued) return;
flushQueued = true;
queueMicrotask(() => {
flushQueued = false;
flushMarkers();
});
}
/**
* Listen for the camera moving, at this layer's own threshold.
*
@@ -159,7 +310,7 @@ export function createRendering({ state, services, parts }) {
function startFrames(viewer) {
if (!state._preRenderRemove)
state._preRenderRemove =
viewer.scene.preRender.addEventListener(onPreRender);
findFrame(viewer)?.on('preRender', onPreRender) ?? null;
}
/** Stop the per-frame glide. */
@@ -170,23 +321,91 @@ export function createRendering({ state, services, parts }) {
}
}
// The camera's pose and the globe's surface version, read once in a task:
// a sweep, a frame or a poll asks for them per vehicle, and reading them
// walks the camera's frames and the scene's primitives. Forgotten when the
// task ends, and at the start of every frame and visibility sweep.
let viewMemo = null;
let viewMemoQueued = false;
function forgetView() {
viewMemo = null;
}
function viewOf() {
if (viewMemo) return viewMemo;
viewMemo = { pose: undefined, surface: undefined };
if (!viewMemoQueued) {
viewMemoQueued = true;
queueMicrotask(() => {
viewMemoQueued = false;
viewMemo = null;
});
}
return viewMemo;
}
/** The camera port's pose, or null without a camera. */
function cameraPose() {
const view = viewOf();
if (view.pose === undefined)
view.pose = findCamera(state._viewer)?.pose() ?? null;
return view.pose;
}
/**
* The camera's height above the ellipsoid, or Infinity when it has none.
* @returns {number}
*/
function cameraHeightM() {
const carto = state._viewer?.camera?.positionCartographic;
return carto && Number.isFinite(carto.height) ? carto.height : Infinity;
const height = cameraPose()?.height;
return Number.isFinite(height) ? height : Infinity;
}
/** The camera's subpoint in degrees, for the sampler's proximity gate. */
function viewerSubpoint() {
const carto = state._viewer?.camera?.positionCartographic;
if (!carto) return { viewerLat: undefined, viewerLon: undefined };
return {
viewerLat: (carto.latitude * 180) / Math.PI,
viewerLon: (carto.longitude * 180) / Math.PI,
const pose = cameraPose();
if (!pose) return { viewerLat: undefined, viewerLon: undefined };
return { viewerLat: pose.lat, viewerLon: pose.lon };
}
// Whether the globe's terrain is the bare ellipsoid, as the height service
// last said for the surface `surfaceVersion` names; asked again whenever
// that changes, keeping the last answer until the new one comes. A terrain
// height that is only the ellipsoid's is one the service counts as a miss
// when asked to, so the ellipsoid is the point answered plainly and missed
// that way.
let flatVersion = null;
let flatTerrain = false;
function askFlat(globe) {
const view = viewOf();
if (view.surface === undefined)
view.surface = globe.surfaceVersion?.() ?? 0;
const version = view.surface;
if (version === flatVersion) return;
flatVersion = version;
const pose = cameraPose();
const point = {
lon: Number.isFinite(pose?.lon) ? pose.lon : 0,
lat: Number.isFinite(pose?.lat) ? pose.lat : 0,
};
const heights = heightsOf(state._viewer);
Promise.all([
heights.batch([point], { against: 'terrain' }),
heights.batch([point], { against: 'terrain', ellipsoidMisses: true }),
]).then(
([[answered], [terrain]]) => {
if (flatVersion !== version) return;
const flat = answered !== null && terrain === null;
if (flat === flatTerrain) return;
flatTerrain = flat;
// Floors read under the last answer are read again under this one,
// in a fresh cycle (which replaces the one pending).
if (state._enabled) parts.height.anchorFloors?.();
},
() => {
// Asked again at the next read.
if (flatVersion === version) flatVersion = null;
},
);
}
/**
@@ -195,44 +414,36 @@ export function createRendering({ state, services, parts }) {
* @returns {'none'|'flat'|'terrain'}
*/
function globeSurface() {
if (state._viewer?.scene?.globe?.show !== true) return 'none';
return state._viewer?.terrainProvider instanceof
Cesium.EllipsoidTerrainProvider
? 'flat'
: 'terrain';
const globe = findGlobe(state._viewer);
if (globe?.isGlobeVisible?.() !== true) return 'none';
askFlat(globe);
return flatTerrain ? 'flat' : 'terrain';
}
/**
* Sample the rendered mesh under floor cells, seeing through these
* vehicles' billboards.
* Sample the rendered mesh under floor cells, seeing through this layer's
* own sets.
* @param {object[]} cells
* @param {object[]} entries
*/
function sampleMeshFloors(cells, entries) {
function sampleMeshFloors(cells) {
if (!sampleMeshFloorCells) return;
const markers = entries.map((entry) => entry.marker).filter(Boolean);
const sets = setIds();
for (let i = 0; i < cells.length; i += 8)
sampleMeshFloorCells(state._viewer?.scene, cells.slice(i, i + 8), {
excludeObjects: markers,
sampleMeshFloorCells(state._viewer, cells.slice(i, i + 8), {
sets,
...viewerSubpoint(),
});
}
/**
* Cartesian position for a lat/lon at a height. Called on POLL, not per
* frame: `fromDegrees` runs trigonometry, and doing that for every vehicle on
* ECEF position for a lat/lon at a height. Called on POLL, not per frame:
* the conversion runs trigonometry, and doing that for every vehicle on
* every frame was most of what made this layer heavy.
*/
function cartesianFor(lat, lon, heightM, out) {
function cartesianFor(lat, lon, heightM, out = { x: 0, y: 0, z: 0 }) {
// `heightM` already carries the shared floor's own lift, so nothing is
// added here: two lifts stacked is a vehicle hovering.
return Cesium.Cartesian3.fromDegrees(
lon,
lat,
heightM || 0,
undefined,
out,
);
return fromDegreesInto(lon, lat, heightM || 0, out);
}
/** Heights are aligned to work with Google 3D tiles. Rebuild both ends. */
@@ -244,13 +455,13 @@ export function createRendering({ state, services, parts }) {
entry.from.lat,
entry.from.lon,
entry.from.h,
entry.fromCart || new Cesium.Cartesian3(),
entry.fromCart || { x: 0, y: 0, z: 0 },
);
entry.toCart = cartesianFor(
entry.to.lat,
entry.to.lon,
entry.to.h,
entry.toCart || new Cesium.Cartesian3(),
entry.toCart || { x: 0, y: 0, z: 0 },
);
entry.endpointRevision = entry.sample.revision;
entry.endpointFromSeq = entry.sample.fromSeq;
@@ -271,9 +482,16 @@ export function createRendering({ state, services, parts }) {
);
entry.surfaceReady = !!known;
entry.heightPending = !known;
entry.marker.show = !!known && vehicleInView(entry);
setShown(entry, !!known && vehicleInView(entry));
if (known) {
entry.marker.position = state._scratchCartesian;
const p = entry.marker.position;
const s = state._scratchCartesian;
if (p.x !== s.x || p.y !== s.y || p.z !== s.z) {
p.x = s.x;
p.y = s.y;
p.z = s.z;
dirty.add(entry);
}
entry.hasRendered = true;
}
}
@@ -288,29 +506,12 @@ export function createRendering({ state, services, parts }) {
if (entry.wakeTimer != null) clearTimeout(entry.wakeTimer);
entry.wakeTimer = null;
}
/** Draw a marker in the moving set, or the still one. */
function migrateMarker(entry, animated) {
const collection = animated ? state._animatedMarkers : state._markers;
if (!entry.marker || entry.markerCollection === collection) return;
const old = entry.marker;
const marker = collection.add({
id: entry.key,
position: old.position,
image: old.image,
width: old.width,
height: old.height,
color: old.color,
scaleByDistance: old.scaleByDistance,
rotation: old.rotation,
alignedAxis: old.alignedAxis,
show: old.show,
disableDepthTestDistance: old.disableDepthTestDistance,
});
entry.markerCollection.remove(old);
entry.marker = marker;
entry.markerCollection = collection;
if (!entry.marker || entry.animated === animated) return;
entry.animated = animated;
entry.markerRevision = (entry.markerRevision || 0) + 1;
// Cached contacts and card getters must follow the replacement billboard.
if (entry.detectContact) entry.detectContact.position = marker.position;
dirty.add(entry);
}
function schedulePlayback(entry) {
cancelWake(entry);
@@ -346,6 +547,7 @@ export function createRendering({ state, services, parts }) {
updatePlayback(entry, Date.now(), performance.now());
placeSample(entry);
schedulePlayback(entry);
flushMarkers();
syncRenderHold();
governorRequestRender('transit-motion-boundary');
},
@@ -365,7 +567,7 @@ export function createRendering({ state, services, parts }) {
return state._visible.has(entry);
}
/** Cesium colour for a preset tuple, cached per profile+mode. */
/** A preset tuple as a colour (0..1 channels), cached per profile+mode. */
const _presetColors = new Map();
function presetColor(style, mode) {
const rgba = presetSpriteRgba(style, mode);
@@ -373,12 +575,12 @@ export function createRendering({ state, services, parts }) {
const key = `${transitStyleProfile(style)}:${mode}`;
let color = _presetColors.get(key);
if (!color) {
color = new Cesium.Color(
color = Object.freeze([
rgba[0] / 255,
rgba[1] / 255,
rgba[2] / 255,
rgba[3],
);
]);
_presetColors.set(key, color);
}
return color;
@@ -416,28 +618,27 @@ export function createRendering({ state, services, parts }) {
entry.detectContact.bracketHalfWidth = Math.ceil(px / 2) + 2;
entry.detectContact.bracketHalfHeight = Math.ceil(px / 2) + 2;
}
const preset = presetColor(style, entry.mode);
if (preset) marker.color = preset;
else
marker.color =
MODE_CESIUM_COLORS[entry.mode] || MODE_CESIUM_COLORS.unknown;
marker.color =
presetColor(style, entry.mode) ||
TRANSIT_MODE_COLORS[entry.mode] ||
TRANSIT_MODE_COLORS.unknown;
dirty.add(entry);
}
function addMarker(key, entry) {
const marker = state._markers.add({
id: key,
position: entry.toCart,
const at = entry.toCart;
const marker = {
position: { x: at?.x ?? 0, y: at?.y ?? 0, z: at?.z ?? 0 },
show: false,
image: transitIcon(entry.mode),
width: MARKER_PIXEL_SIZE,
height: MARKER_PIXEL_SIZE,
color: MODE_CESIUM_COLORS[entry.mode],
color: TRANSIT_MODE_COLORS[entry.mode],
rotation: 0,
alignedAxis: Cesium.Cartesian3.ZERO,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
});
};
entry.marker = marker;
entry.markerCollection = state._markers;
marker.show = false;
entry.animated = false;
entry.drawnIn = null;
applySpriteStyle(entry);
return marker;
}
@@ -462,14 +663,29 @@ export function createRendering({ state, services, parts }) {
if (next === state._stylePreset) return;
state._stylePreset = next;
for (const entry of state._vehicles.values()) applySpriteStyle(entry);
flushMarkers();
parts.trails.style();
governorRequestRender('transit-style');
}
/**
* The screen rotation that points a marker along `course`, projected
* exactly through the query port (see `perspectiveCourseRotation`).
*/
function courseRotation(query, pose, position, course, previous) {
return perspectiveCourseRotation(
query.project,
pose,
position,
course,
previous,
);
}
/**
* Point every glyph along its reported course.
*
* Billboards are camera-facing quads, so a course has to be projected into
* Icons are camera-facing quads, so a course has to be projected into
* screen space — which depends on where the camera is, not only on the
* vehicle. Doing that for the whole fleet on every frame is exactly the kind
* of cost that made this layer heavy, and it buys nothing: a bus icon whose
@@ -478,17 +694,18 @@ export function createRendering({ state, services, parts }) {
* changed somebody's heading.
*/
function refreshRotations(now) {
const scene = state._viewer?.scene;
if (!scene?.camera) return;
if (now - state._rotationAt < ROTATION_REFRESH_MS) return;
const pose = cameraPose();
const query = findQuery(state._viewer);
if (!pose?.position || !query) return;
state._rotationAt = now;
const pose = cameraPoseSignature(scene.camera);
const signature = poseSignature(pose);
const cameraChanged =
state._rotationPose !== pose ||
state._rotationPose !== signature ||
state._rotationRevision !== state._cameraRevision;
if (!cameraChanged && !state._rotationDirty && state._moving.size === 0)
return;
state._rotationPose = pose;
state._rotationPose = signature;
state._rotationRevision = state._cameraRevision;
state._rotationDirty = false;
const monoNow = performance.now();
@@ -496,13 +713,15 @@ export function createRendering({ state, services, parts }) {
// Idle contacts still need a course when their first usable bearing arrives.
if (!state._moving.has(entry)) applyDisplayCourse(entry, monoNow);
if (entry.key === state._selectedKey) continue;
const marker = entry.marker;
const course = entry.courseDeg;
if (!Number.isFinite(course)) {
entry.marker.rotation = 0;
if (marker.rotation !== 0) dirty.add(entry);
marker.rotation = 0;
entry.rotationCourse = null;
continue;
}
const position = entry.marker.position;
const position = marker.position;
if (
!cameraChanged &&
entry.rotationCourse === course &&
@@ -520,12 +739,17 @@ export function createRendering({ state, services, parts }) {
// camera-basis helper aircraft use is orthographic — fine at altitude,
// and wrong by twenty-odd degrees for a street-level contact away from
// the centre of an obliquely pitched view, which is most of them.
entry.marker.rotation = perspectiveProjectedRotation(
scene,
entry.marker.position,
const rotation = courseRotation(
query,
pose,
position,
course,
entry.marker.rotation,
marker.rotation,
);
if (rotation !== marker.rotation) {
marker.rotation = rotation;
dirty.add(entry);
}
}
}
@@ -559,6 +783,7 @@ export function createRendering({ state, services, parts }) {
)
return;
if (!state._enabled) return;
forgetView();
const now = Date.now();
if (state._vehicles.size === 0) {
state._moving.clear();
@@ -598,23 +823,31 @@ export function createRendering({ state, services, parts }) {
refreshRotations(now);
const selected = state._vehicles.get(state._selectedKey);
if (selected && state._visible.has(selected)) {
selected.marker.rotation = Number.isFinite(selected.courseDeg)
? perspectiveProjectedRotation(
state._viewer.scene,
selected.marker.position,
const marker = selected.marker;
const pose = Number.isFinite(selected.courseDeg) ? cameraPose() : null;
const query = pose?.position ? findQuery(state._viewer) : null;
const rotation = query
? courseRotation(
query,
pose,
marker.position,
selected.courseDeg,
selected.marker.rotation,
marker.rotation,
)
: 0;
: Number.isFinite(selected.courseDeg)
? marker.rotation
: 0;
if (rotation !== marker.rotation) {
marker.rotation = rotation;
dirty.add(selected);
}
}
flushMarkers();
if (state._heightDirty.size) governorRequestRender('transit-height-batch');
syncRenderHold();
}
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84);
const sphere = new Cesium.BoundingSphere(undefined, 5);
const cameraPosition = new Cesium.Cartesian3();
const candidatePosition = new Cesium.Cartesian3();
const candidatePosition = { x: 0, y: 0, z: 0 };
/** Visibility work runs off the frame path, coalesced at four sweeps/second. */
function requestVisibility() {
state._visibilityDirty = true;
@@ -627,6 +860,24 @@ export function createRendering({ state, services, parts }) {
Math.max(0, VISIBILITY_REFRESH_MS - (Date.now() - state._visibilityAt)),
);
}
/**
* The planes of the frustum the camera looks through, as the default
* renderer culls with them, or null when the pose does not describe one.
*/
function viewPlanes(pose) {
if (
!pose?.position ||
!pose.direction ||
!pose.up ||
!Number.isFinite(pose.fovy) ||
!Number.isFinite(pose.aspectRatio) ||
!Number.isFinite(pose.near)
)
return null;
return frustumPlanes(pose);
}
function refreshVisibility() {
if (!state._enabled) return 0;
const now = Date.now();
@@ -636,33 +887,22 @@ export function createRendering({ state, services, parts }) {
}
state._visibilityAt = now;
state._visibilityDirty = false;
const viewer = state._viewer,
camera = viewer?.camera;
if (!camera) return 0;
const position =
camera.positionWC ||
Cesium.Ellipsoid.WGS84.cartographicToCartesian(
camera.positionCartographic,
cameraPosition,
);
occluder.cameraPosition = position;
const frustum = camera.frustum?.computeCullingVolume(
position,
camera.directionWC,
camera.upWC,
);
const planes = frustum?.planes;
forgetView();
const pose = cameraPose();
if (!pose) return 0;
const query = findQuery(state._viewer);
const planes = viewPlanes(pose);
let changed = false;
for (const entry of state._vehicles.values()) {
if (!entry.marker) continue;
// Refresh hidden clocks before testing admission, even if no frame has
// ever sampled them. Do not write the billboard until it is admitted.
// ever sampled them. Do not write the marker until it is admitted.
const noSample = !entry.sample || !Number.isFinite(entry.sample.lat);
if (entry.track?.count && (!state._visible.has(entry) || noSample)) {
entry.sample ||= {};
updatePlayback(entry, now, performance.now());
}
sphere.center =
const center =
state._visible.has(entry) || !entry.sample
? entry.marker.position
: cartesianFor(
@@ -675,24 +915,24 @@ export function createRendering({ state, services, parts }) {
// view. The current frustum is authoritative; the horizon still rejects
// the far side when the rectangle is missing or stale.
const bounds = vehicleNearView(state._viewBounds, entry);
const horizon = occluder.isPointVisible(sphere.center);
const horizon = !(query?.isOccluded(center) ?? false);
let inFrustum = true;
if (planes) {
for (let i = 0; i < planes.length; i++) {
const p = planes[i],
c = sphere.center;
if (p.x * c.x + p.y * c.y + p.z * c.z + p.w < -sphere.radius) {
const { normal: n, w } = planes[i];
if (
n.x * center.x + n.y * center.y + n.z * center.z + w <
-CULL_RADIUS_M
) {
inFrustum = false;
break;
}
}
} else if (frustum)
inFrustum =
frustum.computeVisibility(sphere) !== Cesium.Intersect.OUTSIDE;
const visible = (frustum || bounds) && horizon && inFrustum;
}
const visible = (planes || bounds) && horizon && inFrustum;
const visibility = (entry.visibility ||= {});
visibility.bounds = bounds;
visibility.boundsApplied = !frustum;
visibility.boundsApplied = !planes;
visibility.occluder = horizon;
visibility.frustum = inFrustum;
visibility.noSample = noSample;
@@ -713,13 +953,18 @@ export function createRendering({ state, services, parts }) {
placeSample(entry);
}
}
entry.marker.show =
visible && !entry.heightPending && entry.surfaceReady !== false;
setShown(
entry,
Boolean(
visible && !entry.heightPending && entry.surfaceReady !== false,
),
);
visibility.heightPending = !!entry.heightPending;
visibility.surfaceReady = entry.surfaceReady ?? null;
schedulePlayback(entry);
changed ||= visible !== wasVisible || wasShown !== entry.marker.show;
}
flushMarkers();
state._shownCount = state._visible.size;
if (changed) state._detectRevision++;
syncRenderHold();
@@ -740,6 +985,7 @@ export function createRendering({ state, services, parts }) {
placeSample(entry);
schedulePlayback(entry);
}
flushMarkers();
parts.trails.update();
parts.selection.refreshSelectedCard(true);
state._detectRevision++;
@@ -758,6 +1004,7 @@ export function createRendering({ state, services, parts }) {
function paintSelected(entry, selected) {
void selected; // decided from state._selectedKey, which the caller has set
applySpriteStyle(entry);
flushMarkers();
}
let stopProbe = null;
@@ -766,60 +1013,30 @@ export function createRendering({ state, services, parts }) {
stopProbe?.();
}
/** Measure inside Cesium postRender with fixed typed storage; no sample objects per frame. */
function measureFrames(durationMs = 12000) {
/**
* Measure inside the renderer's frames with fixed typed storage; no sample
* objects per frame. `uploads`, when given, counts the bytes the
* renderer uploads for this layer's sets each frame (the Cesium one's is
* `src/render/cesium/uploadProbe.js`, which QA hands in): `reset()` at
* each frame's start, `bytes()` at its end, `stop()` when done.
* @param {number} [durationMs]
* @param {{reset: () => void, bytes: () => number, stop: () => void}|null} [uploads]
*/
function measureFrames(durationMs = 12000, uploads = null) {
stopProbe?.();
const scene = state._viewer.scene;
const frame = findFrame(state._viewer);
const canvas = canvasOf(state._viewer);
const capacity = 20000,
stride = 12,
data = new Float64Array(capacity * stride);
const previousPositions = new Float64Array(state._vehicles.size * 3);
const gl = webglContext(scene);
let active = false,
upload = 0,
cpu = 0,
let cpu = 0,
count = 0,
previous = 0;
const saved = [];
for (const name of ['bufferData', 'bufferSubData']) {
const original = gl[name];
gl[name] = function (...args) {
if (active) {
const value = args[name === 'bufferData' ? 1 : 2];
const offset = args[name === 'bufferData' ? 3 : 3] || 0;
const length = args[4];
upload +=
typeof value === 'number'
? value
: value
? length !== undefined
? length * (value.BYTES_PER_ELEMENT || 1)
: value.byteLength - offset * (value.BYTES_PER_ELEMENT || 1)
: 0;
}
return original.apply(this, args);
};
saved.push(() => {
gl[name] = original;
});
}
for (const collection of [state._markers, state._animatedMarkers]) {
const original = collection.update;
collection.update = function (frame) {
active = true;
try {
return original.call(this, frame);
} finally {
active = false;
}
};
saved.push(() => {
collection.update = original;
});
}
state._preRenderRemove?.();
const removePre = scene.preRender.addEventListener(() => {
upload = 0;
const wasRunning = state._preRenderRemove !== null;
stopFrames();
const removePre = frame.on('preRender', () => {
uploads?.reset();
const start = performance.now();
onPreRender();
cpu = performance.now() - start;
@@ -830,10 +1047,8 @@ export function createRendering({ state, services, parts }) {
clearTimeout(timer);
removePre();
removePost?.();
for (const restore of saved) restore();
if (state._enabled)
state._preRenderRemove =
scene.preRender.addEventListener(onPreRender);
uploads?.stop();
if (wasRunning && state._enabled) startFrames(state._viewer);
stopProbe = null;
const rows = [];
for (let i = 1; i < count; i++) {
@@ -854,12 +1069,12 @@ export function createRendering({ state, services, parts }) {
resolve({
rows,
dpr: devicePixelRatio,
width: scene.canvas.clientWidth,
height: scene.canvas.clientHeight,
width: canvas?.clientWidth,
height: canvas?.clientHeight,
});
};
stopProbe = finish;
removePost = scene.postRender.addEventListener(() => {
removePost = frame.on('postRender', () => {
const now = performance.now();
if (count >= capacity) return;
const k = count++ * stride;
@@ -867,7 +1082,7 @@ export function createRendering({ state, services, parts }) {
data[k] = previous ? now - previous : 0;
previous = now;
data[k + 1] = cpu;
data[k + 2] = upload;
data[k + 2] = uploads ? uploads.bytes() : 0;
let actuallyMoved = 0;
for (const vehicle of state._visible) {
const p = vehicle.marker.position,
@@ -905,7 +1120,13 @@ export function createRendering({ state, services, parts }) {
showMarkers,
clearMarkers,
destroyMarkers,
setIds,
ownsSet,
setNameOf,
markerShown,
markDirty,
flushMarkers,
removeMarker,
watchCamera,
unwatchCamera,
startFrames,
+10 -31
View File
@@ -119,42 +119,21 @@ export function createSelection({ state, services, parts }) {
// (src/input/sensorPick.js) and skips it while a tool holds the pointer.
state._clickSubscription = inputFor(viewer).onClick((event) => {
const position = event.position;
const picked = event.pick;
// The collection of the marker picked: the one its vehicle's marker is
// in, when the pick is one of this layer's markers.
const owner = state._vehicles.get(picked?.primitive?.id);
const collection =
owner && owner.marker === picked.primitive
? owner.markerCollection
: null;
// A marker is an item of one of this layer's two sets, by its key.
const hit = event.drawHit;
const set = parts.rendering.setNameOf(hit?.set);
const key = set && state._vehicles.has(hit.id) ? hit.id : null;
state._lastPickForTest = {
id: typeof picked?.id === 'string' ? picked.id : null,
primitiveId:
typeof picked?.primitive?.id === 'string'
? picked.primitive.id
: null,
id: key,
set: hit?.set ?? null,
x: position.x,
y: position.y,
collection:
collection && collection === state._animatedMarkers
? 'animated'
: collection && collection === state._markers
? 'stationary'
: null,
set === 'moving' ? 'animated' : set === 'still' ? 'stationary' : null,
};
if (picked) {
const primitiveId = picked.primitive?.id;
if (
typeof primitiveId === 'string' &&
state._vehicles.has(primitiveId)
) {
selectVehicle(primitiveId);
return;
}
if (typeof picked.id === 'string' && state._vehicles.has(picked.id)) {
selectVehicle(picked.id);
return;
}
if (key) {
selectVehicle(key);
return;
}
if (state._selectedKey) clearSelection();
});
+10 -4
View File
@@ -23,9 +23,14 @@ export function createState({ services }) {
/** The viewer the layer draws on, or null. */
state._viewer = null;
/** The stationary markers' billboard collection, or null. */
state._markers = null;
state._animatedMarkers = null;
/** The still markers' icon draw set, and the moving ones', or null. */
state._stillIcons = null;
state._movingIcons = null;
/** Their sprite-order registrations. */
state._stillSprite = null;
state._movingSprite = null;
/** Whether the markers are shown (the layer is on). */
state._markersShown = false;
state._visible = new Set();
state._visibilityTimer = null;
state._maintenanceTimer = null;
@@ -119,7 +124,8 @@ export function createState({ services }) {
state._error = null;
state._limitWarned = false;
// Where `samplePosition` writes a marker's position, each frame.
// Where `samplePosition` writes a marker's position, each frame, before
// it is copied into the marker.
state._scratchCartesian = { x: 0, y: 0, z: 0 };
return state;
+13 -3
View File
@@ -108,6 +108,7 @@ export function createTesting({ state, parts }) {
updatePlayback(entry, now, mono);
parts.rendering.placeSample(entry);
}
parts.rendering.flushMarkers();
clearTimeout(state._floorTimer);
state._floorTimer = null;
// Establish the fixture clock without the live re-entry reset.
@@ -147,11 +148,20 @@ export function createTesting({ state, parts }) {
parts.rendering.placeSample(entry);
parts.rendering.schedulePlayback(entry);
}
parts.rendering.flushMarkers();
parts.rendering.syncRenderHold();
},
/** Measure inside the renderer's frames with fixed typed storage. */
_measureTransitFramesForTest(durationMs = 12000) {
return parts.rendering.measureFrames(durationMs);
/**
* Measure inside the renderer's frames with fixed typed storage;
* `uploads` counts what the renderer uploads for the markers' sets
* (`src/render/cesium/uploadProbe.js` on the default renderer).
*/
_measureTransitFramesForTest(durationMs = 12000, uploads = null) {
return parts.rendering.measureFrames(durationMs, uploads);
},
/** The ids of the markers' two draw sets: still, then moving. */
_transitSetIdsForTest() {
return parts.rendering.setIds();
},
_transitVisibilityForTest() {
return [...state._vehicles.values()].map((entry) => {
+157
View File
@@ -949,6 +949,113 @@ export function createCesiumDraw({
return look;
}
/**
* What a billboard draws of an icon item but its position, image, `meta`
* and `lodGroup`, as plain values: the course rotation follows the
* position, so it is written with it.
*/
function iconStyleOf(record, item) {
const color = item.color;
const curve = (c) =>
c ? [c.near, c.nearValue, c.far, c.farValue] : undefined;
return {
width: item.size[0],
height: item.size[1],
scale: item.scale,
color:
Array.isArray(color) || ArrayBuffer.isView(color) ? [...color] : color,
alpha: item.alpha,
focus: item.focus,
anchor: item.anchor,
disableDepthTest: item.disableDepthTest,
heightMode: item.height,
clampTo: record.spec.clampTo,
show: item.show,
displayRange: item.displayRange ? [...item.displayRange] : undefined,
scaleByDistance: curve(item.scaleByDistance),
fadeByDistance: curve(item.fadeByDistance),
rotationMode: item.rotationMode,
rotation: item.rotation,
course: item.course,
};
}
/** Two lists, or two missing ones, alike element by element. */
function sameList(a, b) {
if (!a || !b) return a === b;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
/** A curve as `iconStyleOf` keeps it, and one as an item gives it. */
function sameCurve(a, c) {
return !a || !c
? !a && !c
: a[0] === c.near &&
a[1] === c.nearValue &&
a[2] === c.far &&
a[3] === c.farValue;
}
/**
* Whether `item` draws as `style` (`iconStyleOf`) says, but its position
* and, turned on screen, its rotation (`moveIcon` writes both).
*/
function sameIconStyle(style, record, item) {
const color = item.color;
return (
style.width === item.size[0] &&
style.height === item.size[1] &&
style.scale === item.scale &&
(Array.isArray(color) || ArrayBuffer.isView(color)
? Array.isArray(style.color) && sameList(style.color, color)
: style.color === color) &&
style.alpha === item.alpha &&
style.focus === item.focus &&
style.anchor === item.anchor &&
style.disableDepthTest === item.disableDepthTest &&
style.heightMode === item.height &&
style.clampTo === record.spec.clampTo &&
style.show === item.show &&
sameList(style.displayRange, item.displayRange) &&
sameCurve(style.scaleByDistance, item.scaleByDistance) &&
sameCurve(style.fadeByDistance, item.fadeByDistance) &&
style.rotationMode === item.rotationMode &&
(item.rotationMode === 'screen' || style.rotation === item.rotation) &&
style.course === item.course
);
}
const movedEnu = new Cesium.Matrix4();
const movedAxis = new Cesium.Cartesian3();
/**
* Move a drawn icon whose look is unchanged (`sameIconStyle`): its
* position, the course rotation that follows it or the screen rotation
* it is given, and its pick record.
*/
function moveIcon(record, entry, item) {
const { billboard, placed } = entry;
const position = toCartesianInto(item.pos, placed.position);
billboard.position = position;
if (item.rotationMode === 'course') {
Cesium.Transforms.eastNorthUpToFixedFrame(position, undefined, movedEnu);
// The billboard copies the axis it is given.
billboard.alignedAxis = Cesium.Matrix4.multiplyByPointAsVector(
movedEnu,
Cesium.Cartesian3.UNIT_Y,
movedAxis,
);
}
if (item.rotationMode === 'screen') {
billboard.rotation = item.rotation ?? 0;
entry.style.rotation = item.rotation;
}
billboard.id.meta = item.meta;
billboard.id.lodGroup = item.lodGroup;
billboard.show = shownNow(record, placed);
}
/** Give a billboard its image: a generated one under its key. */
function setIconImage(record, billboard, image) {
if (isKeyed(image)) billboard.setImage(image.key, image.canvas);
@@ -971,6 +1078,8 @@ export function createCesiumDraw({
placed,
image: imageKeyOf(image),
canvas: image?.canvas,
// What it is drawn as, for `patchIcon`'s quick path.
style: iconStyleOf(record, item),
});
}
@@ -982,6 +1091,17 @@ export function createCesiumDraw({
*/
function patchIcon(record, entry, item, image) {
const { billboard, placed } = entry;
// Drawn as it was but for where it is: only that is written, so a set
// whose icons move every frame costs little more than the moves.
if (
entry.style &&
imageKeyOf(image) === entry.image &&
sameIconStyle(entry.style, record, item)
) {
moveIcon(record, entry, item);
return;
}
entry.style = iconStyleOf(record, item);
const position = toCartesian(item.pos);
const look = iconLook(record, item, position);
// Sized first: a new SVG image rasterises at the billboard's size.
@@ -1000,6 +1120,42 @@ export function createCesiumDraw({
billboard.show = shownNow(record, placed);
}
/**
* `syncIcons`' quick case: every item is drawn, every touched one keeps
* the image it is drawn with, and nothing drawn has gone, so each touched
* one is changed where it is and nothing is added, removed or reordered.
* False, changing nothing, otherwise.
* @param {object} record
* @param {readonly string[]} touched
*/
function patchDrawnIcons(record, touched) {
const drawn = record.billboards;
// Nothing to remove: every item drawn, and nothing drawn but items.
if (
!Array.isArray(touched) ||
touched.length === 0 ||
drawn.size !== record.items.size
)
return false;
for (const id of touched) {
const entry = drawn.get(id);
const item = record.items.get(id);
if (!entry || !item) return false;
const image = iconImage(record, item.image);
if (
image === undefined ||
imageKeyOf(image) !== entry.image ||
(isKeyed(image) && image.canvas !== entry.canvas)
)
return false;
}
for (const id of touched) {
const item = record.items.get(id);
patchIcon(record, drawn.get(id), item, iconImage(record, item.image));
}
return true;
}
/**
* Bring an icon set's billboards in line with its items without a
* rebuild: those of items gone (or whose image is gone) are removed, the
@@ -1029,6 +1185,7 @@ export function createCesiumDraw({
host.isDestroyed()
)
return false;
if (!reordered && patchDrawnIcons(record, touched)) return ICONS_KEPT;
const images = new Map();
for (const id of touched) {
const item = record.items.get(id);
+213 -4
View File
@@ -1963,7 +1963,10 @@ test('the installations layer draws its site dots, outlines and selected dot on
rendering.renderRecords();
const after = billboards(dotsId);
assert.equal(after.length, 2);
assert.ok(after.every((dot, i) => dot === dots[i]), 'the same billboards');
assert.ok(
after.every((dot, i) => dot === dots[i]),
'the same billboards',
);
assert.equal(after.find((dot) => dot.id.id === 'b').show, false);
assert.equal(after.find((dot) => dot.id.id === 'a').show, true);
const [selected] = billboards(state.sets.selected.id);
@@ -2020,9 +2023,7 @@ test('the satellites layer draws its dots as one point collection and its rings
assert.equal(points.get(0), iss);
assert.equal(iss.position.x, 6.9e6);
withImageClasses(() =>
rendering._showOrbitPath(25544, TRACKED_ORBIT_COLOR),
);
withImageClasses(() => rendering._showOrbitPath(25544, TRACKED_ORBIT_COLOR));
const all = (host) =>
host instanceof Cesium.PrimitiveCollection
? Array.from({ length: host.length }, (_, i) => all(host.get(i))).flat()
@@ -6460,3 +6461,211 @@ test('the recent imagery box preview drags its ground fill and dashed edge frame
);
assert.equal(await destroyed, 0, 'both sets let go');
});
test('icons that only move are moved on the billboards they have, and still restyle', () => {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.icons({ id: 'icons:moving' });
const icon = (lon, extra = {}) => ({
id: 'a',
pos: Cesium.Cartesian3.fromDegrees(lon, 10, 20),
image: 'a.png',
size: [20, 20],
color: [1, 0, 0, 1],
rotationMode: 'screen',
rotation: 0.25,
disableDepthTest: Infinity,
meta: { lon },
...extra,
});
set.set([icon(0), { ...icon(5), id: 'b' }]);
const [host] = scene.added;
const a = host.get(0);
const version = part.version();
// Only moved: its look is not written again.
let restyles = 0;
const width = Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(a),
'width',
);
Object.defineProperty(a, 'width', {
get: width.get,
set(value) {
restyles += 1;
width.set.call(this, value);
},
configurable: true,
});
for (const lon of [1, 2, 3]) set.upsert([icon(lon)]);
assert.equal(restyles, 0, 'moved, not restyled');
assert.equal(scene.added[0], host, 'the same collection');
assert.equal(host.get(0), a, 'the same billboard');
const at = Cesium.Cartographic.fromCartesian(a.position);
assert.ok(Math.abs(Cesium.Math.toDegrees(at.longitude) - 3) < 1e-9);
assert.ok(Math.abs(at.height - 20) < 1e-6);
assert.equal(a.rotation, 0.25);
assert.ok(Cesium.Color.equals(a.color, Cesium.Color.RED));
assert.deepEqual(a.id.meta, { lon: 3 }, 'picks read the latest meta');
assert.equal(part.version(), version, 'nothing added or removed');
// A look that changes after moves is drawn, then moves go on from it.
set.upsert([icon(3, { color: [0, 1, 0, 1], rotation: 1, size: [30, 30] })]);
assert.equal(restyles, 1, 'restyled once');
assert.ok(Cesium.Color.equals(a.color, Cesium.Color.LIME));
assert.equal(a.rotation, 1);
assert.equal(a.width, 30);
set.upsert([icon(4, { color: [0, 1, 0, 1], rotation: 1, size: [30, 30] })]);
assert.ok(Cesium.Color.equals(a.color, Cesium.Color.LIME));
assert.equal(a.width, 30);
const moved = Cesium.Cartographic.fromCartesian(a.position);
assert.ok(Math.abs(Cesium.Math.toDegrees(moved.longitude) - 4) < 1e-9);
// Turning on screen as it moves is written with the move, not restyled.
set.upsert([icon(5, { color: [0, 1, 0, 1], rotation: 2, size: [30, 30] })]);
assert.equal(restyles, 1, 'a screen turn is not a restyle');
assert.equal(a.rotation, 2);
set.upsert([icon(5, { color: [0, 1, 0, 1], rotation: 2, size: [31, 30] })]);
assert.equal(restyles, 2, 'a new size still restyles');
assert.equal(a.rotation, 2);
// A course-turned icon's axis follows where it moves.
const course = (lon) =>
icon(lon, { rotationMode: 'course', course: 90, rotation: undefined });
set.upsert([course(4)]);
set.upsert([course(60)]);
const north = Cesium.Matrix4.multiplyByPointAsVector(
Cesium.Transforms.eastNorthUpToFixedFrame(
Cesium.Cartesian3.fromDegrees(60, 10, 20),
),
Cesium.Cartesian3.UNIT_Y,
new Cesium.Cartesian3(),
);
assert.ok(Cesium.Cartesian3.equalsEpsilon(a.alignedAxis, north, 1e-12));
assert.equal(a.rotation, -Cesium.Math.toRadians(90));
// Hidden in place, while it moves.
set.upsert([{ ...course(61), show: false }]);
assert.equal(a.show, false);
set.upsert([{ ...course(62), show: false }]);
assert.equal(a.show, false);
set.upsert([course(63)]);
assert.equal(a.show, true);
set.dispose();
});
test('the transit layer draws its vehicles as two icon sets, moving a marker between them, on a viewer of its own', async () => {
const { createRendering } = await import('../../layers/transit/rendering.js');
const { createState } = await import('../../layers/transit/state.js');
const scene = fakeScene();
const viewer = { scene };
const noop = () => {};
const registered = [];
const services = {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
render: {
governorRequestRender: noop,
holdContinuousRender: noop,
releaseContinuousRender: noop,
},
sprites: {
registerSpriteSet: (layerId, setId) => {
const entry = { drawSetId: setId };
registered.push([layerId, setId]);
return entry;
},
unregisterSpriteCollection: noop,
},
};
const state = createState({ services });
state._viewer = viewer;
const rendering = createRendering({
state,
services,
parts: { height: { nearGround: () => false }, trails: { update: noop } },
});
rendering.createMarkers(viewer);
const [stillId, movingId] = rendering.setIds();
assert.deepEqual(registered, [
['transit', stillId],
['transit-motion', movingId],
]);
const hostOf = (setId) => scene.added.find((h) => h.drawSetId === setId);
assert.ok(hostOf(stillId) instanceof Cesium.BillboardCollection);
assert.ok(hostOf(movingId) instanceof Cesium.BillboardCollection);
assert.equal(hostOf(stillId).show, false, 'hidden until the layer shows');
rendering.showMarkers();
const at = Cesium.Cartesian3.fromDegrees(-71.06, 42.36, 12);
const entry = { key: 'mbta:bus', mode: 'bus', toCart: at };
rendering.addMarker(entry.key, entry);
entry.marker.show = true;
entry.marker.rotation = 0.5;
rendering.markDirty(entry);
rendering.flushMarkers();
const still = hostOf(stillId);
assert.equal(still.length, 1);
const billboard = still.get(0);
assert.equal(billboard.id.set, stillId);
assert.equal(billboard.id.id, entry.key);
assert.deepEqual(billboard.id.meta, { layer: 'transit', key: entry.key });
assert.ok(Cesium.Cartesian3.equalsEpsilon(billboard.position, at, 0, 1e-6));
assert.equal(billboard.rotation, 0.5);
assert.equal(billboard.show, true);
assert.equal(billboard.disableDepthTestDistance, Number.POSITIVE_INFINITY);
assert.equal(billboard.width, entry.marker.width);
assert.equal(
rendering.setNameOf(
drawHitOf({ primitive: billboard, id: billboard.id }).set,
),
'still',
);
// Moving it moves the billboard it has.
entry.marker.position.z += 10;
rendering.markDirty(entry);
rendering.flushMarkers();
assert.equal(still.get(0), billboard);
assert.ok(Math.abs(billboard.position.z - (at.z + 10)) < 1e-6);
// Starting to move takes it to the moving set and out of the still one.
entry.animated = true;
rendering.markDirty(entry);
rendering.flushMarkers();
const moving = hostOf(movingId);
assert.equal(moving.length, 1);
assert.equal(moving.get(0).id.id, entry.key);
assert.equal(moving.get(0).id.set, movingId);
const stillNow = hostOf(stillId);
const keysInStill = [];
for (let i = 0; i < stillNow.length; i += 1)
keysInStill.push(stillNow.get(i).id?.id);
assert.deepEqual(keysInStill, [], 'no longer drawn in the still set');
// Markers taken out in one task go in one removal, at its end.
const other = { key: 'mbta:tram', mode: 'tram', toCart: at };
rendering.addMarker(other.key, other);
other.animated = true;
rendering.markDirty(other);
rendering.flushMarkers();
assert.equal(moving.length, 2);
const removals = [];
const remove = state._movingIcons.remove;
state._movingIcons.remove = function (ids) {
removals.push([...ids]);
return remove.call(this, ids);
};
rendering.removeMarker(entry);
rendering.removeMarker(other);
assert.equal(removals.length, 0, 'not yet');
await Promise.resolve();
assert.deepEqual(removals, [[entry.key, other.key]]);
assert.equal(hostOf(movingId).length, 0);
rendering.destroyMarkers(viewer);
assert.equal(hostOf(stillId), undefined);
assert.equal(hostOf(movingId), undefined);
});
+91
View File
@@ -0,0 +1,91 @@
/**
* @module render/cesium/uploadProbe
* @description A QA probe: the bytes the WebGL context is handed
* (`bufferData`, `bufferSubData`) while the hosts of some draw sets update,
* frame by frame. A layer's frame probe takes it as its `uploads` (the
* transit layer's `_measureTransitFramesForTest`), so the layer itself
* stays off the default renderer. Diagnostics only: it wraps the context's
* methods and the hosts' `update` until `stop()`.
*/
import { webglContext } from './internals.js';
/**
* Count the bytes uploaded while the hosts of `setIds` update. Hosts are
* found by the `drawSetId` the draw port names them with, again at each
* `reset()`, so a host a rebuild puts in a set's place is counted too.
* @param {object} viewer A Cesium viewer.
* @param {readonly string[]} setIds
* @returns {{reset: () => void, bytes: () => number, stop: () => void}}
*/
export function countDrawSetUploads(viewer, setIds) {
const scene = viewer.scene;
const ids = new Set(setIds);
const gl = webglContext(scene);
let active = false;
let upload = 0;
const restores = [];
if (gl) {
for (const name of ['bufferData', 'bufferSubData']) {
const original = gl[name];
gl[name] = function (...args) {
if (active) {
const value = args[name === 'bufferData' ? 1 : 2];
const offset = args[3] || 0;
const length = args[4];
upload +=
typeof value === 'number'
? value
: value
? length !== undefined
? length * (value.BYTES_PER_ELEMENT || 1)
: value.byteLength - offset * (value.BYTES_PER_ELEMENT || 1)
: 0;
}
return original.apply(this, args);
};
restores.push(() => {
gl[name] = original;
});
}
}
// Hosts wrapped so far, and how to give each its own `update` back (an
// inherited one by deleting the wrapper).
const wrapped = new Map();
function wrapHosts() {
const primitives = scene.primitives;
for (let i = 0; i < (primitives?.length ?? 0); i++) {
const host = primitives.get(i);
if (!ids.has(host?.drawSetId) || wrapped.has(host)) continue;
const original = host.update;
const own = Object.prototype.hasOwnProperty.call(host, 'update');
host.update = function (frameState) {
active = true;
try {
return original.call(this, frameState);
} finally {
active = false;
}
};
wrapped.set(host, { original, own, wrapper: host.update });
}
}
wrapHosts();
return {
reset() {
upload = 0;
wrapHosts();
},
bytes: () => upload,
stop() {
for (const restore of restores) restore();
restores.length = 0;
for (const [host, { original, own, wrapper }] of wrapped) {
// A host whose update was replaced meanwhile keeps the new one.
if (host.update !== wrapper) continue;
if (own) host.update = original;
else delete host.update;
}
wrapped.clear();
},
};
}
+105
View File
@@ -0,0 +1,105 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { countDrawSetUploads } from './uploadProbe.js';
/** A scene whose context counts nothing itself, and hosts that upload. */
function sceneWith(hosts) {
const gl = {
bufferData() {},
bufferSubData() {},
};
const scene = {
context: { _gl: gl },
primitives: {
get: (i) => hosts[i],
get length() {
return hosts.length;
},
},
};
return { scene, gl };
}
function uploader(gl, drawSetId, bytes) {
return {
drawSetId,
update() {
gl.bufferData(0, new Float32Array(bytes / 4), 0);
gl.bufferSubData(0, 0, new Uint8Array(bytes), 2, 3);
},
};
}
test('only the named sets’ uploads count, from each reset, and stop gives everything back', () => {
const hosts = [];
const { scene, gl } = sceneWith(hosts);
const ownBufferData = gl.bufferData;
const mine = uploader(gl, 'transit:1:still', 16);
const other = uploader(gl, 'traffic:1', 64);
hosts.push(mine, other);
const ownUpdate = mine.update;
const uploads = countDrawSetUploads({ scene }, [
'transit:1:still',
'transit:1:moving',
]);
uploads.reset();
mine.update();
other.update();
// 16 bytes of data, then 3 of the 16-byte view from element 2.
assert.equal(uploads.bytes(), 16 + 3);
// A host that comes later (a rebuild) is found at the next reset.
const later = uploader(gl, 'transit:1:moving', 8);
const laterUpdate = later.update;
hosts.push(later);
uploads.reset();
assert.equal(uploads.bytes(), 0);
later.update();
assert.equal(uploads.bytes(), 8 + 3);
// An update replaced while counting is the one kept.
const replaced = function () {};
mine.update = replaced;
uploads.stop();
assert.equal(gl.bufferData, ownBufferData);
assert.equal(later.update, laterUpdate, 'its own update back');
assert.equal(mine.update, replaced, 'an update replaced meanwhile stays');
assert.notEqual(mine.update, ownUpdate);
// Nothing counts once stopped.
later.update();
assert.equal(uploads.bytes(), 8 + 3);
});
test('an inherited update is given back by removing the wrapper', () => {
const hosts = [];
const { scene, gl } = sceneWith(hosts);
class Host {
update() {
gl.bufferData(0, 4, 0);
}
}
const host = Object.assign(new Host(), { drawSetId: 's' });
hosts.push(host);
const uploads = countDrawSetUploads({ scene }, ['s']);
assert.ok(Object.hasOwn(host, 'update'));
uploads.reset();
host.update();
assert.equal(uploads.bytes(), 4);
uploads.stop();
assert.equal(Object.hasOwn(host, 'update'), false);
assert.equal(host.update, Host.prototype.update);
});
test('a size-only allocation counts its size', () => {
const hosts = [];
const { scene, gl } = sceneWith(hosts);
hosts.push({
drawSetId: 's',
update() {
gl.bufferData(0, 100, 0);
},
});
const uploads = countDrawSetUploads({ scene }, ['s']);
uploads.reset();
hosts[0].update();
assert.equal(uploads.bytes(), 100);
uploads.stop();
});
-1
View File
@@ -8,7 +8,6 @@
"src/cyberSonarScene.js",
"src/data/geoImportPins.js",
"src/layers/traffic/rendering.js",
"src/layers/transit/rendering.js",
"src/layers/weather/shellRendering.js",
"src/layers/wind/gpuRendering.js",
"src/layers/wind/relief.js",
+6
View File
@@ -120,6 +120,12 @@ const DRAW_FROM_CALLER = new Set([
// Its pins, footprints and outlines draw through `drawOf`; its horizon
// cull reads the camera and frame ports.
'./layers/ghostmaps',
// Its moving and still vehicle icons draw through `drawOf`; it projects,
// culls, follows and samples floors through the ports.
'./layers/transit',
// Not Cesium-free (its legacy mesh floor sampler is), but its layer draws
// and reads the view through the ports alone.
'./layers/transit/standalone',
]);
/**
+47 -12
View File
@@ -418,13 +418,21 @@ export function createGroundFloor({ terrain, signal }) {
// is the photogrammetric MESH, which sits above it (measured ~17 m at the
// Austin airport apron). DEM-flooring therefore still buried sprites/trails
// inside the mesh. These cells hold the RENDERED surface height, sampled
// one-shot per coarse cell near the viewer (scene.sampleHeight — the same
// at the callers' points, a few per coarse cell near the viewer, each kept
// where it was taken and read back from the nearest (scene.sampleHeight — the same
// source groundSnap uses, which is why 3D models always looked right) and
// reported here by meshFloorSampler.js. Design principle (owner): NEVER
// below the visible surface; slightly above is always fine. The DEM stays
// the instant global prior/fallback and the sanity gate for samples.
/** @type {Map<string, number>} coarse cell key -> rendered-surface height (m, ellipsoidal). */
/** @type {Map<string, Array<{lat: number, lon: number, h: number}>>}
* coarse cell key -> rendered-surface readings (m, ellipsoidal), each kept
* at the point it was probed. A read answers from the reading nearest the
* asked point, so a viaduct and the street beside it in one cell keep their
* own heights. */
const _meshCells = new Map();
/** @constant {number} Readings closer than this (degrees, about 5 m) are
* one spot: the lower one is kept there. */
const MESH_READING_SAME_SPOT_DEG = 0.00005;
/** @type {boolean} Whether mesh cells apply — true only in the google-3d
* regime (photoreal stack). On globe stacks the rendered surface IS the
* terrain provider (Re:Earth on keyless), so the DEM is already correct
@@ -444,7 +452,8 @@ export function createGroundFloor({ terrain, signal }) {
/**
* Records a sampled rendered-surface height for the cell containing the
* coordinate (one-shot latch — first accepted sample wins).
* coordinate, unchecked, when the cell has no reading yet. The sampler goes
* through `reportValidatedMeshFloorCell`, which keeps a reading per point.
* @param {number} lat @param {number} lon @param {number} heightM
*/
function reportMeshFloorCell(lat, lon, heightM) {
@@ -456,7 +465,7 @@ export function createGroundFloor({ terrain, signal }) {
return;
const c = coarseFloorCoord(lat, lon);
const key = `${c.lat},${c.lon}`;
if (!_meshCells.has(key)) _meshCells.set(key, heightM);
if (!_meshCells.has(key)) _meshCells.set(key, [{ lat, lon, h: heightM }]);
}
/** Return whether a rendered-mesh sample is plausible against a real DEM prior. */
@@ -471,9 +480,10 @@ export function createGroundFloor({ terrain, signal }) {
/**
* Validate and record a rendered-mesh floor through the single shared gate.
* Callers must not bypass this with raw `reportMeshFloorCell`: a coarse-LOD,
* rooftop, or aircraft hit would otherwise win the session-long first-write
* latch and poison every floor consumer in the cell.
* Callers must not bypass this with raw `reportMeshFloorCell`: a coarse-LOD
* or aircraft hit would otherwise poison every floor consumer in the cell.
* The reading is kept at the point it was taken; a second reading at the
* same spot (within about 5 m) keeps the lower of the two.
* @returns {boolean} Whether the sample passed and was reported.
*/
function reportValidatedMeshFloorCell(lat, lon, heightM) {
@@ -481,13 +491,26 @@ export function createGroundFloor({ terrain, signal }) {
const cell = coarseFloorCoord(lat, lon);
const prior = cachedRealEllipsoidalGround(cell.lat, cell.lon);
if (!meshFloorSampleWithinPrior(heightM, prior)) return false;
reportMeshFloorCell(cell.lat, cell.lon, heightM);
const key = `${cell.lat},${cell.lon}`;
const readings = _meshCells.get(key);
if (!readings) {
_meshCells.set(key, [{ lat, lon, h: heightM }]);
return true;
}
const same = readings.find(
(r) =>
Math.abs(r.lat - lat) < MESH_READING_SAME_SPOT_DEG &&
Math.abs(r.lon - lon) < MESH_READING_SAME_SPOT_DEG,
);
if (!same) readings.push({ lat, lon, h: heightM });
else if (heightM < same.h) same.h = heightM;
return true;
}
/**
* Synchronous mesh-cell read — null when the cell is unsampled OR the
* google-3d regime is inactive (globe stacks must floor on the DEM).
* Synchronous mesh-cell read — the cell's reading nearest the point, or
* null when the cell is unsampled OR the google-3d regime is inactive (globe
* stacks must floor on the DEM).
* @param {number} lat @param {number} lon
* @returns {number|null}
*/
@@ -495,8 +518,20 @@ export function createGroundFloor({ terrain, signal }) {
if (!_meshPreferred) return null;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
const c = coarseFloorCoord(lat, lon);
const h = _meshCells.get(`${c.lat},${c.lon}`);
return h != null ? h : null;
const readings = _meshCells.get(`${c.lat},${c.lon}`);
if (!readings) return null;
if (readings.length === 1) return readings[0].h;
const k = Math.cos((lat * Math.PI) / 180) ** 2;
let best = readings[0],
bestD = Infinity;
for (const r of readings) {
const d = (r.lat - lat) ** 2 + k * (r.lon - lon) ** 2;
if (d < bestD) {
bestD = d;
best = r;
}
}
return best.h;
}
/** Test hook: clears mesh cells (never called at runtime — cells are valid all session). */
+37 -7
View File
@@ -25,13 +25,16 @@ export function createMeshFloorSampler({
// which sits above the Re:Earth bare-earth DEM (measured ~17 m at the Austin
// airport apron) — so DEM-floored sprites/trails still buried themselves in
// the mesh while 3D models (which groundSnap against the mesh) looked right.
// This module samples the mesh height ONE-SHOT per coarse cell and reports it
// to groundFloor.js, whose cachedGroundFloor() then answers mesh-first.
// This module samples the mesh height at the callers' points, a few probes
// per coarse cell, and reports them to groundFloor.js, which keeps each
// reading that passes its gate at its own point; cachedGroundFloor() then
// answers mesh-first, from the reading nearest the asked point.
//
// Rationing (the CCTV loading-jitter lesson): scene.sampleHeight forces
// tile-load prioritization at the probe point, so sampling is (a) gated to
// cells NEAR the viewer — where tiles are streamed and where an error is
// visible at all, (b) capped per call, (c) one-shot per cell for the session,
// visible at all, (b) capped per call, (c) at most MAX_PROBES_PER_CELL
// readings per cell for the session, each at a point apart from the others,
// (d) skipped entirely outside the google-3d regime. A returned-undefined
// probe (tiles not streamed yet) is NOT latched — it retries on a later call.
//
@@ -51,6 +54,16 @@ export function createMeshFloorSampler({
* streamed LOD under a high camera is coarse everywhere, so every probe
* would latch junk. */
const MAX_CAMERA_HEIGHT_M = 25_000;
/** @constant {number} Readings per cell: a cell is probed at most this
* many times, each at a point apart from the others, and groundFloor keeps
* each reading at its point (a read answers from the nearest one). */
const MAX_PROBES_PER_CELL = 8;
/** @constant {number} How far apart (degrees, about 17 m) a new probe must
* be from the cell's earlier ones to be worth taking. */
const PROBE_APART_DEG = 0.00015;
/** @type {Map<string, Array<{lat: number, lon: number}>>} Points probed
* per cell that returned a reading. */
const _probedPoints = new Map();
/** @type {Cesium.Cartographic} Scratch for probe coordinates. */
const _scratchProbe = new Cesium.Cartographic();
@@ -85,7 +98,7 @@ export function createMeshFloorSampler({
/**
* Samples the rendered mesh height for the coarse cells containing `points`,
* one-shot per cell, budget-capped, viewer-proximity-gated. Call ONCE per
* a few probes per cell, budget-capped, viewer-proximity-gated. Call ONCE per
* layer poll (never per contact, never per frame). Synchronous — Cesium's
* sampleHeight is a CPU-side query against loaded tiles.
*
@@ -136,8 +149,21 @@ export function createMeshFloorSampler({
const cell = coarseFloorCoord(p.lat, p.lon);
const key = `${cell.lat},${cell.lon}`;
if (attempted.has(key)) continue;
// A latched cell is probed again only at a point well apart from the
// ones already probed, a few times at most, so the cell's readings
// follow where its vehicles actually are.
const probes = _probedPoints.get(key);
if (
cachedMeshFloor(cell.lat, cell.lon) != null &&
(probes?.length >= MAX_PROBES_PER_CELL ||
probes?.some(
(q) =>
Math.abs(q.lat - p.lat) < PROBE_APART_DEG &&
Math.abs(q.lon - p.lon) < PROBE_APART_DEG,
))
)
continue;
attempted.add(key);
if (cachedMeshFloor(cell.lat, cell.lon) != null) continue; // one-shot latch
if (
Number.isFinite(viewerLat) &&
Number.isFinite(viewerLon) &&
@@ -146,14 +172,18 @@ export function createMeshFloorSampler({
) {
continue; // too far: tiles not streamed there, probe would be a guaranteed miss
}
// Probe where the caller's point is, not at the cell's centre: a
// centre that falls on a roof would lift everything in the cell.
const height = heights.now(
Cesium.Cartographic.fromDegrees(cell.lon, cell.lat, 0, _scratchProbe),
Cesium.Cartographic.fromDegrees(p.lon, p.lat, 0, _scratchProbe),
{ exclude },
);
// A miss counts against the budget whatever its cause: past the support
// gate a probe only throws mid-teardown, when every later cell would too.
sampled += 1;
if (height === null) continue; // tiles not loaded yet — no negative latch
if (probes) probes.push({ lat: p.lat, lon: p.lon });
else _probedPoints.set(key, [{ lat: p.lat, lon: p.lon }]);
// Round 5: a REAL Re:Earth prior is REQUIRED before any sample latches.
// - A geoid-fallback prior (cached while the proxy was failing) is a
// sea-level poison that rejected legitimate samples at elevated
@@ -182,7 +212,7 @@ export function createMeshFloorSampler({
// feasible and deliberately deferred — see the P2 in
// the project roadmap, which bundles it with the fly_route probe so
// one post-launch pass settles rendered-mesh sampling everywhere.
reportValidatedMeshFloorCell(cell.lat, cell.lon, height);
reportValidatedMeshFloorCell(p.lat, p.lon, height);
}
}
+61 -16
View File
@@ -397,6 +397,28 @@ test('sensor sampler waits for postRender and reads framebuffer pixels; stopped
}),
}),
};
// The marker record (fresh with each state read, as the fixture's
// wrappers are), and the billboard the draw port drew for the latest one
// in the layer's still set.
let marker = null;
const billboard = {
id: { set: 'transit:1:still', id: 'bus' },
show: true,
color: { alpha: 1 },
rotation: 0,
get position() {
return marker.position;
},
};
scene.primitives = {
length: 1,
get: () => ({
drawSetId: 'transit:1:still',
show: true,
length: 1,
get: () => billboard,
}),
};
globalThis.window = {
__godsEyeView: {
viewer: { scene },
@@ -406,22 +428,22 @@ test('sensor sampler waits for postRender and reads framebuffer pixels; stopped
'transit',
{
module: {
_transitStateForTest: () => ({
_vehicles: new Map([
[
'bus',
{
key: 'bus',
mode: 'bus',
marker: {
show: true,
image: 'raster',
position: { x: 0, y: 0, z: 0 },
},
},
],
]),
}),
_transitSetIdsForTest: () => [
'transit:1:still',
'transit:1:moving',
],
_transitStateForTest: () => {
marker = {
show: true,
image: 'raster',
position: { x: 0, y: 0, z: 0 },
};
return {
_vehicles: new Map([
['bus', { key: 'bus', mode: 'bus', marker }],
]),
};
},
},
},
],
@@ -603,8 +625,30 @@ test('preset baseline clears a previous city selection before comparing fleet si
_selectedKey: entry.key,
_vehicles: new Map([[entry.key, entry]]),
};
// The billboard the draw port drew for the marker, styled as it is.
const billboard = {
id: { set: 'transit:1:still', id: entry.key },
get width() {
return entry.marker.width;
},
get color() {
return entry.marker.color;
},
};
globalThis.window = {
__godsEyeView: {
viewer: {
scene: {
primitives: {
length: 1,
get: () => ({
drawSetId: 'transit:1:still',
length: 1,
get: () => billboard,
}),
},
},
},
dataManager: {
layers: new Map([
[
@@ -612,6 +656,7 @@ test('preset baseline clears a previous city selection before comparing fleet si
{
module: {
_transitStateForTest: () => state,
_transitSetIdsForTest: () => ['transit:1:still'],
_transitPartsForTest: () => ({
selection: {
clearSelection() {