Fix the follow-up review findings in import, layers, startup and engines

- KML/KMZ import: a per-file canvas budget and cache for ground overlays,
  limits on rings and vertices of raised polygons, overlays across 360° and
  near the poles, degenerate holes, polar and single-latitude fills,
  absolute overlays at their altitude, overlay order by drawOrder as on
  Cesium, and pins on tiles keep their measured height.
- Points on the surface: OSM Places and Street Level cones share the
  surface sampler and sit on the terrain before they are measured, within
  a sampling budget per pass; Cockpit's contact-dot bank keeps the dot
  atlas, and a failed fleet model loads again after a pause.
- Startup: the loading screen lifts after the share-link view is restored,
  the retry screen names the failed engine and takes focus, and the
  fallback toast stays for 6 s.
- Engines: an engine switch lands a running camera flight at its
  destination (camera.completeFlight on both engines), the sighting card
  leaves focus on the engine picker after a switch, and a Cesium model
  error stays with the instance that failed.
- The MCP panel builds again: its wind-mesh alias resolves to the stub.
- QA: the wildlife switch waits for the camera to rest, GBFS --w2 says it
  needs the dev server, and test fixtures are shared instead of copied.
This commit is contained in:
German Khokhlov committed 2026-11-10 01:57:11 +04:00
1 parent 0ef29781e5
commit 60fb8fee07
82 files changed
+2363 -1574

No files matched your search

