Ask for heights through one service per scene

About 20 sites called scene.sampleHeight, globe.getHeight,
scene.clampToHeight or the MostDetailed variants directly, each with its own
idea of a miss (undefined, NaN, a throw). They now ask heightsFor(scene) in
src/queries/heights.js:

- now(point, { against, exclude }) answers from what is loaded, or null;
  against is 'surface' (what is drawn) or 'terrain' (loaded terrain only).
- clampNow(position) moves a position onto the drawn surface, or null.
- batch() and clampBatch() wait for the most detailed tiles: null per
  missed point, a rejection when the whole query fails.
- supported() reports { surface, clamp } without allocating.

Cesium still answers now() synchronously, so nothing changes on screen and
nothing is slower: in the live app 1,000 calls cost the same through the
service as direct (terrain 0.5-0.7 ms, surface 2-6 ms a call, run-to-run
noise larger than the difference). Every site already treated a miss as
"hold the last value or fall back"; a renderer that can only answer from a
cache or asynchronously can now plug in at one place.

- A Bhote Koshi evidence point whose terrain sample misses stays at its
  fallback elevation instead of reading the miss as sea level.
- The mesh floor sampler skips a scene without depth-texture support
  instead of spending its budget on probes that throw.
- The world annotation probe's trace reads hit/missed.
- A source scan forbids direct height calls outside the service.

The service is exported as ./queries/heights and documented in
docs/APPLICATION.md.
This commit is contained in:
Sameh Khamis committed 2026-11-04 09:24:30 -08:00
1 parent 02d492a079
commit 9bdeffeca3
32 files changed
+704 -210

No files matched your search

