Import GeoJSON, KML, KMZ and GPX files on Navara: shapes as clamped vector layers, pins as sprites, and the graphics it cannot draw counted and reported

This commit is contained in:
German Khokhlov committed 2026-11-03 21:19:55 +04:00
1 parent eee4f48745
commit d8c63c69d8
22 files changed
+1368 -68

No files matched your search

+36 -2
View File
@@ -3,6 +3,7 @@ import * as Cesium from 'cesium';
import { guardCameraAboveGround } from '../cameraGroundGuard.js';
import { rangeForBoundingSphere } from '../data/cameraFraming.js';
import { cancelCameraArrival } from '../data/cameraArrival.js';
import { isGlobeEngine } from '../globe/contract.js';
/** All visible positions, path vertices, polygon rings, walls and overlay bounds. */
export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) {
@@ -69,7 +70,11 @@ export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) {
return points;
}
/** Fly synchronously to the footprint; later navigation always owns its camera. */
/**
* Fly synchronously to the footprint; later navigation always owns its
* camera. `viewer` is a Cesium viewer or a globe engine (Navara), which flies
* the same sphere through the contract's flyToSphere.
*/
export function flyToDataSource(
viewer,
dataSource,
@@ -87,7 +92,12 @@ export function flyToDataSource(
Cesium.Cartographic.fromDegrees(points[0][0], points[0][1]);
const lat = Cesium.Math.toDegrees(center.latitude),
lon = Cesium.Math.toDegrees(center.longitude);
const terrain = viewer.scene?.globe?.getHeight?.(center);
const engine = isGlobeEngine(viewer) ? viewer : null;
const terrain = engine
? engine.surface.terrainHeightSupported
? engine.surface.terrainHeight(center)
: undefined
: viewer.scene?.globe?.getHeight?.(center);
const cached = ground?.cachedGroundFloor?.(lat, lon);
const height =
Number.isFinite(terrain) && terrain > 0
@@ -109,6 +119,30 @@ export function flyToDataSource(
sphere.radius,
Cesium.Cartesian3.distance(sphere.center, position),
);
if (engine) {
const pose = engine.camera.pose();
const aspect = pose.aspectRatio ?? 1;
// Cesium's frustum fov: the wider side's angle.
const fov =
aspect > 1 ? 2 * Math.atan(Math.tan(pose.fovy / 2) * aspect) : pose.fovy;
engine.camera.flyToSphere(
{ center: sphere.center, radius: sphere.radius },
{
heading: pose.heading || 0,
pitch: -Math.PI / 2,
range: Math.max(
800,
rangeForBoundingSphere(
{ camera: { frustum: { fov, aspectRatio: aspect } } },
sphere.radius,
),
),
duration,
complete: () => guardCameraAboveGround(engine, { lat, lon }),
},
);
return true;
}
viewer.camera?.flyToBoundingSphere?.(sphere, {
offset: new Cesium.HeadingPitchRange(
viewer.camera.heading || 0,
+17
View File
@@ -161,3 +161,20 @@ test('non-finite positions and hidden features never enter the camera footprint'
assert.equal(points.length, 1);
assert.ok(Math.abs(points[0][0] - 20) < 1e-6);
});
test('on a globe engine the footprint is flown to through flyToSphere, straight down at the surface', async () => {
const { createFakeEngine } = await import('../globe/testing/fakeEngine.js');
const engine = createFakeEngine({ kind: 'navara' });
engine.fake.script('terrainHeight', 120);
assert.equal(flyToDataSource(engine, source(), { duration: 0.5 }), true);
const [call] = engine.fake.callsOf('camera.flyToSphere');
assert.ok(call, 'one sphere flight');
const [sphere, options] = call.args;
const center = Cesium.Cartographic.fromCartesian(sphere.center);
assert.ok(Math.abs(center.height - 120) < 1, 'centre on the terrain');
assert.ok(sphere.radius > 100);
assert.equal(options.pitch, -Math.PI / 2);
assert.equal(options.duration, 0.5);
assert.ok(options.range >= 800);
assert.equal(typeof options.complete, 'function');
});
+113 -49
View File
@@ -42,11 +42,14 @@ export function initGeoFileImport({ viewer, ...options }) {
* and returns their disconnect.
*
* The imported files belong to the session; their drawing belongs to the
* attached Cesium viewer. `attachScene({ viewer })` draws them (a file kept
* while no viewer was attached is read again from its bytes) and listens for
* drops and camera gestures there; `detachScene()` takes them off the viewer
* and keeps the list. Without a viewer (an engine without Cesium) the list
* stays, and import and fly-to wait for one.
* attached globe. `attachScene({ viewer })` draws them on a Cesium viewer;
* `attachScene({ engine, draw })` on a globe engine without one (Navara),
* where `draw(dataSource)` resolves with that engine's drawing of a file
* ({ report, setShow, refresh, destroy }: src/layers/shared/render/navaraStory.js).
* A file kept while no globe was attached is read again from its bytes; the
* control listens for drops and camera gestures on the attached globe.
* `detachScene()` takes the files off the globe and keeps the list. Without a
* globe the list stays, and import and fly-to wait for one.
* @returns {{destroy: Function, importFiles: Function, list: Function,
* setVisible: Function, flyTo: Function, remove: Function,
* diagnostics: Function, attachScene: Function, detachScene: Function}|null}
@@ -75,8 +78,8 @@ export function createGeoFileImport({
let cameraIntent = 0;
let hint = '';
const lifetime = new AbortController();
// The attached viewer and the lifetime of that attachment.
let viewer = null;
// The attached globe ({ viewer, engine, draw, controller }): a Cesium
// viewer, or an engine and its drawing; null while none is attached.
let scene = null;
const listen = (target, type, listener, options) => {
@@ -88,13 +91,16 @@ export function createGeoFileImport({
hint = text || '';
present();
};
const render = () => viewer?.scene?.requestRender?.();
const render = () => {
if (scene?.viewer) scene.viewer.scene?.requestRender?.();
else scene?.engine?.render.request('geo-import');
};
let groundTimer,
groundQueued = false,
groundAgain = false;
let groundRemovers = [];
const scheduleGround = () => {
if (destroyed || !viewer || !imports.length) return;
if (destroyed || !scene || !imports.length) return;
if (groundQueued) {
groundAgain = true;
return;
@@ -109,8 +115,10 @@ export function createGeoFileImport({
try {
for (const item of imports) {
if (destroyed || scene !== attached) return;
if (item.visible)
if (item.visible) {
await item.refreshGround?.(attached.controller.signal);
item.drawing?.refresh?.();
}
}
render();
} catch {
@@ -182,6 +190,7 @@ export function createGeoFileImport({
if (!item) return false;
item.visible = Boolean(visible);
if (item.dataSource) item.dataSource.show = item.visible;
item.drawing?.setShow(item.visible);
if (item.visible) scheduleGround();
present();
render();
@@ -189,9 +198,9 @@ export function createGeoFileImport({
}
const fly = (item) => {
if (!viewer || !item.dataSource) return false;
if (!scene || !item.dataSource) return false;
if (!item.visible) setVisible(item.id, true);
flyToSource(viewer, item.dataSource, { ground });
flyToSource(scene.viewer ?? scene.engine, item.dataSource, { ground });
return true;
};
@@ -201,7 +210,7 @@ export function createGeoFileImport({
*/
function flyTo(id) {
const item = find(id);
if (!item || !viewer || !item.dataSource) return false;
if (!item || !scene || !item.dataSource) return false;
if (typeof navigation?.runImmediateNavigation === 'function')
return (
navigation.runImmediateNavigation('file', () => fly(item)) !== false
@@ -223,9 +232,12 @@ export function createGeoFileImport({
: true;
};
/** Take one file's drawing off the viewer; the file stays in the list. */
function undraw(item, from = viewer) {
if (item.dataSource) from?.dataSources?.remove?.(item.dataSource, true);
/** Take one file's drawing off the globe; the file stays in the list. */
function undraw(item, from = scene) {
if (item.dataSource)
from?.viewer?.dataSources?.remove?.(item.dataSource, true);
item.drawing?.destroy();
item.drawing = null;
item.revoke?.();
item.dataSource = null;
item.revoke = null;
@@ -243,17 +255,27 @@ export function createGeoFileImport({
return true;
}
/** Read a file for the attached viewer. Null once that viewer went. */
/** Draw a file read for the attached globe. False once that globe went. */
async function draw(item, attached, loaded) {
item.dataSource = loaded.dataSource;
item.revoke = loaded.revoke;
item.refreshGround = loaded.refreshGround;
item.dataSource.show = item.visible;
await attached.viewer.dataSources.add(item.dataSource);
if (attached.viewer) await attached.viewer.dataSources.add(item.dataSource);
else {
try {
item.drawing = await attached.draw(item.dataSource);
} catch (error) {
undraw(item, attached);
throw error;
}
}
if (destroyed || scene !== attached) {
undraw(item, attached.viewer);
undraw(item, attached);
return false;
}
// What this globe leaves out of the file (Navara: labels, models...).
item.undrawn = item.drawing?.report?.undrawn ?? 0;
loaded.mount?.();
return true;
}
@@ -267,8 +289,8 @@ export function createGeoFileImport({
function importFiles(files) {
const list = [...(files || [])];
if (destroyed || !list.length) return Promise.resolve([]);
if (!viewer) {
// Import draws on the Cesium globe; this engine has none.
if (!scene) {
// Import draws on the attached globe; there is none.
const error = t('Action unavailable or cancelled');
setHint(error);
return Promise.resolve(
@@ -311,6 +333,7 @@ export function createGeoFileImport({
try {
loaded = await load(file, {
viewer: attached.viewer,
engine: attached.engine,
color,
signal: attached.controller.signal,
});
@@ -343,13 +366,26 @@ export function createGeoFileImport({
removed: loaded.removed || 0,
color,
visible: true,
// The bytes, so a later viewer can read the file again.
// The bytes, so a later globe can read the file again.
file,
dataSource: null,
drawing: null,
undrawn: 0,
revoke: null,
refreshGround: null,
};
if (!(await draw(item, attached, loaded))) break;
try {
if (!(await draw(item, attached, loaded))) break;
} catch (error) {
// A Cesium viewer's own failure stops the batch, as it always did.
if (attached.viewer) throw error;
outcomes.push({
name: fileName,
ok: false,
error: t('That file could not be read.'),
});
continue;
}
imports.push(item);
present();
render();
@@ -358,6 +394,7 @@ export function createGeoFileImport({
ok: true,
id: item.id,
removed: item.removed,
undrawn: item.undrawn,
});
if (
outcomes.filter((o) => o.ok).length === 1 &&
@@ -370,7 +407,7 @@ export function createGeoFileImport({
return outcomes;
}
// Draw the files kept while no viewer was attached, as they were.
// Draw the files kept while no globe was attached, as they were.
async function redraw(attached) {
for (const item of [...imports]) {
if (destroyed || scene !== attached) return;
@@ -378,6 +415,7 @@ export function createGeoFileImport({
try {
const loaded = await load(item.file, {
viewer: attached.viewer,
engine: attached.engine,
color: item.color,
signal: attached.controller.signal,
});
@@ -392,6 +430,9 @@ export function createGeoFileImport({
}
}
if (!destroyed && scene === attached) {
// Say what this globe leaves out of the files it drew again.
const left = imports.filter((item) => item.undrawn);
if (left.length) setHint(undrawnHint(left));
present();
render();
}
@@ -423,35 +464,42 @@ export function createGeoFileImport({
target.removeEventListener(type, listener, options);
dragDepth = 0;
setDragging(false);
for (const item of imports) undraw(item, previous.viewer);
viewer = null;
for (const item of imports) undraw(item, previous);
}
function attachScene({
viewer: next = null,
viewer = null,
engine = null,
draw: drawOnEngine = null,
navigation: nextNavigation = navigation,
subscribeMapSource: nextMapSource = subscribeMapSource,
} = {}) {
if (destroyed) return;
detachScene();
if (!next) return;
viewer = next;
if (!viewer && !(engine && drawOnEngine)) return;
// The shell and the map sources of this attachment.
navigation = nextNavigation;
const offMapSource = nextMapSource?.(scheduleGround);
if (typeof offMapSource === 'function') groundRemovers.push(offMapSource);
const attached = (scene = { viewer, controller: new AbortController() });
ownEvent(viewer.camera?.moveEnd, scheduleGround);
ownEvent(viewer.scene?.globe?.tileLoadProgressEvent, (pending) => {
const attached = (scene = {
viewer,
engine: viewer ? null : engine,
draw: viewer ? null : drawOnEngine,
controller: new AbortController(),
});
ownEvent(
viewer ? viewer.camera?.moveEnd : engine.camera.moveEnd,
scheduleGround,
);
ownEvent(viewer?.scene?.globe?.tileLoadProgressEvent, (pending) => {
if (!pending) scheduleGround();
});
const container = viewer.container;
listen(viewer.scene?.canvas || container, 'pointerdown', gesture, {
passive: true,
});
listen(viewer.scene?.canvas || container, 'wheel', gesture, {
passive: true,
});
const container = viewer ? viewer.container : engine.host.container;
const canvas = viewer
? viewer.scene?.canvas || container
: engine.host.canvas;
listen(canvas, 'pointerdown', gesture, { passive: true });
listen(canvas, 'wheel', gesture, { passive: true });
listen(container, 'dragenter', (event) => {
if (!hasFiles(event)) return;
event.preventDefault();
@@ -487,14 +535,17 @@ export function createGeoFileImport({
const handle = {
importFiles,
list: () =>
imports.map(({ id, name, format, entityCount, removed, visible }) => ({
id,
name,
format,
entityCount,
removed,
visible,
})),
imports.map(
({ id, name, format, entityCount, removed, visible, undrawn }) => ({
id,
name,
format,
entityCount,
removed,
visible,
undrawn,
}),
),
setVisible,
flyTo,
remove,
@@ -505,12 +556,12 @@ export function createGeoFileImport({
drawn: imports.filter((item) => item.dataSource).length,
entities: imports.reduce((n, item) => n + item.entityCount, 0),
listeners: listeners.length,
attached: Boolean(viewer),
attached: Boolean(scene),
destroyed,
}),
destroy() {
if (destroyed) return;
const last = viewer;
const last = scene;
detachScene();
destroyed = true;
disconnect();
@@ -558,5 +609,18 @@ export function summarize(outcomes) {
0,
);
if (added && stripped) parts.push(t('Some KML content was left out.'));
const left = outcomes.filter((o) => o.ok && o.undrawn);
if (left.length) parts.push(undrawnHint(left));
return parts.join(' ');
}
/**
* What the attached globe leaves out of the given files (each `{ name,
* undrawn }`): the first file's name and the total count.
*/
export function undrawnHint(items) {
return t('Map objects this engine leaves out of {name}: {count}.', {
name: items[0].name,
count: formatNumber(items.reduce((n, item) => n + item.undrawn, 0)),
});
}
+104
View File
@@ -690,3 +690,107 @@ test('an engine switch keeps the files and draws them again on the next viewer',
assert.equal(t.tool.diagnostics().drawn, 2);
t.tool.destroy();
});
test('on Navara the files draw through the engine drawing, report what it leaves out and switch back to Cesium', async () => {
const t = setup();
await t.tool.importFiles([file('a.geojson')]);
t.tool.detachScene();
const canvas = new FakeElement('canvas');
const container = new FakeElement('div', 'cesiumContainer');
const moveEnd = new Set();
const requests = [];
const engine = {
host: { canvas, container },
camera: {
moveEnd: {
addEventListener: (fn) => (moveEnd.add(fn), () => moveEnd.delete(fn)),
},
},
render: { request: (reason) => requests.push(reason) },
};
const drawings = [];
const draw = async (dataSource) => {
const drawing = {
dataSource,
shown: [],
destroyed: false,
report: { drawn: 2, undrawn: 3, kinds: { label: 3 } },
setShow: (show) => drawing.shown.push(show),
refresh() {},
destroy() {
drawing.destroyed = true;
},
};
drawings.push(drawing);
return drawing;
};
t.loads.length = 0;
t.tool.attachScene({ engine, draw });
await new Promise((resolve) => setTimeout(resolve, 0));
await new Promise((resolve) => setTimeout(resolve, 0));
// The kept file is read again for the engine and drawn by it.
assert.deepEqual(
t.loads.map(({ opts }) => [opts.viewer, opts.engine === engine]),
[[null, true]],
);
assert.equal(drawings.length, 1);
assert.match(t.shown().hint, /leaves out of a\.geojson: 3/);
assert.equal(t.tool.list()[0].undrawn, 3);
assert.ok(canvas.listeners.length > 0, 'gestures on the engine canvas');
assert.ok(container.listeners.length > 0, 'drops on its container');
assert.equal(moveEnd.size, 1);
// A new file: drawn, counted, reported in the batch hint.
const outcomes = await t.tool.importFiles([file('b.geojson')]);
assert.deepEqual(
outcomes.map(({ ok, undrawn }) => [ok, undrawn]),
[[true, 3]],
);
assert.match(t.shown().hint, /Added 1 file\. .*leaves out of b\.geojson: 3/);
const [a] = rows(t);
press(t, a, 'toggle');
assert.deepEqual(drawings[0].shown, [false]);
// Fly-to goes to the engine.
assert.equal(t.tool.flyTo(a.id), true);
assert.equal(t.flights.length > 0, true);
// A switch to Cesium takes the drawing off the engine.
t.tool.detachScene();
assert.ok(drawings.every((drawing) => drawing.destroyed));
assert.equal(canvas.listeners.length, 0);
assert.equal(moveEnd.size, 0);
t.tool.attachScene({ viewer: t.viewer });
await new Promise((resolve) => setTimeout(resolve, 0));
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(t.tool.diagnostics().drawn, 2);
t.tool.destroy();
});
test('an engine drawing that fails reports the file instead of stopping the batch', async () => {
const t = setup();
t.tool.detachScene();
const engine = {
host: { canvas: new FakeElement('canvas'), container: new FakeElement() },
camera: { moveEnd: { addEventListener: () => () => {} } },
render: { request() {} },
};
let calls = 0;
t.tool.attachScene({
engine,
draw: async () => {
if (calls++ === 0) throw new Error('no GPU');
return { report: { undrawn: 0 }, setShow() {}, destroy() {} };
},
});
const outcomes = await t.tool.importFiles([
file('bad.geojson'),
file('good.geojson'),
]);
assert.deepEqual(
outcomes.map(({ name, ok }) => [name, ok]),
[
['bad.geojson', false],
['good.geojson', true],
],
);
assert.deepEqual(t.revoked, ['bad.geojson'], 'the failed read is released');
t.tool.destroy();
});