+6 -3
View File
@@ -1205,10 +1205,13 @@ export function createBhoteKoshiEventLayer({
try {
if (_engine && !_viewer) {
const revision = _engine.maps.terrainRevision();
const heights = await _engine.surface.sampleTerrainMostDetailed(
observations.map(({ lon, lat }) =>
Cesium.Cartographic.fromDegrees(lon, lat),
const heights = await waitForSignal(
_engine.surface.sampleTerrainMostDetailed(
observations.map(({ lon, lat }) =>
Cesium.Cartographic.fromDegrees(lon, lat),
),
),
signal,
);
// Heights of a terrain replaced meanwhile are not the one shown.
if (_engine.maps.terrainRevision() === revision)
+38 -2
View File
@@ -3211,7 +3211,7 @@ test('Bhote Koshi republishes its evidence cards to the incoming engine overlay'
// The event on a Navara engine double: its surface samples the terrain at
// its finest level (or fails to), and its loaded terrain answers `terrain`.
async function navaraEvidenceCard({ sample }) {
async function navaraEvidenceCard({ sample, signal }) {
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
installEventDom();
globalThis.window = { setTimeout: () => 1, clearTimeout() {} };
@@ -3251,7 +3251,7 @@ async function navaraEvidenceCard({ sample }) {
renderHost: { request() {}, hold() {}, release() {} },
});
await layer.init(null, { engine });
await layer.enable(null, { origin: 'local-restore' });
await layer.enable(null, { origin: 'local-restore', signal });
const [first] = event.evidenceSpine;
const card = entries.find(
(entry) => entry.id === `evidence-card-${first.id}`,
@@ -3281,6 +3281,42 @@ test('Navara evidence anchors stand on the most detailed terrain', async () => {
}
});
test('Navara evidence sampling stops waiting when enable is cancelled', async () => {
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
const controller = new AbortController();
const started = Promise.withResolvers();
const sample = Promise.withResolvers();
const enabling = navaraEvidenceCard({
signal: controller.signal,
sample: () => {
started.resolve();
return sample.promise;
},
});
let timer;
try {
await started.promise;
controller.abort();
const outcome = await Promise.race([
enabling.then(
() => 'enabled',
(error) => error.name,
),
new Promise((resolve) => {
timer = setTimeout(() => resolve('still waiting'), 100);
}),
]);
assert.equal(outcome, 'AbortError');
} finally {
clearTimeout(timer);
sample.resolve([]);
await enabling.catch(() => {});
globalThis.document = originalDocument;
globalThis.window = originalWindow;
}
});
test('Navara evidence anchors without a terrain sample follow the terrain near the camera', async () => {
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
+96 -42
View File
@@ -9,18 +9,18 @@
// geoImportPins.js); points on the ground draw over the scene and are
// hidden beyond the horizon instead, as Cesium's clamped billboards
// ignored the depth test;
// - ground overlays: one image imagery layer each over its rectangle, its
// image tinted and turned on a canvas when the KML says so, an absolute
// one raised to its altitude; a plain colour is a ground fill.
// - ground overlays: image layers, or textured meshes at absolute altitudes,
// tinted and turned on a canvas when the KML says so; a plain colour is
// a ground fill.
// Nothing is pickable: an imported file has no card. Ground heights under
// the points come from engine.surface, sampled again by refreshGround():
// the terrain where the globe is drawn, else (3D tiles) the scene drawn
// under a low camera, never an imported point (as Cesium's import kept its
// pins out of height queries).
import earcut from 'earcut';
import * as geo from '../geo/index.js';
import { normalizeGroundItem } from '../globe/ground.js';
import { polygonShape, rectangleShape } from '../scenes/dataPacks/shapes.js';
import { composeIcon } from './geoImportPins.js';
import { recordFootprint } from './geoImportRecords.js';
@@ -37,8 +37,15 @@ const CLAMP_TILES_BELOW_M = 250_000;
const BATCH = 256;
// Canvas pixels every imported icon look shares (64 MiB of RGBA).
const ICON_PIXEL_BUDGET = 16 * 1024 * 1024;
// Canvas pixels every tinted or turned ground overlay of a file shares.
const OVERLAY_PIXEL_BUDGET = 16 * 1024 * 1024;
// The longest side of a tinted or turned ground overlay's canvas.
const MAX_OVERLAY_SIDE = 4096;
// earcut runs on the main thread and grows quadratically with holes and
// vertices: a raised polygon past these draws no fill (past the rings, not
// even its outlines, one line each).
const MAX_RAISED_RINGS = 128;
const MAX_RAISED_VERTICES = 4096;
let serial = 0;
// Each engine's imported point sets, left out of each other's ground.
const pointSets = new WeakMap();
@@ -85,7 +92,7 @@ function overlayBox({ rectangle, rotation = 0 }) {
// What a ground overlay's image layer draws: its image tinted by the
// overlay's colour and turned by its rotation onto the box around the
// turned image (transparent outside it). Null when that box passes a pole.
async function overlayImage(overlay, loadImage, createCanvas) {
async function overlayImage(overlay, loadImage, createCanvas, maxSide, cache) {
const tint = overlay.color.slice(0, 3);
const { box, center, angle } = overlayBox(overlay);
if (tint.every((value) => value === 1) && !angle)
@@ -102,8 +109,14 @@ async function overlayImage(overlay, loadImage, createCanvas) {
east: center[0] + spanX / 2,
north: center[1] + spanY / 2,
};
if (rectangle.south < -90 || rectangle.north > 90 || spanX >= 360)
if (angle && (rectangle.south < -90 || rectangle.north > 90 || spanX >= 360))
return null;
const wrap = (lon) => (lon > 180 ? lon - 360 : lon < -180 ? lon + 360 : lon);
const bounds = angle
? { ...rectangle, west: wrap(rectangle.west), east: wrap(rectangle.east) }
: overlay.rectangle;
const key = JSON.stringify([overlay.url, tint, angle, width / height]);
if (cache.has(key)) return { image: cache.get(key), rectangle: bounds };
let image;
try {
image = await loadImage(overlay.url);
@@ -116,13 +129,13 @@ async function overlayImage(overlay, loadImage, createCanvas) {
image.naturalHeight || image.height,
];
// Pixels per degree: one scale on both axes when turned, so the image
// turns in degrees as Cesium's does.
// turns in degrees as Cesium's does (the canvas budget bounds its size).
let [scaleX, scaleY] = [natural[0] / width, natural[1] / height];
if (angle) scaleX = scaleY = Math.max(scaleX, scaleY);
const fit = Math.min(
1,
MAX_OVERLAY_SIDE / (spanX * scaleX),
MAX_OVERLAY_SIDE / (spanY * scaleY),
maxSide / (spanX * scaleX),
maxSide / (spanY * scaleY),
);
[scaleX, scaleY] = [scaleX * fit, scaleY * fit];
const canvas = createCanvas();
@@ -146,15 +159,8 @@ async function overlayImage(overlay, loadImage, createCanvas) {
pixels.data[i + channel] *= tint[channel];
context.putImageData(pixels, 0, 0);
}
const wrap = (lon) => (lon > 180 ? lon - 360 : lon < -180 ? lon + 360 : lon);
return {
image: canvas,
rectangle: {
...rectangle,
west: wrap(rectangle.west),
east: wrap(rectangle.east),
},
};
cache.set(key, canvas);
return { image: canvas, rectangle: bounds };
}
// KML headings are from north (Cesium's billboard on the Earth's axis):
@@ -240,27 +246,22 @@ export async function drawImportedFile(
const fills = [];
for (const polygon of records.polygons) {
let any = false;
if (polygon.raised && polygon.rings.length > MAX_RAISED_RINGS) {
kinds.complexPolygon = (kinds.complexPolygon ?? 0) + 1;
continue;
}
if (polygon.fill && polygon.raised) {
const vertices = polygon.rings.flat();
const origin = vertices[0]?.[0] ?? 0;
const xy = vertices.flatMap(([lon, lat]) => [
origin + ((((lon - origin + 180) % 360) + 360) % 360) - 180,
lat,
]);
let count = 0;
const holes = polygon.rings
.slice(0, -1)
.map((ring) => (count += ring.length));
const indices = earcut(xy, holes);
if (indices.length) {
const vertices = polygon.rings.reduce((n, ring) => n + ring.length, 0);
const shape =
vertices <= MAX_RAISED_VERTICES && polygonShape(polygon.rings);
if (vertices > MAX_RAISED_VERTICES)
kinds.complexPolygon = (kinds.complexPolygon ?? 0) + 1;
if (shape) {
meshes.push(
engine.meshes.createMesh({
id: `${prefix}-fill-${meshes.length}`,
positions: vertices.flatMap((vertex) => {
const { x, y, z } = cartesian(vertex);
return [x, y, z];
}),
indices,
positions: shape.attributes.position.values,
indices: shape.indices,
color: polygon.fill,
show: shown,
}),
@@ -275,7 +276,7 @@ export async function drawImportedFile(
if (item) {
fills.push(item);
any = true;
}
} else kinds.polygon = (kinds.polygon ?? 0) + 1;
}
if (polygon.raised && polygon.outline)
for (const ring of polygon.rings) {
@@ -293,18 +294,64 @@ export async function drawImportedFile(
}
if (any) drawn++;
}
for (const overlay of records.overlays) {
const overlayCache = new Map();
const overlayImages = new Map();
const overlaySide = Math.min(
MAX_OVERLAY_SIDE,
Math.floor(
Math.sqrt(OVERLAY_PIXEL_BUDGET / Math.max(1, records.overlays.length)),
),
);
// KML drawOrder, then the document's: equal layer orders draw in
// creation order, and a file imported later over this one.
const overlays = [...records.overlays].sort(
(a, b) => (a.drawOrder ?? 0) - (b.drawOrder ?? 0),
);
for (const overlay of overlays) {
// Cesium raises only an absolute overlay, to its altitude.
const raise =
overlay.altitudeMode === 'absolute' && overlay.altitude > 0
? overlay.altitude
: undefined;
if (overlay.url) {
const prepared = await overlayImage(overlay, loadImage, createCanvas);
const prepared = await overlayImage(
overlay,
loadImage,
createCanvas,
overlaySide,
overlayCache,
);
if (!prepared) {
kinds.rotatedOverlay = (kinds.rotatedOverlay ?? 0) + 1;
continue;
}
if (raise) {
let image = prepared.image ?? overlayImages.get(overlay.url);
if (!image) {
try {
image = await loadImage(overlay.url);
overlayImages.set(overlay.url, image);
} catch {
kinds.raisedOverlay = (kinds.raisedOverlay ?? 0) + 1;
continue;
}
}
const { west, south, east, north } = prepared.rectangle;
const shape = rectangleShape([west, south, east, north], raise);
meshes.push(
engine.meshes.createMesh({
id: `${prefix}-overlay-${meshes.length}`,
positions: shape.attributes.position.values,
indices: shape.indices,
uv: shape.attributes.st.values,
image,
color: [1, 1, 1, Math.min(0.99, overlay.color[3])],
show: shown,
}),
);
drawn++;
continue;
}
layers.push(
engine.imagery.createLayer({
id: `${prefix}-overlay-${layers.length}`,
@@ -313,7 +360,6 @@ export async function drawImportedFile(
alpha: Math.min(0.99, overlay.color[3]),
show: shown,
order: OVERLAY_ORDER,
...(raise ? { raise } : {}),
}),
);
drawn++;
@@ -336,7 +382,12 @@ export async function drawImportedFile(
[box.west, box.north],
].map(turn),
];
fills.push({ rings, fill: overlay.color });
const fill = checked('polygon', { rings, fill: overlay.color });
if (!fill) {
kinds.rotatedOverlay = (kinds.rotatedOverlay ?? 0) + 1;
continue;
}
fills.push(fill);
drawn++;
}
if (fills.length) {
@@ -345,10 +396,10 @@ export async function drawImportedFile(
kind: 'polygon',
order: POLYGON_ORDER,
});
groundSets.push(set);
set.replace(fills);
set.commit();
set.show(shown);
groundSets.push(set);
}
const corridors = [];
@@ -379,10 +430,10 @@ export async function drawImportedFile(
kind: 'corridor',
order: LINE_ORDER,
});
groundSets.push(set);
set.replace(corridors);
set.commit();
set.show(shown);
groundSets.push(set);
}
for (const point of records.points) {
@@ -507,6 +558,9 @@ export async function drawImportedFile(
? Math.max(0, terrain)
: terrain
: (pin.ground ?? 0);
// On tiles the last height found stays until the tiles answer again:
// the terrain under them is not where the pin stands.
if (tiles) ground = pin.ground ?? ground;
if (
tiles &&
inWindow(geo.cartesian3.fromDegrees(pin.lon, pin.lat, ground), size)
+553 -6
View File
@@ -6,10 +6,15 @@ import { GROUND_HARNESSES } from '../testSupport/groundDisplayEngines.mjs';
import { drawImportedFile } from './geoImportDisplay.js';
import { emptyRecords, geoJsonRecords } from './geoImportRecords.js';
// A 2D context that only records what draws.
// A 2D context that only records what draws; its image data is one pixel.
const createCanvas = () => ({
getContext: () =>
new Proxy({}, { get: (_, key) => (key in {} ? undefined : () => {}) }),
new Proxy(
{ getImageData: () => ({ data: new Uint8ClampedArray(4) }) },
{
get: (target, key) => target[key] ?? (key in {} ? undefined : () => {}),
},
),
});
for (const make of GROUND_HARNESSES) {
@@ -234,6 +239,49 @@ for (const make of GROUND_HARNESSES) {
},
);
displayTest(
'a pin on the tiles keeps its height while out of the window',
async ({ engine }) => {
engine.imagery.surface = () => 'tiles';
engine.camera.height = () => 1000;
engine.projector.horizonVisible = () => true;
let visible = true;
engine.projector.worldToWindow = () => (visible ? { x: 1, y: 1 } : null);
engine.surface.clampToHeight = (position) => {
const at = geo.cartographic.fromCartesian(position);
return geo.cartesian3.fromRadians(at.longitude, at.latitude, 500);
};
const drawing = await drawImportedFile(
engine,
geoJsonRecords({ type: 'Point', coordinates: [1, 2] }, '#39d0ff'),
{ createCanvas },
);
const height = () => Math.round(drawing.footprint()[0][2]);
assert.equal(height(), 500);
visible = false;
await drawing.refreshGround();
assert.equal(height(), 500, 'the measured tile height was replaced');
let projected;
engine.projector.worldToWindow = (position) => {
projected = Math.round(geo.cartographic.fromCartesian(position).height);
return projected >= 500 ? { x: 1, y: 1 } : null;
};
engine.surface.clampToHeight = () =>
geo.cartesian3.fromDegrees(1, 2, 700);
await drawing.refreshGround();
assert.equal(projected, 500, 'visibility uses the last measured height');
assert.equal(height(), 700);
engine.surface.clampToHeight = () => undefined;
await drawing.refreshGround();
assert.equal(
height(),
700,
'a missing tile sample keeps the last height',
);
drawing.destroy();
},
);
displayTest(
'fills keep holes, raised outlines and plain overlays',
async ({ engine, set }) => {
@@ -288,6 +336,240 @@ for (const make of GROUND_HARNESSES) {
},
);
displayTest(
'icon variants of one file stay within a canvas budget',
async ({ engine }) => {
const records = emptyRecords();
for (let i = 0; i < 2000; i++)
records.points.push({
position: [1, 2, 0],
altitude: 'ground',
icon: { image: { url: 'blob:icon' }, scale: 10 + i / 1000 },
});
const canvases = [];
const drawing = await drawImportedFile(engine, records, {
createCanvas: () => {
const canvas = createCanvas();
canvases.push(canvas);
return canvas;
},
loadImage: async () => ({ width: 32, height: 32 }),
pixelRatio: 2,
});
const bytes = canvases.reduce((n, c) => n + c.width * c.height * 4, 0);
assert.ok(bytes <= 64 * 2 ** 20, `canvas bytes ${bytes / 2 ** 20} MiB`);
drawing.destroy();
},
);
displayTest('a raised polygon fill keeps its heights', async ({ engine }) => {
const meshes = [];
const create = engine.meshes.createMesh;
engine.meshes.createMesh = (options) => {
meshes.push(options);
return create(options);
};
const records = emptyRecords();
records.polygons.push({
rings: [
[
[0, 0, 1000],
[1, 0, 1000],
[1, 1, 1000],
],
],
raised: true,
fill: [1, 0, 0, 1],
outline: { color: [1, 1, 1, 1], widthPx: 1 },
});
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.equal(engine.ground.list().length, 0);
assert.equal(meshes.length, 1);
assert.equal(meshes[0].positions[0], 6379137);
assert.equal(meshes[0].indices.length, 3);
drawing.destroy();
});
displayTest(
'a raised polygon whose vertices share one latitude keeps its fill',
async ({ engine }) => {
const records = emptyRecords();
records.polygons.push({
rings: [
[
[0, 85, 100000],
[120, 85, 100000],
[-120, 85, 100000],
],
],
raised: true,
fill: [0, 1, 0, 0.6],
outline: null,
});
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.equal(engine.meshes.list().length, 1, 'no fill mesh');
drawing.destroy();
},
);
displayTest(
'a raised polygon with 10 000 holes does not block the import',
async ({ engine }) => {
const records = emptyRecords();
const outer = Array.from({ length: 1000 }, (_, i) => {
const a = (i / 1000) * 2 * Math.PI;
return [10 * Math.cos(a), 10 * Math.sin(a), 1000];
});
const holes = [];
for (let i = 0; i < 100; i++)
for (let j = 0; j < 100; j++) {
const [x, y, d] = [-6 + 0.12 * i, -6 + 0.12 * j, 0.03];
holes.push([
[x, y, 1000],
[x + d, y, 1000],
[x + d, y + d, 1000],
[x, y + d, 1000],
]);
}
records.polygons.push({
rings: [outer, ...holes],
raised: true,
fill: [0, 1, 0, 0.6],
outline: { color: [1, 1, 1, 1], widthPx: 1 },
});
const started = performance.now();
const drawing = await drawImportedFile(engine, records, { createCanvas });
const ms = Math.round(performance.now() - started);
assert.ok(ms < 1000, `the import step took ${ms} ms (41 000 vertices)`);
assert.deepEqual(drawing.report, {
drawn: 0,
undrawn: 1,
kinds: { complexPolygon: 1 },
});
assert.equal(engine.meshes.list().length + engine.lines.list().length, 0);
drawing.destroy();
},
);
displayTest(
'a raised fill past the vertex bound is counted, its outline drawn',
async ({ engine }) => {
const records = emptyRecords();
const outer = Array.from({ length: 5000 }, (_, i) => {
const angle = (i * 2 * Math.PI) / 5000;
return [10 * Math.cos(angle), 10 * Math.sin(angle), 1000];
});
records.polygons.push({
rings: [outer],
raised: true,
fill: [1, 0, 0, 1],
outline: { color: [1, 1, 1, 1], widthPx: 1 },
});
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.deepEqual(drawing.report, {
drawn: 1,
undrawn: 1,
kinds: { complexPolygon: 1 },
});
assert.equal(engine.meshes.list().length, 0);
assert.equal(engine.lines.list().length, 1);
drawing.destroy();
},
);
displayTest(
'a polygon with a degenerate hole draws its outer ring',
async ({ engine }) => {
const records = geoJsonRecords(
{
type: 'Polygon',
coordinates: [
[
[0, 0],
[2, 0],
[2, 2],
[0, 2],
[0, 0],
],
[
[1, 1],
[1.1, 1.1],
[1, 1],
],
],
},
'#39d0ff',
);
assert.equal(records.polygons[0].rings.length, 1);
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.deepEqual(drawing.report, { drawn: 1, undrawn: 0, kinds: {} });
drawing.destroy();
},
);
displayTest(
'a polygon the ground contract rejects is counted undrawn',
async ({ engine }) => {
const records = geoJsonRecords(
{
type: 'Polygon',
coordinates: [
[
[0, 0],
[2, 0],
[2, 2],
],
],
},
'#39d0ff',
);
records.polygons[0].rings.push([
[1, 1],
[1.1, 1.1],
[1, 1],
]);
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.deepEqual(drawing.report, {
drawn: 0,
undrawn: 1,
kinds: { polygon: 1 },
});
drawing.destroy();
},
);
for (const kind of ['Polygon', 'LineString'])
displayTest(
`a failed ${kind} ground set is released`,
async ({ engine }) => {
const create = engine.ground.createSet;
engine.ground.createSet = (options) => {
const set = create(options);
set.replace = () => {
throw new Error('replacement failed');
};
return set;
};
const positions = [
[0, 0],
[2, 0],
[2, 2],
];
const records = geoJsonRecords(
{
type: kind,
coordinates: kind === 'Polygon' ? [positions] : positions,
},
'#39d0ff',
);
await assert.rejects(
drawImportedFile(engine, records, { createCanvas }),
/replacement failed/,
);
assert.equal(engine.ground.list().length, 0);
},
);
displayTest(
'failed icon composition releases geometry already created',
async ({ engine }) => {
@@ -384,6 +666,39 @@ for (const make of GROUND_HARNESSES) {
return layers;
};
displayTest(
'overlay drawOrder ranks images stably above the raster layers',
async ({ engine }) => {
const layers = overlayLayer(engine);
const records = emptyRecords();
records.overlays = [10, -2, undefined, 10].map((drawOrder, index) => ({
url: `blob:overlay-${index}`,
drawOrder,
color: [1, 1, 1, 1],
rectangle: { west: 0, south: 0, east: 1, north: 1 },
}));
const drawing = await drawImportedFile(engine, records, { createCanvas });
const later = emptyRecords();
later.overlays = [{ ...records.overlays[0], url: 'blob:later' }];
later.overlays[0].drawOrder = -5;
const over = await drawImportedFile(engine, later, { createCanvas });
const urls = new Map(layers.map(({ id, source }) => [id, source.url]));
assert.deepEqual(
engine.imagery.list().map(({ id }) => urls.get(id)),
[
'blob:overlay-1',
'blob:overlay-2',
'blob:overlay-0',
'blob:overlay-3',
'blob:later',
],
'bottom first; a file imported later draws over this one',
);
over.destroy();
drawing.destroy();
},
);
displayTest(
'colored overlays multiply image RGB and retain layer alpha',
async ({ engine }) => {
@@ -502,10 +817,194 @@ for (const make of GROUND_HARNESSES) {
);
displayTest(
'an absolute overlay is raised to its altitude, a relative one drapes',
'a turned plain-colour overlay past the pole does not fail the file',
async ({ engine }) => {
const records = geoJsonRecords(
{ type: 'Point', coordinates: [1, 2] },
'#39d0ff',
);
records.overlays.push({
url: null,
color: [1, 0, 0, 0.5],
rectangle: { west: 0, south: 80, east: 30, north: 89 },
rotation: 45,
});
const drawing = await drawImportedFile(engine, records, { createCanvas });
assert.deepEqual(drawing.report, {
drawn: 1,
undrawn: 1,
kinds: { rotatedOverlay: 1 },
});
assert.equal(engine.ground.list().length, 0);
drawing.destroy();
},
);
displayTest(
'a tinted, unturned overlay over all longitudes still draws',
async ({ engine }) => {
const layers = overlayLayer(engine);
const records = emptyRecords();
records.overlays.push({
url: 'blob:overlay',
color: [1, 0, 0, 1],
rectangle: { west: -180, south: -90, east: 180, north: 90 },
rotation: 0,
});
const drawing = await drawImportedFile(engine, records, {
createCanvas,
loadImage: async () => ({ width: 64, height: 32 }),
});
assert.deepEqual(drawing.report.kinds, {}, 'counted undrawn');
assert.equal(layers.length, 1);
assert.deepEqual(
{ ...layers[0].source.rectangle },
{ west: -180, south: -90, east: 180, north: 90 },
);
drawing.destroy();
},
);
// Canvases made, their pixels counted.
const countedCanvases = () => {
const canvases = [];
return {
canvases,
pixels: () => canvases.reduce((n, c) => n + c.width * c.height, 0),
createCanvas: () => {
const canvas = createCanvas();
canvases.push(canvas);
return canvas;
},
};
};
const OVERLAY_PIXELS = 16 * 1024 * 1024;
displayTest(
'turned overlays sharing one small image share one bounded canvas',
async ({ engine }) => {
const counted = countedCanvases();
const records = emptyRecords();
for (let i = 0; i < 20; i++)
records.overlays.push({
url: 'blob:overlay',
color: [1, 1, 1, 1],
rectangle: { west: i, south: 10, east: i + 10, north: 10.01 },
rotation: 45,
});
const drawing = await drawImportedFile(engine, records, {
createCanvas: counted.createCanvas,
loadImage: async () => ({ width: 64, height: 64 }),
});
assert.equal(drawing.report.drawn, 20);
assert.equal(counted.canvases.length, 1, 'equal looks share a canvas');
// Each of 20 overlays may hold a twentieth of the budget.
const side = Math.floor(Math.sqrt(OVERLAY_PIXELS / 20));
const [canvas] = counted.canvases;
assert.ok(
canvas.width <= side && canvas.height <= side,
`${canvas.width}`,
);
drawing.destroy();
},
);
displayTest(
'distinct tints of a large image stay within the canvas budget',
async ({ engine }) => {
const counted = countedCanvases();
const records = emptyRecords();
for (let i = 0; i < 100; i++)
records.overlays.push({
url: 'blob:overlay',
color: [1, i / 100, 0, 1],
rectangle: { west: 0, south: 0, east: 1, north: 1 },
rotation: 0,
});
const drawing = await drawImportedFile(engine, records, {
createCanvas: counted.createCanvas,
loadImage: async () => ({ width: 4096, height: 4096 }),
});
assert.equal(drawing.report.drawn, 100);
assert.equal(counted.canvases.length, 100);
assert.ok(
counted.pixels() <= OVERLAY_PIXELS,
`${Math.round((counted.pixels() * 4) / 2 ** 20)} MiB of canvas RGBA`,
);
drawing.destroy();
},
);
displayTest(
'a shared overlay canvas keeps each rectangle and its aspect ratio',
async ({ engine }) => {
const counted = countedCanvases();
const layers = overlayLayer(engine);
const records = emptyRecords();
for (const rectangle of [
{ west: 0, south: 0, east: 2, north: 1 },
{ west: 10, south: 0, east: 12, north: 1 },
{ west: 0, south: 0, east: 1, north: 2 },
])
records.overlays.push({
url: 'blob:overlay',
color: [1, 1, 1, 1],
rectangle,
rotation: 45,
});
const drawing = await drawImportedFile(engine, records, {
createCanvas: counted.createCanvas,
loadImage: async () => ({ width: 64, height: 32 }),
});
assert.equal(counted.canvases.length, 2);
assert.equal(layers[0].source.image, layers[1].source.image);
assert.notEqual(layers[0].source.image, layers[2].source.image);
assert.ok(
Math.abs(
layers[1].source.rectangle.west -
layers[0].source.rectangle.west -
10,
) < 1e-9,
);
drawing.destroy();
},
);
displayTest(
'a turned overlay keeps every source pixel of an image squeezed on one axis',
async ({ engine }) => {
const { calls, canvas } = recordingCanvas();
const records = emptyRecords();
// 32 pixels a degree across, 64 up: both axes draw at 64.
records.overlays.push({
url: 'blob:overlay',
color: [1, 1, 1, 1],
rectangle: { west: 0, south: 0, east: 2, north: 1 },
rotation: 30,
});
const drawing = await drawImportedFile(engine, records, {
createCanvas: () => canvas,
loadImage: async () => ({ width: 64, height: 64 }),
});
const [, , , width, height] = calls.find(
([name]) => name === 'drawImage',
);
assert.deepEqual([width, height], [128, 64]);
drawing.destroy();
},
);
displayTest(
'an absolute overlay stays at its altitude while a relative one drapes',
async ({ engine }) => {
const layers = overlayLayer(engine);
const meshes = [];
const create = engine.meshes.createMesh;
engine.meshes.createMesh = (options) => {
meshes.push(options);
return create(options);
};
const records = emptyRecords();
for (const altitudeMode of ['absolute', 'relative'])
records.overlays.push({
url: 'blob:overlay',
@@ -515,10 +1014,58 @@ for (const make of GROUND_HARNESSES) {
rectangle: { west: 0, south: 0, east: 1, north: 1 },
rotation: 0,
});
const drawing = await drawImportedFile(engine, records, { createCanvas });
const drawing = await drawImportedFile(engine, records, {
createCanvas,
loadImage: async () => ({ width: 32, height: 32 }),
});
assert.deepEqual(drawing.report, { drawn: 2, undrawn: 0, kinds: {} });
assert.equal(layers[0].raise, 1000);
assert.equal(layers[1].raise, undefined);
assert.equal(meshes.length, 1);
assert.equal(layers.length, 1);
assert.equal(layers[0].raise, undefined);
const mesh = meshes[0];
assert.equal(mesh.image.width, 32);
assert.equal(mesh.uv.length, (mesh.positions.length / 3) * 2);
// A fixed height, not imagery's shell that rises with the camera.
for (let i = 0; i < mesh.positions.length; i += 3) {
const position = geo.cartesian3.create(
...mesh.positions.slice(i, i + 3),
);
const { height } = geo.cartographic.fromCartesian(position);
assert.ok(Math.abs(height - 1000) < 0.01, `${height}`);
}
drawing.destroy();
assert.equal(engine.meshes.list().length, 0);
},
);
displayTest(
'absolute overlays share decoded images and report missing ones',
async ({ engine }) => {
const records = emptyRecords();
for (const url of ['blob:overlay', 'blob:overlay', 'blob:missing'])
records.overlays.push({
url,
altitudeMode: 'absolute',
altitude: 1000,
color: [1, 1, 1, 1],
rectangle: { west: 0, south: 0, east: 1, north: 1 },
});
let loads = 0;
const drawing = await drawImportedFile(engine, records, {
createCanvas,
loadImage: async (url) => {
loads++;
if (url === 'blob:missing') throw new Error('image unavailable');
return { width: 32, height: 32 };
},
});
assert.equal(loads, 2);
assert.equal(engine.meshes.list().length, 2);
assert.deepEqual(drawing.report, {
drawn: 2,
undrawn: 1,
kinds: { raisedOverlay: 1 },
});
drawing.destroy();
},
);
-97
View File
@@ -1,97 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { drawImportedFile } from './geoImportDisplay.js';
import { emptyRecords } from './geoImportRecords.js';
// A globe engine double that records what drawImportedFile asks of it.
function recordingEngine() {
const calls = { groundSets: [], lines: [], layers: [], moverSets: [] };
const handle = (extra = {}) => ({
destroy() {},
show() {},
commit() {},
...extra,
});
const engine = {
calls,
render: { request() {} },
ground: {
createSet(options) {
const rec = { options, items: [] };
calls.groundSets.push(rec);
return handle({ replace: (items) => (rec.items = items) });
},
},
lines: {
createLine(options) {
const rec = { options, positions: null };
calls.lines.push(rec);
return handle({ setPositions: (p) => (rec.positions = p) });
},
},
imagery: {
surface: () => 'globe',
createLayer(options) {
calls.layers.push(options);
return handle();
},
},
movers: {
createSet(options) {
const rec = { options, items: [] };
calls.moverSets.push(rec);
return handle({
set: (i, f) => (rec.items[i] = { ...rec.items[i], ...f }),
setCount() {},
});
},
},
surface: { terrainHeightSupported: false, clampToHeightSupported: false },
camera: { height: () => 1e7, livePosition: { x: 1, y: 0, z: 0 } },
projector: { horizonVisible: () => true },
frames: { preRender: { addEventListener: () => () => {} } },
};
return engine;
}
const createCanvas = () => ({
width: 0,
height: 0,
getContext: () =>
new Proxy({}, { get: (_, key) => (key in {} ? undefined : () => {}) }),
});
const draw = (engine, records, extra = {}) =>
drawImportedFile(engine, records, {
createCanvas,
loadImage: async () => ({ width: 32, height: 32 }),
pixelRatio: 2,
...extra,
});
const box = { west: 10, south: 10, east: 11, north: 11 };
test('icon variants of one file stay within a canvas budget', async () => {
const engine = recordingEngine();
const points = [];
for (let i = 0; i < 2000; i++)
points.push({
position: [1, 2, 0],
altitude: 'ground',
icon: { image: { url: 'blob:icon' }, scale: 10 + i / 1000 },
});
let bytes = 0;
await draw(
engine,
{ ...emptyRecords(), points },
{
createCanvas: () => {
const c = createCanvas();
return new Proxy(c, {
set(target, key, value) {
if (key === 'height') bytes += target.width * value * 4;
target[key] = value;
return true;
},
});
},
},
);
assert.ok(bytes <= 256 * 2 ** 20, `canvas bytes ${bytes / 2 ** 20} MiB`);
});
+7 -2
View File
@@ -9,7 +9,11 @@
// overlays as image rectangles. Labels are not drawn (the import never
// drew them); walls and extruded polygons are counted in `undrawn`.
import { emptyRecords, importFeatureName } from './geoImportRecords.js';
import {
emptyRecords,
hasRingVertices,
importFeatureName,
} from './geoImportRecords.js';
// KmlDataSource's billboard: 32 px, scaled by camera distance.
const BILLBOARD_SIZE = 32;
@@ -328,7 +332,7 @@ function readGeometry(geometry, style, name, records) {
coordinates(first(ring, 'coordinates')),
),
)
.filter((ring) => ring.length);
.filter(hasRingVertices);
const poly = style.poly ?? { outline: true, outlineColor: WHITE };
const raised = altitude !== 'ground';
if (raised && extrude)
@@ -379,6 +383,7 @@ function readGroundOverlay(el, records) {
url,
rectangle,
color,
drawOrder: numberOf(el, 'drawOrder') ?? 0,
rotation: numberOf(box, 'rotation') ?? 0,
altitude: numberOf(el, 'altitude') ?? 0,
altitudeMode: altitudeOf(el),
+38
View File
@@ -412,3 +412,41 @@ test('GroundOverlay retains altitude and altitude mode for drawing diagnostics',
assert.equal(records.overlays[0].altitude, 1000);
assert.equal(records.overlays[0].altitudeMode, 'absolute');
});
test('GroundOverlay keeps drawOrder, including negatives and the default', () => {
const records = readKmlRecords(
prepared(
kml(
[10, -2, null, 10]
.map(
(order) => `
<GroundOverlay>
${order === null ? '' : `<drawOrder>${order}</drawOrder>`}
<LatLonBox><west>0</west><east>1</east><south>0</south><north>1</north></LatLonBox>
</GroundOverlay>`,
)
.join(''),
),
),
);
assert.deepEqual(
records.overlays.map((overlay) => overlay.drawOrder),
[10, -2, 0, 10],
);
});
test('KML polygons discard degenerate holes and retain valid ones', () => {
const records = readKmlRecords(
prepared(
kml(`
<Placemark><Polygon>
<outerBoundaryIs><LinearRing><coordinates>0,0 2,0 2,2 0,2 0,0</coordinates></LinearRing></outerBoundaryIs>
<innerBoundaryIs><LinearRing><coordinates>1,1 1.1,1.1 1,1</coordinates></LinearRing></innerBoundaryIs>
<innerBoundaryIs><LinearRing><coordinates>1,1 1.1,1.1 1,1 1.1,1.1</coordinates></LinearRing></innerBoundaryIs>
<innerBoundaryIs><LinearRing><coordinates>0.5,0.5 0.6,0.5 0.6,0.6 0.5,0.5</coordinates></LinearRing></innerBoundaryIs>
</Polygon></Placemark>`),
),
);
assert.equal(records.polygons[0].rings.length, 2);
assert.deepEqual(records.polygons[0].rings[1][0], [0.5, 0.5, 0]);
});
-112
View File
@@ -1,112 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { drawImportedFile } from './geoImportDisplay.js';
import { emptyRecords } from './geoImportRecords.js';
// A globe engine double that records what drawImportedFile asks of it.
function recordingEngine() {
const calls = {
meshes: [],
groundSets: [],
lines: [],
layers: [],
moverSets: [],
};
const handle = (extra = {}) => ({
destroy() {},
show() {},
commit() {},
...extra,
});
const engine = {
calls,
render: { request() {} },
meshes: {
createMesh(options) {
calls.meshes.push(options);
return handle();
},
},
ground: {
createSet(options) {
const rec = { options, items: [] };
calls.groundSets.push(rec);
return handle({ replace: (items) => (rec.items = items) });
},
},
lines: {
createLine(options) {
const rec = { options, positions: null };
calls.lines.push(rec);
return handle({ setPositions: (p) => (rec.positions = p) });
},
},
imagery: {
surface: () => 'globe',
createLayer(options) {
calls.layers.push(options);
return handle();
},
},
movers: {
createSet(options) {
const rec = { options, items: [] };
calls.moverSets.push(rec);
return handle({
set: (i, f) => (rec.items[i] = { ...rec.items[i], ...f }),
setCount() {},
});
},
},
surface: { terrainHeightSupported: false, clampToHeightSupported: false },
camera: { height: () => 1e7, livePosition: { x: 1, y: 0, z: 0 } },
projector: { horizonVisible: () => true },
frames: { preRender: { addEventListener: () => () => {} } },
};
return engine;
}
const createCanvas = () => ({
width: 0,
height: 0,
getContext: () =>
new Proxy({}, { get: (_, key) => (key in {} ? undefined : () => {}) }),
});
const draw = (engine, records, extra = {}) =>
drawImportedFile(engine, records, {
createCanvas,
loadImage: async () => ({ width: 32, height: 32 }),
pixelRatio: 2,
...extra,
});
const box = { west: 10, south: 10, east: 11, north: 11 };
test('a raised polygon fill keeps its heights (not a ground fill)', async () => {
const engine = recordingEngine();
await draw(engine, {
...emptyRecords(),
polygons: [
{
rings: [
[
[0, 0, 1000],
[1, 0, 1000],
[1, 1, 1000],
],
],
raised: true,
fill: [1, 0, 0, 1],
outline: { color: [1, 1, 1, 1], widthPx: 1 },
},
],
});
const groundFills = engine.calls.groundSets
.filter((s) => s.options.kind === 'polygon')
.flatMap((s) => s.items);
assert.equal(
groundFills.length,
0,
'the 1000 m fill is draped on the ground',
);
assert.equal(engine.calls.meshes.length, 1);
assert.equal(engine.calls.meshes[0].positions[0], 6379137);
assert.equal(engine.calls.meshes[0].indices.length, 3);
});
+9 -7
View File
@@ -17,8 +17,8 @@
// @property {ImportedOverlay[]} overlays
// @property {Object<string, number>} undrawn What the file has that no
// engine draws, by kind (`wall`, `extruded`, `latLonQuad`), counted;
// the display adds the overlays it cannot draw (`rotatedOverlay`,
// `raisedOverlay`).
// the display adds overlays and polygons it cannot draw (`rotatedOverlay`,
// `raisedOverlay`, `polygon`, `complexPolygon`).
//
// @typedef {object} ImportedPoint
// @property {number[]} position
@@ -63,6 +63,7 @@
// @property {string|null} url Its image, or null for a plain colour.
// @property {{ west: number, south: number, east: number, north: number }} rectangle
// @property {number[]} color Multiplies the image; its alpha fades it.
// @property {number} drawOrder Higher overlays draw over lower ones.
// @property {number} rotation Degrees counter-clockwise (KML LatLonBox).
// @property {number} altitude Metres (KML altitude); Cesium raises an
// absolute overlay to it.
@@ -99,6 +100,10 @@ export const recordCount = (records) =>
records.polygons.length +
records.overlays.length;
/** A ring needs three different ground positions to enclose a fill. */
export const hasRingVertices = (ring) =>
new Set(ring?.map(([lon, lat]) => `${lon},${lat}`)).size >= 3;
/** `#rrggbb` as rgba in 0..1, with Cesium.Color.fromCssColorString's bytes. */
export function rgbaOfHex(css, alpha = 1) {
const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(
@@ -175,13 +180,10 @@ export function geoJsonRecords(geojson, color) {
color: stroke,
widthPx: GEOJSON_STROKE_PX,
});
else if (
kind === 'Polygon' &&
new Set(part[0]?.map(([lon, lat]) => `${lon},${lat}`)).size >= 3
)
else if (kind === 'Polygon' && hasRingVertices(part[0]))
records.polygons.push({
name,
rings: part.map((ring) => ring.map(position)),
rings: part.filter(hasRingVertices).map((ring) => ring.map(position)),
raised: false,
fill,
outline: { color: stroke, widthPx: GEOJSON_STROKE_PX },