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

+13 -22
View File
@@ -28,6 +28,7 @@ import { createImagerySplit } from '../ui/imagerySplit.js';
import { formatDate, t, tn, msg, onLocaleChange } from '../i18n/index.js';
import { useBhoteKoshiPanelStore } from '../ui/stores/bhoteKoshiPanel.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { heightsFor } from '../queries/heights.js';
export const BHOTE_KOSHI_LAYER_ID = 'bhote-koshi-2026';
export const BHOTE_KOSHI_OVERLAY_SOURCE_ID = 'bhote-koshi-witnesses';
@@ -122,20 +123,11 @@ const DEFAULT_EVENT_LOADER = async () => {
const DEFAULT_IMAGERY_PROVIDER_FACTORY = (url, options) =>
Cesium.SingleTileImageryProvider.fromUrl(url, options);
const DEFAULT_TERRAIN_SAMPLER = async (viewer, observations) => {
if (
!viewer?.terrainProvider ||
!viewer.terrainProvider.availability ||
typeof Cesium.sampleTerrainMostDetailed !== 'function'
) {
return null;
}
const cartographics = observations.map((observation) =>
Cesium.Cartographic.fromDegrees(observation.lon, observation.lat),
);
return Cesium.sampleTerrainMostDetailed(
viewer.terrainProvider,
cartographics,
);
if (!viewer?.scene || !viewer.terrainProvider?.availability) return null;
const heights = await heightsFor(viewer.scene).batch(observations, {
against: 'terrain',
});
return heights.map((height) => ({ height }));
};
const DEFAULT_MEDIA_LOADER = async (url, { signal } = {}) => {
if (typeof createImageBitmap !== 'function') {
@@ -1197,7 +1189,8 @@ export function createBhoteKoshiEventLayer({
}
throwIfEnableCancelled(signal, _enabled);
return observations.map((observation, index) => {
const sampledHeight = Number(sampled?.[index]?.height);
// A miss is null or undefined, never sea level.
const sampledHeight = Number(sampled?.[index]?.height ?? Number.NaN);
const fallbackHeight = Number(observation.fallbackElevationM) || 0;
return Cesium.Cartesian3.fromDegrees(
observation.lon,
@@ -1573,14 +1566,12 @@ export function createBhoteKoshiEventLayer({
// a single high sample can make the front dive backward in screen space.
if (_sceneControls.evidencePathElevation !== 'source') {
// Sample once while preparing the shot, never from an animation frame.
try {
height = _viewer?.scene?.sampleHeight?.(
position,
[_floodCore, _floodHalo, _surgePoint].filter(Boolean),
);
} catch {}
const heights = _viewer?.scene ? heightsFor(_viewer.scene) : null;
height = heights?.now(position, {
exclude: [_floodCore, _floodHalo, _surgePoint].filter(Boolean),
});
if (!Number.isFinite(height))
height = _viewer?.scene?.globe?.getHeight?.(position);
height = heights?.now(position, { against: 'terrain' });
}
if (!Number.isFinite(height)) height = point.fallbackElevationM;
return Cesium.Cartesian3.fromDegrees(point.lon, point.lat, height + 8);
+40
View File
@@ -2992,3 +2992,43 @@ test('Bhote Koshi corridor remains ordered downstream and inside the imagery rec
priorChainage = point.chainageM;
}
});
test('an evidence point whose terrain sample misses sits at its fallback elevation, not sea level', async () => {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
installEventDom();
globalThis.window = { setTimeout: () => 71, clearTimeout() {} };
const viewer = eventViewer();
const publications = [];
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imageryProviderFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: null })),
mediaLoader: async () => {
const error = new Error('fixture media intentionally unavailable');
error.name = 'AbortError';
throw error;
},
overlayHost: { setEntries(_source, entries) { publications.push(entries); }, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
});
try {
layer.setParams({
presentation: 'scene-beat',
sceneSurface: 'evidence-beat',
beatId: 'gyirong-border-gate',
}, { origin: 'scene' });
await layer.enable(viewer, { origin: 'scene' });
const card = publications.at(-1).find((entry) => entry.id === 'evidence-card-gyirong-border-gate');
const fallback = event.evidenceSpine.find(({ id }) => id === 'gyirong-border-gate').fallbackElevationM;
assert.ok(fallback > 100, 'the fixture has a real fallback elevation');
const height = Cesium.Cartographic.fromCartesian(card.position()).height;
assert.ok(Math.abs(height - (fallback + 18)) < 1, `card at ${height} m`);
await layer.disable();
} finally {
await layer.destroy();
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
+4 -2
View File
@@ -3,6 +3,7 @@ import * as Cesium from 'cesium';
import { createImportImageBudget } from './geoImportImages.js';
import { createImportedPins } from './geoImportPins.js';
import { msg } from '../i18n/marker.js';
import { heightsFor } from '../queries/heights.js';
/** Largest file accepted, in bytes. */
const MAX_IMPORT_BYTES = 50 * 1024 * 1024;
@@ -1272,10 +1273,11 @@ async function settleGroundPins(dataSource, viewer, signal) {
// a buried starting point can make the downward mesh ray miss the surface.
const ellipsoid =
viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider;
const heights = viewer.scene ? heightsFor(viewer.scene) : null;
for (let i = 0; i < positions.length; i++) {
const sampled = ellipsoid
? 0
: viewer.scene?.globe?.getHeight?.(positions[i]);
: heights?.now(positions[i], { against: 'terrain' });
positions[i].height = mesh
? (batch[i].groundHeight ??
Math.max(0, Number.isFinite(sampled) ? sampled : 0))
@@ -1295,7 +1297,7 @@ async function settleGroundPins(dataSource, viewer, signal) {
indices.push(i);
if (indices.length) {
const resolved = await boundedImport(
viewer.scene.clampToHeightMostDetailed(
heights.clampBatch(
indices.map((i) => {
const c = positions[i];
return Cesium.Cartesian3.fromRadians(
+37
View File
@@ -1262,3 +1262,40 @@ test('KML namespace repair ignores declaration text inside quoted attribute valu
/note="xmlns:xsi='x'" xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance">/,
);
});
test('a failed mesh clamp fails the import instead of leaving pins at sea level', async () => {
const previous = Cesium.PinBuilder.prototype.fromColor;
Cesium.PinBuilder.prototype.fromColor = () => ({
tagName: 'CANVAS',
toDataURL: () => 'data:image/png;base64,local',
});
try {
const viewer = {
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
camera: {
positionCartographic: { height: 100000 },
computeViewRectangle: () => Cesium.Rectangle.MAX_VALUE,
},
scene: {
frameState: { mode: Cesium.SceneMode.SCENE3D },
globe: { show: false, getHeight: () => 0 },
clampToHeightSupported: true,
clampToHeightMostDetailed: async () => {
throw new Error('tile request failed');
},
},
};
await assert.rejects(
loadGeoFile(
new File(
[JSON.stringify({ type: 'Point', coordinates: [1, 2] })],
'surface.geojson',
),
{ viewer },
),
/Ground heights could not be read/,
);
} finally {
Cesium.PinBuilder.prototype.fromColor = previous;
}
});
+1
View File
@@ -187,6 +187,7 @@ test('consumer build includes only infrastructure code and resolves assets under
const sources = Object.keys(entry.modules).filter((id) => id.endsWith('.js'));
assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [
'dispatcher.js',
'heights.js',
'infrastructure.js',
'infrastructureData.js',
'infrastructureOverlayEntry.js',
+12 -15
View File
@@ -11,6 +11,7 @@ import {
applyInfraEvictionGrace,
shouldRecomputeInfraLod,
} from './localGeojsonLod.js';
import { heightsFor } from '../queries/heights.js';
const DEFAULT_LABEL_MAX = 900;
const DEFAULT_LABEL_GRID_PX = 132;
@@ -1114,9 +1115,11 @@ function refreshLocalTerrainFloor(viewer, record) {
// Camera motion can refine terrain after the first successful depth sample.
// Reuse the loaded mesh on existing bounded walks; never arm a timer or do
// another GPU readback just to maintain this floor. Keep roof elevations.
const height = globe.getHeight?.(record.carto);
const height = heightsFor(viewer.scene).now(record.carto, {
against: 'terrain',
});
if (
!Number.isFinite(height) ||
height === null ||
Math.abs(height) > GROUND_SAMPLE_MAX_ABS_HEIGHT_M ||
height <= record.groundHeight
)
@@ -1131,26 +1134,20 @@ function sampleLocalGroundHeight(viewer, record, now) {
record.lastGroundSampleMs = now;
const globe = viewer.scene.globe;
if (globe?.show && globe.tilesLoaded === false) return false;
let sampled;
try {
sampled = viewer.scene.sampleHeight(record.carto, [record.entity]);
} catch {
return false; // tiles not ready; retry on a later bounded update
}
if (
!Number.isFinite(sampled) ||
Math.abs(sampled) > GROUND_SAMPLE_MAX_ABS_HEIGHT_M
)
const heights = heightsFor(viewer.scene);
// A miss is tiles not ready: retry on a later bounded update.
let sampled = heights.now(record.carto, { exclude: [record.entity] });
if (sampled === null || Math.abs(sampled) > GROUND_SAMPLE_MAX_ABS_HEIGHT_M)
return false;
// A coarse scene-depth sample can lie below the terrain already loaded by
// the visible globe. Keep that terrain as a floor while allowing roofs and
// valid below-sea-level elevations. Photoreal scenes hide the globe, so its
// inactive terrain must not constrain their geometry.
const terrainHeight = globe?.show
? globe.getHeight?.(record.carto)
: undefined;
? heights.now(record.carto, { against: 'terrain' })
: null;
if (
Number.isFinite(terrainHeight) &&
terrainHeight !== null &&
Math.abs(terrainHeight) <= GROUND_SAMPLE_MAX_ABS_HEIGHT_M
) {
sampled = Math.max(sampled, terrainHeight);
+16
View File
@@ -55,6 +55,7 @@ function fakeScene(sampleHeight, { cameraHeightM = 900, tilesLoaded = true, show
Object.defineProperty(tileset, 'tilesLoaded', { value: tilesLoaded, configurable: true });
Object.defineProperty(tileset, 'show', { value: show, configurable: true });
return {
sampleHeightSupported: true,
sampleHeight,
camera: { positionCartographic: { height: cameraHeightM } },
primitives: { length: 1, get: () => tileset },
@@ -137,3 +138,18 @@ test('sampler: a cell just across the antimeridian is still near the viewer', ()
sampleMeshFloorCells(scene, [{ lat: -16.81, lon: 179.999 }], { viewerLat: -16.81, viewerLon: -179.999 });
assert.equal(calls, 2, 'about 200 m apart, so both cells are probed');
});
test('sampler: a scene without depth-texture support is never probed', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
let calls = 0;
const scene = fakeScene(() => {
calls++;
throw new Error('depth textures unsupported');
});
scene.sampleHeightSupported = false;
sampleMeshFloorCells(scene, [cell], { viewerLat: cell.lat, viewerLon: cell.lon });
assert.equal(calls, 0);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), null);
});