mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
Quantized-mesh terrain can supply its tiles through fetchTile, like imagery
A `quantizedMesh` terrain spec takes an optional `fetchTile`, called with the tile (rows from the north), its URL as Cesium resolved it and an abort signal. Cesium still reads `layer.json` at the url and schedules, cancels and decodes the tiles; only the bytes of each tile come from `fetchTile`. A `missing` tile draws its parent's terrain there and a deferred one is asked for again shortly.
This commit is contained in:
1 parent
d9d79ebc4d
commit
eebde0bdca
9 files changed
+390
-6
No files matched your search
@@ -23,6 +23,7 @@ import { createCesiumImagery } from './imagery.js';
|
||||
import { attributionText } from './vectorBase.js';
|
||||
import { loadVectorStyle } from '../vectorBase/index.js';
|
||||
import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js';
|
||||
import { tileFetchResource, trackTileRequests } from './terrainTiles.js';
|
||||
|
||||
// The base marks live outside the adapter, so code that is not Cesium's can
|
||||
// mark a base; they are re-exported here for the code that still is.
|
||||
@@ -68,15 +69,26 @@ async function terrainProvider(spec, { worldDataToken }) {
|
||||
);
|
||||
},
|
||||
});
|
||||
const resource = new Cesium.Resource({
|
||||
const options = {
|
||||
url: spec.url,
|
||||
retryCallback: policy.retryCallback,
|
||||
retryAttempts: policy.retryAttempts,
|
||||
});
|
||||
return Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
};
|
||||
if (spec.fetchTile !== undefined && typeof spec.fetchTile !== 'function')
|
||||
throw new TypeError('Quantized-mesh terrain fetchTile is a function');
|
||||
// With `fetchTile`, Cesium still reads `layer.json` at the url; each
|
||||
// tile's bytes come from `fetchTile`.
|
||||
const tiles = new WeakMap();
|
||||
const resource = spec.fetchTile
|
||||
? tileFetchResource(options, spec.fetchTile, (request) =>
|
||||
request ? tiles.get(request) : undefined,
|
||||
)
|
||||
: new Cesium.Resource(options);
|
||||
const provider = await Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
requestVertexNormals: spec.requestVertexNormals ?? false,
|
||||
requestWaterMask: false,
|
||||
});
|
||||
return spec.fetchTile ? trackTileRequests(provider, tiles) : provider;
|
||||
}
|
||||
throw new TypeError(`Unknown terrain kind: ${spec.kind}`);
|
||||
}
|
||||
|
||||
@@ -491,6 +491,38 @@ test('terrain: quantized mesh at its url, asked again when its host is busy', as
|
||||
);
|
||||
});
|
||||
|
||||
test('terrain: quantized mesh tiles through fetchTile', async (t) => {
|
||||
const { scene, port } = setup();
|
||||
const made = new Cesium.EllipsoidTerrainProvider();
|
||||
const own = made.requestTileGeometry;
|
||||
const asked = [];
|
||||
t.mock.method(Cesium.CesiumTerrainProvider, 'fromUrl', async (...args) => {
|
||||
asked.push(args);
|
||||
return made;
|
||||
});
|
||||
const fetchTile = async () => ({ missing: true });
|
||||
await port.setTerrain({
|
||||
kind: 'quantizedMesh',
|
||||
url: 'https://terrain.example/mesh',
|
||||
fetchTile,
|
||||
});
|
||||
assert.equal(scene.terrainProvider, made);
|
||||
const [[resource]] = asked;
|
||||
assert.equal(resource.url, 'https://terrain.example/mesh');
|
||||
assert.ok(resource.retryAttempts > 0, 'layer.json keeps its retry policy');
|
||||
assert.ok(resource instanceof Cesium.Resource);
|
||||
assert.notEqual(resource.constructor, Cesium.Resource);
|
||||
assert.notEqual(made.requestTileGeometry, own, 'tile requests are tracked');
|
||||
await assert.rejects(
|
||||
port.setTerrain({
|
||||
kind: 'quantizedMesh',
|
||||
url: 'https://terrain.example/mesh',
|
||||
fetchTile: 'nope',
|
||||
}),
|
||||
/fetchTile is a function/,
|
||||
);
|
||||
});
|
||||
|
||||
test('setBase replaces the imagery and says what it drew', async () => {
|
||||
const { scene, port } = setup();
|
||||
const overlay = port.imagery.add({ kind: 'xyz', url: url('overlay') });
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* @module render/cesium/terrainTiles
|
||||
* @description Quantized-mesh terrain tiles fetched through a terrain
|
||||
* spec's `fetchTile`, the way imagery layers fetch theirs.
|
||||
*
|
||||
* Cesium still reads `layer.json` itself, decides which tiles a frame needs,
|
||||
* schedules and cancels their requests and decodes the meshes; only the
|
||||
* fetch of each tile's bytes goes through `fetchTile`. Every resource
|
||||
* Cesium derives from the terrain's resource (its `layer.json`, each tile)
|
||||
* is a {@link tileFetchResource}, so a tile request reaches `fetchTile`
|
||||
* with the tile's URL as Cesium resolved it.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/** Delay before a deferred terrain tile is asked for again. */
|
||||
export const TERRAIN_RETRY_DELAY_MS = 250;
|
||||
|
||||
/** A tile `fetchTile` says is not there; Cesium draws the parent's instead. */
|
||||
export class MissingTerrainTile extends Error {
|
||||
constructor() {
|
||||
super('Terrain tile is missing');
|
||||
this.name = 'MissingTerrainTile';
|
||||
}
|
||||
}
|
||||
|
||||
const wait = (ms, signal) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(done, ms);
|
||||
function done() {
|
||||
signal.removeEventListener('abort', aborted);
|
||||
resolve();
|
||||
}
|
||||
function aborted() {
|
||||
clearTimeout(timer);
|
||||
reject(signal.reason);
|
||||
}
|
||||
signal.addEventListener('abort', aborted, { once: true });
|
||||
});
|
||||
|
||||
/** Whether a resource's template values name one tile. */
|
||||
const isTile = (values) =>
|
||||
Number.isInteger(values?.x) &&
|
||||
Number.isInteger(values?.y) &&
|
||||
Number.isInteger(values?.z);
|
||||
|
||||
/**
|
||||
* A Cesium `Resource` whose tile fetches go through `fetchTile`.
|
||||
*
|
||||
* `tileOf` gives the tile, in the terrain's own tiling scheme (rows from
|
||||
* the north, as `requestTileGeometry` counts them), that a Cesium request
|
||||
* is for; without one it is read from the resolved template values.
|
||||
* @param {object} options Cesium `Resource` options.
|
||||
* @param {(request: {tile: import('../contract/globe').TileRequest,
|
||||
* url: string, signal: AbortSignal})
|
||||
* => Promise<import('../contract/globe').TileFetch>} fetchTile
|
||||
* @param {(request: object|undefined) => import('../contract/globe').TileRequest|undefined} tileOf
|
||||
* @param {{retryDelayMs?: number}} [timing]
|
||||
* @returns {object} A Cesium `Resource`.
|
||||
*/
|
||||
export function tileFetchResource(options, fetchTile, tileOf, timing = {}) {
|
||||
const retryDelayMs = timing.retryDelayMs ?? TERRAIN_RETRY_DELAY_MS;
|
||||
|
||||
class TileFetchResource extends Cesium.Resource {
|
||||
/**
|
||||
* Clones stay of this kind, so derived tile resources keep the hook.
|
||||
* `clone(result)` copies every field onto `result`, its URL included.
|
||||
*/
|
||||
clone(result) {
|
||||
return super.clone(
|
||||
result ?? new TileFetchResource({ url: this.url, parseUrl: false }),
|
||||
);
|
||||
}
|
||||
|
||||
fetchArrayBuffer() {
|
||||
const values = this.templateValues;
|
||||
if (!isTile(values)) return super.fetchArrayBuffer();
|
||||
const request = this.request;
|
||||
const url = this.url;
|
||||
const tile = tileOf(request) ?? {
|
||||
x: values.x,
|
||||
y: values.y,
|
||||
level: values.z,
|
||||
};
|
||||
if (
|
||||
request.state === Cesium.RequestState.ISSUED ||
|
||||
request.state === Cesium.RequestState.ACTIVE
|
||||
)
|
||||
throw new Cesium.RuntimeError('The Resource is already being fetched.');
|
||||
const controller = new AbortController();
|
||||
request.url = url;
|
||||
request.state = Cesium.RequestState.UNISSUED;
|
||||
request.deferred = undefined;
|
||||
// Cesium cancels a request whose tile is no longer wanted.
|
||||
request.cancelFunction = () => controller.abort();
|
||||
request.requestFunction = async () => {
|
||||
for (;;) {
|
||||
const answer = await fetchTile({
|
||||
tile: { ...tile },
|
||||
url,
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.signal.throwIfAborted();
|
||||
if (answer?.defer) {
|
||||
await wait(retryDelayMs, controller.signal);
|
||||
continue;
|
||||
}
|
||||
if (!answer || answer.missing) throw new MissingTerrainTile();
|
||||
return answer.bytes;
|
||||
}
|
||||
};
|
||||
const promise = Cesium.RequestScheduler.request(request);
|
||||
if (!promise) return undefined;
|
||||
return promise.finally(() => {
|
||||
request.cancelFunction = undefined;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new TileFetchResource(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* A terrain provider whose tile requests tell `tileFetchResource` which
|
||||
* tile each is for. Requests Cesium makes without a `Request` are given one.
|
||||
* @param {object} provider Cesium `CesiumTerrainProvider`.
|
||||
* @param {WeakMap<object, import('../contract/globe').TileRequest>} tiles
|
||||
* @returns {object} The same provider.
|
||||
*/
|
||||
export function trackTileRequests(provider, tiles) {
|
||||
const own = provider.requestTileGeometry.bind(provider);
|
||||
provider.requestTileGeometry = (x, y, level, request) => {
|
||||
const asked = request ?? new Cesium.Request({ throttle: false });
|
||||
tiles.set(asked, { x, y, level });
|
||||
return own(x, y, level, asked);
|
||||
};
|
||||
return provider;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
MissingTerrainTile,
|
||||
tileFetchResource,
|
||||
trackTileRequests,
|
||||
} from './terrainTiles.js';
|
||||
|
||||
const ROOT = 'https://terrain.invalid/mesh/';
|
||||
const LAYER = JSON.stringify({
|
||||
tilejson: '2.1.0',
|
||||
format: 'quantized-mesh-1.0',
|
||||
version: '1.0.0',
|
||||
scheme: 'tms',
|
||||
tiles: ['{z}/{x}/{y}.terrain?v={version}'],
|
||||
projection: 'EPSG:4326',
|
||||
bounds: [-180, -90, 180, 90],
|
||||
minzoom: 0,
|
||||
maxzoom: 2,
|
||||
available: [
|
||||
[{ startX: 0, startY: 0, endX: 1, endY: 0 }],
|
||||
[{ startX: 0, startY: 0, endX: 3, endY: 1 }],
|
||||
[{ startX: 0, startY: 0, endX: 7, endY: 3 }],
|
||||
],
|
||||
});
|
||||
|
||||
/** One triangle over the tile: the smallest mesh Cesium decodes. */
|
||||
function meshBytes() {
|
||||
const view = new DataView(new ArrayBuffer(160));
|
||||
let at = 88; // centre, heights, bounding sphere, horizon point: all zero
|
||||
view.setFloat64(24 + 8 + 24, 1, true); // bounding sphere radius
|
||||
const u32 = (v) => (view.setUint32(at, v, true), (at += 4));
|
||||
const u16 = (v) => (view.setUint16(at, v, true), (at += 2));
|
||||
u32(3);
|
||||
// Zig-zag deltas of u (0, 32767, 0), v (0, 0, 32767) and h (0, 0, 0).
|
||||
[0, 65534, 65533, 0, 0, 65534, 0, 0, 0].forEach(u16);
|
||||
u32(1);
|
||||
[0, 0, 0].forEach(u16); // high-water-mark indices 0, 1, 2
|
||||
(u32(2), u16(0), u16(2)); // west
|
||||
(u32(2), u16(0), u16(1)); // south
|
||||
(u32(1), u16(1)); // east
|
||||
(u32(1), u16(2)); // north
|
||||
return view.buffer.slice(0, at);
|
||||
}
|
||||
|
||||
/** Answers `layer.json` the way a host would; tiles never reach the network. */
|
||||
function serveLayer(t) {
|
||||
const fetched = [];
|
||||
t.mock.method(
|
||||
Cesium.Resource._Implementations,
|
||||
'loadWithXhr',
|
||||
(url, responseType, method, data, headers, deferred) => {
|
||||
fetched.push(url);
|
||||
if (url.startsWith(`${ROOT}layer.json`)) deferred.resolve(LAYER);
|
||||
else deferred.reject(new Error(`unexpected fetch ${url}`));
|
||||
},
|
||||
);
|
||||
return fetched;
|
||||
}
|
||||
|
||||
async function terrain(fetchTile, timing) {
|
||||
const tiles = new WeakMap();
|
||||
const resource = tileFetchResource(
|
||||
{ url: ROOT },
|
||||
fetchTile,
|
||||
(request) => (request ? tiles.get(request) : undefined),
|
||||
timing,
|
||||
);
|
||||
const provider = await Cesium.CesiumTerrainProvider.fromUrl(resource, {
|
||||
requestWaterMask: false,
|
||||
});
|
||||
return trackTileRequests(provider, tiles);
|
||||
}
|
||||
|
||||
test('terrain fetchTile: tiles come from fetchTile, layer.json from the url', async (t) => {
|
||||
const fetched = serveLayer(t);
|
||||
const asked = [];
|
||||
const provider = await terrain(async (request) => {
|
||||
asked.push(request);
|
||||
return { bytes: meshBytes() };
|
||||
});
|
||||
const data = await provider.requestTileGeometry(
|
||||
1,
|
||||
0,
|
||||
1,
|
||||
new Cesium.Request(),
|
||||
);
|
||||
assert.ok(data instanceof Cesium.QuantizedMeshTerrainData);
|
||||
assert.deepEqual(
|
||||
fetched.map((u) => new URL(u).pathname),
|
||||
['/mesh/layer.json'],
|
||||
);
|
||||
assert.equal(asked.length, 1);
|
||||
// Rows from the north for the tile; the URL is Cesium's, rows from the
|
||||
// south as the layer's tms scheme counts them.
|
||||
assert.deepEqual(asked[0].tile, { x: 1, y: 0, level: 1 });
|
||||
assert.equal(asked[0].url, `${ROOT}1/1/1.terrain?v=1.0.0`);
|
||||
assert.ok(asked[0].signal instanceof AbortSignal);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a request Cesium makes without a Request still names its tile', async (t) => {
|
||||
serveLayer(t);
|
||||
const asked = [];
|
||||
const provider = await terrain(async (request) => {
|
||||
asked.push(request.tile);
|
||||
return { bytes: meshBytes() };
|
||||
});
|
||||
await provider.requestTileGeometry(3, 1, 2);
|
||||
assert.deepEqual(asked, [{ x: 3, y: 1, level: 2 }]);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a missing tile fails, so the parent is drawn there', async (t) => {
|
||||
serveLayer(t);
|
||||
const provider = await terrain(async () => ({ missing: true }));
|
||||
await assert.rejects(
|
||||
provider.requestTileGeometry(0, 0, 0, new Cesium.Request()),
|
||||
MissingTerrainTile,
|
||||
);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: a deferred tile is asked for again', async (t) => {
|
||||
serveLayer(t);
|
||||
let calls = 0;
|
||||
const provider = await terrain(
|
||||
async () => (++calls < 3 ? { defer: true } : { bytes: meshBytes() }),
|
||||
{ retryDelayMs: 1 },
|
||||
);
|
||||
const data = await provider.requestTileGeometry(
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
new Cesium.Request(),
|
||||
);
|
||||
assert.ok(data instanceof Cesium.QuantizedMeshTerrainData);
|
||||
assert.equal(calls, 3);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: cancelling the request aborts the fetch', async (t) => {
|
||||
serveLayer(t);
|
||||
let signal;
|
||||
const provider = await terrain(
|
||||
(request) =>
|
||||
new Promise((resolve, reject) => {
|
||||
signal = request.signal;
|
||||
signal.addEventListener('abort', () => reject(signal.reason));
|
||||
}),
|
||||
);
|
||||
const request = new Cesium.Request();
|
||||
const pending = provider.requestTileGeometry(0, 0, 0, request);
|
||||
pending.catch(() => {});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(signal.aborted, false);
|
||||
request.cancel();
|
||||
// Cesium's scheduler cancels on its next update.
|
||||
Cesium.RequestScheduler.update();
|
||||
assert.equal(signal.aborted, true);
|
||||
});
|
||||
|
||||
test('terrain fetchTile: resources that are not tiles fetch as before', async (t) => {
|
||||
const fetched = serveLayer(t);
|
||||
const resource = tileFetchResource(
|
||||
{ url: ROOT },
|
||||
async () => assert.fail('not a tile'),
|
||||
() => undefined,
|
||||
);
|
||||
const derived = resource.getDerivedResource({ url: 'layer.json' });
|
||||
assert.equal(derived.constructor, resource.constructor);
|
||||
assert.equal(await derived.fetchArrayBuffer(), LAYER);
|
||||
assert.equal(fetched.length, 1);
|
||||
});
|
||||
Reference in new issue
Block a user