mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
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:
1 parent
02d492a079
commit
9bdeffeca3
32 files changed
+704
-210
No files matched your search
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* @module queries/heights
|
||||
* @description The one place height queries go: how high the rendered
|
||||
* surface or the terrain is under a point, now or after streaming.
|
||||
*
|
||||
* `now()` answers from what is already loaded and may return `null`: tiles
|
||||
* not streamed yet, no depth support, a point off screen. Every caller treats
|
||||
* that as a miss, holding its last value or placing first and patching when
|
||||
* `batch()` resolves. Cesium answers `now()` synchronously from the scene,
|
||||
* so nothing changes on screen; a renderer that can only answer from a cache
|
||||
* or asynchronously plugs in here without touching the callers.
|
||||
*
|
||||
* `against` picks the surface: `'surface'` is what is drawn (3D tiles and the
|
||||
* globe), `'terrain'` the loaded terrain tiles alone. `exclude` lists what the
|
||||
* query must see through, typically the caller's own markers.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/** @typedef {'surface'|'terrain'} HeightSurface */
|
||||
/**
|
||||
* A point in degrees, or a `Cesium.Cartographic` in radians.
|
||||
* @typedef {{lon: number, lat: number}|Cesium.Cartographic} HeightPoint
|
||||
*/
|
||||
/**
|
||||
* @typedef {object} HeightOptions
|
||||
* @property {HeightSurface} [against] Default `'surface'`.
|
||||
* @property {object[]} [exclude] Primitives and entities to see through.
|
||||
*/
|
||||
|
||||
/** @type {WeakMap<object, HeightService>} scene -> service */
|
||||
const services = new WeakMap();
|
||||
|
||||
const scratch = new Cesium.Cartographic();
|
||||
|
||||
/** `supported()` answers, shared so a per-frame check allocates nothing. */
|
||||
const SUPPORT = [
|
||||
[
|
||||
Object.freeze({ surface: false, clamp: false }),
|
||||
Object.freeze({ surface: false, clamp: true }),
|
||||
],
|
||||
[
|
||||
Object.freeze({ surface: true, clamp: false }),
|
||||
Object.freeze({ surface: true, clamp: true }),
|
||||
],
|
||||
];
|
||||
|
||||
const NO_OPTIONS = Object.freeze({});
|
||||
|
||||
/** Plain finite metres, or null. */
|
||||
const metres = (height) => (Number.isFinite(height) ? height : null);
|
||||
|
||||
/**
|
||||
* The point as a Cartographic in radians at height 0. Degrees go through a
|
||||
* shared scratch unless `result` is given; a Cartographic is used as it is.
|
||||
* @param {HeightPoint} point
|
||||
* @param {Cesium.Cartographic} [result]
|
||||
* @returns {Cesium.Cartographic|null}
|
||||
*/
|
||||
function cartographicOf(point, result = scratch) {
|
||||
if (Number.isFinite(point?.longitude) && Number.isFinite(point?.latitude))
|
||||
return point;
|
||||
const lon = Number(point?.lon);
|
||||
const lat = Number(point?.lat);
|
||||
if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null;
|
||||
return Cesium.Cartographic.fromDegrees(lon, lat, 0, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} HeightService
|
||||
* @property {(point: HeightPoint, options?: HeightOptions) => number|null} now
|
||||
* Height in metres above the ellipsoid from what is loaded, or null.
|
||||
* @property {(position: Cesium.Cartesian3, options?: {exclude?: object[]}) => Cesium.Cartesian3|null} clampNow
|
||||
* `position` moved onto the drawn surface along the ellipsoid normal, or null.
|
||||
* @property {(points: HeightPoint[], options?: HeightOptions) => Promise<Array<number|null>>} batch
|
||||
* Heights once the most detailed tiles have streamed; null per miss. A
|
||||
* failed query (a tile request error, a destroyed scene) rejects, so the
|
||||
* caller can tell it from points that are merely uncovered.
|
||||
* @property {(positions: Cesium.Cartesian3[], options?: {exclude?: object[]}) => Promise<Array<Cesium.Cartesian3|null>>} clampBatch
|
||||
* Clamped copies of `positions`; null per miss, rejecting as `batch` does.
|
||||
* @property {() => {surface: boolean, clamp: boolean}} supported
|
||||
* Whether the drawn surface can be queried at all (Cesium needs depth
|
||||
* textures); terrain queries are always attempted.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The scene's height service, made on first use.
|
||||
* @param {object} scene A Cesium scene (or a test double).
|
||||
* @returns {HeightService}
|
||||
*/
|
||||
export function heightsFor(scene) {
|
||||
let service = services.get(scene);
|
||||
if (!service) {
|
||||
service = createHeights(scene);
|
||||
services.set(scene, service);
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
function createHeights(scene) {
|
||||
const terrainProvider = () =>
|
||||
scene.terrainProvider ?? scene.globe?.terrainProvider;
|
||||
|
||||
return {
|
||||
now(point, { against = 'surface', exclude } = NO_OPTIONS) {
|
||||
const carto = cartographicOf(point);
|
||||
if (!carto) return null;
|
||||
try {
|
||||
if (against === 'terrain')
|
||||
return metres(scene.globe?.getHeight?.(carto));
|
||||
// Cesium throws without depth-texture support: that is a miss.
|
||||
return metres(scene.sampleHeight?.(carto, exclude));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
clampNow(position, { exclude } = NO_OPTIONS) {
|
||||
if (!position) return null;
|
||||
try {
|
||||
return scene.clampToHeight?.(position, exclude) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
async batch(points, { against = 'surface', exclude } = NO_OPTIONS) {
|
||||
const cartos = points.map((point) => {
|
||||
const carto = cartographicOf(point, new Cesium.Cartographic());
|
||||
return (
|
||||
carto && new Cesium.Cartographic(carto.longitude, carto.latitude)
|
||||
);
|
||||
});
|
||||
const valid = cartos.filter(Boolean);
|
||||
if (!valid.length) return cartos.map(() => null);
|
||||
if (against === 'terrain') {
|
||||
const provider = terrainProvider();
|
||||
if (!provider) return cartos.map(() => null);
|
||||
await Cesium.sampleTerrainMostDetailed(provider, valid);
|
||||
} else {
|
||||
if (typeof scene.sampleHeightMostDetailed !== 'function')
|
||||
return cartos.map(() => null);
|
||||
await scene.sampleHeightMostDetailed(valid, exclude);
|
||||
}
|
||||
return cartos.map((carto) => (carto ? metres(carto.height) : null));
|
||||
},
|
||||
|
||||
async clampBatch(positions, { exclude } = NO_OPTIONS) {
|
||||
if (typeof scene.clampToHeightMostDetailed !== 'function')
|
||||
return positions.map(() => null);
|
||||
const clones = positions.map((p) => Cesium.Cartesian3.clone(p));
|
||||
const clamped = await scene.clampToHeightMostDetailed(clones, exclude);
|
||||
return clamped.map((p) => p ?? null);
|
||||
},
|
||||
|
||||
supported() {
|
||||
return SUPPORT[+(scene.sampleHeightSupported === true)][
|
||||
+(scene.clampToHeightSupported === true)
|
||||
];
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as Cesium from 'cesium';
|
||||
import { heightsFor } from './heights.js';
|
||||
|
||||
const ROOT = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
'..',
|
||||
'..',
|
||||
);
|
||||
|
||||
const AUSTIN = { lon: -97.74, lat: 30.27 };
|
||||
|
||||
function scene(overrides = {}) {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
sampleHeightSupported: true,
|
||||
clampToHeightSupported: true,
|
||||
sampleHeight(carto, exclude) {
|
||||
calls.push(['sampleHeight', carto, exclude]);
|
||||
return 150;
|
||||
},
|
||||
clampToHeight(position, exclude) {
|
||||
calls.push(['clampToHeight', position, exclude]);
|
||||
return Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 150);
|
||||
},
|
||||
globe: { getHeight: () => 140 },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test('now reads the drawn surface, seeing through what the caller excludes', () => {
|
||||
const s = scene();
|
||||
const own = [{ name: 'own marker' }];
|
||||
assert.equal(heightsFor(s).now(AUSTIN, { exclude: own }), 150);
|
||||
const [[, carto, exclude]] = s.calls;
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Math.toDegrees(carto.longitude) - AUSTIN.lon) < 1e-9,
|
||||
);
|
||||
assert.equal(exclude, own);
|
||||
});
|
||||
|
||||
test('now takes a Cartographic as it is', () => {
|
||||
const s = scene();
|
||||
const carto = Cesium.Cartographic.fromDegrees(AUSTIN.lon, AUSTIN.lat);
|
||||
heightsFor(s).now(carto);
|
||||
assert.equal(s.calls[0][1], carto);
|
||||
});
|
||||
|
||||
test('a miss is null, whatever form it takes', () => {
|
||||
for (const sampleHeight of [
|
||||
() => undefined,
|
||||
() => Number.NaN,
|
||||
() => {
|
||||
throw new Error('depth textures unsupported');
|
||||
},
|
||||
]) {
|
||||
assert.equal(heightsFor(scene({ sampleHeight })).now(AUSTIN), null);
|
||||
}
|
||||
assert.equal(
|
||||
heightsFor(scene({ sampleHeight: undefined })).now(AUSTIN),
|
||||
null,
|
||||
);
|
||||
assert.equal(heightsFor(scene()).now({ lon: 'x', lat: 1 }), null);
|
||||
});
|
||||
|
||||
test('terrain reads the loaded terrain tiles only', () => {
|
||||
const s = scene();
|
||||
assert.equal(heightsFor(s).now(AUSTIN, { against: 'terrain' }), 140);
|
||||
assert.equal(s.calls.length, 0, 'the drawn surface is not sampled');
|
||||
assert.equal(
|
||||
heightsFor(scene({ globe: undefined })).now(AUSTIN, { against: 'terrain' }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('clampNow moves a position onto the surface, or misses with null', () => {
|
||||
const s = scene();
|
||||
const own = [{}];
|
||||
const position = Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0);
|
||||
const clamped = heightsFor(s).clampNow(position, { exclude: own });
|
||||
assert.ok(
|
||||
Math.abs(Cesium.Cartographic.fromCartesian(clamped).height - 150) < 1e-6,
|
||||
);
|
||||
assert.equal(s.calls[0][2], own);
|
||||
assert.equal(
|
||||
heightsFor(scene({ clampToHeight: () => undefined })).clampNow(position),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('batch answers each point once the tiles stream, null per miss', async () => {
|
||||
let seen;
|
||||
const s = scene({
|
||||
async sampleHeightMostDetailed(cartos, exclude) {
|
||||
seen = exclude;
|
||||
cartos.forEach((c, i) => (c.height = i === 1 ? undefined : 100 + i));
|
||||
return cartos;
|
||||
},
|
||||
});
|
||||
const own = [{}];
|
||||
const heights = await heightsFor(s).batch(
|
||||
[
|
||||
AUSTIN,
|
||||
{ lon: 0, lat: 0 },
|
||||
Cesium.Cartographic.fromDegrees(1, 1, 999),
|
||||
{ lon: 'bad' },
|
||||
],
|
||||
{ exclude: own },
|
||||
);
|
||||
assert.deepEqual(heights, [100, null, 102, null]);
|
||||
assert.equal(seen, own);
|
||||
});
|
||||
|
||||
test('batch leaves the caller’s Cartographics alone', async () => {
|
||||
const s = scene({
|
||||
async sampleHeightMostDetailed(cartos) {
|
||||
cartos.forEach((c) => (c.height = 5));
|
||||
return cartos;
|
||||
},
|
||||
});
|
||||
const carto = Cesium.Cartographic.fromDegrees(1, 1, 999);
|
||||
await heightsFor(s).batch([carto]);
|
||||
assert.equal(carto.height, 999);
|
||||
});
|
||||
|
||||
test('batch misses everything when the scene cannot stream, and rejects when it fails', async () => {
|
||||
assert.deepEqual(await heightsFor(scene()).batch([AUSTIN]), [null]);
|
||||
const failing = scene({
|
||||
sampleHeightMostDetailed: async () => {
|
||||
throw new Error('scene destroyed');
|
||||
},
|
||||
clampToHeightMostDetailed: async () => {
|
||||
throw new Error('scene destroyed');
|
||||
},
|
||||
});
|
||||
await assert.rejects(heightsFor(failing).batch([AUSTIN]), /destroyed/);
|
||||
await assert.rejects(
|
||||
heightsFor(failing).clampBatch([Cesium.Cartesian3.UNIT_X]),
|
||||
/destroyed/,
|
||||
);
|
||||
assert.deepEqual(
|
||||
await heightsFor(scene()).batch([AUSTIN], { against: 'terrain' }),
|
||||
[null],
|
||||
'no terrain provider, no terrain heights',
|
||||
);
|
||||
});
|
||||
|
||||
test('clampBatch clamps copies and misses per position', async () => {
|
||||
const s = scene({
|
||||
async clampToHeightMostDetailed(positions) {
|
||||
return positions.map((p, i) => (i === 0 ? p : undefined));
|
||||
},
|
||||
});
|
||||
const position = Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0);
|
||||
const [first, second] = await heightsFor(s).clampBatch([position, position]);
|
||||
assert.notEqual(first, position, 'the caller’s position is not mutated');
|
||||
assert.equal(second, null);
|
||||
});
|
||||
|
||||
test('supported reports whether the drawn surface can be queried', () => {
|
||||
assert.deepEqual(heightsFor(scene()).supported(), {
|
||||
surface: true,
|
||||
clamp: true,
|
||||
});
|
||||
assert.deepEqual(
|
||||
heightsFor(
|
||||
scene({
|
||||
sampleHeightSupported: false,
|
||||
clampToHeightSupported: undefined,
|
||||
}),
|
||||
).supported(),
|
||||
{ surface: false, clamp: false },
|
||||
);
|
||||
});
|
||||
|
||||
test('supported answers without allocating', () => {
|
||||
const s = scene();
|
||||
assert.equal(heightsFor(s).supported(), heightsFor(s).supported());
|
||||
});
|
||||
|
||||
test('one service per scene', () => {
|
||||
const s = scene();
|
||||
assert.equal(heightsFor(s), heightsFor(s));
|
||||
assert.notEqual(heightsFor(s), heightsFor(scene()));
|
||||
});
|
||||
|
||||
test('height queries go through the service', () => {
|
||||
// A renderer that answers heights from a cache or asynchronously plugs in
|
||||
// at src/queries/heights.js; a site that asks Cesium directly bypasses it.
|
||||
const SERVICE = 'src/queries/heights.js';
|
||||
const NAMES =
|
||||
'sampleHeight|clampToHeight|sampleHeightMostDetailed|clampToHeightMostDetailed|getHeight';
|
||||
const direct = new RegExp(
|
||||
`\\.(${NAMES})\\b|\\[\\s*['"\`](${NAMES})['"\`]\\s*\\]|\\bsampleTerrain(MostDetailed)?\\b`,
|
||||
);
|
||||
const walk = (dir) =>
|
||||
fs
|
||||
.readdirSync(path.join(ROOT, dir), { withFileTypes: true })
|
||||
.flatMap((entry) => {
|
||||
const rel = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) return walk(rel);
|
||||
return /\.(js|vue)$/.test(entry.name) ? [rel] : [];
|
||||
});
|
||||
const offenders = walk('src').filter((file) => {
|
||||
if (file === SERVICE) return false;
|
||||
const code = fs
|
||||
.readFileSync(path.join(ROOT, file), 'utf8')
|
||||
.replace(/\/\*[\s\S]*?\*\//g, '')
|
||||
.replace(/^\s*\/\/.*$/gm, '');
|
||||
return direct.test(code);
|
||||
});
|
||||
assert.deepEqual(offenders, []);
|
||||
});
|
||||
Reference in new issue
Block a user