+9 -15
View File
@@ -19,6 +19,7 @@ import {
validAlprGroundHeight,
} from './visuals.js';
import { alprMarkers } from './markerState.js';
import { heightsFor } from '../../queries/heights.js';
/** Per-layer presentation on a caller-owned overlay; Cesium remains the fallback. */
export function createAlprOverlay({
@@ -121,14 +122,11 @@ export function createAlprOverlay({
else if (scene.sampleHeightSupported) {
if (budget.samples <= 0) return null;
budget.samples -= 1;
try {
height = scene.sampleHeight(location, [entity]);
} catch {
/* streaming tiles */
}
// A miss is tiles still streaming.
height = heightsFor(scene).now(location, { exclude: [entity] });
}
if (!validAlprGroundHeight(height) && scene.globe.show)
height = scene.globe.getHeight?.(location);
height = heightsFor(scene).now(location, { against: 'terrain' });
if (!validAlprGroundHeight(height)) return null;
setAnchor(record, entity, height);
return alprMarkers.read(entity)?.canvasPosition;
@@ -202,15 +200,11 @@ export function createAlprOverlay({
continue;
}
budget.samples -= 1;
let sample;
try {
sample = scene.sampleHeight(
Cesium.Cartographic.fromDegrees(record.longitude, record.latitude),
[entity],
);
} catch {
/* streaming tiles */
}
// A miss is tiles still streaming.
const sample = heightsFor(scene).now(
{ lon: record.longitude, lat: record.latitude },
{ exclude: [entity] },
);
const current = Cesium.Cartographic.fromCartesian(anchor).height;
const floor = services.groundFloor.cachedGroundFloor(
record.latitude,
+13 -18
View File
@@ -25,6 +25,7 @@ import {
} from './visuals.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { alprMarkers } from './markerState.js';
import { heightsFor } from '../../queries/heights.js';
export function createAlprPresentation({ state, services, source }) {
const { governorRequestRender } = services.render;
@@ -518,16 +519,13 @@ export function createAlprPresentation({ state, services, source }) {
record.longitude,
record.latitude,
);
let height;
if (state.viewer.scene.sampleHeightSupported) {
try {
height = state.viewer.scene.sampleHeight(location, [nearest]);
} catch {
/* tiles may still be streaming */
}
}
const heights = heightsFor(state.viewer.scene);
// A miss is tiles still streaming.
let height = state.viewer.scene.sampleHeightSupported
? heights.now(location, { exclude: [nearest] })
: null;
if (!validAlprGroundHeight(height) && state.viewer.scene.globe.show)
height = state.viewer.scene.globe.getHeight?.(location);
height = heights.now(location, { against: 'terrain' });
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
const center = Cesium.Cartesian3.fromDegrees(
@@ -598,16 +596,13 @@ export function createAlprPresentation({ state, services, source }) {
record.longitude,
record.latitude,
);
let height;
if (scene.sampleHeightSupported) {
try {
height = scene.sampleHeight(location, [entity]);
} catch {
/* tiles may still be streaming */
}
}
const heights = heightsFor(scene);
// A miss is tiles still streaming.
let height = scene.sampleHeightSupported
? heights.now(location, { exclude: [entity] })
: null;
if (!validAlprGroundHeight(height) && scene.globe.show)
height = scene.globe.getHeight?.(location);
height = heights.now(location, { against: 'terrain' });
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
if (!validAlprGroundHeight(height)) return;
+5 -6
View File
@@ -12,6 +12,7 @@ import {
MAX_TOTAL_POINTS,
COLOR_OUTLINE,
} from './policy.js';
import { heightsFor } from '../../queries/heights.js';
export function createRendering({
state: layerState,
@@ -100,12 +101,10 @@ export function createRendering({
let height = POINT_HEIGHT_OFFSET_M;
// Sample terrain height so points sit on ground rather than at ellipsoid level
if (layerState._viewer?.scene?.sampleHeightSupported) {
const carto = Cesium.Cartographic.fromDegrees(lon, lat);
const sampled = layerState._viewer.scene.sampleHeight(carto);
if (Number.isFinite(sampled)) {
height = sampled + POINT_HEIGHT_OFFSET_M;
}
const scene = layerState._viewer?.scene;
if (scene?.sampleHeightSupported) {
const sampled = heightsFor(scene).now({ lon, lat });
if (sampled !== null) height = sampled + POINT_HEIGHT_OFFSET_M;
}
return Cesium.Cartesian3.fromDegrees(lon, lat, height);
+3 -1
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { plausibleSurfaceHeight, sampledSurfaceHeight } from './view.js';
import { heightsFor } from '../../queries/heights.js';
/** Fly the globe camera once to frame a photo after it opens. */
export function createCameraFraming({ state }) {
@@ -30,7 +31,8 @@ export function createCameraFraming({ state }) {
const scene = state.viewer?.scene;
const carto = Cesium.Cartographic.fromDegrees(lon, lat);
let height = sampledSurfaceHeight(scene, carto);
if (height === null) height = scene?.globe?.getHeight?.(carto);
if (height === null && scene)
height = heightsFor(scene).now(carto, { against: 'terrain' });
if (!plausibleSurfaceHeight(height)) height = fallback;
return plausibleSurfaceHeight(height) ? height : 0;
}
+10 -2
View File
@@ -799,7 +799,11 @@ test('under Google 3D the ground is measured again once its tiles load, without
const viewer = fakeViewer();
// 4 km up the ellipsoid, 2 km over a city whose tiles are still loading.
let ground;
viewer.camera.positionCartographic = { height: 4000 };
viewer.camera.positionCartographic = {
longitude: 0,
latitude: 0,
height: 4000,
};
viewer.scene.globe = { show: false };
viewer.scene.sampleHeightSupported = true;
viewer.scene.sampleHeight = () => ground;
@@ -823,7 +827,11 @@ test('an unknown ground is measured only a few times, and not after the layer is
t.mock.timers.enable({ apis: ['setTimeout'] });
const viewer = fakeViewer();
let samples = 0;
viewer.camera.positionCartographic = { height: 4000 };
viewer.camera.positionCartographic = {
longitude: 0,
latitude: 0,
height: 4000,
};
viewer.scene.globe = { show: false };
viewer.scene.sampleHeightSupported = true;
viewer.scene.sampleHeight = () => {
+6 -8
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { wrapLon } from './tileMath.js';
import { heightsFor } from '../../queries/heights.js';
/** Equirectangular metres between {lon, lat} points, the short way round ±180°; street scale. */
export function metresBetween(a, b) {
@@ -21,12 +22,9 @@ export function plausibleSurfaceHeight(height) {
* underground before tiles load).
*/
export function sampledSurfaceHeight(scene, carto) {
let height = null;
try {
if (scene?.sampleHeightSupported) height = scene.sampleHeight(carto);
} catch {
/* not sampleable yet */
}
const height = scene?.sampleHeightSupported
? heightsFor(scene).now(carto)
: null;
return plausibleSurfaceHeight(height) ? height : null;
}
@@ -41,8 +39,8 @@ export function groundUnderCamera(viewer) {
if (!carto || !scene) return null;
const globe = scene.globe;
if (globe && globe.show !== false) {
const ground = globe.getHeight?.(carto);
if (Number.isFinite(ground)) return ground;
const ground = heightsFor(scene).now(carto, { against: 'terrain' });
if (ground !== null) return ground;
}
const sampled = sampledSurfaceHeight(scene, carto);
return sampled !== null && sampled < carto.height ? sampled : null;
+10 -10
View File
@@ -12,6 +12,7 @@ import {
TILE_CACHE_MAX_ENTRIES,
FAST_FETCH_ALTITUDE,
} from './policy.js';
import { heightsFor } from '../../queries/heights.js';
/** Retain complete parsed snapshots under both an LRU entry cap and a byte budget. */
export function cacheRoadSnapshot(
@@ -273,16 +274,15 @@ export function createIngestion({
const scene = layerState._viewer?.scene;
const location = Cesium.Cartographic.fromDegrees(centerLon, centerLat);
let estimated = services.ground?.cachedGroundFloor?.(centerLat, centerLon);
if (!Number.isFinite(estimated)) {
try {
estimated = scene?.globe?.show
? scene.globe.getHeight?.(location)
: scene?.sampleHeightSupported
? scene.sampleHeight(location, [layerState._pointCollection])
: undefined;
} catch {
/* the local mesh can still be loading */
}
// A miss is the local mesh still loading.
if (!Number.isFinite(estimated) && scene) {
estimated = scene.globe?.show
? heightsFor(scene).now(location, { against: 'terrain' })
: scene.sampleHeightSupported
? heightsFor(scene).now(location, {
exclude: [layerState._pointCollection],
})
: undefined;
}
if (Number.isFinite(estimated) && Math.abs(estimated) <= 9000)
layerState._viewHeightEstimate = estimated;
+5 -4
View File
@@ -1,6 +1,7 @@
import { phaseTiming } from '../../sources/phaseTiming.js';
import * as Cesium from 'cesium';
import { DOT_HEIGHT_OFFSET, MAX_WAYPOINTS_PER_ROAD } from './policy.js';
import { heightsFor } from '../../queries/heights.js';
function surfaceTilesReady(scene) {
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
@@ -333,7 +334,8 @@ export async function prepareRoadSurfaces(
let sampled;
// sampleHeight reads the locally rendered mesh, not unresolved/offscreen
// tiles. Global tilesLoaded can stay false while this street is usable.
if (scene.globe?.show) sampled = scene.globe.getHeight?.(carto);
if (scene.globe?.show)
sampled = heightsFor(scene).now(carto, { against: 'terrain' });
else {
const estimate = Cesium.Cartographic.fromCartesian(
road.waypoints[i],
@@ -351,9 +353,8 @@ export async function prepareRoadSurfaces(
const shown = (excluded || []).filter((p) => p?.show);
for (const primitive of shown) primitive.show = false;
try {
sampled = scene.sampleHeight(carto, excluded);
} catch {
/* local mesh missing */
// A miss is the local mesh still missing.
sampled = heightsFor(scene).now(carto, { exclude: excluded });
} finally {
for (const primitive of shown) primitive.show = true;
}
+7 -4
View File
@@ -7,6 +7,7 @@ import {
HEIGHT_SAMPLE_MAX_ALTITUDE_M,
withinViewBounds,
} from './policy.js';
import { heightsFor } from '../../queries/heights.js';
/** Surface preparation off the render path, shared by markers and history. */
export function createHeight({ state, services, parts }) {
@@ -63,14 +64,16 @@ export function createHeight({ state, services, parts }) {
return { cell, height: fixtureFloor, prior: null };
// On a terrain globe, use the loaded surface under the marker. This is
// synchronous cache work and does not launch a terrain request.
const globe = state._viewer?.scene?.globe;
if (globe?.show === true) {
const scene = state._viewer?.scene;
if (scene?.globe?.show === true) {
Cesium.Cartographic.fromDegrees(lon, lat, 0, terrainPoint);
const rendered = globe.getHeight?.(terrainPoint);
const rendered = heightsFor(scene).now(terrainPoint, {
against: 'terrain',
});
const flat =
state._viewer?.terrainProvider instanceof
Cesium.EllipsoidTerrainProvider;
if (Number.isFinite(rendered) || flat)
if (rendered !== null || flat)
return {
cell,
height: (flat ? 0 : rendered) + GROUND_FLOOR_LIFT_M,