Ground snapping and mesh floor sampling through the renderer ports, off the Cesium list

src/services/groundSnap.js and src/services/meshFloorSampler.js no longer
reach Cesium. Whether the surface has streamed comes from the globe port
(the snap waits for the 'tiles' and 'surface' settle kinds; the sampler
runs only with the globe hidden and 'surface' settled), the camera height
gate from camera.pose(), heights from the query port, and the maths from
src/geo/ellipsoid.js. The raw exclusion path is gone: callers see through
their own draw sets by id. Cockpit's ground probe names the tracked
contact's icon and model sets, which the flights and military layers keep
on its entity record (groundSets), instead of the tracked holder object.

Probing is unchanged: at the caller's point, up to eight readings per cell
about 17 m apart, a read answering from the nearest one.

The application operations entry is now Cesium-free: a viewer with no
renderer bound needs ./render/cesium/unbound loaded first. Tests that used
to get the adapter's factories through ground snapping load it themselves.
This commit is contained in:
Sameh Khamis committed 2026-11-09 01:55:36 -08:00
1 parent 9d4e438e63
commit f53f691a80
20 files changed
+296 -199

No files matched your search

+47 -91
View File
@@ -46,15 +46,10 @@
* are per-layer, keyed by that layer's icao space).
*/
import * as Cesium from 'cesium';
import { heightsFor } from '../render/cesium/heights.js';
import { scaleToGeodeticSurface, toLonLatH } from '../geo/ellipsoid.js';
import { distanceSquared } from '../geo/vector.js';
import { heightsOf } from '../queries/heights.js';
// The application operations entry reaches the annotation resolver and
// locations.js, whose flights and heights go through the camera and query
// ports and which cannot load the Cesium adapter themselves; this listed
// module, on the same entry, loads the factories a viewer with no renderer
// bound gets them from.
import '../render/cesium/camera.js';
import { findGlobe } from '../render/rendererOf.js';
/** Taxi threshold: a cached snap answers directly for moves up to this far from
* the sampled spot (m). Past it the value is demoted to a held last-known and a
@@ -139,40 +134,32 @@ const SAMPLE_BUDGET_PER_WINDOW = 4;
const SAMPLE_WINDOW_MS = 250;
/**
* True when the active photoreal tileset has finished streaming the tiles in
* view (the pattern CCTV's projectionTilesReady once used: first
* Cesium3DTileset found in scene.primitives, duck-typed via its boolean
* tilesLoaded). Sampling before that both blows the frame budget on forced
* synchronous loads and produces misses that would burn retry backoff for
* nothing. With NO tileset present
* (OSM fallback) this returns true so the sample path is not permanently
* blocked — the sample just misses and backs off.
* @param {Cesium.Viewer} viewer
* True when the drawn surface has finished streaming what is in view: the
* base tiles (the globe port's `tiles` settle kind) and whatever surface
* heights answer from (`surface`: the globe's terrain while it is shown,
* otherwise every shown 3D tileset, whoever added it). Sampling
* before that both blows the frame budget on forced synchronous loads and
* produces misses that would burn retry backoff for nothing. With the globe
* hidden and NO tiles drawn the sample could only miss, and this says not
* ready, which is the same miss and backoff without the probe. False
* without a globe port to ask.
* @param {object} viewer
* @returns {boolean}
*/
function _tilesReady(viewer) {
const prims = viewer?.scene?.primitives;
if (!prims) return false;
for (let i = 0; i < prims.length; i++) {
let p = null;
try {
p = prims.get(i);
} catch {
continue;
}
if (p && p.show !== false && typeof p.tilesLoaded === 'boolean') {
return p.tilesLoaded === true;
}
try {
const globe = findGlobe(viewer);
return globe?.isSettled('tiles') === true && globe.isSettled('surface');
} catch {
return false; // mid-teardown
}
return true;
}
/**
* Create a per-layer ground-snap cache.
* @returns {{
* heightFor: (viewer: Cesium.Viewer, icao: string, pos: Cesium.Cartesian3,
* getExclusions?: (() => Array<unknown>)|{sets: string[]})
* => number|null,
* heightFor: (viewer: object, icao: string, pos: {x: number, y: number, z: number},
* exclusions?: {sets: string[]}) => number|null,
* forget: (icao: string) => void,
* clear: () => void,
* }}
@@ -180,7 +167,7 @@ function _tilesReady(viewer) {
export function createGroundSnap({ groundFloor }) {
const { cachedMeshFloor, meshFloorPreferred, reportValidatedMeshFloorCell } =
groundFloor;
/** @type {Map<string, {h: number|null, samplePos: Cesium.Cartesian3|null,
/** @type {Map<string, {h: number|null, samplePos: {x: number, y: number, z: number}|null,
* held: boolean, nextRetryMs: number, misses: number}>} Per-icao snap state:
* the sampled height and the surface point it was measured at, whether that
* pair is still the fresh answer or has been demoted to a bounded last-known
@@ -188,13 +175,6 @@ export function createGroundSnap({ groundFloor }) {
const entries = new Map();
let windowStartMs = 0;
let windowCount = 0;
const scratchCarto = new Cesium.Cartographic();
const scratchSurfacePos = new Cesium.Cartesian3();
/** Separate from `scratchCarto`: the held-evidence check runs on paths that
* return BEFORE the sample writes `scratchCarto`, and on the sampling path it
* must not disturb the cartographic that `reportValidatedMeshFloorCell` reads
* back after the sample lands. */
const scratchHeldCarto = new Cesium.Cartographic();
/**
* The last measurement for a contact whose fresh snap has been demoted — it
@@ -207,15 +187,15 @@ export function createGroundSnap({ groundFloor }) {
* moved does not change with time, so what invalidates the value is the
* contact MOVING, which is exactly what this measures.
*
* @param {{h: number|null, samplePos: Cesium.Cartesian3|null, held: boolean}|undefined} entry
* @param {Cesium.Cartesian3} surfacePos - Contact's position on the ellipsoid.
* @param {{h: number|null, samplePos: {x: number, y: number, z: number}|null, held: boolean}|undefined} entry
* @param {{x: number, y: number, z: number}} surfacePos - Contact's position on the ellipsoid (ECEF).
* @returns {number|null}
*/
function heldSnapM(entry, surfacePos) {
if (!entry || !entry.held || entry.h == null || !entry.samplePos)
return null;
if (
Cesium.Cartesian3.distanceSquared(surfacePos, entry.samplePos) >
distanceSquared(surfacePos, entry.samplePos) >
HELD_SNAP_MAX_DRIFT_M * HELD_SNAP_MAX_DRIFT_M
) {
return dropHold(entry);
@@ -259,20 +239,13 @@ export function createGroundSnap({ groundFloor }) {
* to answer from a single sample — and borrowing one to DISCARD a real
* measurement would let a roof cell hide a correctly placed model.
*
* @param {Cesium.Cartesian3} surfacePos - Contact's position on the ellipsoid.
* @param {{x: number, y: number, z: number}} surfacePos - Contact's position on the ellipsoid (ECEF).
* @returns {number|null}
*/
function freshMeasuredFloorAt(surfacePos) {
const carto = Cesium.Cartographic.fromCartesian(
surfacePos,
Cesium.Ellipsoid.WGS84,
scratchHeldCarto,
);
if (!carto) return null;
return cachedMeshFloor(
Cesium.Math.toDegrees(carto.latitude),
Cesium.Math.toDegrees(carto.longitude),
);
const at = toLonLatH(surfacePos);
if (!at) return null;
return cachedMeshFloor(at.lat, at.lon);
}
/**
@@ -282,30 +255,26 @@ export function createGroundSnap({ groundFloor }) {
* A contact that HAS resolved once keeps that answer through a resample outage;
* see `heldSnapM`.
*
* @param {Cesium.Viewer} viewer - Live viewer (sampling + tiles-ready check).
* @param {object} viewer - Live viewer (sampling + tiles-ready check).
* @param {string} icao - Cache key (per-layer icao space).
* @param {Cesium.Cartesian3} pos - Current display position. Cache movement
* is measured after projecting this input to the WGS84 ellipsoid, so a
* poll-time altitude/datum change cannot invalidate a stationary snap.
* @param {(() => Array<unknown>)|undefined} getExclusions - Lazily builds the
* scene.sampleHeight objectsToExclude list (own billboards/models/entities —
* the vertical pick ray at a plane's OWN lat/lon lands on its icon/model
* otherwise). Only invoked when a sample actually fires. `{sets}` (draw
* set ids) instead samples through the renderer's query port
* @param {{x: number, y: number, z: number}} pos - Current display position
* (ECEF). Cache movement is measured after projecting this input to the
* WGS84 ellipsoid, so a poll-time altitude/datum change cannot invalidate
* a stationary snap.
* @param {{sets?: string[]}} [exclusions] - The caller's own draw set ids
* (its markers and models). The sample asks the renderer's query port
* (`heightsOf`), which sees through every draw set not drawn as ground
* and these: for a caller whose markers and models are on the draw port.
* and these: the vertical ray at a plane's OWN lat/lon would otherwise
* land on its icon or model.
* @returns {number|null}
*/
function heightFor(viewer, icao, pos, getExclusions) {
const surfacePos = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(
pos,
scratchSurfacePos,
);
function heightFor(viewer, icao, pos, exclusions) {
const surfacePos = scaleToGeodeticSurface(pos);
if (!surfacePos) return null;
const cached = entries.get(icao);
if (cached && cached.h != null && cached.samplePos && !cached.held) {
if (
Cesium.Cartesian3.distanceSquared(surfacePos, cached.samplePos) <=
distanceSquared(surfacePos, cached.samplePos) <=
MOVE_INVALIDATE_M * MOVE_INVALIDATE_M
) {
return cached.h;
@@ -360,35 +329,22 @@ export function createGroundSnap({ groundFloor }) {
};
if (!_tilesReady(viewer)) return miss();
windowCount += 1;
const carto = Cesium.Cartographic.fromCartesian(
pos,
Cesium.Ellipsoid.WGS84,
scratchCarto,
);
// Draw-set exclusions ask the renderer's query port, which sees through
// every draw set not drawn as ground (the caller's markers and models).
const sampled = !carto
? null
: Array.isArray(getExclusions?.sets)
? heightsOf(viewer).now(carto, { exclude: getExclusions.sets })
: heightsFor(viewer.scene).now(carto, {
exclude: getExclusions ? getExclusions() : undefined,
});
const at = toLonLatH(pos);
const exclude = Array.isArray(exclusions?.sets)
? exclusions.sets
: undefined;
const sampled = !at ? null : heightsOf(viewer).now(at, { exclude });
// Same sanity floor as cctv.js's sampleGroundHeight: a hit far below the
// ellipsoid is pick garbage, not ground.
if (!Number.isFinite(sampled) || sampled < -150) return miss();
if (meshFloorPreferred()) {
reportValidatedMeshFloorCell(
Cesium.Math.toDegrees(scratchCarto.latitude),
Cesium.Math.toDegrees(scratchCarto.longitude),
sampled,
);
reportValidatedMeshFloorCell(at.lat, at.lon, sampled);
}
// A fresh sample RELEASES any hold: this is a measurement of where the
// contact is now, and it outranks a memory of where it was.
entries.set(icao, {
h: sampled,
samplePos: Cesium.Cartesian3.clone(surfacePos),
samplePos: surfacePos,
held: false,
nextRetryMs: 0,
misses: 0,
+101 -25
View File
@@ -1,8 +1,8 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { createGroundSnap } from './groundSnap.js';
import { bindRenderer } from '../render/rendererOf.js';
import { fromDegrees } from '../geo/ellipsoid.js';
const groundFloor = {
cachedMeshFloor: () => null,
@@ -10,24 +10,34 @@ const groundFloor = {
reportValidatedMeshFloorCell: () => {},
};
/** A viewer whose ground is a loaded 3D tileset, counting height samples. */
/**
* A viewer bound to a fake renderer whose drawn tiles settle as `tileset` says,
* counting height samples.
*/
function makeViewer() {
const calls = { samples: 0 };
const tileset = { show: true, tilesLoaded: true };
return {
calls,
scene: {
primitives: { length: 1, get: () => tileset },
sampleHeight() {
const asked = [];
const viewer = { calls, tileset, asked, surfaceLoaded: true };
bindRenderer(viewer, {
globe: {
isSettled: (kind) =>
kind === 'tiles'
? tileset.tilesLoaded
: kind !== 'surface' || viewer.surfaceLoaded,
},
query: {
sampleHeightNow(point, options) {
calls.samples += 1;
asked.push({ point, options });
return 1650;
},
globe: { getHeight: () => 1600 },
},
};
});
return viewer;
}
const atDenverAirport = Cesium.Cartesian3.fromDegrees(-104.6737, 39.8561, 0);
const atDenverAirport = fromDegrees(-104.6737, 39.8561, 0);
test('a clock that steps back opens a new sample window instead of denying samples until it catches up', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: 1_000_000 });
@@ -48,7 +58,7 @@ test('a clock that steps back opens a new sample window instead of denying sampl
test('a retry backoff stamped before the clock stepped back does not wait for it to catch up', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: 10_000_000 });
const viewer = makeViewer();
const tileset = viewer.scene.primitives.get(0);
const { tileset } = viewer;
const snap = createGroundSnap({ groundFloor });
// Tiles still streaming: a miss, backed off for 2 s.
tileset.tilesLoaded = false;
@@ -62,25 +72,91 @@ test('a retry backoff stamped before the clock stepped back does not wait for it
assert.equal(viewer.calls.samples, 1);
});
test('draw-set exclusions sample through the renderer’s query port', () => {
test('the sample asks the query port, seeing through the caller’s draw sets', () => {
const viewer = makeViewer();
const asked = [];
bindRenderer(viewer, {
query: {
sampleHeightNow(point, options) {
asked.push({ point, options });
return 1655;
},
},
});
const snap = createGroundSnap({ groundFloor });
assert.equal(
snap.heightFor(viewer, 'a00001', atDenverAirport, {
sets: ['mine:models'],
}),
1655,
1650,
);
assert.equal(viewer.calls.samples, 0, 'not the scene’s own sample');
assert.deepEqual(asked[0].options, { exclude: ['mine:models'] });
assert.ok(Math.abs(asked[0].point.lon + 104.6737) < 1e-6);
assert.equal(viewer.calls.samples, 1);
assert.deepEqual(viewer.asked[0].options, { exclude: ['mine:models'] });
assert.ok(Math.abs(viewer.asked[0].point.lon + 104.6737) < 1e-6);
assert.ok(Math.abs(viewer.asked[0].point.lat - 39.8561) < 1e-6);
});
test('a snap waits while the drawn tiles are still streaming', () => {
const viewer = makeViewer();
viewer.tileset.tilesLoaded = false;
const snap = createGroundSnap({ groundFloor });
assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null);
assert.equal(viewer.calls.samples, 0);
});
test('a snap waits while a shown tileset outside the base is still streaming', () => {
const viewer = makeViewer();
viewer.surfaceLoaded = false;
const snap = createGroundSnap({ groundFloor });
assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null);
assert.equal(viewer.calls.samples, 0);
});
test('without a globe port to ask, a snap is a miss', () => {
const viewer = {};
let samples = 0;
bindRenderer(viewer, {
query: {
sampleHeightNow() {
samples += 1;
return 1650;
},
},
});
const snap = createGroundSnap({ groundFloor });
assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null);
assert.equal(samples, 0);
});
test('through the Cesium globe port, a streaming tileset the port did not load holds the snap', async () => {
const Cesium = await import('cesium');
const { createCesiumGlobe } = await import('../render/cesium/globe.js');
const tileset = Object.create(Cesium.Cesium3DTileset.prototype);
Object.defineProperties(tileset, {
show: { value: true, writable: true },
tilesLoaded: { value: false, writable: true },
});
tileset.isDestroyed = () => false;
const scene = {
globe: { show: false, tilesLoaded: true },
imageryLayers: new Cesium.ImageryLayerCollection(),
primitives: { length: 1, get: () => tileset },
preUpdate: new Cesium.Event(),
};
const { port } = createCesiumGlobe(
{ scene },
{
capabilities: new Set(['globeVisibility', 'surfaceIdentity']),
requestRender() {},
},
);
let samples = 0;
const viewer = {};
bindRenderer(viewer, {
globe: port,
query: {
sampleHeightNow() {
samples += 1;
return 1650;
},
},
});
const snap = createGroundSnap({ groundFloor });
assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null);
assert.equal(samples, 0, 'not while the tileset streams');
tileset.tilesLoaded = true;
const later = createGroundSnap({ groundFloor });
assert.equal(later.heightFor(viewer, 'a00001', atDenverAirport), 1650);
assert.equal(samples, 1);
});
+38 -44
View File
@@ -1,7 +1,6 @@
import * as Cesium from 'cesium';
import { approxDistanceKm } from '../data/approxDistance.js';
import { heightsFor } from '../render/cesium/heights.js';
import { heightsOf } from '../queries/heights.js';
import { findCamera, findGlobe } from '../render/rendererOf.js';
/** Construct an instance-owned meshFloorSampler service with explicit dependencies. */
export function createMeshFloorSampler({
@@ -64,8 +63,8 @@ export function createMeshFloorSampler({
/** @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();
/** Scratch for probe coordinates (degrees). */
const _scratchProbe = { lon: 0, lat: 0 };
// Regime tracking: mesh cells only apply while the photoreal (google-3d)
// stack renders. main.js re-dispatches MapStackController.onChange as this
@@ -74,22 +73,22 @@ export function createMeshFloorSampler({
// bundle, and the subscription is idempotent for the app's lifetime.
/**
* True when a VISIBLE 3D tileset in the scene reports its streaming queue
* drained (tilesLoaded) — as CCTV's projectionTilesReady once did (it now
* asks the globe port whether its drawn photoreal tiles have settled).
* Walks top-level primitives only (a handful; once per poll).
* @param {Cesium.Scene} scene
* True when the globe is hidden (the google-3d regime draws the mesh
* alone) and the drawn 3D tiles have loaded what is in view; false with
* the globe shown or no tiles drawn. Asked of the globe port once per poll.
* The globe check matters on its own: the regime flag can still say
* photoreal while a switch to a globe stack is loading, or after a silent
* one, and a probe of the globe there would latch terrain as mesh.
* @param {object} viewer
* @returns {boolean}
*/
function _visibleTilesetLoaded(scene) {
function _surfaceSettled(viewer) {
try {
const prims = scene.primitives;
for (let i = 0; i < prims.length; i++) {
const p = prims.get(i);
if (p instanceof Cesium.Cesium3DTileset && p.show) {
return !!p.tilesLoaded;
}
}
const globe = findGlobe(viewer);
return (
globe?.isGlobeVisible?.() === false &&
globe.isSettled('surface') === true
);
} catch {
/* mid-teardown */
}
@@ -99,48 +98,44 @@ export function createMeshFloorSampler({
/**
* Samples the rendered mesh height for the coarse cells containing `points`,
* a few probes per cell, budget-capped, viewer-proximity-gated. Call ONCE per
* layer poll (never per contact, never per frame). Synchronous — Cesium's
* layer poll (never per contact, never per frame). Synchronous — the renderer's
* sampleHeight is a CPU-side query against loaded tiles.
*
* @param {Cesium.Scene|object|undefined} host - The scene, or the viewer
* whose scene it is (skipped when absent/torn down).
* @param {object|undefined} viewer - The viewer whose renderer draws the
* mesh (skipped when absent/torn down). The probe asks its query port
* (`heightsOf`), which sees through every draw set not drawn as ground.
* @param {Array<{lat: number, lon: number}>} points - Contact/waypoint coords.
* @param {object} [options]
* @param {Array<object>} [options.excludeObjects] - Own billboards/models to
* exclude from the probe (Cesium matches instances/.primitive/.id — pass
* Billboard and Model instances, NOT collections).
* @param {string[]} [options.sets] - Own draw set ids to see through. When
* given, `host` must be the viewer and the probe asks the renderer's
* query port (`heightsOf`), which sees through every draw set not drawn
* as ground; `excludeObjects` is then unused.
* @param {string[]} [options.sets] - The caller's own draw set ids, seen
* through as well.
* @param {number} [options.viewerLat] @param {number} [options.viewerLon]
* Viewer subpoint (computed once by the caller's poll).
*/
function sampleMeshFloorCells(
host,
viewer,
points,
{ excludeObjects = [], sets, viewerLat, viewerLon } = {},
{ sets, viewerLat, viewerLon } = {},
) {
const scene = host?.scene ?? host;
if (!meshFloorPreferred()) return;
const bySets = Array.isArray(sets);
const heights = !scene
? null
: bySets
? heightsOf(host)
: heightsFor(scene);
const exclude = bySets ? sets : excludeObjects;
if (!viewer || viewer.isDestroyed?.()) return;
const heights = heightsOf(viewer);
const exclude = Array.isArray(sets) ? sets : undefined;
// Without depth-texture support every probe throws: nothing to latch.
if (!heights?.supported().surface) return;
if (!Array.isArray(points) || !points.length) return;
// Round-5 hardening (the CCTV projectionTilesReady lesson, ported late):
// while tiles are MID-STREAM a probe returns coarse-LOD heights — real
// numbers, wildly wrong — and the one-shot latch made them permanent.
// Only sample when the visible Google tileset reports tilesLoaded AND the
// Only sample when the drawn tiles report they have settled AND the
// camera is low enough that the streamed LOD near it is fine-grained.
const camH = scene.camera?.positionCartographic?.height;
let camH;
try {
camH = findCamera(viewer)?.pose().height;
} catch {
return; // mid-teardown
}
if (!Number.isFinite(camH) || camH > MAX_CAMERA_HEIGHT_M) return;
if (!_visibleTilesetLoaded(scene)) return;
if (!_surfaceSettled(viewer)) return;
let sampled = 0;
const attempted = new Set();
for (const p of points) {
@@ -174,10 +169,9 @@ export function createMeshFloorSampler({
}
// 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(p.lon, p.lat, 0, _scratchProbe),
{ exclude },
);
_scratchProbe.lon = p.lon;
_scratchProbe.lat = p.lat;
const height = heights.now(_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;