feat(globe): surface height quality

engine.surface.sampleHeightDetailed(place, { exclude, lod }) answers
{ height, source: 'tiles' | 'terrain', tileSizeM? } (src/globe/surfaceDetail.js).
On Navara tileSizeM is the extent of the tile that answered and
lod 'finest' takes the finest loaded tile, drawn or not; Cesium answers
tiles without a size, else the globe's terrain. acceptedSurfaceHeight()
turns an answer into a height or a miss: tiles larger than
MAX_FLOOR_TILE_SIZE_M (4 km) are too coarse, terrain is not the mesh.

The mesh floor sampler and the ground snap are engine-only now (a viewer
or scene reaches its engine through engineFromViewer, which also registers
the scene) and treat a coarse answer as a miss, as they treat undefined.
Measured on Navara at Austin: while the tiles stream, a 27.9 km tile reads
143.2 m where the ground is 122.5 m (a 1.8 km tile).

`exclude` takes the engine's own mover sets (MoverSet.id): Cesium hides a
set's primitive for the synchronous sample (Cesium matches excluded objects
per billboard, not per collection); Navara's ray only meets tiles.

"sampleHeight undefined in the app on Navara" did not reproduce: the
startup Austin sample is 121.9 m (tile 889 m) on Navara and 122.4 m on
Cesium; one ModelMesh class is patched.

S2 QA (scripts/qa-surface-heights.mjs, 20 places at JFK, SFO, AUS, roofs
and streets): Navara within 2 m of Cesium at 19/20 from 800 m and 18/20
from 15 km with lod 'finest' (gates 18 and 15); offsets per region
-0.21 / +0.4 / +0.1 m; the Empire State roof differs by 39 m (spire
geometry). Navara tile sizes at 800 m: 112-314 m.
This commit is contained in:
German Khokhlov committed 2026-10-16 20:51:29 +04:00
1 parent f640890cf6
commit 645f042450
20 files changed
+635 -244

No files matched your search

