mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-21 18:52:18 +00:00
Move scene effects and imported geometry behind the globe contract
Move Cesium viewer, map, sky, projection, trail and sonar internals into its engine. Drive styles, bloom, sharpening and contact sonar through engine.render. Count camera-input suspensions across all three engines and migrate the feature callers. Preserve Cesium's effects and input behaviour; fix transit lens clicks on Cesium and make zero sharpening on Navara disable sharpening, as it does on Cesium. Parse imported files into plain records and draw them through movers, lines, ground and imagery on both engines. Follow Cesium's KML style precedence, preserve local KMZ images and frame the drawable records. Open overlays use imagery when the engine has no native map-overlay API. Run every imported-display case on fake and headless Cesium engines. The shared import path retains these known differences from Cesium's old DataSources: wall fills, extruded prisms and gx:LatLonQuad are undrawn; raised polygon fills drape while outlines retain altitude; GroundOverlay rotation, altitude and RGB tint are not applied; rhumb lines become great circles. Ground heights use the loaded surface synchronously instead of waiting for most-detailed sampling. Supported KMZ ground overlays now draw on Navara too. Document the limits rather than claiming full parity. Combine batches B and C because their disjoint path manifests cannot place the shared boundary and format files in a later commit while keeping B independently valid. This combined commit owns the shared docs, package boundaries, format scope, locale catalogs and coupling baseline. Remove five obsolete import strings from all eleven catalogs. Make the load-time source scan include new files and skip deleted paths so the same checks work before and after recording the moves. Coupling: Navara renderer lines fall from 1695 to 1294, Cesium import files from 25 to 9, viewer lines from 1177 to 1026, SDK loads from 4 to 3 and engine-name lines from 62 to 42. No count grows. The full unit suite and the boundary, format and coupling checks pass. Browser validation remains to be run. Browser checks to run GOOGLE_MAPS_API_KEY= CESIUM_ION_TOKEN= npm run dev -- --port 4291 node scripts/qa-contract-suite.mjs http://localhost:4291 node scripts/qa-navara-visual-styles.mjs http://localhost:4291 node scripts/qa-navara-bloom.mjs http://localhost:4291 node scripts/qa-navara-sonar.mjs http://localhost:4291 QA_BASE_URL=http://localhost:4291 node scripts/qa-visual-effects.mjs QA_BASE_URL=http://localhost:4291 node scripts/qa-zoom-out-guard.mjs node scripts/qa-sky-model-lighting.mjs --url http://localhost:4291 node scripts/qa-geo-import.mjs http://localhost:4291 node scripts/qa-geo-import-regressions.mjs http://localhost:4291 node scripts/qa-geo-import-large.mjs http://localhost:4291 node scripts/qa-navara-geo-import.mjs http://localhost:4291 Use the keyless server for every check. Photoreal-only cases remain unverified; do not enable paid tiles to run them.
This commit is contained in:
1 parent
c079b329d0
commit
97c4dc76ce
130 files changed
+4763
-3495
No files matched your search
@@ -1,9 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/** Camera range with breathing room in both viewport dimensions. */
|
||||
export function rangeForBoundingSphere(viewer, radius) {
|
||||
const frustum = viewer.camera?.frustum;
|
||||
const verticalFov = Number(frustum?.fov) || Cesium.Math.toRadians(60);
|
||||
// Cesium's default frustum: 60°.
|
||||
const verticalFov = Number(frustum?.fov) || Math.PI / 3;
|
||||
const aspectRatio = Math.max(0.5, Number(frustum?.aspectRatio) || 1);
|
||||
const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio);
|
||||
const limitingFov = Math.min(verticalFov, horizontalFov);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { worldToWindowCoordinates } from './render/cesiumProjection.js';
|
||||
import { worldToWindowCoordinates } from '../globe/cesium/sceneProjection.js';
|
||||
import * as geo from '../geo/index.js';
|
||||
|
||||
// A window position through the engine projector the scene carries (the
|
||||
|
||||
+36
-354
@@ -1,10 +1,15 @@
|
||||
/** Session-local geodata loading with bounded geometry and local-only file references. */
|
||||
import * as Cesium from 'cesium';
|
||||
import { cesiumSdkReady, loadCesiumSdk } from '../app/loadCesium.js';
|
||||
import { createImportImageBudget } from './geoImportImages.js';
|
||||
import { createImportedPins } from './geoImportPins.js';
|
||||
import { readKmlRecords } from './geoImportKml.js';
|
||||
import {
|
||||
geoJsonRecords,
|
||||
importFeatureName,
|
||||
recordCount,
|
||||
} from './geoImportRecords.js';
|
||||
import { msg } from '../i18n/marker.js';
|
||||
|
||||
export { importFeatureName };
|
||||
|
||||
/** Largest file accepted, in bytes. */
|
||||
const MAX_IMPORT_BYTES = 50 * 1024 * 1024;
|
||||
/** Largest total a KMZ may inflate to — a zip bomb stops here. */
|
||||
@@ -17,8 +22,6 @@ export const MAX_IMPORT_ENTITIES = 20_000;
|
||||
export const MAX_IMPORT_POSITIONS = 250_000;
|
||||
/** Most normalized style definitions and local image links in one KML/KMZ. */
|
||||
const MAX_KML_LINKS = 2_000;
|
||||
/** Longest plain-text name kept from a file's features. */
|
||||
const MAX_IMPORT_NAME_LENGTH = 120;
|
||||
/** What the file picker offers. */
|
||||
export const GEO_FILE_ACCEPT = '.geojson,.json,.kml,.kmz,.gpx';
|
||||
|
||||
@@ -213,8 +216,8 @@ export function countGeoJsonGeometry(
|
||||
MultiPolygon: 3,
|
||||
}[node.type];
|
||||
if (depth !== undefined) {
|
||||
// Multipart geometries create one Cesium entity per component, even
|
||||
// when the document wraps them in just one Feature.
|
||||
// Multipart geometries create one record per component, even when
|
||||
// the document wraps them in just one Feature.
|
||||
entities += node.type.startsWith('Multi')
|
||||
? Array.isArray(node.coordinates)
|
||||
? node.coordinates.length
|
||||
@@ -294,7 +297,7 @@ function overLimitError({ over, features }) {
|
||||
}
|
||||
|
||||
// The import uses WGS84 ground footprints and a short name only. Remove
|
||||
// loader-sensitive metadata before Cesium allocates properties or entity IDs.
|
||||
// everything else before the records are built.
|
||||
function prepareGeoJson(geojson) {
|
||||
const stack = [geojson];
|
||||
while (stack.length) {
|
||||
@@ -521,7 +524,7 @@ export function kmzImageResolver(
|
||||
* Strip everything from a parsed KML document that would make the page reach
|
||||
* outside the file. `resolveLocal(href)` returns a URL for an image packed in
|
||||
* the same KMZ (or null); every other href is removed, so icons fall back to
|
||||
* Cesium's default pin and a ground overlay without a local image is dropped.
|
||||
* the default pin and a ground overlay without a local image is dropped.
|
||||
* @param {Document} doc
|
||||
* @param {(href: string) => string|null} [resolveLocal]
|
||||
* @returns {{removed: number}} How many elements were taken out.
|
||||
@@ -558,8 +561,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) {
|
||||
drop(overlay);
|
||||
continue;
|
||||
}
|
||||
// An empty Icon explicitly hides the billboard in Cesium. Remove the
|
||||
// blocked icon definition so the loader supplies its local default pin.
|
||||
// An empty Icon explicitly hides the billboard. Remove the blocked
|
||||
// icon definition so the reader supplies its local default pin.
|
||||
// Authored empty Icons (with no blocked href) still mean no marker.
|
||||
drop(
|
||||
icon?.localName === 'Icon' && icon.parentNode?.localName === 'IconStyle'
|
||||
@@ -755,8 +758,8 @@ export function deduplicateKmlStyles(
|
||||
}
|
||||
|
||||
/**
|
||||
* Count placemarks and vertices in a parsed KML document before Cesium reads
|
||||
* it: every `<coordinates>` tuple and every `gx:coord`, plus normalized
|
||||
* Count placemarks and vertices in a parsed KML document before it is
|
||||
* read: every `<coordinates>` tuple and every `gx:coord`, plus normalized
|
||||
* style definitions and distinct image `<href>` values (`links`).
|
||||
* Inline StyleMaps are references, not additional shared style definitions.
|
||||
* @param {Document} doc
|
||||
@@ -806,8 +809,9 @@ export function countKmlGeometry(
|
||||
)
|
||||
throw new GeoImportError(msg('That KML has invalid geometry bounds.'));
|
||||
}
|
||||
// Cesium creates entities for folders, a parent for every placemark, and
|
||||
// a child for each geometry in a MultiGeometry, including nested containers.
|
||||
// The budget counts what Cesium made entities of: folders, a parent for
|
||||
// every placemark, and a child for each geometry in a MultiGeometry,
|
||||
// including nested containers.
|
||||
if (
|
||||
name === 'Placemark' ||
|
||||
name === 'Folder' ||
|
||||
@@ -953,95 +957,6 @@ export function gpxToGeoJson(
|
||||
return { type: 'FeatureCollection', features };
|
||||
}
|
||||
|
||||
/** A feature name as short plain text (no control characters), or undefined. */
|
||||
export function importFeatureName(value) {
|
||||
const text = String(value ?? '')
|
||||
.replace(/[\u0000-\u001f\u007f]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!text) return undefined;
|
||||
return text.length > MAX_IMPORT_NAME_LENGTH
|
||||
? `${text.slice(0, MAX_IMPORT_NAME_LENGTH - 1)}…`
|
||||
: text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make every entity of an imported data source inert: no description,
|
||||
* balloon, extended data or properties, no native label, and a name that is
|
||||
* short plain text. Generated pin canvases share a data URL so Cesium uploads
|
||||
* each image once, rather than allocating a texture entry for every entity.
|
||||
* Returns how many entities were touched.
|
||||
* @param {{entities: {values: object[]}}} dataSource
|
||||
* @returns {number}
|
||||
*/
|
||||
export function scrubImportedEntities(dataSource) {
|
||||
const collection = dataSource?.entities;
|
||||
const list = collection?.values || [];
|
||||
const images = new Map();
|
||||
collection?.suspendEvents?.();
|
||||
try {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const entity = list[i];
|
||||
let name;
|
||||
try {
|
||||
name = importFeatureName(
|
||||
typeof entity.name === 'string' ? entity.name : undefined,
|
||||
);
|
||||
} catch {
|
||||
name = undefined;
|
||||
}
|
||||
entity.name = name;
|
||||
entity.description = undefined;
|
||||
entity.label = undefined;
|
||||
entity.properties = undefined;
|
||||
if (entity.kml && typeof entity.kml === 'object') entity.kml = undefined;
|
||||
if (
|
||||
entity.billboard?.heightReference?.getValue?.() ===
|
||||
Cesium.HeightReference.CLAMP_TO_GROUND
|
||||
)
|
||||
entity.billboard.disableDepthTestDistance = Number.POSITIVE_INFINITY;
|
||||
const property = entity.billboard?.image;
|
||||
if (property?.isConstant === false) continue;
|
||||
const image = property?.getValue?.();
|
||||
if (image?.tagName === 'CANVAS') {
|
||||
let url = images.get(image);
|
||||
if (!url) {
|
||||
url = image.toDataURL();
|
||||
images.set(image, url);
|
||||
}
|
||||
entity.billboard.image = url;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
collection?.resumeEvents?.();
|
||||
}
|
||||
return list.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Take time out of an imported data source so adding it cannot move the app's
|
||||
* shared clock: the data source reports no clock (the viewer adopts the clock
|
||||
* of every added source that has one), every entity is available for all
|
||||
* time. KML tracks have already become their original static vertices in
|
||||
* `sanitizeKmlDocument`, so no sampled-position fallback is needed here.
|
||||
* @param {object} dataSource
|
||||
* @returns {object} The same data source.
|
||||
*/
|
||||
export function detachImportedTime(dataSource) {
|
||||
Object.defineProperty(dataSource, 'clock', {
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
});
|
||||
const list = dataSource?.entities?.values || [];
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const entity = list[i];
|
||||
entity.availability = undefined;
|
||||
}
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
/** Repair only the first KML opening tag, scanning its delimiter once. */
|
||||
export function repairKmlRootNamespaces(value, what = 'KML') {
|
||||
const text = String(value);
|
||||
@@ -1196,171 +1111,6 @@ function checkLocalImages(doc, entries = new Map(), main = '') {
|
||||
}
|
||||
}
|
||||
|
||||
// Cesium also processes KML in deferred tasks; an exception there does not
|
||||
// reject its load promise. Keep a failed file from blocking the serial queue.
|
||||
// The camera and canvas only feed network links, which sanitizing removed; a
|
||||
// globe engine without a Cesium camera (Navara) passes its canvas alone.
|
||||
async function loadKml(doc, { viewer, engine }, signal) {
|
||||
let removeError;
|
||||
try {
|
||||
return await boundedImport(
|
||||
Promise.race([
|
||||
Cesium.KmlDataSource.load(doc, {
|
||||
camera: viewer?.scene.camera,
|
||||
canvas: viewer?.scene.canvas ?? engine?.host.canvas,
|
||||
clampToGround: true,
|
||||
}),
|
||||
new Promise((_, reject) => {
|
||||
const failed = () => {
|
||||
reject(new GeoImportError(msg('That KML could not be read.')));
|
||||
};
|
||||
globalThis.addEventListener?.('error', failed);
|
||||
removeError = () => globalThis.removeEventListener?.('error', failed);
|
||||
}),
|
||||
]),
|
||||
signal,
|
||||
);
|
||||
} finally {
|
||||
removeError?.();
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve a static file's ground pins in batches before they are visualized.
|
||||
// Per-billboard CLAMP_TO_GROUND subscriptions scale poorly on large imports.
|
||||
const groundPins = new WeakMap();
|
||||
async function settleGroundPins(dataSource, { viewer, engine }, signal) {
|
||||
let pins = groundPins.get(dataSource);
|
||||
if (!pins) {
|
||||
pins = [];
|
||||
for (const entity of dataSource.entities.values) {
|
||||
const reference = entity.billboard?.heightReference?.getValue?.();
|
||||
if (
|
||||
reference === Cesium.HeightReference.CLAMP_TO_GROUND ||
|
||||
reference === Cesium.HeightReference.RELATIVE_TO_GROUND
|
||||
) {
|
||||
const position = entity.position?.getValue?.(Cesium.JulianDate.now());
|
||||
if (!position) continue;
|
||||
const cartographic = Cesium.Cartographic.fromCartesian(position);
|
||||
if (!cartographic)
|
||||
throw new GeoImportError(
|
||||
msg('That file has invalid point coordinates.'),
|
||||
);
|
||||
pins.push({
|
||||
entity,
|
||||
original: position,
|
||||
cartographic,
|
||||
offset:
|
||||
reference === Cesium.HeightReference.RELATIVE_TO_GROUND
|
||||
? cartographic.height
|
||||
: 0,
|
||||
});
|
||||
entity.billboard.heightReference = Cesium.HeightReference.NONE;
|
||||
entity.billboard.disableDepthTestDistance = Number.POSITIVE_INFINITY;
|
||||
}
|
||||
}
|
||||
groundPins.set(dataSource, pins);
|
||||
}
|
||||
for (let at = 0; at < pins.length; at += 256) {
|
||||
signal?.throwIfAborted();
|
||||
const batch = pins.slice(at, at + 256);
|
||||
const positions = batch.map(
|
||||
({ cartographic: c }) =>
|
||||
new Cesium.Cartographic(c.longitude, c.latitude, 0),
|
||||
);
|
||||
// A globe engine without a viewer: its terrain under each pin.
|
||||
if (!viewer && engine) {
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const item = batch[i];
|
||||
const sampled = engine.surface.terrainHeightSupported
|
||||
? engine.surface.terrainHeight(positions[i])
|
||||
: undefined;
|
||||
const ground = Number.isFinite(sampled)
|
||||
? sampled
|
||||
: (item.groundHeight ?? 0);
|
||||
item.groundHeight = ground;
|
||||
const height = ground + item.offset;
|
||||
item.entity.position =
|
||||
Math.abs(height - item.cartographic.height) < 1e-6
|
||||
? item.original
|
||||
: Cesium.Cartesian3.fromRadians(
|
||||
item.cartographic.longitude,
|
||||
item.cartographic.latitude,
|
||||
height,
|
||||
);
|
||||
}
|
||||
if (at + batch.length < pins.length)
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
continue;
|
||||
}
|
||||
const mesh =
|
||||
viewer.scene?.globe?.show === false &&
|
||||
viewer.scene?.clampToHeightSupported;
|
||||
// A coarse rendered ellipsoid mesh can report a height kilometres below
|
||||
// zero. Its provider's exact height is zero even while a 3D map hides it;
|
||||
// a buried starting point can make the downward mesh ray miss the surface.
|
||||
const ellipsoid =
|
||||
viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider;
|
||||
for (let i = 0; i < positions.length; i++) {
|
||||
const sampled = ellipsoid
|
||||
? 0
|
||||
: viewer.scene?.globe?.getHeight?.(positions[i]);
|
||||
positions[i].height = mesh
|
||||
? (batch[i].groundHeight ??
|
||||
Math.max(0, Number.isFinite(sampled) ? sampled : 0))
|
||||
: Number.isFinite(sampled)
|
||||
? sampled
|
||||
: batch[i].groundHeight || 0;
|
||||
}
|
||||
const points = positions.map((c) =>
|
||||
Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height),
|
||||
);
|
||||
const height = viewer.camera?.positionCartographic?.height;
|
||||
if (mesh && Number.isFinite(height) && height < 250_000) {
|
||||
const rectangle = viewer.camera.computeViewRectangle?.();
|
||||
const indices = [];
|
||||
for (let i = 0; i < positions.length; i++)
|
||||
if (rectangle && Cesium.Rectangle.contains(rectangle, positions[i]))
|
||||
indices.push(i);
|
||||
if (indices.length) {
|
||||
const resolved = await boundedImport(
|
||||
viewer.scene.clampToHeightMostDetailed(
|
||||
indices.map((i) => {
|
||||
const c = positions[i];
|
||||
return Cesium.Cartesian3.fromRadians(
|
||||
c.longitude,
|
||||
c.latitude,
|
||||
Math.max(0, c.height),
|
||||
);
|
||||
}),
|
||||
),
|
||||
signal,
|
||||
);
|
||||
for (let i = 0; i < indices.length; i++)
|
||||
if (resolved[i]) points[indices[i]] = resolved[i];
|
||||
}
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
for (let i = 0; i < batch.length; i++) {
|
||||
const item = batch[i];
|
||||
const c = points[i] && Cesium.Cartographic.fromCartesian(points[i]);
|
||||
if (!c)
|
||||
throw new GeoImportError(
|
||||
msg(
|
||||
'Ground heights are not available for that file. Try again when the map has loaded.',
|
||||
),
|
||||
);
|
||||
item.groundHeight = c.height;
|
||||
c.height += item.offset;
|
||||
item.entity.position =
|
||||
Math.abs(c.height - item.cartographic.height) < 1e-6
|
||||
? item.original
|
||||
: Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height);
|
||||
}
|
||||
if (at + batch.length < pins.length)
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
async function boundedImport(promise, signal) {
|
||||
let timer, abort;
|
||||
try {
|
||||
@@ -1384,21 +1134,18 @@ async function boundedImport(promise, signal) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a ground footprint, retaining explicit KML altitude modes. Call mount after
|
||||
* adding the source; revoke owns pin and blob cleanup.
|
||||
* Read a file into the import's plain records (src/data/geoImportRecords.js),
|
||||
* keeping explicit KML altitude modes; no engine is involved, and the
|
||||
* drawing is src/data/geoImportDisplay.js's. `revoke` releases the blob URLs
|
||||
* of a KMZ's packed images, which the records name.
|
||||
* @param {File|Blob & {name?: string}} file
|
||||
* @param {{viewer?: Cesium.Viewer, engine?: object, color?: string}} options
|
||||
* `color` is a CSS color. Without a viewer, `engine` (a globe engine:
|
||||
* Navara) supplies the ground under the pins, and the pins stay entities
|
||||
* for that engine's own drawing (src/layers/shared/render/navaraStory.js).
|
||||
* @returns {Promise<{dataSource: Cesium.DataSource, name: string,
|
||||
* format: string, entityCount: number, removed: number, mount: Function, revoke: Function}>}
|
||||
* @param {{color?: string, signal?: AbortSignal}} [options] `color` is the
|
||||
* row's `#rrggbb`: GeoJSON and GPX draw in it; KML keeps its own styles.
|
||||
* @returns {Promise<{records: import('./geoImportRecords.js').ImportedRecords,
|
||||
* name: string, format: string, entityCount: number, removed: number,
|
||||
* revoke: Function}>}
|
||||
*/
|
||||
export async function loadGeoFile(
|
||||
file,
|
||||
{ viewer = null, engine = null, color = '#39d0ff', signal } = {},
|
||||
) {
|
||||
const globe = { viewer, engine };
|
||||
export async function loadGeoFile(file, { color = '#39d0ff', signal } = {}) {
|
||||
signal = signal
|
||||
? AbortSignal.any([signal, AbortSignal.timeout(60_000)])
|
||||
: AbortSignal.timeout(60_000);
|
||||
@@ -1417,18 +1164,12 @@ export async function loadGeoFile(
|
||||
throw new GeoImportError(
|
||||
msg('Only GeoJSON, KML, KMZ and GPX files can be imported.'),
|
||||
);
|
||||
// The import builds Cesium data sources on either globe: a Navara page
|
||||
// loads the Cesium SDK first.
|
||||
if (!cesiumSdkReady()) await boundedImport(loadCesiumSdk(), signal);
|
||||
const stroke = Cesium.Color.fromCssColorString(color);
|
||||
const urls = [];
|
||||
let pins;
|
||||
const revoke = () => {
|
||||
pins?.destroy();
|
||||
urls.splice(0).forEach((url) => URL.revokeObjectURL(url));
|
||||
};
|
||||
const name = importDisplayName(file.name);
|
||||
let dataSource;
|
||||
let records;
|
||||
let removed = 0;
|
||||
try {
|
||||
if (format === 'geojson' || format === 'gpx') {
|
||||
@@ -1444,18 +1185,7 @@ export async function loadGeoFile(
|
||||
throw new GeoImportError(msg('That file has nothing to draw.'));
|
||||
prepareGeoJson(geojson);
|
||||
bytes = null;
|
||||
dataSource = await boundedImport(
|
||||
Cesium.GeoJsonDataSource.load(geojson, {
|
||||
clampToGround: true,
|
||||
stroke,
|
||||
fill: stroke.withAlpha(0.25),
|
||||
strokeWidth: 3,
|
||||
markerColor: stroke,
|
||||
// No HTML description table is built from the file's properties.
|
||||
describe: () => undefined,
|
||||
}),
|
||||
signal,
|
||||
);
|
||||
records = geoJsonRecords(geojson, color);
|
||||
} else {
|
||||
let text;
|
||||
let entries;
|
||||
@@ -1484,7 +1214,7 @@ export async function loadGeoFile(
|
||||
deduplicateKmlStyles(doc);
|
||||
const normalizedSize = countKmlGeometry(doc);
|
||||
if (normalizedSize.over) throw overLimitError(normalizedSize);
|
||||
dataSource = await loadKml(doc, globe, signal);
|
||||
records = readKmlRecords(doc);
|
||||
}
|
||||
} catch (error) {
|
||||
revoke();
|
||||
@@ -1495,7 +1225,7 @@ export async function loadGeoFile(
|
||||
{ format: format.toUpperCase() },
|
||||
);
|
||||
}
|
||||
const entityCount = dataSource.entities.values.length;
|
||||
const entityCount = recordCount(records);
|
||||
if (entityCount > MAX_IMPORT_ENTITIES) {
|
||||
revoke();
|
||||
throw new GeoImportError(
|
||||
@@ -1507,59 +1237,11 @@ export async function loadGeoFile(
|
||||
},
|
||||
);
|
||||
}
|
||||
const now = Cesium.JulianDate.now();
|
||||
const drawable = dataSource.entities.values.some(
|
||||
(e) =>
|
||||
e.billboard?.image?.getValue(now) ||
|
||||
e.point ||
|
||||
e.rectangle ||
|
||||
e.polyline?.positions?.getValue(now)?.length >= 2 ||
|
||||
e.wall?.positions?.getValue(now)?.length >= 2 ||
|
||||
e.polygon?.hierarchy?.getValue(now)?.positions?.length >= 3,
|
||||
);
|
||||
if (!drawable) {
|
||||
if (!entityCount) {
|
||||
revoke();
|
||||
throw new GeoImportError(msg('That file has nothing to draw.'));
|
||||
}
|
||||
scrubImportedEntities(dataSource);
|
||||
try {
|
||||
await settleGroundPins(dataSource, globe, signal);
|
||||
} catch (error) {
|
||||
revoke();
|
||||
throw error instanceof GeoImportError
|
||||
? error
|
||||
: new GeoImportError(
|
||||
msg('Ground heights could not be read. Try that file again.'),
|
||||
);
|
||||
}
|
||||
// Keep the clock invariant explicit even though unused KML dates have
|
||||
// already been stripped and all supported geometries are static.
|
||||
detachImportedTime(dataSource);
|
||||
try {
|
||||
pins = viewer
|
||||
? createImportedPins(dataSource, viewer)
|
||||
: { mount() {}, sync() {}, destroy() {} };
|
||||
} catch {
|
||||
revoke();
|
||||
throw new GeoImportError(msg('That file has invalid point graphics.'));
|
||||
}
|
||||
// The display name travels beside the data source (the file name, not
|
||||
// The display name travels beside the records (the file name, not
|
||||
// anything the document says about itself).
|
||||
return {
|
||||
dataSource,
|
||||
name,
|
||||
format,
|
||||
entityCount,
|
||||
removed,
|
||||
revoke,
|
||||
mount: () => pins.mount(),
|
||||
refreshGround: (refreshSignal) =>
|
||||
settleGroundPins(
|
||||
dataSource,
|
||||
globe,
|
||||
refreshSignal
|
||||
? AbortSignal.any([refreshSignal, AbortSignal.timeout(15_000)])
|
||||
: AbortSignal.timeout(15_000),
|
||||
).then(() => pins.sync()),
|
||||
};
|
||||
return { records, name, format, entityCount, removed, revoke };
|
||||
}
|
||||
+57
-346
@@ -2,7 +2,6 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { deflateRawSync } from 'node:zlib';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
GeoImportError,
|
||||
repairKmlRootNamespaces,
|
||||
@@ -12,10 +11,8 @@ import {
|
||||
countGeoJsonGeometry,
|
||||
countKmlGeometry,
|
||||
deduplicateKmlStyles,
|
||||
detachImportedTime,
|
||||
gpxToGeoJson,
|
||||
importFeatureName,
|
||||
scrubImportedEntities,
|
||||
sanitizeKmlDocument,
|
||||
detectGeoFileFormat,
|
||||
importDisplayName,
|
||||
@@ -28,104 +25,59 @@ import {
|
||||
} from './geoFileImport.js';
|
||||
import { createImportImageBudget, importImageSize } from './geoImportImages.js';
|
||||
|
||||
test('real loader grounds XYZ GeoJSON and strips loader-sensitive metadata before allocation', async () => {
|
||||
const previous = Cesium.PinBuilder.prototype.fromColor;
|
||||
Cesium.PinBuilder.prototype.fromColor = () => ({
|
||||
toDataURL: () => 'data:image/png;base64,local',
|
||||
tagName: 'CANVAS',
|
||||
});
|
||||
try {
|
||||
const object = {
|
||||
type: 'FeatureCollection',
|
||||
crs: { type: 'name', properties: { name: 'unsupported' } },
|
||||
features: [
|
||||
{
|
||||
type: 'Feature',
|
||||
id: 'kartaview-owned',
|
||||
properties: { name: 'Test', addProperty: 1, 'marker-symbol': 'rail' },
|
||||
geometry: { type: 'Point', coordinates: [1, 2, 999] },
|
||||
},
|
||||
{
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[1, 2, 0],
|
||||
[2, 2, 0],
|
||||
[2, 3, 0],
|
||||
[1, 2, 0],
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const loaded = await loadGeoFile(
|
||||
new File([JSON.stringify(object)], 'xyz.geojson'),
|
||||
test('real loader grounds XYZ GeoJSON and keeps only names and footprints in its records', async () => {
|
||||
const object = {
|
||||
type: 'FeatureCollection',
|
||||
crs: { type: 'name', properties: { name: 'unsupported' } },
|
||||
features: [
|
||||
{
|
||||
viewer: {
|
||||
scene: {
|
||||
frameState: { mode: Cesium.SceneMode.SCENE3D },
|
||||
primitives: new Cesium.PrimitiveCollection(),
|
||||
globe: { getHeight: () => 1234 },
|
||||
},
|
||||
type: 'Feature',
|
||||
id: 'kartaview-owned',
|
||||
properties: { name: 'Test', addProperty: 1, 'marker-symbol': 'rail' },
|
||||
geometry: { type: 'Point', coordinates: [1, 2, 999] },
|
||||
},
|
||||
{
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[1, 2, 0],
|
||||
[2, 2, 0],
|
||||
[2, 3, 0],
|
||||
[1, 2, 0],
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
const [point, polygon] =
|
||||
loaded.dataSource.importedEntities || loaded.dataSource.entities.values;
|
||||
assert.notEqual(point.id, 'kartaview-owned');
|
||||
assert.equal(point.name, 'Test');
|
||||
assert.equal(point.properties, undefined);
|
||||
assert.equal(
|
||||
point.billboard.heightReference.getValue(),
|
||||
Cesium.HeightReference.NONE,
|
||||
);
|
||||
assert.equal(point.billboard.disableDepthTestDistance.getValue(), Infinity);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(
|
||||
point.position.getValue(Cesium.JulianDate.now()),
|
||||
).height - 1234,
|
||||
) < 1e-6,
|
||||
);
|
||||
assert.notEqual(polygon.polygon.perPositionHeight?.getValue(), true);
|
||||
assert.equal(loaded.dataSource.clock, undefined);
|
||||
assert.equal(
|
||||
loaded.dataSource.entities.values.length,
|
||||
1,
|
||||
'only polygon geometry remains in the per-frame entity collection',
|
||||
);
|
||||
assert.equal(loaded.dataSource.importedBillboards.length, 1);
|
||||
const update = Cesium.BillboardCollection.prototype.update;
|
||||
let passes = 0;
|
||||
Cesium.BillboardCollection.prototype.update = () => passes++;
|
||||
try {
|
||||
const collection = loaded.dataSource.importedBillboards;
|
||||
collection.update({ passes: { pick: true, offscreen: true } });
|
||||
assert.equal(passes, 0, 'height picks ignore imported markers');
|
||||
collection.update({ passes: { pick: true, offscreen: false } });
|
||||
collection.update({ passes: { render: true, offscreen: true } });
|
||||
assert.equal(passes, 2, 'ordinary picks and screenshots include markers');
|
||||
} finally {
|
||||
Cesium.BillboardCollection.prototype.update = update;
|
||||
}
|
||||
|
||||
loaded.mount();
|
||||
loaded.dataSource.show = false;
|
||||
assert.equal(loaded.dataSource.importedBillboards.show, false);
|
||||
loaded.dataSource.show = true;
|
||||
await loaded.refreshGround();
|
||||
assert.equal(
|
||||
point.billboard.heightReference.getValue(),
|
||||
Cesium.HeightReference.NONE,
|
||||
);
|
||||
loaded.revoke();
|
||||
assert.ok(loaded.dataSource.importedBillboards.isDestroyed());
|
||||
} finally {
|
||||
Cesium.PinBuilder.prototype.fromColor = previous;
|
||||
}
|
||||
],
|
||||
};
|
||||
const loaded = await loadGeoFile(
|
||||
new File([JSON.stringify(object)], 'xyz.geojson'),
|
||||
{ color: '#ffb547' },
|
||||
);
|
||||
assert.equal(loaded.format, 'geojson');
|
||||
assert.equal(loaded.entityCount, 2);
|
||||
const [point] = loaded.records.points;
|
||||
const [polygon] = loaded.records.polygons;
|
||||
assert.deepEqual(Object.keys(point).sort(), [
|
||||
'altitude',
|
||||
'icon',
|
||||
'name',
|
||||
'position',
|
||||
]);
|
||||
assert.equal(point.name, 'Test');
|
||||
assert.equal(point.altitude, 'ground', 'an XYZ point stands on the ground');
|
||||
assert.deepEqual(point.position, [1, 2, 0]);
|
||||
// Cesium's GeoJSON pin in the row colour (a marker-symbol is ignored).
|
||||
assert.equal(point.icon.image.pinSize, 48);
|
||||
assert.deepEqual(point.icon.image.pin, [1, 181 / 255, 71 / 255, 1]);
|
||||
assert.equal(point.icon.origin, 'bottom');
|
||||
assert.equal(polygon.raised, false, 'XYZ polygons drape');
|
||||
assert.deepEqual(polygon.fill, [1, 181 / 255, 71 / 255, 0.25]);
|
||||
assert.equal(polygon.name, undefined);
|
||||
assert.equal('dataSource' in loaded, false, 'no Cesium data source');
|
||||
loaded.revoke();
|
||||
});
|
||||
|
||||
test('real loader refuses empty files and malformed nested geometry before allocating entities', async () => {
|
||||
@@ -144,9 +96,7 @@ test('real loader refuses empty files and malformed nested geometry before alloc
|
||||
].map((coordinates) => ({ type: 'Point', coordinates })),
|
||||
])
|
||||
await assert.rejects(
|
||||
loadGeoFile(new File([JSON.stringify(object)], 'bad.geojson'), {
|
||||
viewer: {},
|
||||
}),
|
||||
loadGeoFile(new File([JSON.stringify(object)], 'bad.geojson')),
|
||||
GeoImportError,
|
||||
);
|
||||
});
|
||||
@@ -235,90 +185,11 @@ test('pending file reads can be cancelled without waiting for the loader timeout
|
||||
size: 1,
|
||||
arrayBuffer: () => new Promise(() => {}),
|
||||
};
|
||||
const promise = loadGeoFile(file, { viewer: {}, signal: controller.signal });
|
||||
const promise = loadGeoFile(file, { signal: controller.signal });
|
||||
controller.abort(new Error('cancelled by teardown'));
|
||||
await assert.rejects(promise, /cancelled by teardown/);
|
||||
});
|
||||
|
||||
test('a hidden coarse globe never seeds a mesh-clamp ray below the surface', async () => {
|
||||
const previous = Cesium.PinBuilder.prototype.fromColor;
|
||||
Cesium.PinBuilder.prototype.fromColor = () => ({
|
||||
tagName: 'CANVAS',
|
||||
toDataURL: () => 'data:image/png;base64,local',
|
||||
});
|
||||
const starts = [];
|
||||
try {
|
||||
for (const terrainProvider of [new Cesium.EllipsoidTerrainProvider(), {}]) {
|
||||
const viewer = {
|
||||
terrainProvider,
|
||||
camera: {
|
||||
positionCartographic: { height: 100000 },
|
||||
computeViewRectangle: () => Cesium.Rectangle.MAX_VALUE,
|
||||
},
|
||||
scene: {
|
||||
frameState: { mode: Cesium.SceneMode.SCENE3D },
|
||||
globe: { show: false, getHeight: () => -12311 },
|
||||
clampToHeightSupported: true,
|
||||
clampToHeightMostDetailed: async (points) =>
|
||||
points.map((p) => {
|
||||
const c = Cesium.Cartographic.fromCartesian(p);
|
||||
starts.push(c.height);
|
||||
return c.height < -9000
|
||||
? undefined
|
||||
: Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, 2000);
|
||||
}),
|
||||
},
|
||||
};
|
||||
const loaded = await loadGeoFile(
|
||||
new File(
|
||||
[JSON.stringify({ type: 'Point', coordinates: [1, 2] })],
|
||||
'surface.geojson',
|
||||
),
|
||||
{ viewer },
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(starts.at(-1)) < 1e-6,
|
||||
`ray started at ${starts.at(-1)}`,
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(
|
||||
loaded.dataSource.importedBillboards.get(0).position,
|
||||
).height - 2000,
|
||||
) < 1e-6,
|
||||
);
|
||||
const sampled = starts.length;
|
||||
viewer.camera.computeViewRectangle = () => undefined;
|
||||
await loaded.refreshGround();
|
||||
assert.equal(
|
||||
starts.length,
|
||||
sampled,
|
||||
'distant points do not start a detailed mesh sweep',
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(
|
||||
loaded.dataSource.importedBillboards.get(0).position,
|
||||
).height - 2000,
|
||||
) < 1e-6,
|
||||
'the last valid mesh height survives outside the camera footprint',
|
||||
);
|
||||
const point = loaded.dataSource.importedEntities[0];
|
||||
const other = new Cesium.Entity({ id: 'unrelated-aircraft' });
|
||||
viewer.trackedEntity = starts.length === 1 ? other : point;
|
||||
viewer.selectedEntity = point;
|
||||
loaded.revoke();
|
||||
assert.equal(viewer.selectedEntity, undefined);
|
||||
assert.equal(
|
||||
viewer.trackedEntity,
|
||||
starts.length === 1 ? other : undefined,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
Cesium.PinBuilder.prototype.fromColor = previous;
|
||||
}
|
||||
});
|
||||
|
||||
const bytes = (text) => new TextEncoder().encode(text);
|
||||
|
||||
/** A minimal zip writer: stored (0) or deflated (8) entries, optional flags. */
|
||||
@@ -1050,71 +921,14 @@ test('a KMZ image gets one blob URL however many hrefs name it', () => {
|
||||
assert.deepEqual(kept, ['blob:test/1', 'blob:test/2']);
|
||||
});
|
||||
|
||||
test('imported entities keep only a short plain-text name: no description, label or properties', () => {
|
||||
const ds = new Cesium.CustomDataSource('t');
|
||||
const e = ds.entities.add({
|
||||
name: 'Trail\u0007 <b>head</b>\n' + 'x'.repeat(300),
|
||||
description: '<img src="https://example.invalid/x.png" onerror="alert(1)">',
|
||||
label: { text: 'Trail head' },
|
||||
properties: { note: '<script>alert(1)</script>' },
|
||||
position: Cesium.Cartesian3.fromDegrees(1, 2),
|
||||
});
|
||||
e.kml = { extendedData: { note: { value: '<iframe src=//x>' } } };
|
||||
ds.entities.add({ name: 42, position: Cesium.Cartesian3.fromDegrees(1, 2) });
|
||||
assert.equal(scrubImportedEntities(ds), 2);
|
||||
assert.equal(e.description, undefined);
|
||||
assert.equal(e.label, undefined);
|
||||
assert.equal(e.properties, undefined);
|
||||
assert.equal(e.kml, undefined);
|
||||
assert.ok(e.name.startsWith('Trail <b>head</b> x'));
|
||||
assert.ok(e.name.length <= 120 && !/[\u0000-\u001f]/.test(e.name));
|
||||
assert.equal(ds.entities.values[1].name, undefined);
|
||||
test('feature names are short plain text', () => {
|
||||
const name = importFeatureName('Trail\u0007 <b>head</b>\n' + 'x'.repeat(300));
|
||||
assert.ok(name.startsWith('Trail <b>head</b> x'));
|
||||
assert.ok(name.length <= 120 && !/[\u0000-\u001f]/.test(name));
|
||||
assert.equal(importFeatureName(42), '42');
|
||||
assert.equal(importFeatureName(' '), undefined);
|
||||
});
|
||||
|
||||
test('generated pin canvases are encoded once and shared without changing authored image URLs', () => {
|
||||
const ds = new Cesium.CustomDataSource('pins');
|
||||
let encoded = 0;
|
||||
const canvas = {
|
||||
tagName: 'CANVAS',
|
||||
toDataURL: () => {
|
||||
encoded++;
|
||||
return 'data:image/png;base64,shared-pin';
|
||||
},
|
||||
};
|
||||
for (let i = 0; i < 1000; i++)
|
||||
ds.entities.add({
|
||||
billboard: { image: canvas },
|
||||
label: { text: 'discard' },
|
||||
properties: { discard: true },
|
||||
});
|
||||
const authored = ds.entities.add({
|
||||
billboard: { image: 'blob:packed-image' },
|
||||
});
|
||||
const dynamicImage = new Cesium.CallbackProperty(() => canvas, false);
|
||||
const dynamic = ds.entities.add({ billboard: { image: dynamicImage } });
|
||||
let notifications = 0;
|
||||
ds.entities.collectionChanged.addEventListener(() => notifications++);
|
||||
scrubImportedEntities(ds);
|
||||
assert.equal(encoded, 1);
|
||||
assert.equal(
|
||||
notifications,
|
||||
1,
|
||||
'normalization publishes one complete collection change',
|
||||
);
|
||||
for (const e of ds.entities.values.slice(0, 1000))
|
||||
assert.equal(
|
||||
e.billboard.image.getValue(),
|
||||
'data:image/png;base64,shared-pin',
|
||||
);
|
||||
assert.equal(authored.billboard.image.getValue(), 'blob:packed-image');
|
||||
assert.equal(
|
||||
dynamic.billboard.image,
|
||||
dynamicImage,
|
||||
'time-dependent image properties stay intact',
|
||||
);
|
||||
});
|
||||
|
||||
test('unused KML time and camera metadata is removed before loading without changing geometry', () => {
|
||||
const coordinates = xmlEl('coordinates', {}, '1,2,0 3,4,0');
|
||||
const placemark = xmlEl('Placemark', {}, [
|
||||
@@ -1133,47 +947,6 @@ test('unused KML time and camera metadata is removed before loading without chan
|
||||
assert.equal(coordinates.textContent, '1,2,0 3,4,0');
|
||||
});
|
||||
|
||||
test('a dated import exposes no clock and draws for all time', () => {
|
||||
// A data source with its own clock, as KmlDataSource has for a dated file.
|
||||
class DatedSource extends Cesium.CustomDataSource {
|
||||
get clock() {
|
||||
return this._testClock;
|
||||
}
|
||||
}
|
||||
const ds = new DatedSource('dated');
|
||||
ds._testClock = new Cesium.DataSourceClock();
|
||||
const start = Cesium.JulianDate.fromIso8601('2020-01-01T00:00:00Z');
|
||||
const stop = Cesium.JulianDate.fromIso8601('2020-01-01T01:00:00Z');
|
||||
const span = new Cesium.TimeIntervalCollection([
|
||||
new Cesium.TimeInterval({ start, stop }),
|
||||
]);
|
||||
// KML tracks become their original static vertices before Cesium loading.
|
||||
const track = ds.entities.add({
|
||||
availability: span,
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([10, 10, 10.1, 10.1]),
|
||||
clampToGround: true,
|
||||
},
|
||||
});
|
||||
const recorded = track.polyline.positions;
|
||||
const pin = ds.entities.add({
|
||||
availability: span,
|
||||
position: Cesium.Cartesian3.fromDegrees(1, 1),
|
||||
});
|
||||
assert.ok(ds.clock);
|
||||
detachImportedTime(ds);
|
||||
assert.equal(ds.clock, undefined);
|
||||
// The viewer reads `clock` from every added source; setting it is ignored.
|
||||
ds.clock = new Cesium.DataSourceClock();
|
||||
assert.equal(ds.clock, undefined);
|
||||
assert.equal(pin.availability, undefined);
|
||||
assert.ok(pin.isAvailable(Cesium.JulianDate.now()));
|
||||
assert.equal(track.availability, undefined);
|
||||
assert.equal(track.polyline.positions, recorded);
|
||||
assert.equal(recorded.getValue(Cesium.JulianDate.now()).length, 2);
|
||||
assert.ok(track.polyline.clampToGround.getValue());
|
||||
});
|
||||
|
||||
test('KML root namespace repair respects quoted delimiters and preserves the document tail', () => {
|
||||
const text =
|
||||
'<KML note="a > b" xmlns:x="first" xmlns:x="second"><Placemark xsi:type="test"/></KML>';
|
||||
@@ -1262,65 +1035,3 @@ test('KML namespace repair ignores declaration text inside quoted attribute valu
|
||||
/note="xmlns:xsi='x'" xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance">/,
|
||||
);
|
||||
});
|
||||
|
||||
test('on a globe engine without a viewer the pins stay entities on the engine terrain', async () => {
|
||||
const { createFakeEngine } = await import('../globe/testing/fakeEngine.js');
|
||||
const previous = Cesium.PinBuilder.prototype.fromColor;
|
||||
Cesium.PinBuilder.prototype.fromColor = () => ({
|
||||
toDataURL: () => 'data:image/png;base64,local',
|
||||
tagName: 'CANVAS',
|
||||
});
|
||||
try {
|
||||
const engine = createFakeEngine({ kind: 'navara' });
|
||||
engine.fake.script('terrainHeight', 321);
|
||||
const object = {
|
||||
type: 'FeatureCollection',
|
||||
features: [
|
||||
{
|
||||
type: 'Feature',
|
||||
properties: { name: 'Pin' },
|
||||
geometry: { type: 'Point', coordinates: [1, 2] },
|
||||
},
|
||||
{
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'LineString',
|
||||
coordinates: [
|
||||
[1, 2],
|
||||
[2, 3],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const loaded = await loadGeoFile(
|
||||
new File([JSON.stringify(object)], 'pins.geojson'),
|
||||
{ engine },
|
||||
);
|
||||
const entities = loaded.dataSource.entities.values;
|
||||
assert.equal(entities.length, 2, 'no Cesium billboard collection');
|
||||
assert.equal(loaded.dataSource.importedBillboards, undefined);
|
||||
const [pin] = entities.filter((entity) => entity.billboard);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(
|
||||
pin.position.getValue(Cesium.JulianDate.now()),
|
||||
).height - 321,
|
||||
) < 1e-3,
|
||||
);
|
||||
// A later ground refresh reads the engine again.
|
||||
engine.fake.script('terrainHeight', 50);
|
||||
await loaded.refreshGround();
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Cesium.Cartographic.fromCartesian(
|
||||
pin.position.getValue(Cesium.JulianDate.now()),
|
||||
).height - 50,
|
||||
) < 1e-3,
|
||||
);
|
||||
loaded.mount();
|
||||
loaded.revoke();
|
||||
} finally {
|
||||
Cesium.PinBuilder.prototype.fromColor = previous;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,438 @@
|
||||
// One imported file (UTILITIES ▸ Import) drawn on the globe contract, the
|
||||
// same on every engine, from its plain records (src/data/geoImportRecords.js),
|
||||
// with Cesium's look as the reference:
|
||||
// - polygons: one ground 'polygon' set of their fills; a raised polygon
|
||||
// (KML absolute or relative) also gets its outline as lines at its
|
||||
// heights, as Cesium drew it (its fill drapes: the ground has no heights);
|
||||
// - ground lines: one ground 'corridor' set in pixels, over the fills;
|
||||
// - lines in the air: one engine line each;
|
||||
// - points: one sprite set per look, each sprite a square centred on its
|
||||
// point holding the billboard where Cesium placed it (src/data/
|
||||
// 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.
|
||||
// Nothing is pickable: an imported file has no card. Ground heights under
|
||||
// the points come from engine.surface, sampled again by refreshGround().
|
||||
|
||||
import * as geo from '../geo/index.js';
|
||||
import { normalizeGroundItem } from '../globe/ground.js';
|
||||
import { composeIcon } from './geoImportPins.js';
|
||||
|
||||
const POLYGON_ORDER = 0;
|
||||
const LINE_ORDER = 1;
|
||||
// Over the layers' rasters, as Cesium's ground rectangle drew over imagery.
|
||||
const OVERLAY_ORDER = 30;
|
||||
// The horizon test lifts each point by this much (as GhostMaps does):
|
||||
// ground can lie below the ellipsoid.
|
||||
const HORIZON_LIFT_M = 2000;
|
||||
// Under this camera height, points on 3D tiles are clamped to the tiles
|
||||
// drawn now; higher up the terrain answers (Cesium's 250 km).
|
||||
const CLAMP_TILES_BELOW_M = 250_000;
|
||||
const BATCH = 256;
|
||||
let serial = 0;
|
||||
|
||||
const imageFromUrl = async (url) => {
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
return image;
|
||||
};
|
||||
|
||||
// A ground item the contract accepts, or null (a degenerate ring or line).
|
||||
function checked(kind, item) {
|
||||
try {
|
||||
normalizeGroundItem(kind, item);
|
||||
return item;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const flat = (positions) => positions.map(([lon, lat]) => [lon, lat]);
|
||||
const cartesian = ([lon, lat, height = 0]) =>
|
||||
geo.cartesian3.fromDegrees(lon, lat, height);
|
||||
|
||||
/** One key per drawn look of an icon, so equal pins share a sprite set. */
|
||||
const lookKey = (icon, depth) =>
|
||||
JSON.stringify([
|
||||
icon.image,
|
||||
icon.widthPx,
|
||||
icon.heightPx,
|
||||
icon.scale,
|
||||
icon.origin,
|
||||
icon.offsetPx,
|
||||
icon.subRegion,
|
||||
icon.scaleByDistance,
|
||||
depth,
|
||||
]);
|
||||
|
||||
/**
|
||||
* Draw one imported file's records on `engine`. Resolves once its icons
|
||||
* are decoded and every set is committed.
|
||||
* @param {import('../globe/contract.js').GlobeEngine} engine
|
||||
* @param {import('./geoImportRecords.js').ImportedRecords} records
|
||||
* @param {{ visible?: boolean, loadImage?: (url: string) => Promise<object>,
|
||||
* createCanvas?: () => object, pixelRatio?: number }} [options]
|
||||
* `loadImage` and `createCanvas` are test seams (icon decoding and the
|
||||
* sprite canvases).
|
||||
* @returns {Promise<{ report: { drawn: number, undrawn: number,
|
||||
* kinds: Object<string, number> }, setShow: (visible: boolean) => void,
|
||||
* refreshGround: (signal?: AbortSignal) => Promise<void>,
|
||||
* destroy: () => void }>}
|
||||
*/
|
||||
export async function drawImportedFile(
|
||||
engine,
|
||||
records,
|
||||
{
|
||||
visible = true,
|
||||
loadImage = imageFromUrl,
|
||||
createCanvas = () => document.createElement('canvas'),
|
||||
pixelRatio = Math.max(1, Math.min(2, globalThis.devicePixelRatio || 1)),
|
||||
} = {},
|
||||
) {
|
||||
if (!engine?.ground || !engine?.movers || !engine?.lines)
|
||||
throw new TypeError('The imported file display needs a globe engine');
|
||||
const prefix = `geo-import-${++serial}`;
|
||||
const request = () => engine.render.request('geo-import');
|
||||
let shown = visible;
|
||||
let destroyed = false;
|
||||
let removeCull = null;
|
||||
const groundSets = [];
|
||||
const lines = [];
|
||||
const layers = [];
|
||||
const looks = new Map();
|
||||
let drawn = 0;
|
||||
|
||||
function release() {
|
||||
destroyed = true;
|
||||
removeCull?.();
|
||||
removeCull = null;
|
||||
for (const set of groundSets.splice(0)) set.destroy();
|
||||
for (const line of lines.splice(0)) line.destroy();
|
||||
for (const layer of layers.splice(0)) layer.destroy();
|
||||
for (const look of looks.values()) look.set?.destroy();
|
||||
looks.clear();
|
||||
}
|
||||
|
||||
try {
|
||||
// Fills under ground lines; a plain-colour overlay is a fill too.
|
||||
const fills = [];
|
||||
for (const polygon of records.polygons) {
|
||||
let any = false;
|
||||
if (polygon.fill) {
|
||||
const item = checked('polygon', {
|
||||
rings: polygon.rings.map(flat),
|
||||
fill: polygon.fill,
|
||||
});
|
||||
if (item) {
|
||||
fills.push(item);
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
if (polygon.raised && polygon.outline)
|
||||
for (const ring of polygon.rings) {
|
||||
if (ring.length < 2) continue;
|
||||
const closed = [...ring, ring[0]].map(cartesian);
|
||||
const line = engine.lines.createLine({
|
||||
id: `${prefix}-outline-${lines.length}`,
|
||||
widthPx: 1,
|
||||
color: polygon.outline.color,
|
||||
});
|
||||
line.setPositions(closed);
|
||||
line.show(shown);
|
||||
lines.push(line);
|
||||
any = true;
|
||||
}
|
||||
if (any) drawn++;
|
||||
}
|
||||
for (const overlay of records.overlays) {
|
||||
if (overlay.url) {
|
||||
layers.push(
|
||||
engine.imagery.createLayer({
|
||||
id: `${prefix}-overlay-${layers.length}`,
|
||||
source: {
|
||||
kind: 'image',
|
||||
url: overlay.url,
|
||||
rectangle: overlay.rectangle,
|
||||
},
|
||||
// Cesium's transparent image material: at most 0.99.
|
||||
alpha: Math.min(0.99, overlay.color[3]),
|
||||
show: shown,
|
||||
order: OVERLAY_ORDER,
|
||||
}),
|
||||
);
|
||||
drawn++;
|
||||
continue;
|
||||
}
|
||||
const { west, south, east, north } = overlay.rectangle;
|
||||
const item = checked('cell', { west, south, east, north });
|
||||
if (!item) continue;
|
||||
const rings = [
|
||||
[
|
||||
[west, south],
|
||||
[east < west ? east + 360 : east, south],
|
||||
[east < west ? east + 360 : east, north],
|
||||
[west, north],
|
||||
],
|
||||
];
|
||||
fills.push({ rings, fill: overlay.color });
|
||||
drawn++;
|
||||
}
|
||||
if (fills.length) {
|
||||
const set = engine.ground.createSet({
|
||||
id: `${prefix}-polygons`,
|
||||
kind: 'polygon',
|
||||
order: POLYGON_ORDER,
|
||||
});
|
||||
set.replace(fills);
|
||||
set.commit();
|
||||
set.show(shown);
|
||||
groundSets.push(set);
|
||||
}
|
||||
|
||||
const corridors = [];
|
||||
for (const record of records.lines) {
|
||||
if (record.ground) {
|
||||
const item = checked('corridor', {
|
||||
positions: flat(record.positions),
|
||||
color: record.color,
|
||||
widthPx: record.widthPx,
|
||||
});
|
||||
if (!item) continue;
|
||||
corridors.push(item);
|
||||
} else {
|
||||
const line = engine.lines.createLine({
|
||||
id: `${prefix}-line-${lines.length}`,
|
||||
widthPx: record.widthPx,
|
||||
color: record.color,
|
||||
});
|
||||
line.setPositions(record.positions.map(cartesian));
|
||||
line.show(shown);
|
||||
lines.push(line);
|
||||
}
|
||||
drawn++;
|
||||
}
|
||||
if (corridors.length) {
|
||||
const set = engine.ground.createSet({
|
||||
id: `${prefix}-lines`,
|
||||
kind: 'corridor',
|
||||
order: LINE_ORDER,
|
||||
});
|
||||
set.replace(corridors);
|
||||
set.commit();
|
||||
set.show(shown);
|
||||
groundSets.push(set);
|
||||
}
|
||||
|
||||
for (const point of records.points) {
|
||||
const depth = point.altitude === 'absolute' ? 'normal' : 'always';
|
||||
const key = lookKey(point.icon, depth);
|
||||
let look = looks.get(key);
|
||||
if (!look)
|
||||
looks.set(
|
||||
key,
|
||||
(look = { icon: point.icon, depth, pins: [], set: null, count: 0 }),
|
||||
);
|
||||
const [lon, lat, height = 0] = point.position;
|
||||
look.pins.push({
|
||||
lon,
|
||||
lat,
|
||||
offset: point.altitude === 'relative' ? height : 0,
|
||||
height: point.altitude === 'absolute' ? height : null,
|
||||
ground: undefined,
|
||||
position: null,
|
||||
horizon: null,
|
||||
show: true,
|
||||
color: point.icon.color ?? [1, 1, 1, 1],
|
||||
rotation: point.icon.rotation ?? 0,
|
||||
});
|
||||
}
|
||||
await Promise.all(
|
||||
[...looks.values()].map(async (look) => {
|
||||
const url = look.icon.image?.url;
|
||||
let image;
|
||||
if (url) {
|
||||
try {
|
||||
image = await loadImage(url);
|
||||
} catch {
|
||||
// An icon that does not decode draws nothing, as a billboard
|
||||
// without an image.
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (destroyed) return;
|
||||
const { canvas, side } = composeIcon(look.icon, {
|
||||
image,
|
||||
createCanvas,
|
||||
ratio: pixelRatio,
|
||||
});
|
||||
look.set = engine.movers.createSet({
|
||||
id: `${prefix}-pins-${look.depth}-${looks.size}-${++serial}`,
|
||||
kind: 'sprite',
|
||||
capacity: look.pins.length,
|
||||
depthTest: look.depth,
|
||||
pickable: false,
|
||||
sprite: {
|
||||
sizePx: side,
|
||||
atlas: { canvas, cells: { icon: [0, 0, 1, 1] } },
|
||||
...(look.icon.scaleByDistance
|
||||
? { scaleByDistance: [...look.icon.scaleByDistance] }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
drawn += look.pins.length;
|
||||
}),
|
||||
);
|
||||
if (destroyed) throw new Error('The imported file was removed');
|
||||
settle(heightContext());
|
||||
for (const look of looks.values()) writePins(look);
|
||||
syncCull();
|
||||
} catch (error) {
|
||||
release();
|
||||
throw error;
|
||||
}
|
||||
request();
|
||||
|
||||
// Where heights come from now: the terrain, or the 3D tiles under a low
|
||||
// camera when they are the drawn surface.
|
||||
function heightContext() {
|
||||
const surface = engine.surface;
|
||||
const tiles =
|
||||
engine.imagery?.surface?.() === 'tiles' &&
|
||||
surface.clampToHeightSupported &&
|
||||
engine.camera.height() < CLAMP_TILES_BELOW_M;
|
||||
const exclude = [...looks.values()].map((look) => look.set).filter(Boolean);
|
||||
return { surface, tiles, exclude };
|
||||
}
|
||||
|
||||
// The ground under a pin, falling back to the last known one.
|
||||
function groundUnder(pin, { surface, tiles, exclude }) {
|
||||
const at = geo.cartographic.fromDegrees(pin.lon, pin.lat, 0);
|
||||
const terrain = surface.terrainHeightSupported
|
||||
? surface.terrainHeight(at)
|
||||
: undefined;
|
||||
// A coarse ellipsoid mesh under 3D tiles can answer far below zero.
|
||||
let ground = Number.isFinite(terrain)
|
||||
? tiles
|
||||
? Math.max(0, terrain)
|
||||
: terrain
|
||||
: (pin.ground ?? 0);
|
||||
if (tiles) {
|
||||
const top = surface.clampToHeight(
|
||||
geo.cartesian3.fromDegrees(pin.lon, pin.lat, Math.max(0, ground)),
|
||||
exclude,
|
||||
);
|
||||
const height = top && geo.cartographic.fromCartesian(top)?.height;
|
||||
ground = Number.isFinite(height) ? height : (pin.ground ?? ground);
|
||||
}
|
||||
return ground;
|
||||
}
|
||||
|
||||
function settle(context, from = 0, to = Infinity) {
|
||||
let at = 0;
|
||||
for (const look of looks.values())
|
||||
for (const pin of look.pins) {
|
||||
if (at++ < from || at > to) continue;
|
||||
if (pin.height === null) pin.ground = groundUnder(pin, context);
|
||||
const height = pin.height ?? pin.ground + pin.offset;
|
||||
pin.position = geo.cartesian3.fromDegrees(pin.lon, pin.lat, height);
|
||||
pin.horizon = geo.cartesian3.fromDegrees(
|
||||
pin.lon,
|
||||
pin.lat,
|
||||
height + HORIZON_LIFT_M,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function writePins(look) {
|
||||
const { set, pins } = look;
|
||||
if (!set) return;
|
||||
const culled = look.depth === 'always';
|
||||
pins.forEach((pin, index) => {
|
||||
if (culled) pin.show = engine.projector.horizonVisible(pin.horizon);
|
||||
set.set(index, {
|
||||
position: pin.position,
|
||||
cell: 'icon',
|
||||
color: pin.color,
|
||||
rotation: pin.rotation,
|
||||
show: pin.show,
|
||||
});
|
||||
});
|
||||
look.count = pins.length;
|
||||
set.setCount(shown ? look.count : 0);
|
||||
set.commit();
|
||||
}
|
||||
|
||||
// Hides the ground points beyond the horizon; true when any show changed.
|
||||
function cull(look) {
|
||||
let changed = false;
|
||||
look.pins.forEach((pin, index) => {
|
||||
const show = engine.projector.horizonVisible(pin.horizon);
|
||||
if (show === pin.show) return;
|
||||
pin.show = show;
|
||||
look.set.set(index, { show });
|
||||
changed = true;
|
||||
});
|
||||
if (changed) look.set.commit();
|
||||
return changed;
|
||||
}
|
||||
function syncCull() {
|
||||
const culled = [...looks.values()].filter(
|
||||
(look) => look.set && look.depth === 'always',
|
||||
);
|
||||
if (!culled.length || !shown) {
|
||||
removeCull?.();
|
||||
removeCull = null;
|
||||
return;
|
||||
}
|
||||
const lastCamera = geo.cartesian3.create(Number.NaN, 0, 0);
|
||||
removeCull ??= engine.frames.preRender.addEventListener(() => {
|
||||
const live = engine.camera.livePosition;
|
||||
if (geo.cartesian3.equals(live, lastCamera)) return;
|
||||
geo.cartesian3.clone(live, lastCamera);
|
||||
let changed = false;
|
||||
for (const look of culled) changed = cull(look) || changed;
|
||||
if (changed) request();
|
||||
});
|
||||
}
|
||||
|
||||
const undrawn = Object.values(records.undrawn).reduce((n, c) => n + c, 0);
|
||||
return {
|
||||
report: { drawn, undrawn, kinds: { ...records.undrawn } },
|
||||
setShow(visibleNow) {
|
||||
visibleNow = Boolean(visibleNow);
|
||||
if (destroyed || visibleNow === shown) return;
|
||||
shown = visibleNow;
|
||||
for (const set of groundSets) set.show(shown);
|
||||
for (const line of lines) line.show(shown);
|
||||
for (const layer of layers) layer.show(shown);
|
||||
for (const look of looks.values()) {
|
||||
look.set?.setCount(shown ? look.count : 0);
|
||||
look.set?.commit();
|
||||
}
|
||||
syncCull();
|
||||
request();
|
||||
},
|
||||
/** Sample the ground under the points again (a map or the terrain changed). */
|
||||
async refreshGround(signal) {
|
||||
const total = [...looks.values()].reduce((n, l) => n + l.pins.length, 0);
|
||||
for (let from = 0; from < total; from += BATCH) {
|
||||
signal?.throwIfAborted();
|
||||
if (destroyed) return;
|
||||
settle(heightContext(), from, from + BATCH);
|
||||
if (from + BATCH < total)
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
if (destroyed) return;
|
||||
for (const look of looks.values()) writePins(look);
|
||||
request();
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
release();
|
||||
request();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../geo/index.js';
|
||||
import { GROUND_HARNESSES } from '../testSupport/groundDisplayEngines.mjs';
|
||||
import { drawImportedFile } from './geoImportDisplay.js';
|
||||
import { geoJsonRecords } from './geoImportRecords.js';
|
||||
|
||||
// A 2D context that only records what draws.
|
||||
const createCanvas = () => ({
|
||||
getContext: () =>
|
||||
new Proxy({}, { get: (_, key) => (key in {} ? undefined : () => {}) }),
|
||||
});
|
||||
|
||||
for (const make of GROUND_HARNESSES) {
|
||||
const displayTest = (name, run) =>
|
||||
test(`${name} (${make.name})`, async (t) => {
|
||||
const harness = make({
|
||||
engineOptions: {
|
||||
imageryFactories: {
|
||||
loadImage: async () => ({ width: 1, height: 1 }),
|
||||
},
|
||||
},
|
||||
});
|
||||
const { engine, viewer } = harness;
|
||||
if (viewer) {
|
||||
viewer.imageryLayers = new Cesium.ImageryLayerCollection();
|
||||
viewer.scene.globe.show = true;
|
||||
viewer.scene.globe.getHeight = () => 0;
|
||||
}
|
||||
t.after(() => harness.destroy());
|
||||
const pins = [];
|
||||
const create = engine.movers.createSet;
|
||||
engine.movers.createSet = (options) => {
|
||||
const set = create(options);
|
||||
const record = { options, items: [], set };
|
||||
pins.push(record);
|
||||
const write = set.set;
|
||||
set.set = (i, fields) => {
|
||||
write(i, fields);
|
||||
record.items[i] = { ...record.items[i], ...fields };
|
||||
};
|
||||
return set;
|
||||
};
|
||||
await run({ ...harness, pins });
|
||||
});
|
||||
|
||||
displayTest(
|
||||
'an imported file draws through the contract and lets go',
|
||||
async ({ engine, viewer }) => {
|
||||
if (viewer) viewer.scene.globe.getHeight = () => 25;
|
||||
else engine.fake.script('terrainHeight', 25);
|
||||
const records = geoJsonRecords(
|
||||
{
|
||||
type: 'FeatureCollection',
|
||||
features: [
|
||||
{
|
||||
type: 'Feature',
|
||||
properties: { name: 'pin' },
|
||||
geometry: { type: 'Point', coordinates: [1, 2] },
|
||||
},
|
||||
{
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'LineString',
|
||||
coordinates: [
|
||||
[1, 2],
|
||||
[2, 3],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[0, 0],
|
||||
[1, 0],
|
||||
[1, 1],
|
||||
[0, 0],
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
'#39d0ff',
|
||||
);
|
||||
records.lines.push({
|
||||
positions: [
|
||||
[0, 0, 100],
|
||||
[1, 1, 200],
|
||||
],
|
||||
ground: false,
|
||||
color: [1, 0, 0, 1],
|
||||
widthPx: 2,
|
||||
});
|
||||
records.overlays.push({
|
||||
url: 'data:image/png;base64,AA',
|
||||
rectangle: { west: 0, south: 0, east: 1, north: 1 },
|
||||
color: [1, 1, 1, 1],
|
||||
rotation: 0,
|
||||
});
|
||||
const drawing = await drawImportedFile(engine, records, { createCanvas });
|
||||
const ours = (list) =>
|
||||
list.filter(({ id }) => id.startsWith('geo-import-'));
|
||||
assert.deepEqual(
|
||||
ours(engine.ground.list()).map(({ kind }) => kind),
|
||||
['polygon', 'corridor'],
|
||||
);
|
||||
assert.equal(
|
||||
ours(engine.movers.list()).reduce((n, set) => n + set.count, 0),
|
||||
1,
|
||||
);
|
||||
assert.equal(ours(engine.lines.list()).length, 1);
|
||||
assert.equal(ours(engine.imagery.list()).length, 1);
|
||||
assert.equal(drawing.report.drawn, 5);
|
||||
drawing.setShow(false);
|
||||
assert.ok(ours(engine.ground.list()).every(({ shown }) => !shown));
|
||||
assert.equal(ours(engine.movers.list())[0].count, 0);
|
||||
assert.ok(ours(engine.lines.list()).every(({ shown }) => !shown));
|
||||
assert.ok(ours(engine.imagery.list()).every(({ shown }) => !shown));
|
||||
await drawing.refreshGround();
|
||||
assert.equal(ours(engine.movers.list())[0].count, 0);
|
||||
drawing.setShow(true);
|
||||
assert.ok(ours(engine.ground.list()).every(({ shown }) => shown));
|
||||
assert.ok(ours(engine.lines.list()).every(({ shown }) => shown));
|
||||
assert.ok(ours(engine.imagery.list()).every(({ shown }) => shown));
|
||||
assert.equal(ours(engine.movers.list())[0].count, 1);
|
||||
drawing.destroy();
|
||||
drawing.destroy();
|
||||
assert.equal(
|
||||
ours(engine.ground.list()).length +
|
||||
ours(engine.movers.list()).length +
|
||||
ours(engine.lines.list()).length +
|
||||
ours(engine.imagery.list()).length,
|
||||
0,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
displayTest(
|
||||
'pins preserve ground, relative and absolute heights across refreshes',
|
||||
async ({ engine, viewer, pins }) => {
|
||||
let ground = 25;
|
||||
if (viewer) viewer.scene.globe.getHeight = () => ground;
|
||||
else engine.fake.script('terrainHeight', () => ground);
|
||||
const records = geoJsonRecords(
|
||||
{
|
||||
type: 'MultiPoint',
|
||||
coordinates: [
|
||||
[1, 2],
|
||||
[1, 2, 10],
|
||||
[1, 2, 500],
|
||||
],
|
||||
},
|
||||
'#39d0ff',
|
||||
);
|
||||
records.points[1].altitude = 'relative';
|
||||
records.points[2].altitude = 'absolute';
|
||||
const drawing = await drawImportedFile(engine, records, { createCanvas });
|
||||
const heights = () =>
|
||||
pins.flatMap(({ items }) =>
|
||||
items.map(({ position }) =>
|
||||
Math.round(geo.cartographic.fromCartesian(position).height),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(heights(), [25, 35, 500]);
|
||||
assert.deepEqual(
|
||||
pins.map(({ options }) => options.depthTest),
|
||||
['always', 'normal'],
|
||||
);
|
||||
assert.ok(pins.every(({ options }) => options.pickable === false));
|
||||
ground = 70;
|
||||
await drawing.refreshGround();
|
||||
assert.deepEqual(heights(), [70, 80, 500]);
|
||||
ground = undefined;
|
||||
await drawing.refreshGround();
|
||||
assert.deepEqual(heights(), [70, 80, 500]);
|
||||
drawing.destroy();
|
||||
},
|
||||
);
|
||||
|
||||
displayTest(
|
||||
'fills keep holes, raised outlines and plain overlays',
|
||||
async ({ engine, set }) => {
|
||||
const records = geoJsonRecords(
|
||||
{
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[0, 0],
|
||||
[2, 0],
|
||||
[2, 2],
|
||||
[0, 0],
|
||||
],
|
||||
[
|
||||
[0.5, 0.5],
|
||||
[1, 0.5],
|
||||
[1, 1],
|
||||
[0.5, 0.5],
|
||||
],
|
||||
],
|
||||
},
|
||||
'#39d0ff',
|
||||
);
|
||||
records.polygons[0].raised = true;
|
||||
records.polygons[0].rings = records.polygons[0].rings.map((ring) =>
|
||||
ring.map(([lon, lat]) => [lon, lat, 100]),
|
||||
);
|
||||
records.overlays.push({
|
||||
url: null,
|
||||
rectangle: { west: 4, south: 4, east: 5, north: 5 },
|
||||
color: [0, 1, 0, 1],
|
||||
});
|
||||
records.undrawn = { wall: 1, extruded: 2 };
|
||||
const drawing = await drawImportedFile(engine, records, {
|
||||
createCanvas,
|
||||
visible: false,
|
||||
});
|
||||
const fill = set(engine.ground.list()[0].id);
|
||||
assert.equal(fill.items.length, 2);
|
||||
assert.equal(fill.items[0].rings.length, 2);
|
||||
assert.ok(fill.items[0].rings.flat().every((p) => p.length === 2));
|
||||
assert.equal(fill.shown, false);
|
||||
assert.equal(engine.lines.list().length, 2);
|
||||
assert.ok(engine.lines.list().every((line) => !line.shown));
|
||||
assert.deepEqual(drawing.report, {
|
||||
drawn: 2,
|
||||
undrawn: 3,
|
||||
kinds: { wall: 1, extruded: 2 },
|
||||
});
|
||||
drawing.destroy();
|
||||
},
|
||||
);
|
||||
|
||||
displayTest(
|
||||
'failed icon composition releases geometry already created',
|
||||
async ({ engine }) => {
|
||||
const records = geoJsonRecords(
|
||||
{
|
||||
type: 'GeometryCollection',
|
||||
geometries: [
|
||||
{ type: 'Point', coordinates: [1, 2] },
|
||||
{
|
||||
type: 'LineString',
|
||||
coordinates: [
|
||||
[1, 2],
|
||||
[2, 3],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
'#39d0ff',
|
||||
);
|
||||
await assert.rejects(
|
||||
drawImportedFile(engine, records, {
|
||||
createCanvas: () => ({ getContext: () => null }),
|
||||
}),
|
||||
/need a canvas/,
|
||||
);
|
||||
assert.equal(engine.ground.list().length, 0);
|
||||
assert.equal(engine.movers.list().length, 0);
|
||||
},
|
||||
);
|
||||
displayTest(
|
||||
'ground pins follow the horizon and release frame listeners',
|
||||
async ({ engine, pins }) => {
|
||||
let front = true;
|
||||
engine.projector.horizonVisible = () => front;
|
||||
const records = geoJsonRecords(
|
||||
{ type: 'Point', coordinates: [1, 2] },
|
||||
'#39d0ff',
|
||||
);
|
||||
const drawing = await drawImportedFile(engine, records, { createCanvas });
|
||||
assert.equal(pins[0].items[0].show, true);
|
||||
front = false;
|
||||
engine.frames.preRender.raiseEvent();
|
||||
assert.equal(pins[0].items[0].show, false);
|
||||
drawing.setShow(false);
|
||||
front = true;
|
||||
drawing.setShow(true);
|
||||
engine.frames.preRender.raiseEvent();
|
||||
assert.equal(pins[0].items[0].show, true);
|
||||
drawing.destroy();
|
||||
engine.frames.preRender.raiseEvent();
|
||||
assert.equal(engine.movers.list().length, 0);
|
||||
},
|
||||
);
|
||||
|
||||
displayTest(
|
||||
'an aborted ground refresh leaves the existing drawing owned',
|
||||
async ({ engine }) => {
|
||||
const records = geoJsonRecords(
|
||||
{ type: 'Point', coordinates: [1, 2] },
|
||||
'#39d0ff',
|
||||
);
|
||||
const drawing = await drawImportedFile(engine, records, { createCanvas });
|
||||
await assert.rejects(drawing.refreshGround(AbortSignal.abort()), {
|
||||
name: 'AbortError',
|
||||
});
|
||||
assert.equal(engine.movers.list()[0].count, 1);
|
||||
drawing.destroy();
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
// A sanitized KML document (src/data/geoFileImport.js: no network links,
|
||||
// remote images, models, descriptions or times, tracks as their recorded
|
||||
// lines) read into the import's plain records (src/data/geoImportRecords.js)
|
||||
// the way Cesium's KmlDataSource read it, without Cesium: the same shared,
|
||||
// inline and StyleMap styles and their precedence, the same defaults (a
|
||||
// yellow map pin, white lines and fills), billboards of 32 px with KML's
|
||||
// distance scale and hot spot, ground lines for clamped and tessellated
|
||||
// paths, lines in the air for absolute and relative ones, and ground
|
||||
// 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';
|
||||
|
||||
// KmlDataSource's billboard: 32 px, scaled by camera distance.
|
||||
const BILLBOARD_SIZE = 32;
|
||||
const BILLBOARD_SCALE_BY_DISTANCE = Object.freeze([
|
||||
2414016, 1.0, 1.6093e7, 0.1,
|
||||
]);
|
||||
// Its pin where no icon is given: Cesium.Color.YELLOW, drawn at 64 px.
|
||||
const DEFAULT_PIN = Object.freeze({
|
||||
pin: Object.freeze([1, 1, 0, 1]),
|
||||
pinSize: 64,
|
||||
});
|
||||
const WHITE = Object.freeze([1, 1, 1, 1]);
|
||||
const GEOMETRY = new Set([
|
||||
'Point',
|
||||
'LineString',
|
||||
'LinearRing',
|
||||
'Polygon',
|
||||
'MultiGeometry',
|
||||
'Model',
|
||||
'Track',
|
||||
'MultiTrack',
|
||||
]);
|
||||
|
||||
/** Child elements of `el` with this local name (any namespace). */
|
||||
const childrenNamed = (el, localName) => {
|
||||
const out = [];
|
||||
const kids = el?.childNodes || [];
|
||||
for (let i = 0; i < kids.length; i++)
|
||||
if (kids[i].nodeType === 1 && kids[i].localName === localName)
|
||||
out.push(kids[i]);
|
||||
return out;
|
||||
};
|
||||
const first = (el, localName) => childrenNamed(el, localName)[0];
|
||||
/** A child's trimmed text, or undefined without the child. */
|
||||
const textOf = (el, localName) => {
|
||||
const child = first(el, localName);
|
||||
return child ? child.textContent.trim() : undefined;
|
||||
};
|
||||
const numberOf = (el, localName) => {
|
||||
const value = Number.parseFloat(textOf(el, localName));
|
||||
return Number.isFinite(value) ? value : undefined;
|
||||
};
|
||||
const booleanOf = (el, localName) => {
|
||||
const value = textOf(el, localName);
|
||||
return value === undefined
|
||||
? undefined
|
||||
: value === '1' || /^true$/i.test(value);
|
||||
};
|
||||
|
||||
/**
|
||||
* A KML colour (aabbggrr) as rgba in 0..1, or undefined; `random`
|
||||
* (colorMode random) draws each non-zero channel at random up to its
|
||||
* value, as Cesium does, on every read.
|
||||
*/
|
||||
export function kmlColor(value, random = false) {
|
||||
const text = String(value ?? '')
|
||||
.trim()
|
||||
.replace(/^#/, '');
|
||||
if (!text) return undefined;
|
||||
const channel = (at) => Number.parseInt(text.substring(at, at + 2), 16) / 255;
|
||||
const [alpha, blue, green, red] = [0, 2, 4, 6].map(channel);
|
||||
const pick = (v) => (random && v > 0 ? Math.random() * v : v);
|
||||
return [pick(red), pick(green), pick(blue), alpha];
|
||||
}
|
||||
const colorOf = (el, localName) =>
|
||||
kmlColor(textOf(el, localName), textOf(el, 'colorMode') === 'random');
|
||||
|
||||
/** One coordinate tuple; Google Earth reads what is missing as 0. */
|
||||
function tuple(text) {
|
||||
const [lon = 0, lat = 0, height = 0] = String(text ?? '')
|
||||
.split(',')
|
||||
.map((v) => Number.parseFloat(v))
|
||||
.map((v) => (Number.isFinite(v) ? v : 0));
|
||||
return [lon, lat, height];
|
||||
}
|
||||
const coordinates = (el) =>
|
||||
el ? (el.textContent.match(/\S+/g) ?? []).map(tuple) : [];
|
||||
|
||||
/** Where a geometry sits, from its altitude modes (Cesium's reading). */
|
||||
function altitudeOf(geometry) {
|
||||
const modes = childrenNamed(geometry, 'altitudeMode');
|
||||
const isGx = (el) => /google\.com\/kml\/ext/.test(el.namespaceURI || '');
|
||||
const mode = modes.find((el) => !isGx(el))?.textContent.trim();
|
||||
const gx = modes.find(isGx)?.textContent.trim();
|
||||
if (mode === 'absolute') return 'absolute';
|
||||
if (mode === 'relativeToGround') return 'relative';
|
||||
if (!mode || mode === 'clampToGround')
|
||||
return gx === 'relativeToSeaFloor' && !mode ? 'relative' : 'ground';
|
||||
return gx === 'relativeToSeaFloor' ? 'relative' : 'ground';
|
||||
}
|
||||
|
||||
// A style as KmlDataSource builds it on an entity: `icon` (its billboard),
|
||||
// `line` (its polyline) and `poly` (its polygon); a property left undefined
|
||||
// is filled by a merged style.
|
||||
function applyStyle(styleEl, target) {
|
||||
for (const node of childrenNamed(styleEl, 'IconStyle')) {
|
||||
const iconEl = first(node, 'Icon');
|
||||
const href = textOf(iconEl, 'href');
|
||||
const icon = (target.icon ??= {});
|
||||
// Blank <Icon> tags mean no icon at all.
|
||||
icon.image = href ? { url: href } : iconEl ? false : undefined;
|
||||
icon.scale = numberOf(node, 'scale');
|
||||
icon.color = colorOf(node, 'color');
|
||||
const region = ['x', 'y', 'w', 'h'].map((key) => numberOf(iconEl, key));
|
||||
if (region.some((v) => v !== undefined))
|
||||
icon.subRegion = region.map((v) => v ?? 0);
|
||||
const heading = numberOf(node, 'heading');
|
||||
// Google Earth reads a heading of 0 as none.
|
||||
if (heading !== undefined && heading !== 0)
|
||||
icon.rotation = (-heading * Math.PI) / 180;
|
||||
const offset = hotSpotOffset(first(node, 'hotSpot'), icon.scale ?? 1);
|
||||
if (offset) icon.offsetPx = offset;
|
||||
}
|
||||
for (const node of childrenNamed(styleEl, 'LineStyle'))
|
||||
target.line = {
|
||||
width: numberOf(node, 'width'),
|
||||
color: colorOf(node, 'color'),
|
||||
};
|
||||
for (const node of childrenNamed(styleEl, 'PolyStyle')) {
|
||||
const poly = (target.poly ??= { outline: true, outlineColor: WHITE });
|
||||
poly.color = colorOf(node, 'color') ?? poly.color;
|
||||
poly.fill = booleanOf(node, 'fill') ?? poly.fill;
|
||||
poly.outline = booleanOf(node, 'outline') ?? poly.outline;
|
||||
}
|
||||
}
|
||||
|
||||
/** A KML hot spot as Cesium's billboard pixel offset (+y down), or null. */
|
||||
function hotSpotOffset(el, scale) {
|
||||
if (!el) return null;
|
||||
const read = (name) => {
|
||||
const value = Number.parseFloat(el.getAttribute(name));
|
||||
return Number.isFinite(value) ? value : undefined;
|
||||
};
|
||||
const x = read('x');
|
||||
const y = read('y');
|
||||
let dx;
|
||||
let dy;
|
||||
if (x !== undefined) {
|
||||
const unit = el.getAttribute('xunits');
|
||||
if (unit === 'pixels') dx = -x * scale;
|
||||
else if (unit === 'insetPixels') dx = (x - BILLBOARD_SIZE) * scale;
|
||||
else if (unit === 'fraction') dx = -x * BILLBOARD_SIZE * scale;
|
||||
dx = (dx ?? Number.NaN) + BILLBOARD_SIZE * 0.5 * scale;
|
||||
}
|
||||
if (y !== undefined) {
|
||||
const unit = el.getAttribute('yunits');
|
||||
if (unit === 'pixels') dy = y * scale;
|
||||
else if (unit === 'insetPixels') dy = (-y + BILLBOARD_SIZE) * scale;
|
||||
else if (unit === 'fraction') dy = y * BILLBOARD_SIZE * scale;
|
||||
dy = (dy ?? Number.NaN) - BILLBOARD_SIZE * 0.5 * scale;
|
||||
}
|
||||
if (dx === undefined && dy === undefined) return null;
|
||||
const finite = (v) => (Number.isFinite(v) ? v : 0);
|
||||
return [finite(dx), finite(dy)];
|
||||
}
|
||||
|
||||
const cloneStyle = (style) => ({
|
||||
icon: style.icon && { ...style.icon },
|
||||
line: style.line && { ...style.line },
|
||||
poly: style.poly && { ...style.poly },
|
||||
});
|
||||
|
||||
/** Entity.merge: what `target` leaves undefined comes from `source`. */
|
||||
function mergeStyle(target, source) {
|
||||
if (!source) return target;
|
||||
for (const key of ['icon', 'line', 'poly']) {
|
||||
if (!source[key]) continue;
|
||||
if (!target[key]) target[key] = { ...source[key] };
|
||||
else
|
||||
for (const [name, value] of Object.entries(source[key]))
|
||||
target[key][name] ??= value;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/** The document's shared styles by '#id', as KmlDataSource collects them. */
|
||||
function sharedStyles(doc) {
|
||||
const styles = new Map();
|
||||
const all = [...doc.getElementsByTagName('*')];
|
||||
for (const el of all) {
|
||||
if (el.localName !== 'Style') continue;
|
||||
const id = el.getAttribute('id');
|
||||
if (id === null || styles.has(`#${id}`)) continue;
|
||||
const style = {};
|
||||
applyStyle(el, style);
|
||||
styles.set(`#${id}`, style);
|
||||
}
|
||||
for (const el of all) {
|
||||
if (el.localName !== 'StyleMap') continue;
|
||||
const id = el.getAttribute('id');
|
||||
if (id === null) continue;
|
||||
for (const pair of childrenNamed(el, 'Pair')) {
|
||||
if (textOf(pair, 'key') !== 'normal' || styles.has(`#${id}`)) continue;
|
||||
const style = {};
|
||||
const url = textOf(pair, 'styleUrl');
|
||||
if (url !== undefined)
|
||||
mergeStyle(style, styles.get(url.startsWith('#') ? url : `#${url}`));
|
||||
else {
|
||||
const inline = first(pair, 'Style');
|
||||
if (inline) applyStyle(inline, style);
|
||||
}
|
||||
styles.set(`#${id}`, style);
|
||||
}
|
||||
}
|
||||
return styles;
|
||||
}
|
||||
|
||||
/** A placemark's final style: its last inline style, then its styleUrl. */
|
||||
function placemarkStyle(placemark, styles) {
|
||||
const lookup = (url) => styles.get(url) ?? styles.get(`#${url}`);
|
||||
const result = {};
|
||||
const inline = [...(placemark.childNodes || [])]
|
||||
.filter(
|
||||
(el) =>
|
||||
el.nodeType === 1 &&
|
||||
(el.localName === 'Style' || el.localName === 'StyleMap'),
|
||||
)
|
||||
.at(-1);
|
||||
if (inline?.localName === 'Style') applyStyle(inline, result);
|
||||
else if (inline)
|
||||
for (const pair of childrenNamed(inline, 'Pair')) {
|
||||
if (textOf(pair, 'key') !== 'normal') continue;
|
||||
const url = textOf(pair, 'styleUrl');
|
||||
if (url !== undefined) mergeStyle(result, lookup(url));
|
||||
else {
|
||||
const style = first(pair, 'Style');
|
||||
if (style) applyStyle(style, result);
|
||||
}
|
||||
}
|
||||
const external = textOf(placemark, 'styleUrl');
|
||||
if (external !== undefined) mergeStyle(result, lookup(external));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The polyline Cesium draws for a style: its colour (white) and width (1). */
|
||||
const lineLook = (style) => ({
|
||||
color: style.line?.color ?? WHITE,
|
||||
widthPx: style.line?.width ?? 1,
|
||||
});
|
||||
|
||||
function readGeometry(geometry, style, name, records) {
|
||||
const kind = geometry.localName;
|
||||
if (kind === 'MultiGeometry') {
|
||||
for (const child of geometry.childNodes || [])
|
||||
if (child.nodeType === 1 && GEOMETRY.has(child.localName))
|
||||
readGeometry(child, style, name, records);
|
||||
return;
|
||||
}
|
||||
const altitude = altitudeOf(geometry);
|
||||
const extrude = booleanOf(geometry, 'extrude') === true;
|
||||
if (kind === 'Point') {
|
||||
const [position = [0, 0, 0]] = coordinates(first(geometry, 'coordinates'));
|
||||
const icon = style.icon ?? {};
|
||||
if (icon.image !== false)
|
||||
records.points.push({
|
||||
name,
|
||||
position,
|
||||
altitude,
|
||||
icon: {
|
||||
image: icon.image || DEFAULT_PIN,
|
||||
widthPx: BILLBOARD_SIZE,
|
||||
heightPx: BILLBOARD_SIZE,
|
||||
scale: icon.scale,
|
||||
color: icon.color,
|
||||
offsetPx: icon.offsetPx,
|
||||
subRegion: icon.subRegion,
|
||||
rotation: icon.rotation,
|
||||
scaleByDistance: BILLBOARD_SCALE_BY_DISTANCE,
|
||||
},
|
||||
});
|
||||
// A drop line from an extruded point down to the ellipsoid.
|
||||
if (extrude && altitude !== 'ground')
|
||||
records.lines.push({
|
||||
name,
|
||||
positions: [position, [position[0], position[1], 0]],
|
||||
ground: false,
|
||||
...lineLook(style),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (kind === 'LineString' || kind === 'LinearRing') {
|
||||
const positions = coordinates(first(geometry, 'coordinates'));
|
||||
if (positions.length < 2) return;
|
||||
const tessellate = booleanOf(geometry, 'tessellate') === true;
|
||||
if (altitude !== 'ground' && extrude) {
|
||||
// A wall; its outline's top edge draws as the path.
|
||||
records.undrawn.wall = (records.undrawn.wall ?? 0) + 1;
|
||||
records.lines.push({
|
||||
name,
|
||||
positions,
|
||||
ground: false,
|
||||
...lineLook(style),
|
||||
});
|
||||
} else if (altitude === 'ground' && tessellate)
|
||||
records.lines.push({ name, positions, ground: true, ...lineLook(style) });
|
||||
else
|
||||
records.lines.push({
|
||||
name,
|
||||
positions:
|
||||
altitude === 'ground'
|
||||
? positions.map(([lon, lat]) => [lon, lat, 0])
|
||||
: positions,
|
||||
ground: false,
|
||||
...lineLook(style),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (kind === 'Polygon') {
|
||||
const ringOf = (boundary) =>
|
||||
coordinates(first(first(boundary, 'LinearRing'), 'coordinates'));
|
||||
const outer = ringOf(first(geometry, 'outerBoundaryIs'));
|
||||
if (!outer.length) return;
|
||||
const holes = childrenNamed(geometry, 'innerBoundaryIs')
|
||||
.flatMap((boundary) =>
|
||||
childrenNamed(boundary, 'LinearRing').map((ring) =>
|
||||
coordinates(first(ring, 'coordinates')),
|
||||
),
|
||||
)
|
||||
.filter((ring) => ring.length);
|
||||
const poly = style.poly ?? { outline: true, outlineColor: WHITE };
|
||||
const raised = altitude !== 'ground';
|
||||
if (raised && extrude)
|
||||
records.undrawn.extruded = (records.undrawn.extruded ?? 0) + 1;
|
||||
records.polygons.push({
|
||||
name,
|
||||
rings: [outer, ...holes],
|
||||
raised,
|
||||
fill: poly.fill === false ? null : (poly.color ?? WHITE),
|
||||
outline:
|
||||
poly.outline === false
|
||||
? null
|
||||
: {
|
||||
color: style.line
|
||||
? (style.line.color ?? WHITE)
|
||||
: (poly.outlineColor ?? WHITE),
|
||||
widthPx: style.line?.width ?? 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
// A Model or a Track left by the sanitizer has nothing to draw.
|
||||
}
|
||||
|
||||
function readGroundOverlay(el, records) {
|
||||
const name = importFeatureName(textOf(el, 'name'));
|
||||
const color = colorOf(el, 'color') ?? WHITE;
|
||||
const quad = first(el, 'LatLonQuad');
|
||||
if (quad) {
|
||||
records.undrawn.latLonQuad = (records.undrawn.latLonQuad ?? 0) + 1;
|
||||
return;
|
||||
}
|
||||
const box = first(el, 'LatLonBox');
|
||||
if (!box) return;
|
||||
// Cesium's negativePiToPi and latitude clamp.
|
||||
const lon = (v = 0) =>
|
||||
v >= -180 && v <= 180 ? v : ((((v + 180) % 360) + 360) % 360) - 180;
|
||||
const lat = (v = 0) => Math.max(-90, Math.min(90, v));
|
||||
const rectangle = {
|
||||
west: lon(numberOf(box, 'west')),
|
||||
south: lat(numberOf(box, 'south')),
|
||||
east: lon(numberOf(box, 'east')),
|
||||
north: lat(numberOf(box, 'north')),
|
||||
};
|
||||
if (!(rectangle.north > rectangle.south)) return;
|
||||
const url = textOf(first(el, 'Icon'), 'href') || null;
|
||||
records.overlays.push({
|
||||
name,
|
||||
url,
|
||||
rectangle,
|
||||
color,
|
||||
rotation: numberOf(box, 'rotation') ?? 0,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a sanitized KML document into records, placemarks and ground
|
||||
* overlays in document order.
|
||||
* @param {Document} doc
|
||||
* @returns {import('./geoImportRecords.js').ImportedRecords}
|
||||
*/
|
||||
export function readKmlRecords(doc) {
|
||||
const records = emptyRecords();
|
||||
const styles = sharedStyles(doc);
|
||||
for (const el of doc.getElementsByTagName('*')) {
|
||||
if (el.localName === 'GroundOverlay') {
|
||||
readGroundOverlay(el, records);
|
||||
continue;
|
||||
}
|
||||
if (el.localName !== 'Placemark') continue;
|
||||
const name = importFeatureName(textOf(el, 'name'));
|
||||
const style = cloneStyle(placemarkStyle(el, styles));
|
||||
// Only a placemark's first geometry draws.
|
||||
const geometry = [...(el.childNodes || [])].find(
|
||||
(child) => child.nodeType === 1 && GEOMETRY.has(child.localName),
|
||||
);
|
||||
if (geometry) readGeometry(geometry, style, name, records);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
// The KML reader against Cesium's KmlDataSource, the reference it replaces:
|
||||
// the same sanitized documents read by both give the same pins, lines,
|
||||
// polygons and overlays with the same styles. Cesium stays a test
|
||||
// dependency here only.
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
deduplicateKmlStyles,
|
||||
loadGeoFile,
|
||||
parseXml,
|
||||
sanitizeKmlDocument,
|
||||
} from './geoFileImport.js';
|
||||
import { kmlColor, readKmlRecords } from './geoImportKml.js';
|
||||
|
||||
// happy-dom's getElementsByTagNameNS('*', name) finds nothing in a parsed
|
||||
// XML document; KmlDataSource queries every element through it.
|
||||
function byNamespace(namespace, localName) {
|
||||
return [...this.getElementsByTagName('*')].filter(
|
||||
(el) =>
|
||||
(localName === '*' || el.localName === localName) &&
|
||||
(namespace === '*' || el.namespaceURI === namespace),
|
||||
);
|
||||
}
|
||||
const probe = new DOMParser().parseFromString('<a><b/></a>', 'application/xml');
|
||||
for (const node of [probe, probe.documentElement])
|
||||
for (let p = Object.getPrototypeOf(node); p; p = Object.getPrototypeOf(p))
|
||||
if (Object.hasOwn(p, 'getElementsByTagNameNS')) {
|
||||
p.getElementsByTagNameNS = byNamespace;
|
||||
break;
|
||||
}
|
||||
|
||||
const TRAP = 'gev-qa-trap.invalid';
|
||||
const PNG =
|
||||
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==';
|
||||
const kml = (body) => `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
|
||||
<Document>${body}</Document></kml>`;
|
||||
|
||||
// scripts/qa-geo-import.mjs's KML, with a packed icon and overlay as in its KMZ.
|
||||
const QA = kml(`
|
||||
<Style id="s"><IconStyle><Icon><href>${PNG}</href></Icon></IconStyle></Style>
|
||||
<Style id="palette"><IconStyle><Icon><href>root://icons/palette-4.png</href><gx:x>32</gx:x><gx:y>64</gx:y></Icon></IconStyle></Style>
|
||||
<NetworkLink><Link><href>https://${TRAP}/link.kml</href></Link></NetworkLink>
|
||||
<Placemark><name>QA KML pin</name><styleUrl>#s</styleUrl>
|
||||
<description><img src="https://${TRAP}/balloon.png"></description>
|
||||
<TimeSpan><begin>2019-01-01T00:00:00Z</begin><end>2019-01-02T00:00:00Z</end></TimeSpan>
|
||||
<Point><coordinates>-122.47,37.77,0</coordinates></Point></Placemark>
|
||||
<Placemark><name>QA palette pin</name><styleUrl>#palette</styleUrl>
|
||||
<Point><coordinates>-122.48,37.771,0</coordinates></Point></Placemark>
|
||||
<Placemark><name>QA moving</name>
|
||||
<gx:Track><when>2019-01-01T00:00:00Z</when><when>2019-01-01T01:00:00Z</when>
|
||||
<gx:coord>-122.49 37.767 0</gx:coord><gx:coord>-122.475 37.772 0</gx:coord></gx:Track></Placemark>
|
||||
<Placemark><name>QA split tracks</name><gx:MultiTrack>
|
||||
<gx:Track><gx:coord>-122.50 37.767 0</gx:coord><gx:coord>-122.49 37.768 0</gx:coord></gx:Track>
|
||||
<gx:Track><gx:coord>-122.47 37.771 0</gx:coord><gx:coord>-122.46 37.772 0</gx:coord></gx:Track>
|
||||
</gx:MultiTrack></Placemark>
|
||||
<Placemark><name>QA remote style</name><styleUrl>https://${TRAP}/styles.kml#x</styleUrl>
|
||||
<LineString><coordinates>-122.50,37.766 -122.46,37.772</coordinates></LineString></Placemark>
|
||||
<GroundOverlay><Icon><href>${PNG}</href></Icon>
|
||||
<LatLonBox><north>37.77</north><south>37.76</south><east>-122.46</east><west>-122.47</west></LatLonBox></GroundOverlay>`);
|
||||
|
||||
// Styles and geometries the import keeps, each the way KML allows.
|
||||
const STYLED = kml(`
|
||||
<Style id="red"><LineStyle><color>ff0000ff</color><width>4</width></LineStyle>
|
||||
<PolyStyle><color>7f00ff00</color></PolyStyle></Style>
|
||||
<Style id="pin"><IconStyle><scale>1.5</scale><color>ff00ffff</color><heading>30</heading>
|
||||
<Icon><href>${PNG}</href><gx:x>0</gx:x><gx:y>0</gx:y><gx:w>1</gx:w><gx:h>1</gx:h></Icon>
|
||||
<hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/></IconStyle></Style>
|
||||
<Style id="frac"><IconStyle><hotSpot x="0.5" y="0" xunits="fraction" yunits="fraction"/></IconStyle></Style>
|
||||
<Style id="inset"><IconStyle><scale>2</scale><hotSpot x="4" y="6" xunits="insetPixels" yunits="insetPixels"/></IconStyle></Style>
|
||||
<Style id="none"><IconStyle><Icon></Icon></IconStyle></Style>
|
||||
<Style id="hollow"><PolyStyle><fill>0</fill><outline>1</outline></PolyStyle><LineStyle><color>ffff0000</color><width>3</width></LineStyle></Style>
|
||||
<StyleMap id="map"><Pair><key>normal</key><styleUrl>#red</styleUrl></Pair>
|
||||
<Pair><key>highlight</key><styleUrl>#pin</styleUrl></Pair></StyleMap>
|
||||
<StyleMap id="inlineMap"><Pair><key>normal</key><Style><LineStyle><color>ff00ff00</color></LineStyle></Style></Pair></StyleMap>
|
||||
<Placemark><name>default pin</name><Point><coordinates>1,1</coordinates></Point></Placemark>
|
||||
<Placemark><name>styled pin</name><styleUrl>#pin</styleUrl><Point><coordinates>1,2,50</coordinates></Point></Placemark>
|
||||
<Placemark><name>fraction</name><styleUrl>#frac</styleUrl><Point><altitudeMode>absolute</altitudeMode><coordinates>1,3,500</coordinates></Point></Placemark>
|
||||
<Placemark><name>inset</name><styleUrl>#inset</styleUrl><Point><altitudeMode>relativeToGround</altitudeMode><extrude>1</extrude><coordinates>1,4,80</coordinates></Point></Placemark>
|
||||
<Placemark><name>hidden icon</name><styleUrl>#none</styleUrl><Point><coordinates>1,5</coordinates></Point></Placemark>
|
||||
<Placemark><name>mapped line</name><styleUrl>#map</styleUrl><LineString><coordinates>0,0 1,1 2,1</coordinates></LineString></Placemark>
|
||||
<Placemark><name>inline map line</name><styleUrl>#inlineMap</styleUrl><LineString><coordinates>0,0 1,0</coordinates></LineString></Placemark>
|
||||
<Placemark><name>override</name><styleUrl>#red</styleUrl><Style><LineStyle><width>9</width></LineStyle></Style>
|
||||
<LineString><coordinates>0,1 1,2</coordinates></LineString></Placemark>
|
||||
<Placemark><name>air line</name><styleUrl>#red</styleUrl><LineString><altitudeMode>absolute</altitudeMode><coordinates>0,2,100 1,3,200</coordinates></LineString></Placemark>
|
||||
<Placemark><name>relative line</name><LineString><tessellate>0</tessellate><altitudeMode>relativeToGround</altitudeMode><coordinates>0,3,10 1,4,20</coordinates></LineString></Placemark>
|
||||
<Placemark><name>wall</name><styleUrl>#red</styleUrl><LineString><extrude>1</extrude><altitudeMode>absolute</altitudeMode><coordinates>0,4,100 1,5,100</coordinates></LineString></Placemark>
|
||||
<Placemark><name>ring</name><LinearRing><coordinates>0,0 1,0 1,1 0,0</coordinates></LinearRing></Placemark>
|
||||
<Placemark><name>filled</name><styleUrl>#red</styleUrl><Polygon>
|
||||
<outerBoundaryIs><LinearRing><coordinates>0,0 2,0 2,2 0,2 0,0</coordinates></LinearRing></outerBoundaryIs>
|
||||
<innerBoundaryIs><LinearRing><coordinates>0.5,0.5 1,0.5 1,1 0.5,0.5</coordinates></LinearRing></innerBoundaryIs></Polygon></Placemark>
|
||||
<Placemark><name>hollow raised</name><styleUrl>#hollow</styleUrl><Polygon><altitudeMode>absolute</altitudeMode>
|
||||
<outerBoundaryIs><LinearRing><coordinates>3,0,10 4,0,10 4,1,10 3,0,10</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
|
||||
<Placemark><name>plain</name><Polygon><outerBoundaryIs><LinearRing><coordinates>5,0 6,0 6,1 5,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
|
||||
<Placemark><name>multi</name><styleUrl>#red</styleUrl><MultiGeometry>
|
||||
<Point><coordinates>7,7</coordinates></Point>
|
||||
<LineString><coordinates>7,7 8,8</coordinates></LineString>
|
||||
<MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>7,0 8,0 8,1 7,0</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>
|
||||
</MultiGeometry></Placemark>
|
||||
<Folder><Placemark><name>in folder</name><styleUrl>#red</styleUrl><Point><coordinates>9,9</coordinates></Point></Placemark></Folder>
|
||||
<GroundOverlay><color>80ffffff</color><Icon><href>${PNG}</href></Icon>
|
||||
<LatLonBox><north>11</north><south>10</south><east>-179</east><west>179</west><rotation>15</rotation></LatLonBox></GroundOverlay>
|
||||
<GroundOverlay><color>ff0000ff</color><LatLonBox><north>13</north><south>12</south><east>13</east><west>12</west></LatLonBox></GroundOverlay>
|
||||
<Style id="a"><LineStyle><color>ff123456</color></LineStyle></Style>
|
||||
<Style id="b"><LineStyle><color>ff123456</color></LineStyle></Style>
|
||||
<Placemark><name>deduplicated a</name><styleUrl>#a</styleUrl><LineString><coordinates>3,3 4,4</coordinates></LineString></Placemark>
|
||||
<Placemark><name>deduplicated b</name><styleUrl>#b</styleUrl><LineString><coordinates>4,4 5,5</coordinates></LineString></Placemark>`);
|
||||
|
||||
/** A document as the import prepares it for reading. */
|
||||
function prepared(text) {
|
||||
const doc = parseXml(text, 'KML');
|
||||
sanitizeKmlDocument(doc);
|
||||
deduplicateKmlStyles(doc);
|
||||
return doc;
|
||||
}
|
||||
|
||||
// To 1e-6, and -0 as 0.
|
||||
const round = (v) =>
|
||||
v === undefined ? undefined : Math.round(v * 1e6) / 1e6 + 0;
|
||||
const rgba = (c) => c && [c.red, c.green, c.blue, c.alpha].map(round);
|
||||
const lonLatH = (cartesian) => {
|
||||
const c = Cesium.Cartographic.fromCartesian(cartesian);
|
||||
return [
|
||||
Cesium.Math.toDegrees(c.longitude),
|
||||
Cesium.Math.toDegrees(c.latitude),
|
||||
c.height,
|
||||
].map((v) => Math.round(v * 1e4) / 1e4 + 0);
|
||||
};
|
||||
const roundPosition = (p) => p.map((v) => Math.round(v * 1e4) / 1e4 + 0);
|
||||
const HEIGHT_MODE = {
|
||||
[Cesium.HeightReference.CLAMP_TO_GROUND]: 'ground',
|
||||
[Cesium.HeightReference.RELATIVE_TO_GROUND]: 'relative',
|
||||
[Cesium.HeightReference.NONE]: 'absolute',
|
||||
};
|
||||
|
||||
/** What Cesium's KmlDataSource draws of a document, as comparable data. */
|
||||
async function cesiumReading(text) {
|
||||
const previous = Cesium.PinBuilder.prototype.fromColor;
|
||||
Cesium.PinBuilder.prototype.fromColor = (color, size) => ({
|
||||
pin: rgba(color),
|
||||
pinSize: size,
|
||||
});
|
||||
try {
|
||||
const ds = await Cesium.KmlDataSource.load(prepared(text), {
|
||||
clampToGround: true,
|
||||
});
|
||||
const now = Cesium.JulianDate.now();
|
||||
const value = (property) => property?.getValue?.(now);
|
||||
const out = { points: [], lines: [], polygons: [], overlays: [], walls: 0 };
|
||||
for (const entity of ds.entities.values) {
|
||||
const billboard = entity.billboard;
|
||||
const image = value(billboard?.image);
|
||||
if (billboard && entity.position && image) {
|
||||
const offset = value(billboard.pixelOffset);
|
||||
const rotation = value(billboard.rotation);
|
||||
const region = value(billboard.imageSubRegion);
|
||||
out.points.push({
|
||||
name: entity.name,
|
||||
position: lonLatH(value(entity.position)),
|
||||
altitude: HEIGHT_MODE[value(billboard.heightReference)],
|
||||
image: image.pin ? image : { url: image.url ?? String(image) },
|
||||
scale: round(value(billboard.scale) ?? 1),
|
||||
color: rgba(value(billboard.color)) ?? [1, 1, 1, 1],
|
||||
offset: offset ? [offset.x, offset.y].map(round) : [0, 0],
|
||||
rotation: round(rotation ?? 0),
|
||||
subRegion: region
|
||||
? [region.x, region.y, region.width, region.height]
|
||||
: undefined,
|
||||
size: [value(billboard.width), value(billboard.height)],
|
||||
});
|
||||
}
|
||||
if (entity.polyline) {
|
||||
const ground = value(entity.polyline.clampToGround) === true;
|
||||
out.lines.push({
|
||||
name: entity.name,
|
||||
positions: value(entity.polyline.positions).map((p) => {
|
||||
const [lon, lat, h] = lonLatH(p);
|
||||
return ground ? [lon, lat] : [lon, lat, h];
|
||||
}),
|
||||
ground,
|
||||
color: rgba(value(entity.polyline.material)?.color) ??
|
||||
rgba(entity.polyline.material?.color?.getValue(now)) ?? [
|
||||
1, 1, 1, 1,
|
||||
],
|
||||
width: value(entity.polyline.width) ?? 1,
|
||||
});
|
||||
}
|
||||
if (entity.wall) out.walls += 1;
|
||||
if (entity.polygon) {
|
||||
const polygon = entity.polygon;
|
||||
const hierarchy = value(polygon.hierarchy);
|
||||
const raised = value(polygon.perPositionHeight) === true;
|
||||
const ring = (positions) =>
|
||||
positions.map((p) => {
|
||||
const [lon, lat, h] = lonLatH(p);
|
||||
return raised ? [lon, lat, h] : [lon, lat];
|
||||
});
|
||||
const fill = value(polygon.fill) ?? true;
|
||||
const outline = value(polygon.outline) ?? false;
|
||||
out.polygons.push({
|
||||
name: entity.name,
|
||||
rings: [
|
||||
ring(hierarchy.positions),
|
||||
...hierarchy.holes.map((h) => ring(h.positions)),
|
||||
],
|
||||
raised,
|
||||
fill: fill
|
||||
? (rgba(polygon.material?.color?.getValue(now)) ?? [1, 1, 1, 1])
|
||||
: null,
|
||||
outline: outline
|
||||
? {
|
||||
color: rgba(value(polygon.outlineColor)) ?? [1, 1, 1, 1],
|
||||
widthPx: value(polygon.outlineWidth) ?? 1,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
}
|
||||
if (entity.rectangle) {
|
||||
const r = value(entity.rectangle.coordinates);
|
||||
const material = entity.rectangle.material;
|
||||
const url = material?.image?.getValue(now);
|
||||
out.overlays.push({
|
||||
rectangle: [r.west, r.south, r.east, r.north].map((v) =>
|
||||
round(Cesium.Math.toDegrees(v)),
|
||||
),
|
||||
url: url ? (url.url ?? String(url)) : null,
|
||||
color: rgba(material?.color?.getValue(now)) ??
|
||||
rgba(material?.getValue?.(now)?.color) ?? [1, 1, 1, 1],
|
||||
rotation: round(
|
||||
Cesium.Math.toDegrees(value(entity.rectangle.rotation) ?? 0),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} finally {
|
||||
Cesium.PinBuilder.prototype.fromColor = previous;
|
||||
}
|
||||
}
|
||||
|
||||
/** The reader's records of a document, in the same comparable form. */
|
||||
function ourReading(text) {
|
||||
const records = readKmlRecords(prepared(text));
|
||||
return {
|
||||
points: records.points.map(({ name, position, altitude, icon }) => ({
|
||||
name,
|
||||
position: roundPosition(position),
|
||||
altitude,
|
||||
image: icon.image.pin
|
||||
? { pin: icon.image.pin.map(round), pinSize: icon.image.pinSize }
|
||||
: icon.image,
|
||||
scale: round(icon.scale ?? 1),
|
||||
color: (icon.color ?? [1, 1, 1, 1]).map(round),
|
||||
offset: (icon.offsetPx ?? [0, 0]).map(round),
|
||||
rotation: round(icon.rotation ?? 0),
|
||||
subRegion: icon.subRegion,
|
||||
size: [icon.widthPx, icon.heightPx],
|
||||
})),
|
||||
lines: records.lines.map(({ name, positions, ground, color, widthPx }) => ({
|
||||
name,
|
||||
positions: positions.map((p) =>
|
||||
ground ? roundPosition(p).slice(0, 2) : roundPosition(p),
|
||||
),
|
||||
ground,
|
||||
color: color.map(round),
|
||||
width: widthPx,
|
||||
})),
|
||||
polygons: records.polygons.map(
|
||||
({ name, rings, raised, fill, outline }) => ({
|
||||
name,
|
||||
rings: rings.map((ring) =>
|
||||
ring.map((p) =>
|
||||
raised ? roundPosition(p) : roundPosition(p).slice(0, 2),
|
||||
),
|
||||
),
|
||||
raised,
|
||||
fill: fill && fill.map(round),
|
||||
outline: outline && {
|
||||
color: outline.color.map(round),
|
||||
widthPx: outline.widthPx,
|
||||
},
|
||||
}),
|
||||
),
|
||||
overlays: records.overlays.map(
|
||||
({ rectangle: r, url, color, rotation }) => ({
|
||||
rectangle: [r.west, r.south, r.east, r.north].map(round),
|
||||
url,
|
||||
// Cesium's transparent image material caps the alpha at 0.99, as the
|
||||
// display's imagery alpha does.
|
||||
color: (url
|
||||
? [...color.slice(0, 3), Math.min(0.99, color[3])]
|
||||
: color
|
||||
).map(round),
|
||||
rotation: round(rotation),
|
||||
}),
|
||||
),
|
||||
walls: records.undrawn.wall ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
for (const [name, text] of [
|
||||
['the QA file', QA],
|
||||
['styles, altitudes, multigeometries and overlays', STYLED],
|
||||
]) {
|
||||
test(`KML records match Cesium's reading: ${name}`, async () => {
|
||||
const cesium = await cesiumReading(text);
|
||||
const ours = ourReading(text);
|
||||
assert.deepEqual(ours.points, cesium.points);
|
||||
// Cesium draws a wall's outline where the reader draws its top edge as
|
||||
// a line; every other line is the same.
|
||||
assert.deepEqual(
|
||||
ours.lines.filter((line) => line.name !== 'wall'),
|
||||
cesium.lines,
|
||||
);
|
||||
assert.equal(ours.walls, cesium.walls);
|
||||
assert.deepEqual(ours.polygons, cesium.polygons);
|
||||
assert.deepEqual(ours.overlays, cesium.overlays);
|
||||
});
|
||||
}
|
||||
|
||||
test('the QA file reads to pins, ground lines and a packed overlay, with nothing remote', () => {
|
||||
const records = readKmlRecords(prepared(QA));
|
||||
assert.deepEqual(
|
||||
records.points.map(({ name, icon }) => [name, Boolean(icon.image.pin)]),
|
||||
[
|
||||
['QA KML pin', false],
|
||||
// A blocked palette icon falls back to Cesium's yellow pin.
|
||||
['QA palette pin', true],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
records.lines.map(({ name, ground, positions }) => [
|
||||
name,
|
||||
ground,
|
||||
positions.length,
|
||||
]),
|
||||
[
|
||||
['QA moving', true, 2],
|
||||
['QA split tracks', true, 2],
|
||||
['QA split tracks', true, 2],
|
||||
['QA remote style', true, 2],
|
||||
],
|
||||
);
|
||||
assert.equal(records.overlays.length, 1);
|
||||
assert.ok(!JSON.stringify(records).includes(TRAP));
|
||||
// No time survives: a dated placemark draws for all time.
|
||||
assert.ok(!/2019/.test(JSON.stringify(records)));
|
||||
});
|
||||
|
||||
test('extruded polygons and quads are counted as undrawn', () => {
|
||||
const records = readKmlRecords(
|
||||
prepared(
|
||||
kml(`<Placemark><Polygon><extrude>1</extrude><altitudeMode>absolute</altitudeMode>
|
||||
<outerBoundaryIs><LinearRing><coordinates>0,0,9 1,0,9 1,1,9 0,0,9</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
|
||||
<GroundOverlay><Icon><href>${PNG}</href></Icon><gx:LatLonQuad><coordinates>0,0 1,0 1,1 0,1</coordinates></gx:LatLonQuad></GroundOverlay>`),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(records.undrawn, { extruded: 1, latLonQuad: 1 });
|
||||
assert.equal(records.polygons[0].raised, true);
|
||||
});
|
||||
|
||||
test('KML colours are aabbggrr; a random colour stays within its channels', () => {
|
||||
assert.deepEqual(kmlColor('7f00ff00'), [0, 1, 0, 127 / 255]);
|
||||
assert.equal(kmlColor(' '), undefined);
|
||||
const [red, green, blue, alpha] = kmlColor('ff0000ff', true);
|
||||
assert.ok(red >= 0 && red <= 1 && green === 0 && blue === 0 && alpha === 1);
|
||||
});
|
||||
|
||||
test('a KML file loads to records with its name, count and outside content removed', async () => {
|
||||
const loaded = await loadGeoFile(new File([QA], 'remote-bits.kml'));
|
||||
assert.equal(loaded.format, 'kml');
|
||||
assert.equal(loaded.entityCount, 7);
|
||||
assert.ok(loaded.removed > 0);
|
||||
assert.equal(loaded.records.points[0].name, 'QA KML pin');
|
||||
loaded.revoke();
|
||||
});
|
||||
+133
-122
@@ -1,128 +1,139 @@
|
||||
import * as Cesium from 'cesium';
|
||||
// The images of imported points (UTILITIES ▸ Import), without Cesium: the
|
||||
// map pin Cesium's PinBuilder drew for a GeoJSON point or a KML placemark
|
||||
// without an icon, and each point's look composed onto one square sprite
|
||||
// whose centre is the point (src/data/geoImportDisplay.js), so the pin's
|
||||
// tip, a KML hot spot or an icon's sub-region lands where Cesium put it.
|
||||
|
||||
const STYLE = [
|
||||
'image',
|
||||
'scale',
|
||||
'rotation',
|
||||
'alignedAxis',
|
||||
'horizontalOrigin',
|
||||
'verticalOrigin',
|
||||
'color',
|
||||
'eyeOffset',
|
||||
'pixelOffset',
|
||||
'width',
|
||||
'height',
|
||||
'scaleByDistance',
|
||||
'translucencyByDistance',
|
||||
'pixelOffsetScaleByDistance',
|
||||
'distanceDisplayCondition',
|
||||
'sizeInMeters',
|
||||
'disableDepthTestDistance',
|
||||
'imageSubRegion',
|
||||
];
|
||||
/** Cesium.Color's CSS form of rgba in 0..1 (its float-to-byte conversion). */
|
||||
export function cssOf([red, green, blue, alpha = 1]) {
|
||||
const byte = (v) => (v === 1 ? 255 : (v * 256) | 0);
|
||||
const rgb = `${byte(red)},${byte(green)},${byte(blue)}`;
|
||||
return alpha === 1 ? `rgb(${rgb})` : `rgba(${rgb},${alpha})`;
|
||||
}
|
||||
|
||||
/** Own static imported pins without a per-frame Entity visualizer walk. */
|
||||
export function createImportedPins(dataSource, viewer) {
|
||||
class ImportedBillboards extends Cesium.BillboardCollection {
|
||||
update(frameState) {
|
||||
// Height queries should find the map, never another imported marker.
|
||||
// Ordinary click picks and rendered screenshots still include the pins.
|
||||
if (frameState.passes.pick && frameState.passes.offscreen) return;
|
||||
super.update(frameState);
|
||||
}
|
||||
}
|
||||
/** Cesium.Color#brighten. */
|
||||
const brighten = ([red, green, blue, alpha = 1], magnitude) => {
|
||||
const keep = 1 - magnitude;
|
||||
return [
|
||||
1 - (1 - red) * keep,
|
||||
1 - (1 - green) * keep,
|
||||
1 - (1 - blue) * keep,
|
||||
alpha,
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Draw Cesium's map pin (PinBuilder's drawPin, from its Assets/Textures/
|
||||
* pin.svg) of `color` (rgba in 0..1) into a `size` square at the context's
|
||||
* origin.
|
||||
*/
|
||||
export function drawPin(context, color, size) {
|
||||
context.save();
|
||||
context.scale(size / 24, size / 24);
|
||||
context.fillStyle = cssOf(color);
|
||||
context.strokeStyle = cssOf(brighten(color, 0.6));
|
||||
context.lineWidth = 0.846;
|
||||
context.beginPath();
|
||||
context.moveTo(6.72, 0.422);
|
||||
context.lineTo(17.28, 0.422);
|
||||
context.bezierCurveTo(18.553, 0.422, 19.577, 1.758, 19.577, 3.415);
|
||||
context.lineTo(19.577, 10.973);
|
||||
context.bezierCurveTo(19.577, 12.63, 18.553, 13.966, 17.282, 13.966);
|
||||
context.lineTo(14.386, 14.008);
|
||||
context.lineTo(11.826, 23.578);
|
||||
context.lineTo(9.614, 14.008);
|
||||
context.lineTo(6.719, 13.965);
|
||||
context.bezierCurveTo(5.446, 13.983, 4.422, 12.629, 4.422, 10.972);
|
||||
context.lineTo(4.422, 3.416);
|
||||
context.bezierCurveTo(4.423, 1.76, 5.447, 0.423, 6.718, 0.423);
|
||||
context.closePath();
|
||||
context.fill();
|
||||
context.stroke();
|
||||
context.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an icon draws around its point, in CSS pixels, as Cesium placed the
|
||||
* billboard: `width` × `height` (the icon's own size when the record gives
|
||||
* none) times `scale`, centred on the point (`origin: 'center'`) or standing
|
||||
* on it (`'bottom'`), then moved by `offsetPx` (+y down). Returns the box's
|
||||
* centre ([x, y] from the point) and size, and the side of the square
|
||||
* sprite centred on the point that holds it.
|
||||
* @param {object} icon An imported point's icon (src/data/geoImportRecords.js).
|
||||
* @param {{ width: number, height: number }} [natural] The image's own size.
|
||||
*/
|
||||
export function iconBox(icon, natural) {
|
||||
const pinSize = icon.image?.pin ? icon.image.pinSize : 0;
|
||||
const ownWidth = icon.subRegion?.[2] || natural?.width || pinSize || 32;
|
||||
const ownHeight = icon.subRegion?.[3] || natural?.height || pinSize || 32;
|
||||
const scale = icon.scale ?? 1;
|
||||
const width = (icon.widthPx ?? ownWidth) * scale;
|
||||
const height = (icon.heightPx ?? ownHeight) * scale;
|
||||
const [dx, dy] = icon.offsetPx ?? [0, 0];
|
||||
const center = [dx, dy - (icon.origin === 'bottom' ? height / 2 : 0)];
|
||||
const side =
|
||||
2 *
|
||||
Math.max(
|
||||
Math.abs(center[0]) + width / 2,
|
||||
Math.abs(center[1]) + height / 2,
|
||||
0.5,
|
||||
);
|
||||
return { center, width, height, side };
|
||||
}
|
||||
|
||||
const all = dataSource.entities.values.slice();
|
||||
const now = Cesium.JulianDate.now();
|
||||
const pins = all.filter((entity) => entity.billboard && entity.position);
|
||||
if (!pins.length) return { mount() {}, sync() {}, destroy() {} };
|
||||
const collection = new ImportedBillboards({ scene: viewer.scene });
|
||||
const billboards = [];
|
||||
try {
|
||||
for (const entity of pins) {
|
||||
const position = entity.position.getValue(now);
|
||||
if (
|
||||
!position ||
|
||||
![position.x, position.y, position.z].every(Number.isFinite)
|
||||
)
|
||||
throw new Error('Invalid imported point position.');
|
||||
const options = {
|
||||
id: entity,
|
||||
position,
|
||||
show:
|
||||
entity.isShowing && entity.billboard.show?.getValue(now) !== false,
|
||||
heightReference: Cesium.HeightReference.NONE,
|
||||
};
|
||||
for (const key of STYLE) {
|
||||
const value = entity.billboard[key]?.getValue(now);
|
||||
if (value !== undefined) options[key] = value;
|
||||
/**
|
||||
* Compose one icon onto a square canvas centred on its point (see iconBox).
|
||||
* `image` is the decoded image of a `url` icon (ignored for a pin);
|
||||
* `ratio` canvas pixels per CSS pixel. Returns the canvas and the sprite's
|
||||
* side in CSS pixels.
|
||||
*/
|
||||
export function composeIcon(icon, { image, createCanvas, ratio = 1 } = {}) {
|
||||
const natural = image
|
||||
? {
|
||||
width: image.naturalWidth || image.width,
|
||||
height: image.naturalHeight || image.height,
|
||||
}
|
||||
billboards.push(collection.add(options));
|
||||
}
|
||||
} catch (error) {
|
||||
collection.destroy();
|
||||
throw error;
|
||||
: undefined;
|
||||
const box = iconBox(icon, natural);
|
||||
// At least one canvas pixel per icon pixel, at most 512 a side.
|
||||
const k = Math.min(ratio, 512 / box.side);
|
||||
const canvas = createCanvas();
|
||||
canvas.width = Math.max(1, Math.ceil(box.side * k));
|
||||
canvas.height = canvas.width;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) throw new Error('Imported icons need a canvas');
|
||||
const x = (box.side / 2 + box.center[0] - box.width / 2) * k;
|
||||
const y = (box.side / 2 + box.center[1] - box.height / 2) * k;
|
||||
if (icon.image?.pin) {
|
||||
// PinBuilder draws the pin at its own size; the billboard then
|
||||
// stretches that canvas over the box.
|
||||
context.translate(x, y);
|
||||
context.scale(
|
||||
box.width / icon.image.pinSize,
|
||||
box.height / icon.image.pinSize,
|
||||
);
|
||||
context.scale(k, k);
|
||||
drawPin(context, icon.image.pin, icon.image.pinSize);
|
||||
} else if (image) {
|
||||
const [sx, sy, sw, sh] = icon.subRegion ?? [
|
||||
0,
|
||||
0,
|
||||
natural.width,
|
||||
natural.height,
|
||||
];
|
||||
// Cesium's imageSubRegion counts y up from the image's bottom.
|
||||
const top = icon.subRegion ? natural.height - sy - sh : sy;
|
||||
context.drawImage(
|
||||
image,
|
||||
sx,
|
||||
top,
|
||||
sw,
|
||||
sh,
|
||||
x,
|
||||
y,
|
||||
box.width * k,
|
||||
box.height * k,
|
||||
);
|
||||
}
|
||||
// Rebuild once before the source is added to DataSourceDisplay. Removing
|
||||
// one entity at a time would itself make this transition quadratic.
|
||||
dataSource.entities.suspendEvents();
|
||||
try {
|
||||
dataSource.entities.removeAll();
|
||||
for (const entity of all)
|
||||
if (!entity.billboard || !entity.position)
|
||||
dataSource.entities.add(entity);
|
||||
} finally {
|
||||
dataSource.entities.resumeEvents();
|
||||
}
|
||||
Object.defineProperty(dataSource, 'importedEntities', {
|
||||
value: all,
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(dataSource, 'importedBillboards', {
|
||||
value: collection,
|
||||
configurable: true,
|
||||
});
|
||||
let show = dataSource.show,
|
||||
mounted = false,
|
||||
destroyed = false;
|
||||
Object.defineProperty(dataSource, 'show', {
|
||||
configurable: true,
|
||||
get: () => show,
|
||||
set(value) {
|
||||
show = Boolean(value);
|
||||
dataSource.entities.show = show;
|
||||
collection.show = show;
|
||||
},
|
||||
});
|
||||
collection.show = show;
|
||||
return {
|
||||
mount() {
|
||||
if (destroyed || mounted) return;
|
||||
viewer.scene.primitives?.add(collection);
|
||||
mounted = true;
|
||||
},
|
||||
sync() {
|
||||
if (destroyed) return;
|
||||
for (let i = 0; i < pins.length; i++) {
|
||||
billboards[i].position = pins[i].position.getValue(now);
|
||||
billboards[i].show =
|
||||
pins[i].isShowing && pins[i].billboard.show?.getValue(now) !== false;
|
||||
}
|
||||
viewer.scene.requestRender?.();
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
if (viewer.trackedEntity && pins.includes(viewer.trackedEntity))
|
||||
viewer.trackedEntity = undefined;
|
||||
if (viewer.selectedEntity && pins.includes(viewer.selectedEntity))
|
||||
viewer.selectedEntity = undefined;
|
||||
if (mounted && !viewer.scene.primitives?.isDestroyed?.())
|
||||
viewer.scene.primitives?.remove(collection);
|
||||
if (!collection.isDestroyed()) collection.destroy();
|
||||
all.length = 0;
|
||||
pins.length = 0;
|
||||
billboards.length = 0;
|
||||
},
|
||||
};
|
||||
return { canvas, side: box.side };
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
// The parsed-file model of UTILITIES ▸ Import: what a GeoJSON, GPX, KML or
|
||||
// KMZ file draws, as plain records, engine-neutral and without a Cesium
|
||||
// DataSource. src/data/geoFileImport.js reads a file into it (GeoJSON and
|
||||
// GPX here, KML and KMZ in src/data/geoImportKml.js), and
|
||||
// src/data/geoImportDisplay.js draws it on any globe engine.
|
||||
//
|
||||
// Positions are [longitude, latitude, height] in degrees and metres above
|
||||
// the ellipsoid; colours are rgba in 0..1. Every record has a short
|
||||
// plain-text `name` (or undefined). The import keeps no descriptions,
|
||||
// properties or times: a file's HTML never reaches the page, and a dated
|
||||
// file never moves the app's clock (it draws as it is, for all time).
|
||||
//
|
||||
// @typedef {object} ImportedRecords
|
||||
// @property {ImportedPoint[]} points
|
||||
// @property {ImportedLine[]} lines
|
||||
// @property {ImportedPolygon[]} polygons
|
||||
// @property {ImportedOverlay[]} overlays
|
||||
// @property {Object<string, number>} undrawn What the file has that no
|
||||
// engine draws, by kind (`wall`, `extruded`, `latLonQuad`), counted.
|
||||
//
|
||||
// @typedef {object} ImportedPoint
|
||||
// @property {number[]} position
|
||||
// @property {'ground'|'relative'|'absolute'} altitude On the ground (the
|
||||
// height is ignored), that high above it, or that high above the
|
||||
// ellipsoid.
|
||||
// @property {ImportedIcon} icon
|
||||
//
|
||||
// @typedef {object} ImportedIcon How Cesium drew the point's billboard:
|
||||
// @property {{ pin: number[], pinSize: number } | { url: string }} image
|
||||
// Cesium's map pin of that colour, drawn at pinSize px, or an image of the
|
||||
// file's own (a data: or blob: URL; nothing remote).
|
||||
// @property {number} [widthPx] Drawn width before `scale` (the image's own
|
||||
// when omitted); `heightPx` likewise.
|
||||
// @property {number} [heightPx]
|
||||
// @property {number} [scale] 1 when omitted.
|
||||
// @property {number[]} [color] Multiplies the image (white when omitted).
|
||||
// @property {'center'|'bottom'} [origin] The point is the box's centre
|
||||
// (the default) or the middle of its bottom edge.
|
||||
// @property {number[]} [offsetPx] [x, y], +y down: the box moved by this.
|
||||
// @property {number[]} [subRegion] [x, y, width, height] of the image in
|
||||
// pixels, y up from its bottom (Cesium's imageSubRegion).
|
||||
// @property {number[]} [scaleByDistance] [nearM, nearScale, farM, farScale].
|
||||
// @property {number} [rotation] Radians counter-clockwise.
|
||||
//
|
||||
// @typedef {object} ImportedLine
|
||||
// @property {number[][]} positions At least two.
|
||||
// @property {boolean} ground Draped on the ground (heights ignored), else a
|
||||
// line through the positions' heights.
|
||||
// @property {number[]} color
|
||||
// @property {number} widthPx
|
||||
//
|
||||
// @typedef {object} ImportedPolygon
|
||||
// @property {number[][][]} rings [outer, ...holes], each closed or not.
|
||||
// @property {boolean} raised Drawn at its positions' heights on Cesium
|
||||
// (KML absolute and relative altitudes); else draped on the ground.
|
||||
// @property {number[]|null} fill
|
||||
// @property {{ color: number[], widthPx: number }|null} outline Cesium
|
||||
// draws it only on a raised polygon (an outline on terrain is not drawn).
|
||||
//
|
||||
// @typedef {object} ImportedOverlay A KML ground overlay.
|
||||
// @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} rotation Degrees counter-clockwise (KML LatLonBox).
|
||||
|
||||
/** Longest plain-text name kept from a file's features. */
|
||||
const MAX_IMPORT_NAME_LENGTH = 120;
|
||||
|
||||
/** A feature name as short plain text (no control characters), or undefined. */
|
||||
export function importFeatureName(value) {
|
||||
const text = String(value ?? '')
|
||||
.replace(/[\u0000-\u001f\u007f]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!text) return undefined;
|
||||
return text.length > MAX_IMPORT_NAME_LENGTH
|
||||
? `${text.slice(0, MAX_IMPORT_NAME_LENGTH - 1)}…`
|
||||
: text;
|
||||
}
|
||||
|
||||
/** An empty set of records. */
|
||||
export const emptyRecords = () => ({
|
||||
points: [],
|
||||
lines: [],
|
||||
polygons: [],
|
||||
overlays: [],
|
||||
undrawn: {},
|
||||
});
|
||||
|
||||
/** How many map objects the records hold. */
|
||||
export const recordCount = (records) =>
|
||||
records.points.length +
|
||||
records.lines.length +
|
||||
records.polygons.length +
|
||||
records.overlays.length;
|
||||
|
||||
/** `#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(
|
||||
String(css).trim(),
|
||||
);
|
||||
if (!match) throw new TypeError(`Unsupported colour: ${css}`);
|
||||
return [
|
||||
parseInt(match[1], 16) / 255,
|
||||
parseInt(match[2], 16) / 255,
|
||||
parseInt(match[3], 16) / 255,
|
||||
alpha,
|
||||
];
|
||||
}
|
||||
|
||||
// The look Cesium's GeoJsonDataSource gave an import in the row's colour.
|
||||
const GEOJSON_STROKE_PX = 3;
|
||||
const GEOJSON_FILL_ALPHA = 0.25;
|
||||
const GEOJSON_PIN_PX = 48;
|
||||
|
||||
/**
|
||||
* The records of a checked GeoJSON object (src/data/geoFileImport.js has
|
||||
* already cut it to names and ground positions), drawn as Cesium drew it
|
||||
* in the row's colour `color` (`#rrggbb`): points as a 48 px map pin of
|
||||
* that colour standing on the ground, lines as 3 px ground lines, polygons
|
||||
* as a fill at 0.25 (the 3 px outline Cesium leaves out on terrain).
|
||||
* Multipart geometries and geometry collections give one record per part.
|
||||
* @param {object} geojson
|
||||
* @param {string} color
|
||||
* @returns {ImportedRecords}
|
||||
*/
|
||||
export function geoJsonRecords(geojson, color) {
|
||||
const stroke = rgbaOfHex(color);
|
||||
const fill = [...stroke.slice(0, 3), GEOJSON_FILL_ALPHA];
|
||||
const records = emptyRecords();
|
||||
const position = ([lon, lat, height = 0]) => [lon, lat, height];
|
||||
const stack = [[geojson, undefined]];
|
||||
while (stack.length) {
|
||||
const [node, name] = stack.pop();
|
||||
if (!node) continue;
|
||||
if (node.type === 'FeatureCollection') {
|
||||
for (let i = node.features.length - 1; i >= 0; i--)
|
||||
stack.push([node.features[i], undefined]);
|
||||
continue;
|
||||
}
|
||||
if (node.type === 'Feature') {
|
||||
stack.push([node.geometry, node.properties?.name]);
|
||||
continue;
|
||||
}
|
||||
if (node.type === 'GeometryCollection') {
|
||||
for (let i = node.geometries.length - 1; i >= 0; i--)
|
||||
stack.push([node.geometries[i], name]);
|
||||
continue;
|
||||
}
|
||||
const parts = node.type.startsWith('Multi')
|
||||
? node.coordinates
|
||||
: [node.coordinates];
|
||||
const kind = node.type.replace(/^Multi/, '');
|
||||
for (const part of parts) {
|
||||
if (kind === 'Point')
|
||||
records.points.push({
|
||||
name,
|
||||
position: position(part),
|
||||
altitude: 'ground',
|
||||
icon: {
|
||||
image: { pin: stroke, pinSize: GEOJSON_PIN_PX },
|
||||
origin: 'bottom',
|
||||
},
|
||||
});
|
||||
else if (kind === 'LineString')
|
||||
records.lines.push({
|
||||
name,
|
||||
positions: part.map(position),
|
||||
ground: true,
|
||||
color: stroke,
|
||||
widthPx: GEOJSON_STROKE_PX,
|
||||
});
|
||||
else if (kind === 'Polygon' && part[0]?.length)
|
||||
records.polygons.push({
|
||||
name,
|
||||
rings: part.map((ring) => ring.map(position)),
|
||||
raised: false,
|
||||
fill,
|
||||
outline: { color: stroke, widthPx: GEOJSON_STROKE_PX },
|
||||
});
|
||||
}
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every position the records draw, as [lon, lat, height], for framing:
|
||||
* what lies on the ground at height 0, and each overlay's corners.
|
||||
* @param {ImportedRecords} records
|
||||
* @returns {number[][]}
|
||||
*/
|
||||
export function recordFootprint(records) {
|
||||
const out = [];
|
||||
const add = ([lon, lat, height = 0], grounded) => {
|
||||
if (Number.isFinite(lon) && Number.isFinite(lat))
|
||||
out.push([lon, lat, grounded || !Number.isFinite(height) ? 0 : height]);
|
||||
};
|
||||
for (const point of records.points)
|
||||
add(point.position, point.altitude === 'ground');
|
||||
for (const line of records.lines)
|
||||
for (const position of line.positions) add(position, line.ground);
|
||||
for (const polygon of records.polygons)
|
||||
for (const ring of polygon.rings)
|
||||
for (const position of ring) add(position, !polygon.raised);
|
||||
for (const { rectangle: r } of records.overlays) {
|
||||
const east = r.east < r.west ? r.east + 360 : r.east;
|
||||
for (const lon of [r.west, east])
|
||||
for (const lat of [r.south, r.north])
|
||||
add([lon > 180 ? lon - 360 : lon, lat, 0], true);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
import {
|
||||
worldToWindowCoordinates,
|
||||
horizonOccluder,
|
||||
} from './render/cesiumProjection.js';
|
||||
} from '../globe/cesium/sceneProjection.js';
|
||||
import * as geo from '../geo/index.js';
|
||||
|
||||
// A window position through the engine projector the scene carries (the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Sky background
|
||||
|
||||
Catalogue stars over a soft Milky Way, drawn by `src/sky/starrySky.js` in
|
||||
Catalogue stars over a soft Milky Way, drawn by `src/globe/cesium/starrySky.js` in
|
||||
place of Cesium's blocky Tycho-2 sky box.
|
||||
|
||||
| File | Content | Size |
|
||||
|
||||
+60
-120
@@ -1,5 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { NO_IMAGERY_HOST, resolveImageryHost } from '../maps/imageryHost.js';
|
||||
import { NO_IMAGERY_HOST } from '../maps/imageryHost.js';
|
||||
|
||||
/**
|
||||
* @file Open-data raster overlays: OpenSeaMap sea marks and OpenSnowMap ski
|
||||
@@ -16,10 +15,13 @@ import { NO_IMAGERY_HOST, resolveImageryHost } from '../maps/imageryHost.js';
|
||||
* - OpenInfraMap serves MapLibre vector tiles, not raster XYZ tiles. That
|
||||
* needs a vector-tile rendering pipeline, not an imagery-layer drop-in.
|
||||
*
|
||||
* The overlays drape on whatever surface the active map stack offers (see
|
||||
* `maps/imageryHost.js`): the globe on the OSM and Bing stacks, the Google
|
||||
* Photorealistic tileset's own `imageryLayers` on Google 3D. Only a stack with
|
||||
* neither leaves them hidden, and the row says so.
|
||||
* The overlays drape through the globe engine on whatever surface the
|
||||
* active map stack offers: `engine.imagery` (on Cesium the globe on the OSM
|
||||
* and Bing stacks, the Google Photorealistic tileset's own imagery on Google
|
||||
* 3D; the engine follows stack switches), or Navara's own raster overlay
|
||||
* (`engine.maps.addOverlay`, per-tile levels on its terrain) where the
|
||||
* engine has one. Only a surface with neither leaves them hidden, and the
|
||||
* row says so.
|
||||
* @module data/osmOverlays
|
||||
*/
|
||||
|
||||
@@ -54,101 +56,66 @@ export function osmOverlayHiddenReason(enabled, hostKind) {
|
||||
return enabled && hostKind === 'none' ? NO_IMAGERY_HOST : null;
|
||||
}
|
||||
|
||||
// Over the heat rasters, under event imagery and the weather.
|
||||
const OVERLAY_ORDER = 10;
|
||||
const HOST_KIND = Object.freeze({ globe: 'globe', tiles: 'tileset' });
|
||||
|
||||
/**
|
||||
* Create the layer for one overlay descriptor. Each application catalog gets
|
||||
* its own instances; the Cesium factories are injectable so tests run without
|
||||
* WebGL.
|
||||
* its own instances.
|
||||
*/
|
||||
export function createOsmOverlayLayer(
|
||||
overlay,
|
||||
{
|
||||
host = resolveImageryHost,
|
||||
createProvider = (descriptor) =>
|
||||
new Cesium.UrlTemplateImageryProvider({
|
||||
url: descriptor.urlTemplate,
|
||||
credit: descriptor.credit,
|
||||
maximumLevel: descriptor.maximumLevel,
|
||||
}),
|
||||
createImageryLayer = (provider) => new Cesium.ImageryLayer(provider),
|
||||
} = {},
|
||||
) {
|
||||
export function createOsmOverlayLayer(overlay) {
|
||||
if (!OSM_OVERLAYS.includes(overlay))
|
||||
throw new TypeError(`Unknown open map overlay: ${overlay?.id}`);
|
||||
let viewer = null;
|
||||
// A globe engine without a Cesium viewer (Navara) takes the overlay
|
||||
// through engine.maps.addOverlay; its removal while shown.
|
||||
let engine = null;
|
||||
let removeEngineOverlay = null;
|
||||
let mapStack = null;
|
||||
let unsubscribeMap = null;
|
||||
let enabled = false;
|
||||
let hostInfo = { collection: null, kind: 'none' };
|
||||
/** The imagery layer this instance owns while enabled, and where it sits. */
|
||||
/** The drape this instance owns while enabled: an imagery layer or a removal. */
|
||||
let owned = null;
|
||||
|
||||
const usable = (collection) => collection && !collection.isDestroyed?.();
|
||||
/** Where the drape lies now: 'globe', 'tileset' or 'none'. */
|
||||
function hostKind() {
|
||||
if (!owned) return 'none';
|
||||
if (owned.remove) return 'globe';
|
||||
return HOST_KIND[engine?.imagery?.surface?.()] ?? 'none';
|
||||
}
|
||||
|
||||
function detach(destroy) {
|
||||
function release() {
|
||||
if (!owned) return;
|
||||
const { collection, layer } = owned;
|
||||
if (usable(collection) && collection.contains(layer))
|
||||
collection.remove(layer, destroy);
|
||||
else if (destroy && !layer.isDestroyed?.()) layer.destroy?.();
|
||||
owned.collection = null;
|
||||
if (destroy) owned = null;
|
||||
const { layer, remove } = owned;
|
||||
owned = null;
|
||||
if (remove) remove();
|
||||
else layer.destroy();
|
||||
}
|
||||
|
||||
function resolveHost() {
|
||||
return (
|
||||
host({ viewer, tileset: mapStack?.getImageryHostTileset?.() }) || {
|
||||
collection: null,
|
||||
kind: 'none',
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/** Create, move or drop the owned imagery layer to match the state. */
|
||||
/** Create or drop the owned drape to match the state. */
|
||||
function sync() {
|
||||
if (!viewer) {
|
||||
syncEngine();
|
||||
if (!engine || !enabled) {
|
||||
release();
|
||||
return;
|
||||
}
|
||||
hostInfo = enabled ? resolveHost() : { collection: null, kind: 'none' };
|
||||
if (!enabled) {
|
||||
detach(true);
|
||||
} else {
|
||||
owned ||= {
|
||||
layer: createImageryLayer(createProvider(overlay)),
|
||||
collection: null,
|
||||
};
|
||||
if (owned.collection !== hostInfo.collection) {
|
||||
detach(false);
|
||||
if (usable(hostInfo.collection)) {
|
||||
// Appended, so it draws above the map stack's base imagery.
|
||||
hostInfo.collection.add(owned.layer);
|
||||
owned.collection = hostInfo.collection;
|
||||
}
|
||||
}
|
||||
if (owned) return;
|
||||
const remove = engine.maps?.addOverlay?.({
|
||||
url: overlay.urlTemplate,
|
||||
maxZoom: overlay.maximumLevel,
|
||||
credit: overlay.credit,
|
||||
});
|
||||
if (typeof remove === 'function') {
|
||||
owned = { remove };
|
||||
return;
|
||||
}
|
||||
viewer.scene?.requestRender?.();
|
||||
}
|
||||
|
||||
function syncEngine() {
|
||||
if (!engine) return;
|
||||
if (enabled && !removeEngineOverlay)
|
||||
removeEngineOverlay =
|
||||
engine.maps?.addOverlay?.({
|
||||
if (!engine.imagery) return;
|
||||
owned = {
|
||||
layer: engine.imagery.createLayer({
|
||||
id: `osm-overlay-${overlay.id}`,
|
||||
source: {
|
||||
kind: 'tiles',
|
||||
url: overlay.urlTemplate,
|
||||
maxZoom: overlay.maximumLevel,
|
||||
maxLevel: overlay.maximumLevel,
|
||||
credit: overlay.credit,
|
||||
}) ?? null;
|
||||
else if (!enabled && removeEngineOverlay) {
|
||||
removeEngineOverlay();
|
||||
removeEngineOverlay = null;
|
||||
}
|
||||
hostInfo = removeEngineOverlay
|
||||
? { collection: null, kind: 'globe' }
|
||||
: { collection: null, kind: 'none' };
|
||||
},
|
||||
order: OVERLAY_ORDER,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -157,33 +124,19 @@ export function createOsmOverlayLayer(
|
||||
icon: overlay.icon,
|
||||
source: overlay.source,
|
||||
updateInterval: 0,
|
||||
init(nextViewer, { engine: nextEngine = null } = {}) {
|
||||
this.attachRenderer(nextViewer, { engine: nextEngine });
|
||||
init(viewer, options) {
|
||||
this.attachRenderer(viewer, options);
|
||||
},
|
||||
/** Drape on a globe: the Cesium viewer's imagery, or the engine's. */
|
||||
attachRenderer(nextViewer, { engine: nextEngine = null } = {}) {
|
||||
viewer = nextViewer ?? null;
|
||||
engine = viewer ? null : nextEngine;
|
||||
/** Drape on a globe engine's imagery. */
|
||||
attachRenderer(_viewer, { engine: nextEngine = null } = {}) {
|
||||
release();
|
||||
engine = nextEngine;
|
||||
sync();
|
||||
},
|
||||
/** Leave the globe; the enabled state stays for the next one. */
|
||||
detachRenderer() {
|
||||
detach(true);
|
||||
removeEngineOverlay?.();
|
||||
removeEngineOverlay = null;
|
||||
viewer = null;
|
||||
release();
|
||||
engine = null;
|
||||
hostInfo = { collection: null, kind: 'none' };
|
||||
},
|
||||
/** Follow map-stack switches so the drape moves with the surface. */
|
||||
attachMapStackController(controller) {
|
||||
unsubscribeMap?.();
|
||||
unsubscribeMap = null;
|
||||
mapStack = controller || null;
|
||||
const off = controller?.subscribe?.(() => {
|
||||
if (enabled) sync();
|
||||
});
|
||||
unsubscribeMap = typeof off === 'function' ? off : null;
|
||||
},
|
||||
enable() {
|
||||
enabled = true;
|
||||
@@ -197,32 +150,19 @@ export function createOsmOverlayLayer(
|
||||
return true;
|
||||
},
|
||||
getStats() {
|
||||
// Without a controller subscription the stats poll doubles as the
|
||||
// map-stack watch.
|
||||
if (enabled && viewer && !unsubscribeMap) {
|
||||
const next = resolveHost();
|
||||
if (next.collection !== hostInfo.collection) sync();
|
||||
}
|
||||
return {
|
||||
count: enabled ? 1 : 0,
|
||||
error: osmOverlayHiddenReason(enabled, hostInfo.kind),
|
||||
error: osmOverlayHiddenReason(enabled, hostKind()),
|
||||
};
|
||||
},
|
||||
/** Owned layer count and host kind, for tests and live gates. */
|
||||
/** Owned drape count and host kind, for tests and live gates. */
|
||||
diagnostics() {
|
||||
return { host: hostInfo.kind, ownedCount: owned ? 1 : 0 };
|
||||
return { host: hostKind(), ownedCount: owned ? 1 : 0 };
|
||||
},
|
||||
destroy() {
|
||||
enabled = false;
|
||||
detach(true);
|
||||
removeEngineOverlay?.();
|
||||
removeEngineOverlay = null;
|
||||
release();
|
||||
engine = null;
|
||||
unsubscribeMap?.();
|
||||
unsubscribeMap = null;
|
||||
mapStack = null;
|
||||
viewer = null;
|
||||
hostInfo = { collection: null, kind: 'none' };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,67 +7,25 @@ import {
|
||||
osmOverlayHiddenReason,
|
||||
} from './osmOverlays.js';
|
||||
import { NO_IMAGERY_HOST } from '../maps/imageryHost.js';
|
||||
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
|
||||
|
||||
function fakeCollection() {
|
||||
const layers = [];
|
||||
const removed = [];
|
||||
return {
|
||||
layers,
|
||||
removed,
|
||||
add(layer) {
|
||||
layers.push(layer);
|
||||
},
|
||||
contains(layer) {
|
||||
return layers.includes(layer);
|
||||
},
|
||||
remove(layer, destroy) {
|
||||
const index = layers.indexOf(layer);
|
||||
if (index < 0) return false;
|
||||
layers.splice(index, 1);
|
||||
removed.push({ layer, destroy });
|
||||
if (destroy) layer.destroyed = true;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fakeMapStack() {
|
||||
const subscribers = new Set();
|
||||
return {
|
||||
tileset: null,
|
||||
getImageryHostTileset() {
|
||||
return this.tileset;
|
||||
},
|
||||
subscribe(fn) {
|
||||
subscribers.add(fn);
|
||||
return () => subscribers.delete(fn);
|
||||
},
|
||||
emit() {
|
||||
for (const fn of subscribers) fn();
|
||||
},
|
||||
subscribers,
|
||||
};
|
||||
}
|
||||
|
||||
/** A layer on the fake engine, whose imagery drapes where `surface()` says. */
|
||||
function setup(overlay = OSM_OVERLAYS[0]) {
|
||||
const globe = fakeCollection();
|
||||
const viewer = {
|
||||
imageryLayers: globe,
|
||||
scene: { globe: { show: true }, requestRender() {} },
|
||||
let surface = 'globe';
|
||||
const fake = createFakeEngine({ kind: 'cesium' });
|
||||
const engine = {
|
||||
...fake,
|
||||
imagery: { ...fake.imagery, surface: () => surface },
|
||||
};
|
||||
const layer = createOsmOverlayLayer(overlay);
|
||||
layer.init(null, { engine });
|
||||
return {
|
||||
layer,
|
||||
engine,
|
||||
layers: () =>
|
||||
engine.imagery.list().filter(({ id }) => id.startsWith('osm-overlay-')),
|
||||
setSurface: (next) => (surface = next),
|
||||
};
|
||||
const created = [];
|
||||
const layer = createOsmOverlayLayer(overlay, {
|
||||
createProvider: (descriptor) => ({ descriptor }),
|
||||
createImageryLayer: (provider) => {
|
||||
const imagery = { provider, destroyed: false };
|
||||
created.push(imagery);
|
||||
return imagery;
|
||||
},
|
||||
});
|
||||
const mapStack = fakeMapStack();
|
||||
layer.init(viewer);
|
||||
layer.attachMapStackController(mapStack);
|
||||
return { layer, viewer, globe, created, mapStack };
|
||||
}
|
||||
|
||||
test('OSM_OVERLAYS: the two shipped layers, each with a tile template and credit', () => {
|
||||
@@ -104,66 +62,60 @@ test('osmOverlayHiddenReason: only when enabled with no imagery host', () => {
|
||||
});
|
||||
|
||||
test('a layer owns no imagery until enabled and destroys it on disable', () => {
|
||||
const { layer, globe, created } = setup(OSM_OVERLAYS[1]);
|
||||
assert.equal(created.length, 0);
|
||||
const { layer, engine, layers } = setup(OSM_OVERLAYS[1]);
|
||||
assert.equal(layers().length, 0);
|
||||
|
||||
layer.enable();
|
||||
assert.equal(globe.layers.length, 1);
|
||||
assert.equal(globe.layers[0].provider.descriptor.id, 'ski-pistes');
|
||||
assert.equal(layers().length, 1);
|
||||
const [{ id }] = layers();
|
||||
assert.equal(id, 'osm-overlay-ski-pistes');
|
||||
const { source, options } = engine.fake.imageryLayer(id);
|
||||
assert.equal(source.url, OSM_OVERLAYS[1].urlTemplate);
|
||||
assert.equal(source.maxLevel, 18);
|
||||
assert.equal(source.credit, OSM_OVERLAYS[1].credit);
|
||||
assert.equal(options.order, 10);
|
||||
assert.deepEqual(layer.getStats(), { count: 1, error: null });
|
||||
|
||||
layer.disable();
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(created[0].destroyed, true);
|
||||
assert.equal(layers().length, 0);
|
||||
assert.deepEqual(layer.diagnostics(), { host: 'none', ownedCount: 0 });
|
||||
assert.deepEqual(layer.getStats(), { count: 0, error: null });
|
||||
|
||||
layer.enable();
|
||||
assert.equal(created.length, 2, 're-enabling creates a fresh imagery layer');
|
||||
assert.equal(layers().length, 1, 're-enabling creates a fresh layer');
|
||||
});
|
||||
|
||||
test('the overlay follows a map-stack switch onto the Google 3D tileset and back', () => {
|
||||
const { layer, viewer, globe, mapStack } = setup();
|
||||
test('the overlay reports the surface the engine drapes it on', () => {
|
||||
const { layer, setSurface } = setup();
|
||||
layer.enable();
|
||||
const [imagery] = globe.layers;
|
||||
|
||||
const tileset = { imageryLayers: fakeCollection() };
|
||||
viewer.scene.globe.show = false;
|
||||
mapStack.tileset = tileset;
|
||||
mapStack.emit();
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.deepEqual(tileset.imageryLayers.layers, [imagery]);
|
||||
assert.equal(globe.removed[0].destroy, false);
|
||||
assert.equal(layer.diagnostics().host, 'globe');
|
||||
setSurface('tiles');
|
||||
assert.equal(layer.diagnostics().host, 'tileset');
|
||||
assert.equal(layer.getStats().error, null);
|
||||
|
||||
viewer.scene.globe.show = true;
|
||||
mapStack.tileset = null;
|
||||
mapStack.emit();
|
||||
assert.deepEqual(globe.layers, [imagery]);
|
||||
assert.equal(tileset.imageryLayers.layers.length, 0);
|
||||
});
|
||||
|
||||
test('with no surface to drape on the row explains itself, and recovers when one appears', () => {
|
||||
const { layer, viewer, globe, mapStack } = setup();
|
||||
viewer.scene.globe.show = false;
|
||||
const { layer, setSurface } = setup();
|
||||
setSurface('none');
|
||||
layer.enable();
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(layer.getStats().error, NO_IMAGERY_HOST);
|
||||
|
||||
viewer.scene.globe.show = true;
|
||||
mapStack.emit();
|
||||
assert.equal(globe.layers.length, 1);
|
||||
setSurface('globe');
|
||||
assert.equal(layer.getStats().error, null);
|
||||
});
|
||||
|
||||
test('destroy removes owned imagery and unsubscribes from the map stack', () => {
|
||||
const { layer, globe, created, mapStack } = setup();
|
||||
test('destroy and a renderer detach remove the owned imagery', () => {
|
||||
const { layer, layers, engine } = setup();
|
||||
layer.enable();
|
||||
layer.detachRenderer();
|
||||
assert.equal(layers().length, 0);
|
||||
layer.attachRenderer(null, { engine });
|
||||
assert.equal(
|
||||
layers().length,
|
||||
1,
|
||||
'the enabled state stays for the next globe',
|
||||
);
|
||||
layer.destroy();
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(created[0].destroyed, true);
|
||||
assert.equal(mapStack.subscribers.size, 0);
|
||||
assert.equal(layers().length, 0);
|
||||
});
|
||||
|
||||
test('on Navara an overlay drapes through engine.maps and follows the globe', () => {
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
// Native constants shared by the W1 adapters; keep the SDK import here.
|
||||
// Read on call: the production build's Cesium global loads with the first
|
||||
// Cesium globe, after this module has loaded on a Navara start.
|
||||
import { ScreenSpaceEventType } from 'cesium';
|
||||
|
||||
export const trackingEventTypes = () => ScreenSpaceEventType;
|
||||
@@ -1,17 +0,0 @@
|
||||
import * as Cesium from 'cesium';
|
||||
export function worldToWindowCoordinates(scene, position, result) {
|
||||
return Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
result,
|
||||
);
|
||||
}
|
||||
let occluder;
|
||||
export function horizonOccluder(camera) {
|
||||
occluder ??= new Cesium.EllipsoidalOccluder(
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
occluder.cameraPosition = camera.positionWC;
|
||||
return occluder;
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
/**
|
||||
* @module trailRenderer
|
||||
* @description Shared track-history renderer (PRD WS-F F4; rebuilt round 6,
|
||||
* 2026-07-06).
|
||||
*
|
||||
* One trail = one ENTITY polyline. Round 6 replaced the faded per-vertex
|
||||
* Primitive for two owner directives from the field:
|
||||
* - "the line must ALWAYS be visible": the Primitive's depthFailAppearance
|
||||
* did not reliably render segments below the photoreal mesh — entity
|
||||
* polylines with `depthFailMaterial` DO (in-repo proof: CCTV's frustum
|
||||
* wireframes read through geometry with exactly this), so occluded
|
||||
* segments now draw dimmed instead of vanishing.
|
||||
* - "show actual tracks, don't style them too much": the tail-fade is gone;
|
||||
* the whole history renders at one readable alpha (dimmer where it passes
|
||||
* behind/below geometry).
|
||||
*
|
||||
* Trails update at poll cadence (~15-60 s) plus once on history backfill, so
|
||||
* assigning a fresh positions array per update is cheap. `allowPicking` has
|
||||
* no entity equivalent; the polyline entity is excluded from clicks by never
|
||||
* carrying a pick id the layers' click handlers resolve.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { registerPickOwner } from '../pickRegistry.js';
|
||||
|
||||
// Round 6: trail ENTITIES are pickable (the old Primitive had
|
||||
// allowPicking:false). A trail hugs its aircraft, so an unclaimed pick would
|
||||
// read as "empty space" in every layer's click handler and deselect the very
|
||||
// plane being tracked. Claiming the 'gev-trail:' id namespace makes
|
||||
// isOwnedByOtherLayer() true for every layer — clicking a trail is a no-op
|
||||
// everywhere. Registered once at module load; the predicate is pure.
|
||||
registerPickOwner('trails', (pickedId) =>
|
||||
String(pickedId).startsWith('gev-trail:'),
|
||||
);
|
||||
|
||||
/** @type {number} Uniquifier for trail entity ids (Cesium requires unique entity ids). */
|
||||
let _trailSeq = 0;
|
||||
|
||||
/** @constant {number} Alpha where the trail passes the depth test. */
|
||||
const TRAIL_ALPHA = 0.85;
|
||||
/** @constant {number} Alpha where the trail is behind/below scene geometry —
|
||||
* visible (owner: never vanish) but readable as occluded. */
|
||||
const TRAIL_OCCLUDED_ALPHA = 0.4;
|
||||
/** @constant {number} Squared distance (m^2) below which consecutive points are merged. */
|
||||
const MIN_SEGMENT_DISTANCE_SQ = 0.01;
|
||||
|
||||
/**
|
||||
* Create an always-visible polyline trail bound to a viewer.
|
||||
* @param {Cesium.Viewer} viewer - Viewer whose entity collection owns the trail.
|
||||
* @param {object} options - Trail options.
|
||||
* @param {string} options.color - CSS color string for the trail hue.
|
||||
* @param {number} [options.width=2.5] - Polyline width in pixels.
|
||||
* @returns {{setPositions: function(Cesium.Cartesian3[]): void, setVisible: function(boolean): void, clear: function(): void, destroy: function(): void}}
|
||||
* Trail handle: setPositions replaces the geometry, setVisible temporarily
|
||||
* hides it without discarding history, clear empties it, and destroy removes
|
||||
* the entity permanently.
|
||||
*/
|
||||
export function createTrail(viewer, { color, width = 2.5 }) {
|
||||
const baseColor = Cesium.Color.fromCssColorString(color);
|
||||
/** @type {Cesium.Cartesian3[]} Current deduped positions (owned copy). */
|
||||
let current = [];
|
||||
let destroyed = false;
|
||||
let visible = true;
|
||||
/** @type {Cesium.Entity|null} */
|
||||
let entity = null;
|
||||
|
||||
function ensureEntity() {
|
||||
if (entity || destroyed || !viewer || viewer.isDestroyed()) return;
|
||||
entity = viewer.entities.add({
|
||||
id: `gev-trail:${++_trailSeq}`,
|
||||
show: visible,
|
||||
polyline: {
|
||||
// CallbackProperty so a positions swap never rebuilds the entity —
|
||||
// Cesium re-reads on change; `false` marks it non-constant.
|
||||
positions: new Cesium.CallbackProperty(() => current, false),
|
||||
width,
|
||||
material: baseColor.withAlpha(TRAIL_ALPHA),
|
||||
// The owner-locked rule (round 6): a segment below the photoreal
|
||||
// mesh renders dimmed — it must never disappear into the ground.
|
||||
depthFailMaterial: baseColor.withAlpha(TRAIL_OCCLUDED_ALPHA),
|
||||
// Round 8 (owner: UAL1104's Pacific trail "cutting through the
|
||||
// globe"): NONE draws straight 3D chords between waypoints — over a
|
||||
// sparse trans-oceanic trace a single segment spans hundreds of km
|
||||
// and tunnels through the planet. GEODESIC subdivides each segment
|
||||
// along the curved surface (heights interpolated), so long legs hug
|
||||
// the globe instead of chording through it.
|
||||
arcType: Cesium.ArcType.GEODESIC,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
/**
|
||||
* Replace the trail geometry with a chronological position list
|
||||
* (oldest first). Fewer than 2 distinct positions clears the trail.
|
||||
* @param {Cesium.Cartesian3[]} cartesians - Positions, oldest -> newest.
|
||||
*/
|
||||
setPositions(cartesians) {
|
||||
if (destroyed || !viewer || viewer.isDestroyed()) return;
|
||||
// Drop consecutive near-duplicates: zero-length segments add nothing.
|
||||
const positions = [];
|
||||
for (const position of Array.isArray(cartesians) ? cartesians : []) {
|
||||
if (!position) continue;
|
||||
const last = positions[positions.length - 1];
|
||||
if (
|
||||
last &&
|
||||
Cesium.Cartesian3.distanceSquared(last, position) <
|
||||
MIN_SEGMENT_DISTANCE_SQ
|
||||
)
|
||||
continue;
|
||||
positions.push(position);
|
||||
}
|
||||
current = positions.length >= 2 ? positions : [];
|
||||
ensureEntity();
|
||||
},
|
||||
|
||||
/** Temporarily hide/show the trail without discarding accumulated history. */
|
||||
setVisible(nextVisible) {
|
||||
visible = nextVisible !== false;
|
||||
if (entity) entity.show = visible;
|
||||
},
|
||||
|
||||
/** Empty the trail without removing the entity (cheap re-arm). */
|
||||
clear() {
|
||||
current = [];
|
||||
},
|
||||
|
||||
/** Remove the trail entity permanently (layer disable/teardown). */
|
||||
destroy() {
|
||||
destroyed = true;
|
||||
current = [];
|
||||
if (entity && viewer && !viewer.isDestroyed()) {
|
||||
try {
|
||||
viewer.entities.remove(entity);
|
||||
} catch {
|
||||
/* torn down */
|
||||
}
|
||||
}
|
||||
entity = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { trackingEventTypes } from './render/cesiumConstants.js';
|
||||
import { trackingEventTypes } from '../globe/cesium/screenEvents.js';
|
||||
import { isPointerFree } from './inputOwnership.js';
|
||||
|
||||
export const MAX_TRACKING_CLICK_TRAVEL_PX = 6;
|
||||
|
||||
@@ -1 +1 @@
|
||||
export { createTrail } from './render/cesiumTrailRenderer.js';
|
||||
export { createTrail } from '../globe/cesium/trail.js';
|
||||
Reference in new issue
Block a user