mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Areas, buildings, routes, arrows, pins and labels are draw-port shapes, lines and points, one set per mark, faded by upserting their colours. Pins pulse their ring and size it by camera height; arrows drape. Ground heights come from the heights service. The module leaves the Cesium allow-list.
789 lines
33 KiB
JavaScript
789 lines
33 KiB
JavaScript
import { test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import * as Cesium from 'cesium';
|
|
import { createPinia } from 'pinia';
|
|
import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js';
|
|
import { createHybridAnnotationRenderer } from './hybridAnnotationRenderer.js';
|
|
import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js';
|
|
import { bindFakeCesiumCredits, fakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
|
|
import { bindRenderer } from '../render/rendererOf.js';
|
|
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
|
|
|
|
/** A hybrid renderer whose screen board is presented to its own store. */
|
|
function hybridWithBoard(viewer) {
|
|
const store = useScreenAnnotationsStore(createPinia());
|
|
const renderer = createHybridAnnotationRenderer(viewer, { screen: { store } });
|
|
return { store, renderer };
|
|
}
|
|
|
|
/** The screen marks the board shows, fading ones included. */
|
|
function annotationGroups(store) {
|
|
return store.board?.marks ?? [];
|
|
}
|
|
|
|
const childrenWithClass = (mark, name) =>
|
|
mark.children.filter((child) => child.attrs?.class?.split(' ').includes(name));
|
|
|
|
function cameraLookingAt(lon, lat) {
|
|
const target = Cesium.Cartesian3.fromDegrees(lon, lat);
|
|
const radial = Cesium.Cartesian3.normalize(target, new Cesium.Cartesian3());
|
|
const position = Cesium.Cartesian3.multiplyByScalar(
|
|
radial,
|
|
Cesium.Cartesian3.magnitude(target) + 1_000_000,
|
|
new Cesium.Cartesian3(),
|
|
);
|
|
const direction = Cesium.Cartesian3.normalize(
|
|
Cesium.Cartesian3.subtract(target, position, new Cesium.Cartesian3()),
|
|
new Cesium.Cartesian3(),
|
|
);
|
|
const right = Cesium.Cartesian3.normalize(
|
|
Cesium.Cartesian3.cross(direction, Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3()),
|
|
new Cesium.Cartesian3(),
|
|
);
|
|
const up = Cesium.Cartesian3.normalize(
|
|
Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3()),
|
|
new Cesium.Cartesian3(),
|
|
);
|
|
const frustum = new Cesium.PerspectiveFrustum({
|
|
fov: Cesium.Math.toRadians(60),
|
|
aspectRatio: 1280 / 720,
|
|
near: 1,
|
|
far: 20_000_000,
|
|
});
|
|
return {
|
|
positionWC: position,
|
|
directionWC: direction,
|
|
rightWC: right,
|
|
upWC: up,
|
|
viewMatrix: Cesium.Matrix4.computeView(
|
|
position,
|
|
direction,
|
|
up,
|
|
right,
|
|
new Cesium.Matrix4(),
|
|
),
|
|
frustum,
|
|
positionCartographic: { height: 1_000_000 },
|
|
};
|
|
}
|
|
|
|
/** Install the browser globals both renderers touch, restored after the test. */
|
|
function installBrowserGlobals(t) {
|
|
const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
|
|
const originalWindow = globalThis.window;
|
|
const originalBrowserConstructors = new Map([
|
|
['HTMLCanvasElement', globalThis.HTMLCanvasElement],
|
|
['HTMLImageElement', globalThis.HTMLImageElement],
|
|
['ImageBitmap', globalThis.ImageBitmap],
|
|
['OffscreenCanvas', globalThis.OffscreenCanvas],
|
|
]);
|
|
globalThis.requestAnimationFrame = (callback) => { callback(); return 1; };
|
|
globalThis.window = { setTimeout: (fn) => { fn(); return 1; } };
|
|
for (const name of originalBrowserConstructors.keys()) globalThis[name] = class {};
|
|
t.after(() => {
|
|
if (originalRequestAnimationFrame === undefined) delete globalThis.requestAnimationFrame;
|
|
else globalThis.requestAnimationFrame = originalRequestAnimationFrame;
|
|
if (originalWindow === undefined) delete globalThis.window;
|
|
else globalThis.window = originalWindow;
|
|
for (const [name, original] of originalBrowserConstructors) {
|
|
if (original === undefined) delete globalThis[name];
|
|
else globalThis[name] = original;
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* `viewer` with the fake scene's camera, query, frame and draw ports and the
|
|
* fake credits bound over it as one renderer.
|
|
*/
|
|
function withScenePorts(viewer) {
|
|
const { unbind, ...ports } = bindFakeCesiumScene(viewer);
|
|
unbind();
|
|
bindRenderer(viewer, { ...ports, credits: fakeCesiumCredits(viewer) });
|
|
return ports.draw;
|
|
}
|
|
|
|
/** What the world renderer draws, each item of its live sets (of `kind`). */
|
|
function worldItems(draw, kind) {
|
|
const items = [];
|
|
for (const record of draw.sets.values())
|
|
if (
|
|
!record.disposed &&
|
|
record.spec.id.startsWith('annotations:') &&
|
|
(!kind || record.kind === kind)
|
|
)
|
|
items.push(...record.items.values());
|
|
return items;
|
|
}
|
|
|
|
/** Surface heights the scene samples: `height(lon, lat)` in degrees. */
|
|
function sampleHeights(scene, height) {
|
|
scene.sampleHeightSupported = true;
|
|
scene.sampleHeight = (carto) =>
|
|
height(Cesium.Math.toDegrees(carto.longitude), Cesium.Math.toDegrees(carto.latitude));
|
|
}
|
|
|
|
/** A viewer whose scene/camera is just enough for both sub-renderers. */
|
|
function fakeViewer(lon, lat) {
|
|
const credits = new Set();
|
|
const camera = cameraLookingAt(lon, lat);
|
|
const frames = controlledFrames();
|
|
const scene = {
|
|
camera,
|
|
canvas: { clientWidth: 1280, clientHeight: 720, width: 1280, height: 720 },
|
|
frameState: { mode: Cesium.SceneMode.SCENE3D },
|
|
clampToHeightSupported: true,
|
|
clampToHeight: (world) => world,
|
|
postRender: frames.event,
|
|
renderRequests: 0,
|
|
requestRender() {
|
|
scene.renderRequests += 1;
|
|
},
|
|
};
|
|
const viewer = {
|
|
credits,
|
|
creditDisplay: {
|
|
addStaticCredit: (credit) => credits.add(credit),
|
|
removeStaticCredit: (credit) => credits.delete(credit),
|
|
},
|
|
scene,
|
|
camera,
|
|
canvas: scene.canvas,
|
|
trackedEntity: null,
|
|
};
|
|
const draw = withScenePorts(viewer);
|
|
return { draw, frames, viewer };
|
|
}
|
|
|
|
function controlledFrames() {
|
|
const listeners = new Set();
|
|
return {
|
|
event: {
|
|
addEventListener(listener) { listeners.add(listener); },
|
|
removeEventListener(listener) { listeners.delete(listener); },
|
|
},
|
|
emit() { for (const listener of [...listeners]) listener(); },
|
|
snapshot() { return [...listeners]; },
|
|
get size() { return listeners.size; },
|
|
};
|
|
}
|
|
|
|
function buildingAnnotation(id, offset = 0) {
|
|
const ring = [
|
|
[-99 + offset, 31], [-98.999 + offset, 31],
|
|
[-98.999 + offset, 31.001], [-99 + offset, 31.001],
|
|
[-99 + offset, 31],
|
|
];
|
|
return {
|
|
id, type: 'area', color: 'primary', label: null, alpha: 1,
|
|
anchor: { ...naiveRingCentroid(ring), height: 100 },
|
|
ring, footprintKind: 'building', buildingHeight: 20, outlineCredit: 'tiles',
|
|
};
|
|
}
|
|
|
|
function naiveRingCentroid(ring) {
|
|
const totals = ring.reduce(
|
|
(sum, [lon, lat]) => ({ lon: sum.lon + lon, lat: sum.lat + lat }),
|
|
{ lon: 0, lat: 0 },
|
|
);
|
|
return { lon: totals.lon / ring.length, lat: totals.lat / ring.length, height: 0 };
|
|
}
|
|
|
|
test('hybrid outline upgrade preserves the screen group and adds world geometry', async (t) => {
|
|
const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
|
|
const originalWindow = globalThis.window;
|
|
globalThis.window = { setTimeout: (fn) => { fn(); return 1; } };
|
|
const originalBrowserConstructors = new Map([
|
|
['HTMLCanvasElement', globalThis.HTMLCanvasElement],
|
|
['HTMLImageElement', globalThis.HTMLImageElement],
|
|
['ImageBitmap', globalThis.ImageBitmap],
|
|
['OffscreenCanvas', globalThis.OffscreenCanvas],
|
|
]);
|
|
globalThis.requestAnimationFrame = (callback) => { callback(); return 1; };
|
|
for (const name of originalBrowserConstructors.keys()) globalThis[name] = class {};
|
|
t.after(() => {
|
|
if (originalRequestAnimationFrame === undefined) delete globalThis.requestAnimationFrame;
|
|
else globalThis.requestAnimationFrame = originalRequestAnimationFrame;
|
|
if (originalWindow === undefined) delete globalThis.window;
|
|
else globalThis.window = originalWindow;
|
|
for (const [name, original] of originalBrowserConstructors) {
|
|
if (original === undefined) delete globalThis[name];
|
|
else globalThis[name] = original;
|
|
}
|
|
});
|
|
|
|
const camera = cameraLookingAt(-99, 31);
|
|
const frames = controlledFrames();
|
|
const scene = {
|
|
camera,
|
|
canvas: { clientWidth: 1280, clientHeight: 720, width: 1280, height: 720 },
|
|
frameState: { mode: Cesium.SceneMode.SCENE3D },
|
|
clampToHeightSupported: true,
|
|
clampToHeight: (world) => world,
|
|
postRender: frames.event,
|
|
requestRender() {},
|
|
};
|
|
const viewer = {
|
|
scene,
|
|
camera,
|
|
canvas: scene.canvas,
|
|
trackedEntity: null,
|
|
};
|
|
// The screen board projects through the renderer's camera and query; the
|
|
// world renderer draws through its draw port.
|
|
const { draw } = bindFakeCesiumScene(viewer);
|
|
const { store, renderer } = hybridWithBoard(viewer);
|
|
const anno = {
|
|
id: 'anno-hybrid-fb3',
|
|
type: 'area',
|
|
color: 'primary',
|
|
label: 'Texas',
|
|
alpha: 1,
|
|
anchor: { lon: -99, lat: 31, height: 0 },
|
|
ring: null,
|
|
footprintKind: null,
|
|
synthesized: false,
|
|
};
|
|
|
|
renderer.add(anno);
|
|
const [before] = annotationGroups(store);
|
|
assert.equal(childrenWithClass(before, 'gev-anno-ring').length, 2);
|
|
assert.equal(worldItems(draw).length, 0);
|
|
|
|
const ring = [
|
|
[-106, 25],
|
|
[-93, 25],
|
|
[-93, 36],
|
|
[-106, 36],
|
|
[-106, 25],
|
|
];
|
|
const centroid = naiveRingCentroid(ring);
|
|
anno.ring = ring;
|
|
anno.anchor = centroid;
|
|
anno.footprintKind = 'area';
|
|
renderer.update(anno);
|
|
|
|
const [after, ...others] = annotationGroups(store);
|
|
const expectedWindow = Cesium.SceneTransforms.worldToWindowCoordinates(
|
|
scene,
|
|
Cesium.Cartesian3.fromDegrees(centroid.lon, centroid.lat, centroid.height),
|
|
);
|
|
assert.equal(after.key, before.key, 'the real hybrid keeps the existing screen mark');
|
|
assert.equal(others.length, 0);
|
|
assert.equal(childrenWithClass(after, 'gev-anno-ring').length, 0, 'screen reticle rings are removed');
|
|
assert.deepEqual(
|
|
after.children.map((child) => child.key),
|
|
['dot', 'leader', 'callout'],
|
|
'the dot, leader and callout are retained',
|
|
);
|
|
const dot = after.children.find((child) => child.key === 'dot');
|
|
assert.equal(dot.attrs.cx, expectedWindow.x.toFixed(1));
|
|
assert.equal(dot.attrs.cy, expectedWindow.y.toFixed(1));
|
|
assert.deepEqual(centroid, { lon: -100.8, lat: 29.4, height: 0 }, 'closed-ring vertex mean stays pinned');
|
|
assert.equal(worldItems(draw).length, 2, 'world area adds one fill and one outline');
|
|
assert.equal(worldItems(draw, 'shapes').length, 1);
|
|
assert.equal(worldItems(draw, 'lines').length, 1);
|
|
assert.equal(Object.hasOwn(anno, '_draw'), false, 'world draw state stays on the inherited proxy');
|
|
const outer = [
|
|
[-99, 31],
|
|
[-98.999, 31],
|
|
[-98.999, 31.001],
|
|
[-99, 31.001],
|
|
[-99, 31],
|
|
];
|
|
const hole = [
|
|
[-98.9998, 31.0002],
|
|
[-98.9996, 31.0002],
|
|
[-98.9996, 31.0004],
|
|
[-98.9998, 31.0004],
|
|
[-98.9998, 31.0002],
|
|
];
|
|
const island = outer.map(([lon, lat]) => [lon + 0.002, lat]);
|
|
const building = {
|
|
...anno,
|
|
id: 'anno-multipart-building',
|
|
label: 'Building',
|
|
anchor: { lon: -99, lat: 31, height: 0 },
|
|
ring: outer,
|
|
polygons: [[outer, hole], [island]],
|
|
footprintKind: 'building',
|
|
buildingHeight: 20,
|
|
};
|
|
const completion = renderer.add(building);
|
|
assert.equal(worldItems(draw).length, 2, 'building geometry waits for all probes');
|
|
for (let frame = 0; frame < 8; frame += 1) frames.emit();
|
|
assert.equal((await completion).status, 'installed');
|
|
const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:'));
|
|
assert.equal(
|
|
fills.length,
|
|
2,
|
|
'every building part gets a volume',
|
|
);
|
|
assert.equal(fills[0].geometry.rings.length, 2, 'the first with its hole');
|
|
assert.equal(fills[1].geometry.rings.length, 1);
|
|
assert.deepEqual(fills[0].fill, fills[1].fill, 'parts share the fill colour');
|
|
assert.equal(
|
|
worldItems(draw, 'lines').filter((item) => item.id.startsWith('base:')).length,
|
|
3,
|
|
'all outer and hole outlines are retained',
|
|
);
|
|
renderer.remove(building);
|
|
assert.equal(
|
|
worldItems(draw).length,
|
|
2,
|
|
'multipart removal leaves only the earlier area',
|
|
);
|
|
renderer.destroy();
|
|
});
|
|
|
|
// ── Partial-add rollback (review round 2) ─────────────────────────────────────
|
|
//
|
|
// The hybrid builds a mark across TWO sub-renderers. It used to record the
|
|
// route only after both had run, so a throw in the second one left the first
|
|
// one's content live with nothing pointing at it: remove() was a no-op and the
|
|
// engine's rollback (which knows only the id) could not reach it. The next
|
|
// annotate of the same geometry then stacked a fresh mark over that orphan.
|
|
|
|
test('a sub-renderer throw mid-add leaves state the rollback can still remove', (t) => {
|
|
installBrowserGlobals(t);
|
|
const { viewer, draw } = fakeViewer(-99, 31);
|
|
const { store, renderer } = hybridWithBoard(viewer);
|
|
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
|
|
const anno = {
|
|
id: 'anno-partial-add',
|
|
type: 'area',
|
|
color: 'primary',
|
|
label: 'Texas',
|
|
alpha: 1,
|
|
anchor: naiveRingCentroid(ring),
|
|
ring,
|
|
footprintKind: 'area',
|
|
synthesized: false,
|
|
};
|
|
|
|
// The world drape lands first; the screen caption then fails the way a lost
|
|
// context does, AFTER the world geometry is already on the board.
|
|
const publish = store.publish;
|
|
let failNextInsert = true;
|
|
store.publish = (board) => {
|
|
if (failNextInsert) {
|
|
failNextInsert = false;
|
|
throw new Error('screen insert failed');
|
|
}
|
|
return publish(board);
|
|
};
|
|
|
|
assert.throws(() => renderer.add(anno), /screen insert failed/);
|
|
assert.equal(worldItems(draw).length, 2, 'the world drape is already live');
|
|
assert.equal(annotationGroups(store).length, 0, 'the half-built screen group detached itself');
|
|
|
|
// The engine's rollback path — it must reach the partial state by id.
|
|
renderer.remove(anno);
|
|
assert.equal(worldItems(draw).length, 0, 'partial world state must be released');
|
|
|
|
// …and the id is free again: a retry draws ONE mark, not a second one over
|
|
// an orphan nothing owns.
|
|
renderer.add(anno);
|
|
assert.equal(worldItems(draw).length, 2, 'the retry draws exactly one world drape');
|
|
assert.equal(annotationGroups(store).length, 1, 'and exactly one screen caption');
|
|
renderer.remove(anno);
|
|
assert.equal(worldItems(draw).length, 0);
|
|
renderer.destroy();
|
|
});
|
|
|
|
test('a release that throws keeps the mark addressable for a retry cleanup', (t) => {
|
|
installBrowserGlobals(t);
|
|
const { viewer, draw } = fakeViewer(-99, 31);
|
|
const { store, renderer } = hybridWithBoard(viewer);
|
|
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
|
|
const anno = {
|
|
id: 'anno-release-throw',
|
|
type: 'area',
|
|
color: 'primary',
|
|
label: 'Texas',
|
|
alpha: 1,
|
|
anchor: naiveRingCentroid(ring),
|
|
ring,
|
|
footprintKind: 'area',
|
|
synthesized: false,
|
|
};
|
|
|
|
renderer.add(anno);
|
|
assert.equal(worldItems(draw).length, 2);
|
|
assert.equal(annotationGroups(store).length, 1);
|
|
|
|
// The world route releases fine, then the screen release fails part-way
|
|
// (its fade-out timer throws) — so its mark is still on the board.
|
|
const workingSetTimeout = globalThis.window.setTimeout;
|
|
globalThis.window.setTimeout = () => { throw new Error('teardown scheduling failed'); };
|
|
assert.throws(() => renderer.remove(anno), /teardown scheduling failed/);
|
|
assert.equal(worldItems(draw).length, 0, 'the world route did release');
|
|
assert.equal(annotationGroups(store).length, 1, 'the screen route did NOT — that is the orphan');
|
|
|
|
// Dropping the routing entry here would make that orphan permanently
|
|
// unreachable. It must still be addressable, so a retry finishes the job.
|
|
globalThis.window.setTimeout = workingSetTimeout;
|
|
renderer.remove(anno);
|
|
assert.equal(annotationGroups(store).length, 0, 'the retry cleanup must reach the orphan');
|
|
assert.equal(worldItems(draw).length, 0, 'without double-releasing the world route');
|
|
|
|
// Fully released now — a third call is inert.
|
|
renderer.remove(anno);
|
|
assert.equal(annotationGroups(store).length, 0);
|
|
renderer.destroy();
|
|
});
|
|
|
|
test('a world add that fails mid-way leaves its landed entities removable', (t) => {
|
|
installBrowserGlobals(t);
|
|
const { viewer, draw } = fakeViewer(-99, 31);
|
|
const { store, renderer } = hybridWithBoard(viewer);
|
|
const ring = [[-106, 25], [-93, 25], [-93, 36], [-106, 36], [-106, 25]];
|
|
const anno = {
|
|
id: 'anno-partial-world-add',
|
|
type: 'area',
|
|
color: 'primary',
|
|
label: 'Texas',
|
|
alpha: 1,
|
|
anchor: naiveRingCentroid(ring),
|
|
ring,
|
|
footprintKind: 'area',
|
|
synthesized: false,
|
|
};
|
|
|
|
// The draped fill lands; the outline throws (bad geometry / lost context).
|
|
const realLines = draw.lines;
|
|
draw.lines = (spec) => {
|
|
const set = realLines(spec);
|
|
set.set = () => { throw new Error('draw failed'); };
|
|
return set;
|
|
};
|
|
|
|
assert.throws(() => renderer.add(anno), /draw failed/);
|
|
assert.equal(worldItems(draw).length, 1, 'one item landed before the failure');
|
|
|
|
draw.lines = realLines;
|
|
renderer.remove(anno);
|
|
assert.equal(worldItems(draw).length, 0,
|
|
'the rollback must see the items that landed before the throw');
|
|
|
|
renderer.add(anno);
|
|
assert.equal(worldItems(draw).length, 2, 'the retry draws a complete mark');
|
|
assert.equal(annotationGroups(store).length, 1);
|
|
renderer.destroy();
|
|
});
|
|
|
|
function workTrace() {
|
|
return { timeOrigin: performance.timeOrigin, slices: [], dropped: 0 };
|
|
}
|
|
|
|
test('buildings share one probe per frame and preserve probe geometry, filtering and fallback', async (t) => {
|
|
installBrowserGlobals(t);
|
|
const { viewer, draw, frames } = fakeViewer(-99, 31);
|
|
const renderer = createHybridAnnotationRenderer(viewer);
|
|
t.after(() => renderer.destroy());
|
|
const first = buildingAnnotation('sampled-building');
|
|
const second = buildingAnnotation('fallback-building', 0.01);
|
|
second.outlineCredit = 'osm';
|
|
const otherOwner = {};
|
|
showOsmCredit(viewer, otherOwner);
|
|
const probes = [];
|
|
const outcomes = [-500, 120, 30, null, new Error('tile unavailable'), 60, 9001, 90];
|
|
sampleHeights(viewer.scene, (lon, lat) => {
|
|
probes.push([lon, lat]);
|
|
const outcome = outcomes[probes.length - 1];
|
|
if (outcome instanceof Error) throw outcome;
|
|
return outcome == null ? undefined : outcome;
|
|
});
|
|
// Suppress screen points: these counts concern the eight outside-building
|
|
// probes, not the screen renderer's separate anchor-height sampling.
|
|
const firstTrace = workTrace();
|
|
const secondTrace = workTrace();
|
|
let diagnosticWriteFaults = 0;
|
|
Object.defineProperty(secondTrace, 'groundDetailDropped', {
|
|
get: () => 0,
|
|
set() {
|
|
diagnosticWriteFaults += 1;
|
|
throw new Error('diagnostic sink unavailable');
|
|
},
|
|
enumerable: true,
|
|
});
|
|
const firstCompletion = renderer.add(first, { pendingVisible: false, workTrace: firstTrace });
|
|
const secondCompletion = renderer.add(second, { pendingVisible: false, workTrace: secondTrace });
|
|
assert.equal(probes.length, 0, 'enqueue must not probe synchronously');
|
|
assert.equal(worldItems(draw).length, 0);
|
|
assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1,
|
|
'pending outlines add no tile credit to the other owner');
|
|
for (let frame = 0; frame < 16; frame += 1) {
|
|
const before = probes.length;
|
|
frames.emit();
|
|
assert.equal(probes.length, before + 1, 'the two buildings share one total probe budget');
|
|
if (frame < 7) assert.equal(worldItems(draw).length, 0, 'no partial world parts');
|
|
}
|
|
const [installed, fallback] = await Promise.all([firstCompletion, secondCompletion]);
|
|
assert.equal(installed.status, 'installed');
|
|
assert.equal(fallback.status, 'installed');
|
|
assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 2);
|
|
assert.equal(installed.timing.probes, 8);
|
|
assert.equal(fallback.timing.probes, 8);
|
|
assert.ok(diagnosticWriteFaults > 0, 'the diagnostic failure was exercised');
|
|
for (const trace of [firstTrace, secondTrace]) {
|
|
assert.equal(trace.probes, 8);
|
|
assert.equal(trace.samplerStatus, 'installed');
|
|
assert.equal(trace.rendererStatus, 'installed');
|
|
assert.equal(trace.slices.filter(s => s.phase === 'ground-step').length, 8);
|
|
assert.equal(trace.slices.filter(s => s.phase === 'hybrid-complete').length, 1);
|
|
assert.equal(trace.dropped, 0);
|
|
assert.ok(trace.slices.every(s => Number.isFinite(s.start) && Number.isFinite(s.end) && s.end >= s.start));
|
|
assert.equal(trace.timeOrigin, performance.timeOrigin);
|
|
const parents = trace.slices.filter(s => s.phase === 'ground-step');
|
|
for (const [index, parent] of parents.entries()) {
|
|
const detail = parent.detail;
|
|
assert.equal(detail.index, index);
|
|
assert.equal(detail.status, trace === firstTrace ? 'recorded' : 'missing');
|
|
// The fourth probe finds nothing and the fifth throws: both are misses.
|
|
assert.equal(detail.clampResult,
|
|
trace === firstTrace && index !== 3 && index !== 4 ? 'hit' : 'missed');
|
|
assert.ok(Number.isFinite(detail.clampStart) && Number.isFinite(detail.clampEnd));
|
|
assert.ok(parent.start <= detail.clampStart && detail.clampStart <= detail.clampEnd && detail.clampEnd <= parent.end);
|
|
if (index === 7) {
|
|
assert.equal(detail.commitStatus, 'attempted');
|
|
assert.ok(Number.isFinite(detail.commitStart) && Number.isFinite(detail.commitEnd));
|
|
assert.ok(detail.clampEnd <= detail.commitStart && detail.commitStart <= detail.commitEnd && detail.commitEnd <= parent.end);
|
|
} else {
|
|
assert.equal(detail.commitStatus, 'not-run');
|
|
assert.equal(detail.commitStart, null);
|
|
assert.equal(detail.commitEnd, null);
|
|
}
|
|
}
|
|
}
|
|
assert.notEqual(firstTrace.slices, secondTrace.slices);
|
|
assert.ok(firstTrace.slices.filter(s => s.phase === 'ground-step').at(-1).end <= secondTrace.slices.find(s => s.phase === 'ground-step').start, 'each queued task records only its own sampling frames');
|
|
const centroid = naiveRingCentroid(first.ring);
|
|
const lonScale = 111320 * Math.cos(Cesium.Math.toRadians(centroid.lat));
|
|
const radius = Math.max(...first.ring.map(([lon, lat]) =>
|
|
Math.hypot((lon - centroid.lon) * lonScale, (lat - centroid.lat) * 111320)));
|
|
const distance = radius * 1.5 + 12;
|
|
const directions = [[1, 0], [-1, 0], [0, 1], [0, -1], [0.7, 0.7], [-0.7, -0.7], [0.7, -0.7], [-0.7, 0.7]];
|
|
for (let index = 0; index < 8; index += 1) {
|
|
const [dx, dy] = directions[index];
|
|
assert.ok(Math.abs(probes[index][0] - (centroid.lon + dx * distance / lonScale)) < 1e-10);
|
|
assert.ok(Math.abs(probes[index][1] - (centroid.lat + dy * distance / 111320)) < 1e-10);
|
|
assert.ok(Math.abs(probes[index + 8][0] - probes[index][0] - 0.01) < 1e-10);
|
|
assert.ok(Math.abs(probes[index + 8][1] - probes[index][1]) < 1e-10);
|
|
}
|
|
assert.equal(new Set(probes.slice(0, 8).map((point) => point.join(','))).size, 8);
|
|
const fills = worldItems(draw, 'shapes').filter((item) => item.id.startsWith('volume:'));
|
|
assert.equal(fills.length, 2);
|
|
assert.ok(Math.abs(fills[0].geometry.rings[0][0].height - 57) < 1e-6, 'four accepted samples select floor(4 * 0.3), height 60 minus 3');
|
|
assert.ok(Math.abs(fills[1].geometry.rings[0][0].height - 77) < 1e-6, 'all unavailable probes retain anchor minus building height fallback');
|
|
const afterCompletion = probes.length;
|
|
frames.emit();
|
|
assert.equal(probes.length, afterCompletion, 'completion releases the sampler');
|
|
renderer.remove(first);
|
|
assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1,
|
|
'removing the last tile proxy retains the OSM building and other owner');
|
|
renderer.remove(second);
|
|
assert.equal([...viewer.credits].filter(c => c.showOnScreen).length, 1);
|
|
hideOsmCredit(viewer, otherOwner);
|
|
assert.equal(viewer.credits.size, 0);
|
|
});
|
|
|
|
test('a building queued behind others gets its full budget on a slow device', async (t) => {
|
|
installBrowserGlobals(t);
|
|
t.mock.timers.enable({ apis: ['setTimeout'] });
|
|
t.after(() => t.mock.timers.reset());
|
|
// The renderers' per-frame budget checks read performance.now(); it follows
|
|
// the same mocked clock as the timers.
|
|
let now = 0;
|
|
t.mock.method(globalThis.performance, 'now', () => now);
|
|
const { viewer, frames } = fakeViewer(-99, 31);
|
|
const renderer = createHybridAnnotationRenderer(viewer);
|
|
sampleHeights(viewer.scene, () => 0);
|
|
const traces = [workTrace(), workTrace(), workTrace()];
|
|
const completions = [0, 0.01, 0.02].map((offset, index) =>
|
|
renderer.add(buildingAnnotation(`queued-${index}`, offset), {
|
|
pendingVisible: false,
|
|
workTrace: traces[index],
|
|
}));
|
|
// Eight probes per building at one probe per frame, at about 5 fps: each
|
|
// building samples for 1.5 s, so the third waits 3 s in line. Pending
|
|
// promise work runs between frames, as it does in a browser.
|
|
for (let building = 0; building < 3; building += 1) {
|
|
for (let frame = 0; frame < 8; frame += 1) {
|
|
now += 187.5;
|
|
t.mock.timers.tick(187.5);
|
|
frames.emit();
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
}
|
|
}
|
|
const results = await Promise.all(completions);
|
|
assert.deepEqual(results.map((result) => result.status), ['installed', 'installed', 'installed']);
|
|
assert.deepEqual(traces.map((trace) => trace.samplerStatus), ['installed', 'installed', 'installed']);
|
|
assert.ok(traces[2].samplerHeadAt - traces[2].samplerStart >= 2000, 'the third waited longer than one budget');
|
|
assert.ok(traces[2].samplerHeadAt >= traces[1].samplerHeadAt);
|
|
});
|
|
|
|
test('building cancellation, queued deadline and destroy prevent saved callbacks from committing', async (t) => {
|
|
installBrowserGlobals(t);
|
|
t.mock.timers.enable({ apis: ['setTimeout'] });
|
|
t.after(() => t.mock.timers.reset());
|
|
const { viewer, draw, frames } = fakeViewer(-99, 31);
|
|
const renderer = createHybridAnnotationRenderer(viewer);
|
|
let probeCount = 0;
|
|
sampleHeights(viewer.scene, () => { probeCount += 1; return 0; });
|
|
const cancelled = buildingAnnotation('cancelled-building');
|
|
const cancelledTrace = workTrace();
|
|
const cancelledCompletion = renderer.add(cancelled, { pendingVisible: false, workTrace: cancelledTrace });
|
|
const savedCancelled = frames.snapshot();
|
|
renderer.remove(cancelled);
|
|
assert.equal((await cancelledCompletion).status, 'cancelled');
|
|
assert.equal(cancelledTrace.samplerStatus, 'cancelled');
|
|
assert.equal(cancelledTrace.rendererStatus, 'cancelled');
|
|
assert.equal(cancelledTrace.slices.filter(s => s.phase === 'ground-step').length, 0);
|
|
for (const listener of savedCancelled) listener();
|
|
assert.equal(probeCount, 0);
|
|
assert.equal(viewer.credits.size, 0);
|
|
|
|
const head = buildingAnnotation('deadline-head');
|
|
const tail = buildingAnnotation('deadline-tail', 0.01);
|
|
const headCompletion = renderer.add(head, { pendingVisible: false });
|
|
const tailTrace = workTrace();
|
|
const tailCompletion = renderer.add(tail, { pendingVisible: false, workTrace: tailTrace });
|
|
frames.emit();
|
|
assert.equal(probeCount, 1);
|
|
const savedTimeout = frames.snapshot();
|
|
// No further renderer frames arrive: the head's deadline fires, then the
|
|
// tail gets its own budget from the moment it reaches the head and still
|
|
// times out without frames, even though it never had a chance to sample.
|
|
const rendersBefore = viewer.scene.renderRequests;
|
|
t.mock.timers.tick(2000);
|
|
assert.equal((await headCompletion).status, 'timeout');
|
|
assert.ok(viewer.scene.renderRequests > rendersBefore, 'a promoted tail asks for a frame');
|
|
assert.equal(tailTrace.samplerStatus, undefined, 'queue wait does not spend the tail budget');
|
|
assert.ok(Number.isFinite(tailTrace.samplerHeadAt), 'the tail starts its own budget at the head');
|
|
t.mock.timers.tick(2000);
|
|
const tailResult = await tailCompletion;
|
|
assert.equal(tailResult.status, 'timeout');
|
|
assert.equal(tailResult.timing.probes, 0);
|
|
assert.equal(tailTrace.samplerStatus, 'timeout');
|
|
assert.equal(tailTrace.rendererStatus, 'timeout');
|
|
assert.equal(tailTrace.slices.filter(s => s.phase === 'ground-step').length, 0);
|
|
assert.equal(tailTrace.slices.filter(s => s.phase === 'hybrid-complete').length, 1);
|
|
assert.equal(viewer.credits.size, 0);
|
|
for (const listener of savedTimeout) listener();
|
|
assert.equal(probeCount, 1, 'saved callbacks cannot revive timed-out tasks');
|
|
assert.equal(worldItems(draw).length, 0);
|
|
|
|
const pending = buildingAnnotation('destroyed-building');
|
|
const destruction = renderer.add(pending, { pendingVisible: false });
|
|
const savedDestroy = frames.snapshot();
|
|
renderer.destroy();
|
|
assert.equal((await destruction).status, 'cancelled');
|
|
for (const listener of savedDestroy) listener();
|
|
t.mock.timers.tick(2000);
|
|
assert.equal(probeCount, 1);
|
|
assert.ok([...draw.sets.values()].every((record) => record.disposed), 'destroy lets every set go');
|
|
assert.equal(frames.size, 0, 'destroy removes frame listeners');
|
|
assert.equal(viewer.credits.size, 0);
|
|
});
|
|
|
|
test('a timed-out building upgrade keeps its existing pending screen group', async (t) => {
|
|
installBrowserGlobals(t);
|
|
t.mock.timers.enable({ apis: ['setTimeout'] });
|
|
t.after(() => t.mock.timers.reset());
|
|
const { viewer, draw, frames } = fakeViewer(-99, 31);
|
|
const { store, renderer } = hybridWithBoard(viewer);
|
|
const anno = { ...buildingAnnotation('pending-upgrade'), ring: null, label: 'Building' };
|
|
renderer.add(anno);
|
|
const [before] = annotationGroups(store);
|
|
anno.ring = buildingAnnotation('geometry').ring;
|
|
const completion = renderer.update(anno);
|
|
t.mock.timers.tick(2000);
|
|
assert.equal((await completion).status, 'timeout');
|
|
const [after, ...others] = annotationGroups(store);
|
|
assert.equal(after.key, before.key);
|
|
assert.equal(others.length, 0);
|
|
assert.ok(childrenWithClass(after, 'gev-anno-ring').length > 0, 'the honest pending point is not converted');
|
|
assert.equal(worldItems(draw).length, 0);
|
|
frames.emit();
|
|
assert.equal(worldItems(draw).length, 0);
|
|
renderer.destroy();
|
|
});
|
|
|
|
test('an asynchronous caption-conversion throw rolls back multipart world geometry and remains removable', async (t) => {
|
|
installBrowserGlobals(t);
|
|
const { viewer, draw, frames } = fakeViewer(-99, 31);
|
|
const { store, renderer } = hybridWithBoard(viewer);
|
|
const anno = { ...buildingAnnotation('caption-failure'), ring: null, label: 'Building' };
|
|
renderer.add(anno);
|
|
anno.ring = buildingAnnotation('geometry').ring;
|
|
const hole = anno.ring.map(([lon, lat]) => [lon + 0.0002, lat + 0.0002]);
|
|
const island = anno.ring.map(([lon, lat]) => [lon + 0.002, lat]);
|
|
anno.polygons = [[anno.ring, hole], [island]];
|
|
const captionTrace = workTrace();
|
|
const completion = renderer.update(anno, { workTrace: captionTrace });
|
|
// Frame projection is still ordinary pending-point work. Arm the failure
|
|
// only after sampling completes, before its promise converts the caption.
|
|
for (let frame = 0; frame < 8; frame += 1) frames.emit();
|
|
assert.ok(worldItems(draw).length > 0, 'multipart world geometry landed before caption conversion');
|
|
assert.equal(viewer.credits.size, 2, 'credit belongs to the committed world proxy');
|
|
// The caption conversion fails when it presents the converted mark.
|
|
const publish = store.publish;
|
|
const failure = new Error('caption conversion failed');
|
|
let armed = true;
|
|
store.publish = (board) => {
|
|
if (armed) {
|
|
armed = false;
|
|
throw failure;
|
|
}
|
|
return publish(board);
|
|
};
|
|
// Also fail screen teardown once: the routing entry must survive this second
|
|
// failure so explicit cleanup can still reach the partial screen state.
|
|
const workingSetTimeout = globalThis.window.setTimeout;
|
|
globalThis.window.setTimeout = () => { throw new Error('teardown scheduling failed'); };
|
|
const rejected = assert.rejects(completion, (error) => error === failure);
|
|
await rejected;
|
|
assert.equal(captionTrace.rendererStatus, 'failed');
|
|
assert.equal(captionTrace.slices.filter(s => s.phase === 'ground-step').length, 8);
|
|
assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-complete').length, 1);
|
|
assert.equal(captionTrace.slices.filter(s => s.phase === 'hybrid-rollback').length, 1);
|
|
assert.equal(worldItems(draw).length, 0, 'all classification, cage and outline parts roll back');
|
|
assert.equal(viewer.credits.size, 0, 'caption rollback releases that same proxy');
|
|
assert.equal(annotationGroups(store).length, 1, 'failed screen cleanup remains addressable');
|
|
globalThis.window.setTimeout = workingSetTimeout;
|
|
store.publish = publish;
|
|
renderer.remove(anno);
|
|
assert.equal(annotationGroups(store).length, 0);
|
|
renderer.remove(anno);
|
|
renderer.destroy();
|
|
});
|
|
|
|
test('a deadline passed during caption conversion leaves a drawn pending point', async (t) => {
|
|
installBrowserGlobals(t);
|
|
let now = 0;
|
|
t.mock.method(globalThis.performance, 'now', () => now);
|
|
const { viewer, frames } = fakeViewer(-99, 31);
|
|
const { store, renderer } = hybridWithBoard(viewer);
|
|
// Unlabeled: the conversion empties the screen group rather than relabelling it.
|
|
const anno = { ...buildingAnnotation('late-timeout'), ring: null };
|
|
renderer.add(anno);
|
|
anno.ring = buildingAnnotation('geometry').ring;
|
|
const completion = renderer.update(anno);
|
|
for (let frame = 0; frame < 8; frame += 1) frames.emit();
|
|
// The clock passes the deadline while the conversion presents the board.
|
|
const publish = store.publish;
|
|
store.publish = (board) => {
|
|
now = 1e9;
|
|
return publish(board);
|
|
};
|
|
assert.equal((await completion).status, 'timeout');
|
|
store.publish = publish;
|
|
const live = annotationGroups(store).filter((mark) => !mark.className?.includes('gev-out'));
|
|
assert.equal(live.length, 1);
|
|
assert.ok(childrenWithClass(live[0], 'gev-anno-ring').length > 0, 'the pending point still draws');
|
|
assert.notEqual(live[0].display, 'none', 'and is on screen');
|
|
renderer.remove(anno);
|
|
renderer.destroy();
|
|
});
|