+16 -30
View File
@@ -47,7 +47,9 @@
*/
import * as geo from '../geo/index.js';
import { isGlobeEngine } from '../globe/contract.js';
import { engineFromViewer } from '../globe/cesium/engineFromViewer.js';
import { acceptedSurfaceHeight } from '../globe/surfaceDetail.js';
import { MAX_FLOOR_TILE_SIZE_M } from './meshFloorSampler.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
@@ -131,24 +133,6 @@ const SAMPLE_BUDGET_PER_WINDOW = 4;
/** Budget window length (ms). */
const SAMPLE_WINDOW_MS = 250;
/**
* True when the active photoreal tileset has finished streaming the tiles in
* view (cctv.js's projectionTilesReady pattern: 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
* @returns {boolean}
*/
function _tilesReady(viewer) {
const prims = viewer?.scene?.primitives;
if (!prims) return false;
const tileset = firstVisibleTileset(prims);
return tileset ? tileset.tilesLoaded === true : true;
}
/**
* The first shown primitive that reports a boolean `tilesLoaded` (a 3D
* tileset, duck-typed), or null.
@@ -282,21 +266,21 @@ export function createGroundSnap({ groundFloor }) {
* A contact that HAS resolved once keeps that answer through a resample outage;
* see `heldSnapM`.
*
* @param {object} target - The globe engine (`engine.surface`: sampleHeight
* and tilesLoaded), or a live Cesium viewer from callers that still hold
* one (scene.sampleHeight and the first visible tileset's tilesLoaded).
* @param {object} target - The globe engine (`engine.surface`:
* sampleHeightDetailed and tilesLoaded), or a viewer whose engine is
* registered (engineFromViewer); without one, no sample.
* @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.
* surface `exclude` list (the layer's mover sets, or its own Cesium
* billboards/models/entities — the vertical ray at a plane's OWN lat/lon
* lands on its icon/model otherwise). Only invoked when a sample fires.
* @returns {number|null}
*/
function heightFor(target, icao, pos, getExclusions) {
const engine = isGlobeEngine(target) ? target : null;
const engine = engineFromViewer(target);
const surfacePos = geo.ellipsoid.WGS84.scaleToGeodeticSurface(
pos,
scratchSurfacePos,
@@ -348,7 +332,7 @@ export function createGroundSnap({ groundFloor }) {
entries.set(icao, next);
return heldSnapM(next, surfacePos);
};
if (!(engine ? engine.surface.tilesLoaded() : _tilesReady(target)))
if (!engine || engine.isDestroyed?.() || !engine.surface.tilesLoaded())
return miss();
windowCount += 1;
let sampled;
@@ -360,9 +344,11 @@ export function createGroundSnap({ groundFloor }) {
);
// sampleHeight throws when unsupported (no depth textures) — that's a miss.
const exclusions = getExclusions ? getExclusions() : undefined;
sampled = engine
? engine.surface.sampleHeight(carto, exclusions)
: target.scene.sampleHeight(carto, exclusions);
// A coarse tile's answer, or only terrain, is a miss.
sampled = acceptedSurfaceHeight(
engine.surface.sampleHeightDetailed(carto, { exclude: exclusions }),
{ maxTileSizeM: MAX_FLOOR_TILE_SIZE_M },
);
} catch {
sampled = undefined;
}
+36 -5
View File
@@ -23,9 +23,9 @@ test('on a globe engine a snap samples engine.surface once and caches it', () =>
};
assert.equal(snap.heightFor(engine, 'a1', KAUS, exclude), 138.5);
assert.equal(snap.heightFor(engine, 'a1', KAUS, exclude), 138.5);
const calls = engine.fake.callsOf('surface.sampleHeight');
const calls = engine.fake.callsOf('surface.sampleHeightDetailed');
assert.equal(calls.length, 1, 'one sample, then the cache');
assert.deepEqual(calls[0].args[1], ['own-model']);
assert.deepEqual(calls[0].args[1].exclude, ['own-model']);
assert.equal(exclusions, 1);
assert.ok(
Math.abs(geo.math.toDegrees(calls[0].args[0].latitude) - 30.19) < 1e-9,
@@ -39,15 +39,46 @@ test('on a globe engine loading tiles or a miss return null without a sample cac
engine.fake.script('tilesLoaded', false);
engine.fake.script('sampleHeight', () => 10);
assert.equal(snap.heightFor(engine, 'b1', KAUS), null);
assert.equal(engine.fake.callsOf('surface.sampleHeight').length, 0);
assert.equal(engine.fake.callsOf('surface.sampleHeightDetailed').length, 0);
engine.fake.script('tilesLoaded', true);
engine.fake.script('sampleHeight', () => undefined);
assert.equal(snap.heightFor(engine, 'c1', KAUS), null);
assert.equal(engine.fake.callsOf('surface.sampleHeight').length, 1);
assert.equal(engine.fake.callsOf('surface.sampleHeightDetailed').length, 1);
assert.equal(
snap.heightFor(engine, 'c1', KAUS),
null,
'backoff after a miss',
);
assert.equal(engine.fake.callsOf('surface.sampleHeight').length, 1);
assert.equal(engine.fake.callsOf('surface.sampleHeightDetailed').length, 1);
});
test('a coarse tile answer or only terrain is a miss; a viewer reaches its engine', async () => {
const { registerViewerEngine } =
await import('../globe/cesium/engineFromViewer.js');
const snap = createGroundSnap({ groundFloor: groundFloor() });
const engine = createFakeEngine();
engine.fake.script('sampleHeightDetailed', () => ({
height: 143.2,
source: 'tiles',
tileSizeM: 27_914,
}));
assert.equal(snap.heightFor(engine, 'd1', KAUS), null, 'coarse');
engine.fake.script('sampleHeightDetailed', () => ({
height: 121,
source: 'terrain',
}));
assert.equal(snap.heightFor(engine, 'd2', KAUS), null, 'terrain');
engine.fake.script('sampleHeightDetailed', () => ({
height: 122.5,
source: 'tiles',
tileSizeM: 1_797,
}));
const viewer = {};
const unregister = registerViewerEngine(viewer, engine);
try {
assert.equal(snap.heightFor(viewer, 'd3', KAUS), 122.5);
} finally {
unregister();
}
assert.equal(snap.heightFor({}, 'd4', KAUS), null, 'no engine: no sample');
});
+34 -61
View File
@@ -1,6 +1,12 @@
import * as Cesium from 'cesium';
import * as geo from '../geo/index.js';
import { isGlobeEngine } from '../globe/contract.js';
import { engineFromViewer } from '../globe/cesium/engineFromViewer.js';
import { acceptedSurfaceHeight } from '../globe/surfaceDetail.js';
/** Answers from tiles larger than this are too coarse to latch (m): on
* Navara at Austin a 1.8 km tile read the ground (122.5 m) and the 28 km
* tile shown while streaming read 143.2 m. Cesium does not size its
* answers, so its gates are the camera height and tilesLoaded below. */
export const MAX_FLOOR_TILE_SIZE_M = 4000;
/** Construct an instance-owned meshFloorSampler service with explicit dependencies. */
export function createMeshFloorSampler({
@@ -50,8 +56,6 @@ 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;
/** @type {Cesium.Cartographic} Scratch for probe coordinates. */
const _scratchProbe = new Cesium.Cartographic();
const _scratchEngineProbe = geo.cartographic.create();
// Regime tracking: mesh cells only apply while the photoreal (google-3d)
@@ -60,28 +64,6 @@ export function createMeshFloorSampler({
// preference. Module-scope listener: the module only loads in the browser
// 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) — the mirror of cctv.js's projectionTilesReady.
* Walks top-level primitives only (a handful; once per poll).
* @param {Cesium.Scene} scene
* @returns {boolean}
*/
function _visibleTilesetLoaded(scene) {
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;
}
}
} catch {
/* mid-teardown */
}
return false;
}
/**
* Equirectangular distance (km) — same approximation the flights clamp uses.
*/
@@ -99,13 +81,13 @@ export function createMeshFloorSampler({
* sampleHeight is a CPU-side query against loaded tiles.
*
* @param {object|undefined} target - The globe engine (engine.surface,
* camera.height, maps.photorealActive), or the Cesium scene from callers
* that still hold one (skipped when absent/torn down).
* camera.height, maps.photorealActive), or a viewer or scene whose
* engine is registered (engineFromViewer); without one, nothing.
* @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 {Array<object>} [options.excludeObjects] - What the probe passes
* through: the layer's engine mover sets, or (Cesium layers) its own
* Billboard and Model instances.
* @param {number} [options.viewerLat] @param {number} [options.viewerLon]
* Viewer subpoint (computed once by the caller's poll).
*/
@@ -115,25 +97,17 @@ export function createMeshFloorSampler({
{ excludeObjects = [], viewerLat, viewerLon } = {},
) {
if (!meshFloorPreferred()) return;
const engine = isGlobeEngine(target) ? target : null;
const scene = engine ? null : target;
if (engine ? !engine.surface.supported : !scene) return;
if (!engine && typeof scene.sampleHeight !== 'function') return;
const engine = engineFromViewer(target);
if (!engine || engine.isDestroyed?.() || !engine.surface.supported) 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
// camera is low enough that the streamed LOD near it is fine-grained.
const camH = engine
? engine.camera.height()
: scene.camera?.positionCartographic?.height;
const camH = engine.camera.height();
if (!Number.isFinite(camH) || camH > MAX_CAMERA_HEIGHT_M) return;
if (
!(engine
? engine.maps.photorealActive() && engine.surface.tilesLoaded()
: _visibleTilesetLoaded(scene))
)
if (!(engine.maps.photorealActive() && engine.surface.tilesLoaded()))
return;
let sampled = 0;
const attempted = new Set();
@@ -154,23 +128,19 @@ export function createMeshFloorSampler({
}
let height;
try {
if (engine) {
const carto = geo.cartographic.fromDegrees(
cell.lon,
cell.lat,
0,
_scratchEngineProbe,
);
height = engine.surface.sampleHeight(carto, excludeObjects);
} else {
const carto = Cesium.Cartographic.fromDegrees(
cell.lon,
cell.lat,
0,
_scratchProbe,
);
height = scene.sampleHeight(carto, excludeObjects);
}
const carto = geo.cartographic.fromDegrees(
cell.lon,
cell.lat,
0,
_scratchEngineProbe,
);
// A coarse tile's answer, or only terrain, is a miss (no latch).
height = acceptedSurfaceHeight(
engine.surface.sampleHeightDetailed(carto, {
exclude: excludeObjects,
}),
{ maxTileSizeM: MAX_FLOOR_TILE_SIZE_M },
);
sampled += 1;
} catch {
continue; // scene mid-teardown — try again next poll
@@ -223,6 +193,9 @@ export function createMeshFloorSampler({
return {
sampleMeshFloorCells,
cachedGroundFloor,
visibleTilesetLoaded: _visibleTilesetLoaded,
/** Whether the engine of `target` (a scene or viewer) has its tiles
* loaded (street level's mesh sampler gate). */
visibleTilesetLoaded: (target) =>
engineFromViewer(target)?.surface.tilesLoaded() ?? false,
};
}