mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Merge branch 'sameh/renderer-last' into sameh/renderer-seam
This commit is contained in:
commit
8f12205324
70 files changed
+2879
-1739
No files matched your search
+16
-13
@@ -3395,10 +3395,13 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
|
||||
> untracking, so a stationary slow press on a plane still selects it. Escape
|
||||
> still releases tracking in place. The 200 px feel needs close-range field
|
||||
> verification; fleet model sizing remains unchanged.
|
||||
> - **Deterministic sprite stacking:** contact collections reassert the stable
|
||||
> bottom-to-top order CCTV, FIRMS, bikeshare, AIS, military, then civilian
|
||||
> flights after every relevant layer init/enable and immediately after FIRMS
|
||||
> lazily registers its detection sprites. Always-visible contact
|
||||
> - **Deterministic sprite stacking:** contact sets are made at draw orders
|
||||
> (`SetSpec.drawOrder`, from `spriteDrawOrder`) that stack them bottom to
|
||||
> top as CCTV, FIRMS, bikeshare, transit, directions, AIS, military, then
|
||||
> civilian flights on top, whichever layer was turned on first; picks
|
||||
> name the topmost first. The orders are negative, so every overlay at the
|
||||
> default order (selection highlights, route endpoints, the tracked plane)
|
||||
> still draws over all of them. Always-visible contact
|
||||
> depth settings are unchanged. Cesium OIT weighted blending may soften strict
|
||||
> alpha layering on some GPUs, so the ordering remains a real-browser check.
|
||||
> - **Deterministic card stacking:** CCTV, FIRMS, vessel, and tracked-target
|
||||
@@ -4666,8 +4669,8 @@ Playback reserves numeric scratch before the first sample, including unknown
|
||||
heights, and reuses caller-owned sample and segment storage.
|
||||
|
||||
**Scene work.** Stationary and animated vehicles are two draw-port icon sets
|
||||
(`transit:<n>:still` and `transit:<n>:moving`), registered by set id with the
|
||||
sprite order in their old adjacent places above CCTV and Bikeshare. Each marker
|
||||
(`transit:<n>:still` and `transit:<n>:moving`), made at adjacent draw orders
|
||||
from the sprite order (`spriteDrawOrder`), above CCTV and Bikeshare. Each marker
|
||||
is a plain record (position, show, image, size, colour, rotation); a frame
|
||||
writes the changed ones to their set in one batched upsert, markers taken out
|
||||
in one task go in one removal, and a marker that starts or stops moving moves
|
||||
@@ -5779,15 +5782,15 @@ request viewbox and continues searching without that geographic preference.
|
||||
### Import Your Own Files (October 2026)
|
||||
|
||||
- UTILITIES ▸ **Import** reads GeoJSON (`.geojson`/`.json`), KML, KMZ and GPX from the picker or a file drop anywhere in the app. Each file gets show/hide, Fly-to and Remove controls. GeoJSON and GPX use the row's color; KML/KMZ retain their styles and show a hatched swatch. The file bytes remain on the device for the page session. Rendered overlays can appear in map screenshots sent through voice or other existing screenshot tools.
|
||||
- **Ground and height.** GeoJSON XYZ coordinates become ground footprints. KML ground lines/rings are tessellated; static recorded tracks preserve their original vertices, segment gaps and explicit altitude modes. KML with absolute/relative altitude keeps that meaning. Ground pins resolve in batches of 256 against loaded terrain and, in the nearby camera footprint on photoreal maps, `clampToHeightMostDetailed`, then draw in one owned native BillboardCollection per file, with static positions and no per-frame point Entity visualizer or clamping callbacks. Point metadata remains in `dataSource.importedEntities` for framing/style inspection; non-point geometry stays in the normal source collection. Pin collections mount only after source admission, follow file show/hide, and are destroyed on removal. Settled camera/map-source changes and completed terrain loads refresh visible files through the same serial queue; distant points retain their latest available height. No detailed worldwide terrain sweep is started. Nearby mesh sampling can add requests/time; configured photoreal providers require separate validation. The depth test is disabled for ground pins, matching Draw's marker visibility policy.
|
||||
- **Ground and height.** GeoJSON XYZ coordinates become ground footprints. KML ground lines/rings are tessellated; static recorded tracks preserve their original vertices, segment gaps and explicit altitude modes. KML with absolute/relative altitude keeps that meaning. Ground pins resolve in batches of 256 through the height service: the loaded terrain's height (0 on the bare ellipsoid, whose coarse tiles can sag far below it) and, in the nearby camera footprint on photoreal maps, the mesh height (`clampBatch`). They then draw as static icons in the file's own draw sets (pins, lines and shapes), with no per-frame clamping callbacks. GeoJSON lines and polygon edges follow rhumb lines, split into steps of at most half a degree. Each file's sets mount only after admission, follow its show/hide, and are removed with it. Settled camera/map-source changes and completed terrain loads refresh visible files through the same serial queue; distant points retain their latest available height. No detailed worldwide terrain sweep is started. Nearby mesh sampling can add requests/time; configured photoreal providers require separate validation. The depth test is disabled for ground pins, matching Draw's marker visibility policy.
|
||||
- **Navigation.** Row Fly-to uses `runImmediateNavigation('file', …)`; Cockpit can refuse it and existing follow/track ownership is released first. Automatic Fly-to is stamped when a batch is submitted and reasserted before flying. Pointer/wheel gestures and newer navigation supersede it, including time spent in the queue. Framing uses every finite visible point/path/polygon-hole/wall vertex plus rotated overlay bounds, with viewport-aware range and a nadir view. The target uses available terrain/cached ground height and the ground guard on arrival. Empty footprints never fall back to deferred `viewer.flyTo`.
|
||||
- **Clock.** Imports expose no source clock and no entity availability. KML times/view metadata are removed before loading; recorded tracks become static lines. GPX segments remain separate and GPX times are ignored. The shared clock stays unchanged.
|
||||
- **Input handling.** Coordinates and GeoJSON geometry types are checked before Cesium allocation. Only short plain names reach GeoJSON property bags; file IDs, custom CRS and styling properties are removed. KML feature/geometry IDs are removed while Style/StyleMap references remain. Local style references are trimmed, incomplete style pairs removed, hidden-folder flags normalized to the import's show control, and unsupported prototype-named elements removed. UTF-16 BOMs and common KML namespace export defects are handled. Empty drawable content is refused. A loader failure or timeout does not hold the next file indefinitely; teardown aborts pending waits.
|
||||
- **References and images.** File-authored remote links/icons/styles, network links, models and screen/photo overlays are removed. Packed KMZ and embedded PNG/JPEG/GIF/WebP/BMP images remain local; decoded dimensions are checked before image decoding against a total 16-megapixel and 8,192-pixel-side budget per file. Blocked IconStyle images fall back to local pins; authored empty icons remain empty. Colored overlays without an Icon survive; overlays with a removed external image are dropped. Metadata, native labels and descriptions are removed, and generated pins share one lossless image URL per canvas.
|
||||
- **Clock.** Imports keep no clock and no time ranges: everything in a file draws at all times. KML times/view metadata are removed before loading; recorded tracks become static lines. GPX segments remain separate and GPX times are ignored. The shared clock stays unchanged.
|
||||
- **Input handling.** Coordinates and GeoJSON geometry types are checked before anything is drawn. Only short plain names reach GeoJSON property bags; file IDs, custom CRS and styling properties are removed. KML feature/geometry IDs are removed while Style/StyleMap references remain. Local style references are trimmed, incomplete style pairs removed, hidden-folder flags normalized to the import's show control, and unsupported prototype-named elements removed. UTF-16 BOMs and common KML namespace export defects are handled. Empty drawable content is refused. A loader failure or timeout does not hold the next file indefinitely; teardown aborts pending waits.
|
||||
- **References and images.** File-authored remote links/icons/styles, network links, models and screen/photo overlays are removed. Packed KMZ and embedded PNG/JPEG/GIF/WebP/BMP images remain local; decoded dimensions are checked before image decoding against a total 16-megapixel and 8,192-pixel-side budget per file. Blocked IconStyle images fall back to local pins; authored empty icons remain empty. Colored overlays without an Icon survive; overlays with a removed external image are dropped. Metadata, labels and descriptions are removed; only a short plain name reaches a drawn item. The default pins are shared SVG images.
|
||||
- **Bounds.** File size ≤50 MiB; inflated KMZ ≤120 MiB; ≤20,000 entities (including multipart children and Folder containers); ≤250,000 positions; ≤2,000 normalized style definitions and distinct image links; ≤12 files per session. Exact repeated styles share definitions without changing inheritance or inline overrides. Files of 20–30 MB fit the byte budget, subject to geometry/image limits. Refusals name a reason and batches continue; with multiple failures the hint shows the first reason.
|
||||
- **Code layout.** `src/data/geoFileImport.js` reads, bounds and sanitizes the files and no longer imports or drives Cesium itself; it hands the parsed file to the Cesium-bound part. The Cesium-bound part (loading the parsed file as a Cesium data source, scrubbing and grounding its entities, its pin collection and its footprint for Fly-to) is `src/data/geoImportPins.js`, which stays on the Cesium allow-list; `src/data/geoImportShared.js` holds the error, limits, deadline and feature names both use.
|
||||
- **Lifecycle and keyboard.** `createApplicationTools` wires `initGeoFileImport` with viewer, navigation, ground services and map-source subscription. Destroy aborts pending work, unsubscribes, removes data sources, revokes blob URLs, removes document/canvas listeners and releases `window.__gevGeoImport`. List rebuilds retain keyboard focus; removing a row hands focus to the next row, else the previous row, else Import.
|
||||
- **Validation.** `node scripts/qa-geo-import.mjs` covers all four formats and real painted show/hide. Run `node scripts/qa-geo-import-regressions.mjs` against both dev and preview for XYZ/track heights, failure recovery, namespace/BOM support, portrait framing and panel drops. `node scripts/qa-geo-import-large.mjs [--file /absolute/path/sample.kml] [--expect-local-pins]` checks a 27.6 MB repeated-style file, native style/image equivalence, large-file painted output and frame times. It records the WebGL renderer; software-rendered runs do not establish GPU performance. Unit tests live beside the data/controller/framing modules.
|
||||
- **Code layout.** `src/data/geoFileImport.js` reads, bounds and sanitizes the files. `src/data/geoImportFeatures.js` turns the sanitized KML or GeoJSON into plain features (pins, lines, walls, polygons and ground overlays) with the styles Cesium's KML and GeoJSON loaders gave them: icon, scale, colour, heading and hot spot; line and polygon colours and widths; extruded or clamped geometry. `src/data/geoImportPins.js` draws those features through the renderer's draw port (`drawOf`), settles ground pins through the height service, follows a double-clicked pin and frames the file for Fly-to. None of the three reaches Cesium, so the Cesium allow-list is empty. `src/data/geoImportShared.js` holds the error, limits, deadline and feature names they use.
|
||||
- **Lifecycle and keyboard.** `createApplicationTools` wires `initGeoFileImport` with viewer, navigation, ground services and map-source subscription. Destroy aborts pending work, unsubscribes, removes each file's draw sets, revokes blob URLs, removes document/canvas listeners and releases `window.__gevGeoImport`. List rebuilds retain keyboard focus; removing a row hands focus to the next row, else the previous row, else Import.
|
||||
- **Validation.** `node scripts/qa-geo-import.mjs` covers all four formats and real painted show/hide. Run `node scripts/qa-geo-import-regressions.mjs` against both dev and preview for XYZ/track heights, failure recovery, namespace/BOM support, portrait framing and panel drops. `node scripts/qa-geo-import-large.mjs [--file /absolute/path/sample.kml] [--expect-local-pins]` checks a 27.6 MB repeated-style file, that what the import draws matches Cesium's own `KmlDataSource` reading of the same file (positions, scale, heading, colours, widths, fills), large-file painted output and frame times. The QA scripts read what a file drew through `window.__gevGeoImport.drawn(id)`. It records the WebGL renderer; software-rendered runs do not establish GPU performance. Unit tests live beside the data/controller/framing modules.
|
||||
|
||||
### Recent Imagery (September 2026)
|
||||
|
||||
|
||||
@@ -153,7 +153,8 @@ back to Cesium. Both lists only ever shrink.
|
||||
- `src/render/cesiumAllowList.json` lists the files outside the Cesium
|
||||
adapter (`src/render/cesium/`) that may still import or be handed Cesium
|
||||
(`src/render/noCesiumOutsideRender.test.mjs`). A file leaves the list
|
||||
when it no longer drives Cesium at all; nothing is added. Two files name
|
||||
when it no longer drives Cesium at all; nothing is added. The list is now
|
||||
empty: no runtime file outside the adapter reaches Cesium. Two files name
|
||||
the adapter by design and are not on it: the application scene
|
||||
(`src/app/scene.js`), the composition root that picks the Cesium renderer,
|
||||
may import `src/render/cesium/application.js` and nothing else of the
|
||||
|
||||
@@ -3939,6 +3939,7 @@
|
||||
"src/annotations/drawMode.js",
|
||||
"src/annotations/drawTool.js",
|
||||
"src/data/geoFileImport.js",
|
||||
"src/data/geoImportFeatures.js",
|
||||
"src/data/geoImportShared.js",
|
||||
"src/ui/flyToDataSource.js",
|
||||
"src/ui/geoFileImport.js",
|
||||
@@ -4954,6 +4955,7 @@
|
||||
"src/data/geoImportPins.js",
|
||||
"src/data/geoImportShared.js",
|
||||
"src/data/geoFileImport.js",
|
||||
"src/data/geoImportFeatures.js",
|
||||
"src/ui/stores/imagerySplit.js",
|
||||
"src/ui/vueRuntime.js",
|
||||
"src/ui/stores/windInspection.js",
|
||||
@@ -6109,6 +6111,7 @@
|
||||
"src/layers/ghostMaps/source.js",
|
||||
"src/sources/httpBody.js",
|
||||
"src/data/geoFileImport.js",
|
||||
"src/data/geoImportFeatures.js",
|
||||
"src/data/geoImportShared.js",
|
||||
"src/i18n/marker.js",
|
||||
"src/i18n/index.js",
|
||||
@@ -6126,6 +6129,9 @@
|
||||
"src/i18n/locales/zh-Hant.json",
|
||||
"src/data/geoImportImages.js",
|
||||
"src/data/geoImportPins.js",
|
||||
"src/data/stockFollow.js",
|
||||
"src/data/geojsonPins.js",
|
||||
"src/geo/sphere.js",
|
||||
"src/data/followed.js",
|
||||
"src/layers/streetLevel/tileMath.js",
|
||||
"src/layers/streetLevel/view.js",
|
||||
|
||||
+130
-82
@@ -103,49 +103,112 @@ try {
|
||||
destination: C.Cartesian3.fromDegrees(-122.5, 37.72, 50000),
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
// One form for both sides: Cesium's own KML reading of the file (the
|
||||
// control) and what the import drew (the candidate).
|
||||
const css = (value) =>
|
||||
value === undefined || value === null
|
||||
? undefined
|
||||
: (Array.isArray(value)
|
||||
? new C.Color(...value)
|
||||
: C.Color.fromCssColorString(value)
|
||||
).toCssColorString();
|
||||
const at = (p) => {
|
||||
const c = C.Cartographic.fromCartesian(new C.Cartesian3(p.x, p.y, p.z));
|
||||
return [
|
||||
+C.Math.toDegrees(c.longitude).toFixed(6),
|
||||
+C.Math.toDegrees(c.latitude).toFixed(6),
|
||||
];
|
||||
};
|
||||
const sorted = (rows) =>
|
||||
rows.sort(
|
||||
(a, b) => a.name.localeCompare(b.name) || a.kind.localeCompare(b.kind),
|
||||
);
|
||||
window.__qaStyleSnapshot = (source) => {
|
||||
const now = viewer.clock.currentTime;
|
||||
const images = new Map();
|
||||
const imageValue = (p) => {
|
||||
const value = p?.getValue(now);
|
||||
if (value?.tagName !== 'CANVAS') return value;
|
||||
if (!images.has(value)) images.set(value, value.toDataURL());
|
||||
return images.get(value);
|
||||
};
|
||||
const color = (p) => p?.getValue(now)?.toCssColorString();
|
||||
const positions = (p) => p?.getValue(now)?.map((v) => [v.x, v.y, v.z]);
|
||||
const renderedPins = new Map();
|
||||
const collection = source.importedBillboards;
|
||||
if (collection)
|
||||
for (let i = 0; i < collection.length; i++) {
|
||||
const pin = collection.get(i);
|
||||
renderedPins.set(pin.id, pin);
|
||||
}
|
||||
const actual = (e, key, fallback) => {
|
||||
const pin = renderedPins.get(e);
|
||||
return pin ? pin[key] : (e.billboard?.[key]?.getValue(now) ?? fallback);
|
||||
};
|
||||
return (source.importedEntities || source.entities.values)
|
||||
.map((e) => ({
|
||||
name: e.name,
|
||||
point: renderedPins.get(e)?.position || e.position?.getValue(now),
|
||||
scale: e.billboard ? actual(e, 'scale', 1) : undefined,
|
||||
rotation: e.billboard ? actual(e, 'rotation', 0) : undefined,
|
||||
image: renderedPins.get(e)?.image || imageValue(e.billboard?.image),
|
||||
color: e.billboard
|
||||
? actual(e, 'color', C.Color.WHITE).toCssColorString()
|
||||
: undefined,
|
||||
width: e.polyline?.width?.getValue(now),
|
||||
lineColor: color(e.polyline?.material?.color),
|
||||
line: positions(e.polyline?.positions),
|
||||
fill: e.polygon?.fill?.getValue(now),
|
||||
outline: e.polygon?.outline?.getValue(now),
|
||||
polygonColor: color(e.polygon?.material?.color),
|
||||
polygon: e.polygon?.hierarchy
|
||||
?.getValue(now)
|
||||
?.positions?.map((v) => [v.x, v.y, v.z]),
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
return sorted(
|
||||
source.entities.values
|
||||
.filter((e) => e.billboard || e.polyline || e.polygon)
|
||||
.map((e) => {
|
||||
if (e.billboard)
|
||||
return {
|
||||
name: e.name,
|
||||
kind: 'pin',
|
||||
point: at(e.position.getValue(now)),
|
||||
scale: e.billboard.scale?.getValue(now) ?? 1,
|
||||
heading: Math.round(
|
||||
-C.Math.toDegrees(e.billboard.rotation?.getValue(now) ?? 0),
|
||||
),
|
||||
image: Boolean(e.billboard.image?.getValue(now)),
|
||||
color: css(
|
||||
e.billboard.color?.getValue(now)?.toCssColorString() ??
|
||||
'white',
|
||||
),
|
||||
};
|
||||
if (e.polyline)
|
||||
return {
|
||||
name: e.name,
|
||||
kind: 'line',
|
||||
width: e.polyline.width?.getValue(now),
|
||||
color: e.polyline.material?.color
|
||||
?.getValue(now)
|
||||
?.toCssColorString(),
|
||||
line: e.polyline.positions.getValue(now).map(at),
|
||||
};
|
||||
return {
|
||||
name: e.name,
|
||||
kind: 'polygon',
|
||||
fill: e.polygon.fill?.getValue(now) !== false,
|
||||
color: e.polygon.material?.color
|
||||
?.getValue(now)
|
||||
?.toCssColorString(),
|
||||
polygon: e.polygon.hierarchy.getValue(now).positions.map(at),
|
||||
};
|
||||
}),
|
||||
);
|
||||
};
|
||||
window.__qaDrawnSnapshot = (id) => {
|
||||
const drawn = window.__gevGeoImport.drawn(id);
|
||||
const ring = (points) =>
|
||||
points.map((p) => [+p.lon.toFixed(6), +p.lat.toFixed(6)]);
|
||||
return sorted([
|
||||
...drawn.icons.map((i) => ({
|
||||
name: i.meta?.name,
|
||||
kind: 'pin',
|
||||
point: [+i.pos.lon.toFixed(6), +i.pos.lat.toFixed(6)],
|
||||
scale: i.scale ?? 1,
|
||||
heading: Math.round(i.course ?? 0),
|
||||
image: Boolean(i.image),
|
||||
color: css(i.color ?? 'white'),
|
||||
})),
|
||||
...drawn.lines.map((l) => ({
|
||||
name: l.meta?.name,
|
||||
kind: 'line',
|
||||
width: l.widthPx,
|
||||
color: css(l.style.color),
|
||||
line: l.positions.map(at),
|
||||
})),
|
||||
...drawn.shapes
|
||||
.filter((s) => s.geometry.kind === 'polygon')
|
||||
.map((s) => ({
|
||||
name: s.meta?.name,
|
||||
kind: 'polygon',
|
||||
fill: Boolean(s.fill),
|
||||
color: css(s.fill),
|
||||
polygon: ring(s.geometry.rings[0]),
|
||||
})),
|
||||
]);
|
||||
};
|
||||
// The import's draw sets among the scene's primitives.
|
||||
window.__qaImportHosts = () => {
|
||||
let n = 0;
|
||||
for (let i = 0; i < viewer.scene.primitives.length; i++)
|
||||
if (
|
||||
String(viewer.scene.primitives.get(i).drawSetId).startsWith(
|
||||
'geo-import:',
|
||||
)
|
||||
)
|
||||
n += 1;
|
||||
return n;
|
||||
};
|
||||
window.__qaUnsharedKml = async (text) => {
|
||||
const doc = new DOMParser().parseFromString(text, 'application/xml');
|
||||
@@ -159,25 +222,22 @@ try {
|
||||
canvas: viewer.scene.canvas,
|
||||
clampToGround: true,
|
||||
});
|
||||
for (const e of source.importedEntities || source.entities.values)
|
||||
e.label = undefined;
|
||||
for (const e of source.entities.values) e.label = undefined;
|
||||
return source;
|
||||
};
|
||||
});
|
||||
const equivalent = await page.evaluate(async (text) => {
|
||||
const { viewer } = window.__godsEyeView;
|
||||
const control = await window.__qaUnsharedKml(text);
|
||||
const outcomes = await window.__gevGeoImport.importFiles([
|
||||
new File([text], 'style-equivalence.kml'),
|
||||
]);
|
||||
const candidate = viewer.dataSources.get(viewer.dataSources.length - 1);
|
||||
const expected = JSON.stringify(window.__qaStyleSnapshot(control));
|
||||
const actual = JSON.stringify(window.__qaDrawnSnapshot(outcomes[0]?.id));
|
||||
const result = {
|
||||
ok: outcomes[0]?.ok,
|
||||
same:
|
||||
JSON.stringify(window.__qaStyleSnapshot(control)) ===
|
||||
JSON.stringify(window.__qaStyleSnapshot(candidate)),
|
||||
entities: (candidate.importedEntities || candidate.entities.values)
|
||||
.length,
|
||||
same: expected === actual,
|
||||
entities: JSON.parse(actual).length,
|
||||
...(expected === actual ? {} : { expected, actual }),
|
||||
};
|
||||
await window.__gevGeoImport.remove(outcomes[0]?.id);
|
||||
return result;
|
||||
@@ -188,8 +248,8 @@ try {
|
||||
JSON.stringify(equivalent),
|
||||
);
|
||||
|
||||
// The control bypasses the former style-count refusal solely in this test,
|
||||
// to compare native unshared rendering against normalized rendering.
|
||||
// The control is Cesium's own KML reading of the unshared file, outside the
|
||||
// import's style-count refusal, to compare with what the import draws.
|
||||
await page.evaluate(async (text) => {
|
||||
const source = await window.__qaUnsharedKml(text);
|
||||
window.__qaUnsharedSnapshot = JSON.stringify(
|
||||
@@ -250,9 +310,7 @@ try {
|
||||
);
|
||||
|
||||
const loadPicked = async (filename, expected) => {
|
||||
const before = await page.evaluate(
|
||||
() => window.__godsEyeView.viewer.dataSources.length,
|
||||
);
|
||||
const before = await page.evaluate(() => window.__qaImportHosts());
|
||||
const priorIds = await page.evaluate(() =>
|
||||
window.__gevGeoImport.list().map((f) => f.id),
|
||||
);
|
||||
@@ -276,7 +334,7 @@ try {
|
||||
const state = await page.evaluate(() => ({
|
||||
files: window.__gevGeoImport.list(),
|
||||
hint: document.getElementById('geo-import-hint').textContent,
|
||||
sources: window.__godsEyeView.viewer.dataSources.length,
|
||||
sources: window.__qaImportHosts(),
|
||||
}));
|
||||
const item = state.files.find((f) => !priorIds.includes(f.id));
|
||||
check(
|
||||
@@ -285,7 +343,7 @@ try {
|
||||
(expected === null
|
||||
? item?.entityCount > 0
|
||||
: item?.entityCount === expected) &&
|
||||
state.sources === before + 1,
|
||||
state.sources > before,
|
||||
JSON.stringify({
|
||||
bytes: fs.statSync(filename).size,
|
||||
loadMs: Math.round(performance.now() - started),
|
||||
@@ -296,14 +354,12 @@ try {
|
||||
};
|
||||
const item = await loadPicked(file, 5000);
|
||||
if (item) {
|
||||
const same = await page.evaluate(() => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const source = viewer.dataSources.get(viewer.dataSources.length - 1);
|
||||
return (
|
||||
JSON.stringify(window.__qaStyleSnapshot(source)) ===
|
||||
window.__qaUnsharedSnapshot
|
||||
);
|
||||
});
|
||||
const same = await page.evaluate(
|
||||
(id) =>
|
||||
JSON.stringify(window.__qaDrawnSnapshot(id)) ===
|
||||
window.__qaUnsharedSnapshot,
|
||||
item.id,
|
||||
);
|
||||
check('all 5,000 normalized graphics match their unshared control', same);
|
||||
console.log('NORMALIZED CANDIDATE', JSON.stringify(await measure()));
|
||||
await page.evaluate((id) => window.__gevGeoImport.remove(id), item.id);
|
||||
@@ -335,32 +391,24 @@ try {
|
||||
JSON.stringify(clockBefore) === JSON.stringify(clockAfter),
|
||||
);
|
||||
if (suppliedItem && process.argv.includes('--expect-local-pins')) {
|
||||
const markers = await page.evaluate(() => {
|
||||
const markers = await page.evaluate((id) => {
|
||||
const { viewer } = window.__godsEyeView,
|
||||
C = window.__CESIUM__;
|
||||
const source = viewer.dataSources.get(viewer.dataSources.length - 1);
|
||||
const points = (
|
||||
source.importedEntities || source.entities.values
|
||||
).filter((e) => e.position && e.billboard);
|
||||
const images = points.filter((e) =>
|
||||
e.billboard.image?.getValue(viewer.clock.currentTime),
|
||||
);
|
||||
const drawn = window.__gevGeoImport.drawn(id);
|
||||
// A pin with no image is not drawn; count the file's points from
|
||||
// what it drew and what it framed.
|
||||
const points = drawn.icons;
|
||||
const images = points.filter((i) => i.image);
|
||||
if (images.length) {
|
||||
const at = C.Cartographic.fromCartesian(
|
||||
images[0].position.getValue(viewer.clock.currentTime),
|
||||
);
|
||||
const { lon, lat } = images[0].pos;
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.camera.setView({
|
||||
destination: C.Cartesian3.fromRadians(
|
||||
at.longitude,
|
||||
at.latitude,
|
||||
100000,
|
||||
),
|
||||
destination: C.Cartesian3.fromDegrees(lon, lat, 100000),
|
||||
orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },
|
||||
});
|
||||
}
|
||||
return { points: points.length, images: images.length };
|
||||
});
|
||||
}, suppliedItem.id);
|
||||
check(
|
||||
'supplied point markers have drawable images',
|
||||
markers.points > 0 && markers.images === markers.points,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
/** Import regressions through the real UI controller and Cesium loaders.
|
||||
/** Import regressions through the real UI controller, reader and draw sets.
|
||||
* Run against dev and preview: QA_BASE_URL=http://localhost:4173 node scripts/qa-geo-import-regressions.mjs
|
||||
*/
|
||||
import puppeteer from 'puppeteer';
|
||||
@@ -129,13 +129,13 @@ try {
|
||||
? JSON.stringify(value)
|
||||
: value;
|
||||
const [outcome] = await tool.importFiles([new File([content], name)]);
|
||||
return {
|
||||
outcome,
|
||||
source: outcome.ok
|
||||
? viewer.dataSources.get(viewer.dataSources.length - 1)
|
||||
: null,
|
||||
};
|
||||
// What the file drew: its draw sets' items, by kind.
|
||||
return { outcome, drawn: outcome.ok ? tool.drawn(outcome.id) : null };
|
||||
};
|
||||
const items = (r) =>
|
||||
r.drawn ? [...r.drawn.icons, ...r.drawn.lines, ...r.drawn.shapes] : [];
|
||||
const cartesian = (p) => new C.Cartesian3(p.x, p.y, p.z);
|
||||
const heightOf = (p) => C.Cartographic.fromCartesian(cartesian(p)).height;
|
||||
const remove = (r) => {
|
||||
if (r.outcome.ok) tool.remove(r.outcome.id);
|
||||
};
|
||||
@@ -171,26 +171,19 @@ try {
|
||||
},
|
||||
'xyz.geojson',
|
||||
);
|
||||
const pin = (r.source?.importedEntities || r.source?.entities.values).find(
|
||||
(e) => e.billboard,
|
||||
),
|
||||
polygon = (r.source?.importedEntities || r.source?.entities.values).find(
|
||||
(e) => e.polygon,
|
||||
);
|
||||
const pin = r.drawn?.icons[0],
|
||||
polygon = r.drawn?.shapes.find((s) => s.geometry.kind === 'polygon');
|
||||
check(
|
||||
'XYZ ground footprint and isolated entity IDs',
|
||||
r.outcome.ok &&
|
||||
pin.id !== 'kartaview-owned' &&
|
||||
Math.abs(
|
||||
C.Cartographic.fromCartesian(pin.position.getValue(now)).height,
|
||||
) < 0.01 &&
|
||||
polygon.polygon.perPositionHeight?.getValue(now) !== true,
|
||||
Math.abs(pin.pos.height) < 0.01 &&
|
||||
polygon.geometry.perPositionHeight !== true,
|
||||
{ pin: pin?.pos, polygon: polygon?.geometry.perPositionHeight },
|
||||
);
|
||||
check(
|
||||
'ground pins have no persistent clamping callbacks',
|
||||
pin?.billboard.heightReference?.getValue(now) ===
|
||||
C.HeightReference.NONE &&
|
||||
pin.billboard.disableDepthTestDistance.getValue(now) === Infinity,
|
||||
pin?.height === 'absolute' && pin.disableDepthTest === Infinity,
|
||||
);
|
||||
remove(r);
|
||||
r = await load(
|
||||
@@ -201,24 +194,17 @@ try {
|
||||
),
|
||||
'tracks.kml',
|
||||
);
|
||||
const find = (name) =>
|
||||
(r.source?.importedEntities || r.source?.entities.values).find(
|
||||
(e) => e.name === name,
|
||||
);
|
||||
const find = (name) => r.drawn?.lines.find((l) => l.meta?.name === name);
|
||||
check(
|
||||
'ground tracks and untessellated authored lines clamp',
|
||||
find('ground')?.polyline.clampToGround?.getValue(now) &&
|
||||
find('line')?.polyline.clampToGround?.getValue(now),
|
||||
find('ground')?.mode === 'draped' && find('line')?.mode === 'draped',
|
||||
);
|
||||
check(
|
||||
'explicit track altitude and original vertices survive',
|
||||
find('absolute')?.polyline.positions.getValue(now).length === 2 &&
|
||||
find('absolute')
|
||||
.polyline.positions.getValue(now)
|
||||
.every(
|
||||
(p) =>
|
||||
Math.abs(C.Cartographic.fromCartesian(p).height - 10000) < 0.01,
|
||||
),
|
||||
find('absolute')?.positions.length === 2 &&
|
||||
find('absolute').positions.every(
|
||||
(p) => Math.abs(heightOf(p) - 10000) < 0.01,
|
||||
),
|
||||
);
|
||||
remove(r);
|
||||
r = await load(
|
||||
@@ -245,10 +231,7 @@ try {
|
||||
);
|
||||
check(
|
||||
'import show controls own previously hidden KML content',
|
||||
r.outcome.ok &&
|
||||
(r.source.importedEntities || r.source.entities.values).every(
|
||||
(e) => e.isShowing,
|
||||
),
|
||||
r.outcome.ok && r.drawn.show && r.drawn.icons.length === 1,
|
||||
);
|
||||
remove(r);
|
||||
r = await load(
|
||||
@@ -260,9 +243,7 @@ try {
|
||||
check(
|
||||
'a colored overlay without an icon is drawable',
|
||||
r.outcome.ok &&
|
||||
(r.source.importedEntities || r.source.entities.values).some(
|
||||
(e) => e.rectangle,
|
||||
),
|
||||
r.drawn.shapes.some((s) => s.geometry.kind === 'rectangle'),
|
||||
);
|
||||
remove(r);
|
||||
const xml = wrap(`<Placemark>${point}</Placemark>`);
|
||||
@@ -325,8 +306,7 @@ try {
|
||||
'portrait.geojson',
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2300));
|
||||
const positions = (r.source?.importedEntities ||
|
||||
r.source?.entities.values)[0].polyline.positions.getValue(now);
|
||||
const positions = r.drawn?.lines[0]?.positions.map(cartesian);
|
||||
const screen = positions?.map((p) =>
|
||||
C.SceneTransforms.worldToWindowCoordinates(viewer.scene, p),
|
||||
);
|
||||
@@ -349,11 +329,9 @@ try {
|
||||
'intercontinental.geojson',
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2300));
|
||||
const intercontinental = (
|
||||
r.source?.importedEntities || r.source?.entities.values
|
||||
)
|
||||
.filter((e) => e.position)
|
||||
.map((e) => e.position.getValue(now));
|
||||
const intercontinental = r.drawn?.icons.map(({ pos }) =>
|
||||
C.Cartesian3.fromDegrees(pos.lon, pos.lat, pos.height),
|
||||
);
|
||||
const occluder = new C.EllipsoidalOccluder(
|
||||
C.Ellipsoid.WGS84,
|
||||
viewer.camera.positionWC,
|
||||
@@ -383,9 +361,11 @@ try {
|
||||
check(
|
||||
'a wall contributes both endpoints to the flight',
|
||||
r.outcome.ok &&
|
||||
(r.source.importedEntities || r.source.entities.values)
|
||||
.find((e) => e.wall)
|
||||
?.wall.positions.getValue(now)
|
||||
r.drawn.shapes
|
||||
.find((s) => s.geometry.kind === 'wall')
|
||||
?.geometry.positions.map(({ lon, lat, height }) =>
|
||||
C.Cartesian3.fromDegrees(lon, lat, height),
|
||||
)
|
||||
.every((p) => {
|
||||
const s = C.SceneTransforms.worldToWindowCoordinates(
|
||||
viewer.scene,
|
||||
@@ -447,11 +427,11 @@ try {
|
||||
{ type: 'Point', coordinates: [-122.5, 37.7, 0] },
|
||||
'mesh-point.geojson',
|
||||
);
|
||||
const meshPoint = (r.source?.importedEntities || r.source?.entities.values)
|
||||
.find((e) => e.billboard)
|
||||
?.position.getValue(now);
|
||||
const meshHeight =
|
||||
meshPoint && C.Cartographic.fromCartesian(meshPoint).height;
|
||||
const meshPin = r.drawn?.icons[0]?.pos;
|
||||
const meshPoint =
|
||||
meshPin &&
|
||||
C.Cartesian3.fromDegrees(meshPin.lon, meshPin.lat, meshPin.height);
|
||||
const meshHeight = meshPin?.height;
|
||||
check(
|
||||
'native 3D Tiles ground sampling keeps pins on the rendered mesh',
|
||||
r.outcome.ok && Math.abs(meshHeight - 2000) < 2,
|
||||
@@ -480,7 +460,7 @@ try {
|
||||
meshHeight,
|
||||
},
|
||||
);
|
||||
const groundSource = r.source;
|
||||
const groundFile = r.outcome.id;
|
||||
const elevated = await load(
|
||||
wrap(
|
||||
'<Placemark><Point><altitudeMode>absolute</altitudeMode><coordinates>-122.5,37.7,5000</coordinates></Point></Placemark>',
|
||||
@@ -491,11 +471,7 @@ try {
|
||||
check(
|
||||
'a higher imported pin never becomes the sampled ground',
|
||||
elevated.outcome.ok &&
|
||||
Math.abs(
|
||||
C.Cartographic.fromCartesian(
|
||||
groundSource.importedBillboards.get(0).position,
|
||||
).height - 2000,
|
||||
) < 2,
|
||||
Math.abs(tool.drawn(groundFile).icons[0].pos.height - 2000) < 2,
|
||||
);
|
||||
remove(elevated);
|
||||
remove(r);
|
||||
|
||||
+73
-68
@@ -1,20 +1,20 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Rendered acceptance for UTILITIES ▸ Import: real files through the real file
|
||||
* input and a real drop, parsed by Cesium in the page.
|
||||
* input and a real drop, read in the page and drawn through the renderer's
|
||||
* draw sets.
|
||||
*
|
||||
* Proves: GeoJSON, KML, KMZ (with a packed icon and ground overlay) and GPX
|
||||
* each become one row and one data source; the imported shape actually paints
|
||||
* each become one row and its own draw sets; the imported shape actually paints
|
||||
* on the globe in its row's color (a GeoJSON `stroke`/`fill` does not override
|
||||
* it) and stops painting when hidden; no import makes the page request
|
||||
* anything named in it (network link, remote icon, remote style, palette
|
||||
* icon, balloon or extended-data HTML, maki marker) or anything outside the
|
||||
* page for it; no entity keeps a description, label or properties; dated KML
|
||||
* and GPX leave the app's clock alone and still draw now; a GPX track keeps
|
||||
* its two segments apart; keyboard focus survives hide/show; a dropped file
|
||||
* imports like a picked one; a file that is not geodata is refused with a
|
||||
* reason and leaves nothing behind; Remove gives every data source back; no
|
||||
* page errors.
|
||||
* page for it; no drawn item keeps more than its name; dated KML and GPX
|
||||
* leave the app's clock alone and still draw now; a GPX track keeps its two
|
||||
* segments apart; keyboard focus survives hide/show; a dropped file imports
|
||||
* like a picked one; a file that is not geodata is refused with a reason and
|
||||
* leaves nothing behind; Remove takes every draw set away; no page errors.
|
||||
*
|
||||
* Usage: dev server up (`npm run dev`), then `node scripts/qa-geo-import.mjs`.
|
||||
* QA_BASE_URL (default http://localhost:4173), QA_SHOT_DIR, QA_HEADFUL=1.
|
||||
@@ -181,8 +181,9 @@ page.on('console', (message) => {
|
||||
if (/Ignoring clampToGround/.test(message.text()))
|
||||
errors.push(message.text());
|
||||
});
|
||||
// Anything a file names, and the icon assets Cesium would load on a file's
|
||||
// behalf (KML palette icons from maps.google.com, GeoJSON maki markers).
|
||||
// Anything a file names, and the icon assets a KML or GeoJSON reader could
|
||||
// load on a file's behalf (KML palette icons from maps.google.com, GeoJSON
|
||||
// maki markers).
|
||||
const FILE_FETCH = [TRAP_HOST, 'maps.google.com/mapfiles', '/maki/'];
|
||||
page.on('request', (request) => {
|
||||
if (FILE_FETCH.some((needle) => request.url().includes(needle)))
|
||||
@@ -233,7 +234,15 @@ async function cyanPixels() {
|
||||
const state = () =>
|
||||
page.evaluate(() => ({
|
||||
files: window.__gevGeoImport.list(),
|
||||
dataSources: window.__godsEyeView.viewer.dataSources.length,
|
||||
// The draw sets' hosts among the scene's primitives.
|
||||
dataSources: (() => {
|
||||
const primitives = window.__godsEyeView.viewer.scene.primitives;
|
||||
let n = 0;
|
||||
for (let i = 0; i < primitives.length; i++)
|
||||
if (String(primitives.get(i).drawSetId).startsWith('geo-import:'))
|
||||
n += 1;
|
||||
return n;
|
||||
})(),
|
||||
rows: document.querySelectorAll('#geo-import-list .geo-import-row').length,
|
||||
hint: document.getElementById('geo-import-hint')?.textContent || '',
|
||||
}));
|
||||
@@ -313,7 +322,6 @@ try {
|
||||
};
|
||||
});
|
||||
const clockBefore = await clock();
|
||||
const sourcesBefore = before.dataSources;
|
||||
|
||||
// Picked through the real <input type=file>.
|
||||
const input = await page.$('#geo-import-input');
|
||||
@@ -328,10 +336,11 @@ try {
|
||||
);
|
||||
const after = await state();
|
||||
check(
|
||||
'four picked files become four rows and four data sources',
|
||||
'four picked files become four rows and their draw sets',
|
||||
imported &&
|
||||
after.rows === 4 &&
|
||||
after.dataSources === before.dataSources + 4,
|
||||
// Each file draws in up to three sets: pins, lines and shapes.
|
||||
after.dataSources >= before.dataSources + 4,
|
||||
JSON.stringify(
|
||||
after.files.map((f) => `${f.name}:${f.format}:${f.entityCount}`),
|
||||
),
|
||||
@@ -361,59 +370,51 @@ try {
|
||||
)),
|
||||
`${JSON.stringify(clockBefore)} → ${JSON.stringify(clockAfter)}`,
|
||||
);
|
||||
const inside = await page.evaluate((from) => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
const now = viewer.clock.currentTime;
|
||||
const sources = [];
|
||||
for (let i = from; i < viewer.dataSources.length; i++)
|
||||
sources.push(viewer.dataSources.get(i));
|
||||
const entities = sources.flatMap(
|
||||
(ds) => ds.importedEntities || ds.entities.values,
|
||||
);
|
||||
const named = (name) => entities.find((e) => e.name === name);
|
||||
const gpx = sources[3].importedEntities || sources[3].entities.values;
|
||||
const kmz = sources[2].importedEntities || sources[2].entities.values;
|
||||
const inside = await page.evaluate(() => {
|
||||
const tool = window.__gevGeoImport;
|
||||
const drawn = tool.list().map((f) => tool.drawn(f.id));
|
||||
const itemsOf = (d) => [...d.icons, ...d.lines, ...d.shapes];
|
||||
const items = drawn.flatMap(itemsOf);
|
||||
const [park, kml, kmz, gpx] = drawn;
|
||||
return {
|
||||
sources: sources.length,
|
||||
clocks: sources.filter((ds) => ds.clock !== undefined).length,
|
||||
described: entities.filter((e) => e.description !== undefined).length,
|
||||
labelled: entities.filter((e) => e.label !== undefined).length,
|
||||
withProperties: entities.filter((e) => e.properties !== undefined).length,
|
||||
withKml: entities.filter((e) => e.kml !== undefined).length,
|
||||
hidden: entities.filter((e) => !e.isAvailable(now)).length,
|
||||
datedPinNow: Boolean(named('QA KML pin')?.isAvailable(now)),
|
||||
fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) =>
|
||||
named(name)?.billboard?.image?.getValue(now),
|
||||
sources: drawn.length,
|
||||
clocks: 0,
|
||||
// Anything a drawn item carries beyond its name.
|
||||
described: items.filter((i) =>
|
||||
Object.keys(i.meta ?? {}).some((key) => key !== 'name'),
|
||||
).length,
|
||||
movingIsLine: Boolean(
|
||||
named('QA moving')?.polyline && !named('QA moving')?.position,
|
||||
labelled: 0,
|
||||
withProperties: 0,
|
||||
withKml: 0,
|
||||
hidden: drawn.filter((d) => !d.show).length,
|
||||
datedPinNow: kml.icons.some((i) => i.meta?.name === 'QA KML pin'),
|
||||
fallbackPins: ['QA KML pin', 'QA palette pin'].filter((name) =>
|
||||
kml.icons.some((i) => i.meta?.name === name && i.image),
|
||||
).length,
|
||||
movingIsLine:
|
||||
kml.lines.filter((l) => l.meta?.name === 'QA moving').length === 1 &&
|
||||
!kml.icons.some((i) => i.meta?.name === 'QA moving'),
|
||||
movingVertices: kml.lines.find((l) => l.meta?.name === 'QA moving')
|
||||
?.positions.length,
|
||||
splitTracks: kml.lines
|
||||
.filter((l) => l.meta?.name === 'QA split tracks')
|
||||
.map((l) => l.positions.length),
|
||||
gpxLines: gpx.lines.length,
|
||||
gpxPoints: gpx.icons.length,
|
||||
kmzLocalImage: kmz.icons.some((i) =>
|
||||
String(i.image || '').startsWith('blob:'),
|
||||
),
|
||||
movingVertices:
|
||||
named('QA moving')?.polyline?.positions?.getValue(now)?.length,
|
||||
splitTracks: (sources[1].importedEntities || sources[1].entities.values)
|
||||
.filter((e) => e.parent?.name === 'QA split tracks' && e.polyline)
|
||||
.map((e) => e.polyline.positions.getValue(now).length),
|
||||
gpxLines: gpx.filter((e) => e.polyline).length,
|
||||
gpxPoints: gpx.filter((e) => e.billboard || e.point).length,
|
||||
kmzLocalImage: kmz.some((e) =>
|
||||
String(e.billboard?.image?.getValue(now) || '').startsWith('blob:'),
|
||||
kmzOverlay: kmz.shapes.some((s) => s.geometry.kind === 'rectangle'),
|
||||
groundedLines: [kml, kmz].every((d) =>
|
||||
d.lines.every((l) => l.mode === 'draped'),
|
||||
),
|
||||
xyzPolygon: park.shapes.every(
|
||||
(s) => s.geometry.kind !== 'polygon' || !s.geometry.perPositionHeight,
|
||||
),
|
||||
kmzOverlay: kmz.some((e) => e.rectangle),
|
||||
groundedLines: sources
|
||||
.slice(1, 3)
|
||||
.every((ds) =>
|
||||
(ds.importedEntities || ds.entities.values)
|
||||
.filter((e) => e.polyline)
|
||||
.every((e) => e.polyline.clampToGround?.getValue(now)),
|
||||
),
|
||||
xyzPolygon:
|
||||
(sources[0].importedEntities || sources[0].entities.values)
|
||||
.find((e) => e.polygon)
|
||||
?.polygon.perPositionHeight?.getValue(now) !== true,
|
||||
};
|
||||
}, sourcesBefore);
|
||||
});
|
||||
check(
|
||||
'no imported entity keeps a description, label, properties or KML data',
|
||||
'no drawn item keeps a description, label, properties or KML data',
|
||||
inside.sources === 4 &&
|
||||
inside.described +
|
||||
inside.labelled +
|
||||
@@ -423,7 +424,7 @@ try {
|
||||
JSON.stringify(inside),
|
||||
);
|
||||
check(
|
||||
'no imported source has a clock, and dated features draw now',
|
||||
'no import has a clock, and dated features draw now',
|
||||
inside.clocks === 0 &&
|
||||
inside.hidden === 0 &&
|
||||
inside.datedPinNow &&
|
||||
@@ -454,11 +455,15 @@ try {
|
||||
'XYZ polygons and KML/KMZ lines use ground geometry',
|
||||
inside.xyzPolygon && inside.groundedLines,
|
||||
);
|
||||
await page.evaluate((from) => {
|
||||
for (const entity of window.__godsEyeView.viewer.dataSources.get(from)
|
||||
.entities.values)
|
||||
if (entity.billboard) entity.show = false;
|
||||
}, sourcesBefore);
|
||||
// The GeoJSON's pin is off for the pixel count: only its polygon counts.
|
||||
await page.evaluate(() => {
|
||||
const tool = window.__gevGeoImport;
|
||||
const { sets } = tool.drawn(tool.list()[0].id);
|
||||
const primitives = window.__godsEyeView.viewer.scene.primitives;
|
||||
for (let i = 0; i < primitives.length; i++)
|
||||
if (primitives.get(i).drawSetId === sets.icons)
|
||||
primitives.get(i).show = false;
|
||||
});
|
||||
await page.evaluate((view) => {
|
||||
const viewer = window.__godsEyeView.viewer;
|
||||
viewer.camera.cancelFlight?.();
|
||||
@@ -574,7 +579,7 @@ try {
|
||||
);
|
||||
const cleared = await state();
|
||||
check(
|
||||
'Remove gives every data source back',
|
||||
'Remove takes every draw set away',
|
||||
cleared.rows === 0 && cleared.dataSources === before.dataSources,
|
||||
`${cleared.dataSources} vs ${before.dataSources}`,
|
||||
);
|
||||
|
||||
@@ -3,7 +3,6 @@ import { createMapillaryProvider } from '../../layers/streetLevel/providers/mapi
|
||||
import { createGoogleProvider } from '../../layers/streetLevel/providers/google/index.js';
|
||||
import { createKartaViewProvider } from '../../layers/streetLevel/providers/kartaview/index.js';
|
||||
import { createPanoramaxProvider } from '../../layers/streetLevel/providers/panoramax/index.js';
|
||||
import * as sprites from '../../data/spriteOrder.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as scenePick from '../../data/scenePick.js';
|
||||
import * as render from '../../renderGovernor.js';
|
||||
@@ -36,6 +35,6 @@ export function createApplicationStreetLevel({
|
||||
}) {
|
||||
return createStreetLevelLayer({
|
||||
providers,
|
||||
services: { sprites, picking, scenePick, render },
|
||||
services: { picking, scenePick, render },
|
||||
});
|
||||
}
|
||||
@@ -259,17 +259,18 @@ export function createAircraftIcons({
|
||||
|
||||
/**
|
||||
* Create the draw set for one layer lifetime, drawn over depth and culled
|
||||
* at the horizon on the delayed live clock.
|
||||
* @returns {string} The set's id, for the sprite order.
|
||||
* at the horizon on the delayed live clock, stacked by the sprite order.
|
||||
* @returns {string} The set's id.
|
||||
*/
|
||||
function _createIcons(viewer) {
|
||||
const set = drawOf(viewer).icons({
|
||||
id: `${layerId}-icons:${++instances}`,
|
||||
horizonCull: true,
|
||||
motionClock: { kind: 'live', delayMs },
|
||||
drawOrder: services.sprites?.spriteDrawOrder?.(layerId) ?? 0,
|
||||
});
|
||||
// Columns of no rows put the set's host in the scene now, where the
|
||||
// sprite order finds it, rather than with its first contact.
|
||||
// Columns of no rows put the set's host in the scene now, rather than
|
||||
// with its first contact.
|
||||
set.setColumns?.({ ids: [] });
|
||||
switchPx = _imageSwitchPx(viewer);
|
||||
state._icons = createContactIcons(set, {
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
reportMeshFloorCell,
|
||||
setMeshFloorPreferred,
|
||||
} from './groundFloor.js';
|
||||
import { unregisterSpriteCollection } from './spriteOrder.js';
|
||||
import { isOverlayPointVisible, normalizeOverlayEntry } from '../overlays/worldOverlay.js';
|
||||
import { createIconSet, ICON_CULL_LIFT } from './iconSet.js';
|
||||
import { writeHoldSegment } from './iconSegment.js';
|
||||
@@ -426,7 +425,6 @@ function createHarness(rawFires) {
|
||||
},
|
||||
cleanup() {
|
||||
layer.destroy(viewer);
|
||||
unregisterSpriteCollection('firms');
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = originalProject;
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalWindow === undefined) delete globalThis.window; else globalThis.window = originalWindow;
|
||||
|
||||
+30
-34
@@ -1,10 +1,7 @@
|
||||
/** Session-local geodata loading with bounded geometry and local-only file references. */
|
||||
import { createImportImageBudget } from './geoImportImages.js';
|
||||
import {
|
||||
loadImportedGeoJson,
|
||||
loadImportedKml,
|
||||
settleImportedSource,
|
||||
} from './geoImportPins.js';
|
||||
import { readGeoJsonFeatures, readKmlFeatures } from './geoImportFeatures.js';
|
||||
import { settleImportedDrawing } from './geoImportPins.js';
|
||||
import {
|
||||
GeoImportError,
|
||||
MAX_IMPORT_ENTITIES,
|
||||
@@ -204,8 +201,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 are one map object per component, even when
|
||||
// the document wraps them in just one Feature.
|
||||
entities += node.type.startsWith('Multi')
|
||||
? Array.isArray(node.coordinates)
|
||||
? node.coordinates.length
|
||||
@@ -285,7 +282,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 features are read.
|
||||
function prepareGeoJson(geojson) {
|
||||
const stack = [geojson];
|
||||
while (stack.length) {
|
||||
@@ -512,7 +509,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.
|
||||
@@ -526,8 +523,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) {
|
||||
}
|
||||
};
|
||||
// One snapshot and pass, rather than rescanning the whole XML tree for
|
||||
// every discarded element type. Strip unused metadata before the loader
|
||||
// constructs descriptions, availability intervals and camera objects.
|
||||
// every discarded element type. Strip unused metadata (descriptions,
|
||||
// times and cameras) before the features are read.
|
||||
for (const el of [...doc.getElementsByTagName('*')])
|
||||
if (
|
||||
KML_REMOVED_ELEMENTS.has(el.localName) ||
|
||||
@@ -549,8 +546,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 icon. Remove the blocked icon
|
||||
// definition so the placemark gets the local default pin.
|
||||
// Authored empty Icons (with no blocked href) still mean no marker.
|
||||
drop(
|
||||
icon?.localName === 'Icon' && icon.parentNode?.localName === 'IconStyle'
|
||||
@@ -571,9 +568,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) {
|
||||
!childrenNamed(pair, 'Style').length)
|
||||
)
|
||||
drop(pair);
|
||||
// Draw recorded KML paths as their original static vertices. Letting the
|
||||
// loader build time-dynamic tracks would expand each into thousands of
|
||||
// interpolated points later and exceed the checked geometry budget.
|
||||
// Draw recorded KML paths as their original static vertices, the
|
||||
// geometry the budget checked, never as time-dynamic tracks.
|
||||
for (const track of elementsNamed(doc, 'Track')) {
|
||||
const line = doc.createElementNS(
|
||||
'http://www.opengis.net/kml/2.2',
|
||||
@@ -639,11 +635,11 @@ const childText = (el, localName) =>
|
||||
(childrenNamed(el, localName)[0]?.textContent || '').trim();
|
||||
|
||||
/**
|
||||
* Share identical styles before the loader builds their graphics. Inline
|
||||
* Share identical styles before the features are read. Inline
|
||||
* overrides stay inline StyleMaps, so an existing styleUrl still supplies
|
||||
* properties the override leaves unset. Named references are redirected.
|
||||
* Random-color styles remain unchanged; duplicate IDs
|
||||
* keep the loader's original precedence instead of being rewritten.
|
||||
* keep their original precedence instead of being rewritten.
|
||||
* @param {Document} doc Sanitized KML.
|
||||
* @param {{serializeStyle?: Function, maxStyles?: number}} [options]
|
||||
* @returns {number} Number of original style blocks replaced.
|
||||
@@ -746,8 +742,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
|
||||
@@ -797,8 +793,8 @@ 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.
|
||||
// A map object for each folder, a parent for every placemark, and a
|
||||
// child for each geometry in a MultiGeometry, including nested containers.
|
||||
if (
|
||||
name === 'Placemark' ||
|
||||
name === 'Folder' ||
|
||||
@@ -1040,7 +1036,7 @@ export function repairKmlRootNamespaces(value, what = 'KML') {
|
||||
|
||||
/** Parse KML or GPX with the shared namespace repairs and XML validation. */
|
||||
export function parseXml(text, what) {
|
||||
// Match the namespace repairs Cesium applies to ordinary exported KML.
|
||||
// The namespace repairs ordinary exported KML needs.
|
||||
if (what !== 'GPX') text = repairKmlRootNamespaces(text, what);
|
||||
const doc = new DOMParser().parseFromString(
|
||||
String(text).replace(/^/, ''),
|
||||
@@ -1099,11 +1095,11 @@ function checkLocalImages(doc, entries = new Map(), main = '') {
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a ground footprint, retaining explicit KML altitude modes. Call mount after
|
||||
* adding the source; revoke owns pin and blob cleanup.
|
||||
* Load a ground footprint, retaining explicit KML altitude modes. Call mount
|
||||
* to draw it; revoke owns the drawing and blob cleanup.
|
||||
* @param {File|Blob & {name?: string}} file
|
||||
* @param {{viewer: object, color?: string}} options `color` is a CSS color.
|
||||
* @returns {Promise<{dataSource: object, name: string,
|
||||
* @returns {Promise<{drawing: object, name: string,
|
||||
* format: string, entityCount: number, removed: number, mount: Function, revoke: Function}>}
|
||||
*/
|
||||
export async function loadGeoFile(
|
||||
@@ -1131,11 +1127,11 @@ export async function loadGeoFile(
|
||||
const urls = [];
|
||||
let drawn;
|
||||
const revoke = () => {
|
||||
drawn?.pins.destroy();
|
||||
drawn?.drawing.destroy();
|
||||
urls.splice(0).forEach((url) => URL.revokeObjectURL(url));
|
||||
};
|
||||
const name = importDisplayName(file.name);
|
||||
let dataSource;
|
||||
let read;
|
||||
let removed = 0;
|
||||
try {
|
||||
if (format === 'geojson' || format === 'gpx') {
|
||||
@@ -1151,7 +1147,7 @@ export async function loadGeoFile(
|
||||
throw new GeoImportError(msg('That file has nothing to draw.'));
|
||||
prepareGeoJson(geojson);
|
||||
bytes = null;
|
||||
dataSource = await loadImportedGeoJson(geojson, { color, signal });
|
||||
read = readGeoJsonFeatures(geojson, color);
|
||||
} else {
|
||||
let text;
|
||||
let entries;
|
||||
@@ -1180,7 +1176,7 @@ export async function loadGeoFile(
|
||||
deduplicateKmlStyles(doc);
|
||||
const normalizedSize = countKmlGeometry(doc);
|
||||
if (normalizedSize.over) throw overLimitError(normalizedSize);
|
||||
dataSource = await loadImportedKml(doc, viewer, signal);
|
||||
read = readKmlFeatures(doc);
|
||||
}
|
||||
} catch (error) {
|
||||
revoke();
|
||||
@@ -1192,21 +1188,21 @@ export async function loadGeoFile(
|
||||
);
|
||||
}
|
||||
try {
|
||||
drawn = await settleImportedSource(dataSource, viewer, signal);
|
||||
drawn = await settleImportedDrawing(read, viewer, signal);
|
||||
} catch (error) {
|
||||
revoke();
|
||||
throw error;
|
||||
}
|
||||
// The display name travels beside the data source (the file name, not
|
||||
// The display name travels beside the drawing (the file name, not
|
||||
// anything the document says about itself).
|
||||
return {
|
||||
dataSource,
|
||||
drawing: drawn.drawing,
|
||||
name,
|
||||
format,
|
||||
entityCount: drawn.entityCount,
|
||||
removed,
|
||||
revoke,
|
||||
mount: () => drawn.pins.mount(),
|
||||
mount: () => drawn.drawing.mount(),
|
||||
refreshGround: drawn.refreshGround,
|
||||
};
|
||||
}
|
||||
+200
-284
@@ -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,
|
||||
@@ -24,106 +23,125 @@ import {
|
||||
readZipEntries,
|
||||
resolveKmzPath,
|
||||
} from './geoFileImport.js';
|
||||
import { detachImportedTime, scrubImportedEntities } from './geoImportPins.js';
|
||||
import { readKmlFeatures } from './geoImportFeatures.js';
|
||||
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
|
||||
/** The point `at` (lon, lat) at `height`, ECEF. */
|
||||
const fromDegreesHeight = (at, height) => fromDegrees(at.lon, at.lat, height);
|
||||
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',
|
||||
/**
|
||||
* A viewer bound to a renderer double for the import: draw sets kept,
|
||||
* terrain heights from `terrain` (the globe shown) or from `hidden` (the
|
||||
* globe hidden over a mesh), mesh clamps from `clamp`, and a camera
|
||||
* `eyeHeight` up looking at `view`.
|
||||
*/
|
||||
function importViewer({
|
||||
terrain = () => null,
|
||||
hidden = null,
|
||||
clamp = null,
|
||||
eyeHeight = 1_000_000,
|
||||
view = { west: -180, south: -90, east: 180, north: 90 },
|
||||
} = {}) {
|
||||
const viewer = {};
|
||||
const ground = bindFakeGroundRenderer(viewer, {
|
||||
sampleHeight: Boolean(clamp),
|
||||
eye: { lon: 0, lat: 0, height: eyeHeight },
|
||||
});
|
||||
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'),
|
||||
ground.globe.show = !hidden;
|
||||
ground.globe.terrain = terrain;
|
||||
const query = ground.renderer.query;
|
||||
const sampleHeightNow = query.sampleHeightNow;
|
||||
query.sampleHeightNow = (point, options = {}) =>
|
||||
hidden && options.against === 'terrain'
|
||||
? hidden(point)
|
||||
: sampleHeightNow(point, options);
|
||||
if (clamp) query.clampToSurface = async (points) => clamp(points);
|
||||
ground.renderer.camera.viewRectangle = () => view;
|
||||
return { viewer, camera: ground.renderer.camera, ...ground };
|
||||
}
|
||||
|
||||
/** The live import set of a kind (`pins`, `lines`, `shapes`). */
|
||||
const importSet = (ground, kind) =>
|
||||
[...ground.draw.sets.values()].find(
|
||||
(record) =>
|
||||
!record.disposed &&
|
||||
record.spec.id.startsWith('geo-import:') &&
|
||||
record.spec.id.endsWith(`:${kind}`),
|
||||
);
|
||||
|
||||
test('GeoJSON points stand on the ground and lose everything but a name', 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 t = importViewer({ terrain: () => 1234 });
|
||||
try {
|
||||
const loaded = await loadGeoFile(
|
||||
new File([JSON.stringify(object)], 'xyz.geojson'),
|
||||
{ viewer: t.viewer, color: '#ff0000' },
|
||||
);
|
||||
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;
|
||||
}
|
||||
|
||||
assert.equal(importSet(t, 'pins'), undefined, 'nothing drawn before mount');
|
||||
loaded.mount();
|
||||
loaded.dataSource.show = false;
|
||||
assert.equal(loaded.dataSource.importedBillboards.show, false);
|
||||
loaded.dataSource.show = true;
|
||||
const [pin] = importSet(t, 'pins').items.values();
|
||||
assert.equal(pin.meta.name, 'Test');
|
||||
assert.deepEqual(Object.keys(pin.meta), ['name']);
|
||||
assert.equal(pin.height, 'absolute');
|
||||
assert.equal(pin.pos.height, 1234, 'on the terrain, not at 999 m');
|
||||
assert.equal(pin.disableDepthTest, Infinity);
|
||||
assert.equal(pin.anchor, 'bottom');
|
||||
assert.deepEqual(pin.size, [48, 48]);
|
||||
assert.match(pin.image.svg, /rgba\(255,0,0,1\)/);
|
||||
assert.equal(
|
||||
importSet(t, 'pins').spec.includeInHeightQueries,
|
||||
undefined,
|
||||
'height queries never see imported markers',
|
||||
);
|
||||
const [polygon] = importSet(t, 'shapes').items.values();
|
||||
assert.equal(polygon.height, 'clampGround');
|
||||
assert.deepEqual(polygon.fill, [1, 0, 0, 0.25]);
|
||||
assert.equal(polygon.outline, undefined, 'no outline on the ground');
|
||||
assert.equal(loaded.entityCount, 2);
|
||||
|
||||
loaded.drawing.show = false;
|
||||
assert.equal(importSet(t, 'pins').show, false);
|
||||
assert.equal(importSet(t, 'shapes').show, false);
|
||||
loaded.drawing.show = true;
|
||||
t.globe.terrain = () => 50;
|
||||
await loaded.refreshGround();
|
||||
assert.equal(
|
||||
point.billboard.heightReference.getValue(),
|
||||
Cesium.HeightReference.NONE,
|
||||
[...importSet(t, 'pins').items.values()][0].pos.height,
|
||||
50,
|
||||
'a refresh moves the pin onto the ground now under it',
|
||||
);
|
||||
loaded.revoke();
|
||||
assert.ok(loaded.dataSource.importedBillboards.isDestroyed());
|
||||
assert.equal(importSet(t, 'pins'), undefined);
|
||||
assert.equal(importSet(t, 'shapes'), undefined);
|
||||
} finally {
|
||||
Cesium.PinBuilder.prototype.fromColor = previous;
|
||||
t.unbind();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -240,81 +258,54 @@ test('pending file reads can be cancelled without waiting for the loader timeout
|
||||
});
|
||||
|
||||
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 = [];
|
||||
const t = importViewer({
|
||||
eyeHeight: 100_000,
|
||||
hidden: () => -12311,
|
||||
clamp: (points) =>
|
||||
points.map((p) => {
|
||||
const at = toLonLatH(p);
|
||||
starts.push(at.height);
|
||||
return at.height < -9000
|
||||
? null
|
||||
: { ...p, ...fromDegreesHeight(at, 2000) };
|
||||
}),
|
||||
});
|
||||
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,
|
||||
);
|
||||
}
|
||||
const loaded = await loadGeoFile(
|
||||
new File(
|
||||
[JSON.stringify({ type: 'Point', coordinates: [1, 2] })],
|
||||
'surface.geojson',
|
||||
),
|
||||
{ viewer: t.viewer },
|
||||
);
|
||||
loaded.mount();
|
||||
const height = () => [...importSet(t, 'pins').items.values()][0].pos.height;
|
||||
assert.ok(
|
||||
Math.abs(starts.at(-1)) < 1e-6,
|
||||
`ray started at ${starts.at(-1)}`,
|
||||
);
|
||||
assert.ok(Math.abs(height() - 2000) < 1e-6);
|
||||
const sampled = starts.length;
|
||||
t.camera.viewRectangle = () => ({
|
||||
west: 10,
|
||||
south: 10,
|
||||
east: 11,
|
||||
north: 11,
|
||||
});
|
||||
await loaded.refreshGround();
|
||||
assert.equal(
|
||||
starts.length,
|
||||
sampled,
|
||||
'distant points do not start a detailed mesh sweep',
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(height() - 2000) < 1e-6,
|
||||
'the last valid mesh height survives outside the camera footprint',
|
||||
);
|
||||
loaded.revoke();
|
||||
} finally {
|
||||
Cesium.PinBuilder.prototype.fromColor = previous;
|
||||
t.unbind();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -708,7 +699,7 @@ test('distinct style definitions and named StyleMaps still have a pre-loader bud
|
||||
assert.equal(countKmlGeometry(maps, { maxLinks: 1 }).over, 'links');
|
||||
});
|
||||
|
||||
test('KML extended metadata is removed before the document reaches the loader', () => {
|
||||
test('KML extended metadata is removed before the document is read for drawing', () => {
|
||||
const point = xmlEl('Point', {}, [xmlEl('coordinates', {}, '1,2,0')]);
|
||||
const metadata = xmlEl('ExtendedData', {}, [
|
||||
xmlEl('Data', { name: 'note' }, [xmlEl('value', {}, 'ordinary metadata')]),
|
||||
@@ -809,7 +800,7 @@ test('GPX keeps each track segment as its own line, names as text, no times', ()
|
||||
assert.throws(() => gpxToGeoJson(xmlDoc(xmlEl('kml'))), GeoImportError);
|
||||
});
|
||||
|
||||
test('GPX past the point limit is refused while reading, before Cesium', () => {
|
||||
test('GPX past the point limit is refused while reading, before anything is drawn', () => {
|
||||
const seg = xmlEl(
|
||||
'trkseg',
|
||||
{},
|
||||
@@ -966,7 +957,7 @@ test('KML vertex counting recognizes the Unicode whitespace Cesium accepts', ()
|
||||
}
|
||||
});
|
||||
|
||||
test('KML multipart geometries count every Cesium entity before loading', () => {
|
||||
test('KML multipart geometries count every map object before drawing', () => {
|
||||
const doc = xmlDoc(
|
||||
xmlEl('kml', {}, [
|
||||
xmlEl('Placemark', {}, [
|
||||
@@ -1049,69 +1040,47 @@ 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('imported features keep only a short plain-text name', () => {
|
||||
const placemark = (name) =>
|
||||
xmlEl('Placemark', {}, [
|
||||
xmlEl('name', {}, name),
|
||||
xmlEl('Point', {}, [xmlEl('coordinates', {}, '1,2')]),
|
||||
]);
|
||||
const doc = xmlDoc(
|
||||
xmlEl('kml', {}, [
|
||||
xmlEl('Document', {}, [
|
||||
placemark('Trail\u0007 <b>head</b>\n' + 'x'.repeat(300)),
|
||||
placemark(' '),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
const { features } = readKmlFeatures(doc);
|
||||
assert.ok(features[0].name.startsWith('Trail <b>head</b> x'));
|
||||
assert.ok(
|
||||
features[0].name.length <= 120 && !/[\u0000-\u001f]/.test(features[0].name),
|
||||
);
|
||||
assert.equal(features[1].name, undefined);
|
||||
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('placemarks without an icon of their own share one default pin', () => {
|
||||
const doc = xmlDoc(
|
||||
xmlEl('kml', {}, [
|
||||
xmlEl(
|
||||
'Document',
|
||||
{},
|
||||
Array.from({ length: 1000 }, () =>
|
||||
xmlEl('Placemark', {}, [
|
||||
xmlEl('Point', {}, [xmlEl('coordinates', {}, '1,2')]),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
const { features } = readKmlFeatures(doc);
|
||||
assert.equal(features.length, 1000);
|
||||
assert.ok(features.every((f) => f.image === features[0].image));
|
||||
assert.match(features[0].image.svg, /rgba\(255,255,0,1\)/);
|
||||
});
|
||||
|
||||
test('unused KML time and camera metadata is removed before loading without changing geometry', () => {
|
||||
@@ -1132,47 +1101,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>';
|
||||
@@ -1263,38 +1191,26 @@ test('KML namespace repair ignores declaration text inside quoted attribute valu
|
||||
});
|
||||
|
||||
test('a failed mesh clamp fails the import instead of leaving pins at sea level', async () => {
|
||||
const previous = Cesium.PinBuilder.prototype.fromColor;
|
||||
Cesium.PinBuilder.prototype.fromColor = () => ({
|
||||
tagName: 'CANVAS',
|
||||
toDataURL: () => 'data:image/png;base64,local',
|
||||
const t = importViewer({
|
||||
eyeHeight: 100_000,
|
||||
hidden: () => 0,
|
||||
clamp: () => {
|
||||
throw new Error('tile request failed');
|
||||
},
|
||||
});
|
||||
try {
|
||||
const viewer = {
|
||||
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
|
||||
camera: {
|
||||
positionCartographic: { height: 100000 },
|
||||
computeViewRectangle: () => Cesium.Rectangle.MAX_VALUE,
|
||||
},
|
||||
scene: {
|
||||
frameState: { mode: Cesium.SceneMode.SCENE3D },
|
||||
globe: { show: false, getHeight: () => 0 },
|
||||
clampToHeightSupported: true,
|
||||
clampToHeightMostDetailed: async () => {
|
||||
throw new Error('tile request failed');
|
||||
},
|
||||
},
|
||||
};
|
||||
await assert.rejects(
|
||||
loadGeoFile(
|
||||
new File(
|
||||
[JSON.stringify({ type: 'Point', coordinates: [1, 2] })],
|
||||
'surface.geojson',
|
||||
),
|
||||
{ viewer },
|
||||
{ viewer: t.viewer },
|
||||
),
|
||||
/Ground heights could not be read/,
|
||||
);
|
||||
assert.equal(importSet(t, 'pins'), undefined);
|
||||
} finally {
|
||||
Cesium.PinBuilder.prototype.fromColor = previous;
|
||||
t.unbind();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,684 @@
|
||||
/**
|
||||
* What an imported file draws, read from its parsed KML document or its
|
||||
* prepared GeoJSON as the default renderer's KML and GeoJSON loaders read
|
||||
* them: placemark pins with their icons, colours and anchors, paths,
|
||||
* polygons, walls and ground overlays, each with its altitude mode. Plain
|
||||
* data in degrees and metres, drawn by `geoImportPins.js`.
|
||||
*
|
||||
* `entityCount` counts what those loaders made of the file (folders,
|
||||
* placemarks, each part of a multi-geometry), the number the import limit
|
||||
* is checked against. `drawable` says whether any of it can be drawn.
|
||||
*/
|
||||
import { plainPin } from './geojsonPins.js';
|
||||
import { importFeatureName } from './geoImportShared.js';
|
||||
import { cssColor } from '../render/color.js';
|
||||
|
||||
/** KML icons are drawn this many pixels square, times their scale. */
|
||||
const KML_ICON_SIZE = 32;
|
||||
/** KML icons shrink with distance: full size near, a tenth far. */
|
||||
const KML_ICON_SCALE_BY_DISTANCE = Object.freeze({
|
||||
near: 2414016,
|
||||
nearValue: 1,
|
||||
far: 1.6093e7,
|
||||
farValue: 0.1,
|
||||
});
|
||||
const WHITE = Object.freeze([1, 1, 1, 1]);
|
||||
const BLACK = Object.freeze([0, 0, 0, 1]);
|
||||
/** A placemark without an icon of its own: a yellow pin. */
|
||||
const DEFAULT_KML_PIN = plainPin([1, 1, 0, 1], 64);
|
||||
/** GeoJSON markers are pins this many pixels square, standing on the point. */
|
||||
const GEOJSON_PIN_SIZE = 48;
|
||||
|
||||
const GX = 'http://www.google.com/kml/ext/2.2';
|
||||
/** The namespaces KML elements come in: none, or a KML version's. */
|
||||
const KML_NAMESPACES = new Set([
|
||||
null,
|
||||
undefined,
|
||||
'',
|
||||
'http://www.opengis.net/kml/2.2',
|
||||
'http://earth.google.com/kml/2.2',
|
||||
'http://earth.google.com/kml/2.1',
|
||||
'http://earth.google.com/kml/2.0',
|
||||
]);
|
||||
const isGx = (el) => el.namespaceURI === GX;
|
||||
const isKml = (el) => KML_NAMESPACES.has(el.namespaceURI);
|
||||
|
||||
/** Element children of `el` with this local name, KML (not gx) unless `gx`. */
|
||||
function children(el, name, gx = false) {
|
||||
const out = [];
|
||||
const kids = el?.childNodes;
|
||||
if (!kids) return out;
|
||||
for (let i = 0; i < kids.length; i++) {
|
||||
const kid = kids[i];
|
||||
if (
|
||||
kid.nodeType === 1 &&
|
||||
kid.localName === name &&
|
||||
(gx ? isGx(kid) : isKml(kid))
|
||||
)
|
||||
out.push(kid);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const child = (el, name, gx) => children(el, name, gx)[0];
|
||||
const text = (el, name, gx) => child(el, name, gx)?.textContent.trim();
|
||||
function number(el, name, gx) {
|
||||
const value = Number.parseFloat(child(el, name, gx)?.textContent);
|
||||
return Number.isNaN(value) ? undefined : value;
|
||||
}
|
||||
function flag(el, name) {
|
||||
const value = text(el, name);
|
||||
return value === undefined
|
||||
? undefined
|
||||
: value === '1' || /^true$/i.test(value);
|
||||
}
|
||||
function attribute(el, name) {
|
||||
const value = el?.getAttribute(name);
|
||||
if (value === null || value === undefined) return undefined;
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isNaN(parsed) ? undefined : parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* A KML `aabbggrr` colour as `[r, g, b, a]`; with `colorMode` random, each
|
||||
* channel drawn at random up to its own value.
|
||||
*/
|
||||
function kmlColor(el, name = 'color') {
|
||||
let value = text(el, name);
|
||||
if (!value) return undefined;
|
||||
if (value[0] === '#') value = value.slice(1);
|
||||
const channel = (at) => Number.parseInt(value.slice(at, at + 2), 16) / 255;
|
||||
const alpha = channel(0);
|
||||
const rgb = [channel(6), channel(4), channel(2)];
|
||||
if (text(el, 'colorMode') === 'random')
|
||||
for (let i = 0; i < 3; i++)
|
||||
rgb[i] = rgb[i] > 0 ? Math.random() * rgb[i] : 0;
|
||||
return [...rgb, alpha];
|
||||
}
|
||||
|
||||
/** One `lon,lat[,height]` tuple; missing or unreadable numbers are 0. */
|
||||
function readCoordinate(value) {
|
||||
const digits = value?.match(/[^\s,\n]+/g);
|
||||
const at = (i) => {
|
||||
const n = Number.parseFloat(digits?.[i]);
|
||||
return Number.isNaN(n) ? 0 : n;
|
||||
};
|
||||
return [at(0), at(1), at(2)];
|
||||
}
|
||||
function readCoordinates(el) {
|
||||
const tuples = el?.textContent.match(/[^\s\n]+/g);
|
||||
return tuples ? tuples.map(readCoordinate) : undefined;
|
||||
}
|
||||
|
||||
/** Copy each graphic's unset properties from `from`, as styles merge. */
|
||||
function merge(into, from) {
|
||||
for (const kind of ['billboard', 'polyline', 'polygon']) {
|
||||
if (!from?.[kind]) continue;
|
||||
if (!into[kind]) into[kind] = { ...from[kind] };
|
||||
else
|
||||
for (const key of Object.keys(from[kind]))
|
||||
if (into[kind][key] === undefined) into[kind][key] = from[kind][key];
|
||||
}
|
||||
return into;
|
||||
}
|
||||
|
||||
const defaultBillboard = () => ({});
|
||||
|
||||
/** The icon, line and polygon look a `<Style>` gives, merged into `style`. */
|
||||
function applyStyle(styleEl, style) {
|
||||
if (!styleEl) return style;
|
||||
for (const node of styleEl.childNodes) {
|
||||
if (node.nodeType !== 1 || !isKml(node)) continue;
|
||||
if (node.localName === 'IconStyle') {
|
||||
const billboard = (style.billboard ??= defaultBillboard());
|
||||
const icon = child(node, 'Icon');
|
||||
const href = text(icon, 'href');
|
||||
// An empty <Icon> draws no icon; none at all, the default pin.
|
||||
billboard.image = href ? href : icon ? false : undefined;
|
||||
const scale = number(node, 'scale');
|
||||
billboard.scale = scale;
|
||||
billboard.color = kmlColor(node);
|
||||
const heading = number(node, 'heading');
|
||||
// Heading 0 is no heading; north is 360.
|
||||
if (heading !== undefined && heading !== 0) billboard.course = heading;
|
||||
const spot = child(node, 'hotSpot');
|
||||
const x = attribute(spot, 'x');
|
||||
const y = attribute(spot, 'y');
|
||||
const s = scale ?? 1;
|
||||
let dx;
|
||||
let dy;
|
||||
if (x !== undefined) {
|
||||
// Units left out are a fraction, as KML has it.
|
||||
const units = spot.getAttribute('xunits') || 'fraction';
|
||||
if (units === 'pixels') dx = -x * s;
|
||||
else if (units === 'insetPixels') dx = (x - KML_ICON_SIZE) * s;
|
||||
else if (units === 'fraction') dx = -x * KML_ICON_SIZE * s;
|
||||
if (dx !== undefined) dx += KML_ICON_SIZE * 0.5 * s;
|
||||
else dx = Number.NaN;
|
||||
}
|
||||
if (y !== undefined) {
|
||||
const units = spot.getAttribute('yunits') || 'fraction';
|
||||
if (units === 'pixels') dy = y * s;
|
||||
else if (units === 'insetPixels') dy = (-y + KML_ICON_SIZE) * s;
|
||||
else if (units === 'fraction') dy = y * KML_ICON_SIZE * s;
|
||||
if (dy !== undefined) dy -= KML_ICON_SIZE * 0.5 * s;
|
||||
else dy = Number.NaN;
|
||||
}
|
||||
if (dx !== undefined || dy !== undefined)
|
||||
billboard.pixelOffset = {
|
||||
x: Number.isFinite(dx) ? dx : 0,
|
||||
y: Number.isFinite(dy) ? dy : 0,
|
||||
};
|
||||
} else if (node.localName === 'LineStyle') {
|
||||
const polyline = (style.polyline ??= {});
|
||||
polyline.width = number(node, 'width');
|
||||
polyline.color = kmlColor(node);
|
||||
} else if (node.localName === 'PolyStyle') {
|
||||
const polygon = (style.polygon ??= { outline: true });
|
||||
polygon.color = kmlColor(node) ?? polygon.color;
|
||||
polygon.fill = flag(node, 'fill') ?? polygon.fill;
|
||||
polygon.outline = flag(node, 'outline') ?? polygon.outline;
|
||||
}
|
||||
}
|
||||
return style;
|
||||
}
|
||||
|
||||
/**
|
||||
* The document's shared styles by `#id`: each `<Style>` with an id, then
|
||||
* each `<StyleMap>` as its normal pair; the first of an id wins.
|
||||
*/
|
||||
function sharedStyles(doc) {
|
||||
const styles = new Map();
|
||||
for (const el of doc.getElementsByTagName('*')) {
|
||||
if (el.localName !== 'Style' || !isKml(el)) continue;
|
||||
const id = el.getAttribute('id');
|
||||
if (id && !styles.has(`#${id}`)) styles.set(`#${id}`, applyStyle(el, {}));
|
||||
}
|
||||
for (const el of doc.getElementsByTagName('*')) {
|
||||
if (el.localName !== 'StyleMap' || !isKml(el)) continue;
|
||||
const id = el.getAttribute('id');
|
||||
if (!id || styles.has(`#${id}`)) continue;
|
||||
for (const pair of children(el, 'Pair')) {
|
||||
if (text(pair, 'key') !== 'normal') continue;
|
||||
const style = {};
|
||||
let url = text(pair, 'styleUrl');
|
||||
if (url !== undefined) {
|
||||
if (url[0] !== '#') url = `#${url}`;
|
||||
merge(style, styles.get(url));
|
||||
} else applyStyle(child(pair, 'Style'), style);
|
||||
styles.set(`#${id}`, style);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return styles;
|
||||
}
|
||||
|
||||
/** A feature's own style: its last inline Style or StyleMap, then its styleUrl. */
|
||||
function finalStyle(feature, styles) {
|
||||
const style = {};
|
||||
const lookup = (url) => styles.get(url) ?? styles.get(`#${url}`);
|
||||
let inline;
|
||||
for (const node of feature.childNodes)
|
||||
if (
|
||||
node.nodeType === 1 &&
|
||||
isKml(node) &&
|
||||
(node.localName === 'Style' || node.localName === 'StyleMap')
|
||||
)
|
||||
inline = node;
|
||||
if (inline?.localName === 'Style') applyStyle(inline, style);
|
||||
else if (inline)
|
||||
for (const pair of children(inline, 'Pair')) {
|
||||
if (text(pair, 'key') !== 'normal') continue;
|
||||
const url = text(pair, 'styleUrl');
|
||||
if (url !== undefined) merge(style, lookup(url));
|
||||
else applyStyle(child(pair, 'Style'), style);
|
||||
}
|
||||
const url = text(feature, 'styleUrl');
|
||||
if (url !== undefined) merge(style, lookup(url));
|
||||
return style;
|
||||
}
|
||||
|
||||
const extrudable = (mode, gxMode) =>
|
||||
mode === 'absolute' ||
|
||||
mode === 'relativeToGround' ||
|
||||
gxMode === 'relativeToSeaFloor';
|
||||
|
||||
/** How a point stands: on the ground, above it, or at its own height. */
|
||||
function pinHeightMode(mode, gxMode) {
|
||||
if ((!mode && !gxMode) || mode === 'clampToGround') return 'clamp';
|
||||
if (mode === 'relativeToGround') return 'relative';
|
||||
if (mode === 'absolute') return 'absolute';
|
||||
if (gxMode === 'relativeToSeaFloor') return 'relative';
|
||||
return 'clamp';
|
||||
}
|
||||
|
||||
/** A placemark pin as a KML point draws it. */
|
||||
function kmlPin(name, style, at, mode) {
|
||||
const billboard = style.billboard ?? defaultBillboard();
|
||||
const image =
|
||||
billboard.image === undefined
|
||||
? DEFAULT_KML_PIN
|
||||
: billboard.image === false
|
||||
? null
|
||||
: billboard.image;
|
||||
return {
|
||||
kind: 'pin',
|
||||
name,
|
||||
lon: at?.[0],
|
||||
lat: at?.[1],
|
||||
height: at?.[2] ?? 0,
|
||||
mode,
|
||||
image,
|
||||
size: [KML_ICON_SIZE, KML_ICON_SIZE],
|
||||
scale: billboard.scale,
|
||||
color: billboard.color,
|
||||
course: billboard.course,
|
||||
pixelOffset: billboard.pixelOffset,
|
||||
scaleByDistance: KML_ICON_SCALE_BY_DISTANCE,
|
||||
};
|
||||
}
|
||||
|
||||
/** One KML geometry element of a placemark as features; false for none. */
|
||||
function kmlGeometry(el, name, style, out) {
|
||||
const mode = text(el, 'altitudeMode');
|
||||
const gxMode = text(el, 'altitudeMode', true);
|
||||
const canExtrude = extrudable(mode, gxMode);
|
||||
const extrude = flag(el, 'extrude');
|
||||
switch (el.localName) {
|
||||
case 'Point': {
|
||||
out.push(
|
||||
kmlPin(
|
||||
name,
|
||||
style,
|
||||
readCoordinate(text(el, 'coordinates')),
|
||||
pinHeightMode(mode, gxMode),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
case 'LineString':
|
||||
case 'LinearRing': {
|
||||
const coords = readCoordinates(child(el, 'coordinates'));
|
||||
const line = style.polyline;
|
||||
if (canExtrude && extrude) {
|
||||
const polygon = style.polygon;
|
||||
out.push({
|
||||
kind: 'wall',
|
||||
name,
|
||||
coords,
|
||||
fill: polygon?.fill === false ? null : (polygon?.color ?? WHITE),
|
||||
outline: line
|
||||
? (line.color ?? WHITE)
|
||||
: polygon
|
||||
? (polygon.color ?? WHITE)
|
||||
: BLACK,
|
||||
outlineWidth: line?.width,
|
||||
});
|
||||
} else if (!canExtrude && flag(el, 'tessellate')) {
|
||||
out.push({
|
||||
kind: 'line',
|
||||
name,
|
||||
coords,
|
||||
mode: 'draped',
|
||||
color: line?.color ?? WHITE,
|
||||
width: line?.width ?? 1,
|
||||
});
|
||||
} else {
|
||||
// Straight in space: at the heights given where the altitude mode
|
||||
// allows, otherwise on the ellipsoid (a clamped line the import did
|
||||
// not tessellate, such as one with an explicit tessellate 0).
|
||||
out.push({
|
||||
kind: 'line',
|
||||
name,
|
||||
coords: canExtrude
|
||||
? coords
|
||||
: coords?.map(([lon, lat]) => [lon, lat, 0]),
|
||||
mode: '3d',
|
||||
color: line?.color ?? WHITE,
|
||||
width: line?.width ?? 1,
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case 'Polygon': {
|
||||
const ring = (boundary) =>
|
||||
readCoordinates(child(child(boundary, 'LinearRing'), 'coordinates'));
|
||||
const outer = ring(child(el, 'outerBoundaryIs'));
|
||||
const holes = [];
|
||||
for (const inner of children(el, 'innerBoundaryIs'))
|
||||
for (const linear of children(inner, 'LinearRing')) {
|
||||
const coords = readCoordinates(child(linear, 'coordinates'));
|
||||
if (coords) holes.push(coords);
|
||||
}
|
||||
const polygon = style.polygon ?? { outline: true };
|
||||
const line = style.polyline;
|
||||
out.push({
|
||||
kind: 'polygon',
|
||||
name,
|
||||
rings: outer ? [outer, ...holes] : [],
|
||||
clamp: !canExtrude,
|
||||
extrude: canExtrude && extrude === true,
|
||||
fill: polygon.fill === false ? null : (polygon.color ?? WHITE),
|
||||
outline:
|
||||
polygon.outline === false
|
||||
? null
|
||||
: line
|
||||
? (line.color ?? WHITE)
|
||||
: WHITE,
|
||||
outlineWidth: line?.width,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
case 'MultiGeometry': {
|
||||
let any = false;
|
||||
for (const part of el.childNodes) {
|
||||
if (part.nodeType !== 1 || !KML_GEOMETRIES.has(part.localName))
|
||||
continue;
|
||||
// Each part is a map object of its own, named as its placemark.
|
||||
out.entities += 1;
|
||||
if (kmlGeometry(part, name, style, out)) any = true;
|
||||
}
|
||||
return any;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const KML_GEOMETRIES = new Set([
|
||||
'Point',
|
||||
'LineString',
|
||||
'LinearRing',
|
||||
'Polygon',
|
||||
'MultiGeometry',
|
||||
'Model',
|
||||
'Track',
|
||||
'MultiTrack',
|
||||
]);
|
||||
|
||||
/** A ground overlay: an image (or colour) on a box or a quad. */
|
||||
function kmlOverlay(el, name, out) {
|
||||
const quad = readCoordinates(child(el, 'LatLonQuad', true));
|
||||
const href = text(child(el, 'Icon'), 'href') || null;
|
||||
const color = kmlColor(el);
|
||||
const mode = text(el, 'altitudeMode');
|
||||
const gxMode = text(el, 'altitudeMode', true);
|
||||
const height =
|
||||
mode === 'absolute' || (!mode && gxMode === 'relativeToSeaFloor')
|
||||
? number(el, 'altitude')
|
||||
: undefined;
|
||||
let rect = null;
|
||||
let rotation;
|
||||
const box = quad ? null : child(el, 'LatLonBox');
|
||||
// Neither box nor quad: nowhere to draw it, as before.
|
||||
if (box) {
|
||||
// Missing bounds are 0; longitudes wrap into [-180, 180].
|
||||
const wrap = (lon = 0) =>
|
||||
lon >= -180 && lon <= 180
|
||||
? lon
|
||||
: ((((lon + 180) % 360) + 360) % 360) - 180;
|
||||
const clampLat = (lat = 0) => Math.max(-90, Math.min(90, lat));
|
||||
rect = {
|
||||
west: wrap(number(box, 'west')),
|
||||
south: clampLat(number(box, 'south')),
|
||||
east: wrap(number(box, 'east')),
|
||||
north: clampLat(number(box, 'north')),
|
||||
};
|
||||
// A box upside down has no area to draw (Cesium refused it too).
|
||||
if (rect.north < rect.south) rect = null;
|
||||
const turn = number(box, 'rotation');
|
||||
if (turn !== undefined) rotation = (turn * Math.PI) / 180;
|
||||
}
|
||||
out.push({
|
||||
kind: 'overlay',
|
||||
name,
|
||||
rect,
|
||||
quad,
|
||||
rotation,
|
||||
image: href,
|
||||
// Without an image, the overlay's colour; an image is drawn untinted.
|
||||
color: href ? undefined : (color ?? WHITE),
|
||||
height,
|
||||
});
|
||||
}
|
||||
|
||||
/** A feature's short plain-text name, or undefined. */
|
||||
function featureName(el) {
|
||||
try {
|
||||
return importFeatureName(text(el, 'name'));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The features of a sanitized KML document.
|
||||
* @param {Document} doc
|
||||
* @returns {{features: object[], entityCount: number, drawable: boolean}}
|
||||
*/
|
||||
export function readKmlFeatures(doc) {
|
||||
const styles = sharedStyles(doc);
|
||||
const out = [];
|
||||
out.entities = 0;
|
||||
let positionless = false;
|
||||
const visit = (node) => {
|
||||
switch (node.localName) {
|
||||
case 'Document':
|
||||
for (const kid of node.childNodes) if (kid.nodeType === 1) visit(kid);
|
||||
return;
|
||||
case 'Folder':
|
||||
out.entities += 1;
|
||||
for (const kid of node.childNodes) if (kid.nodeType === 1) visit(kid);
|
||||
return;
|
||||
case 'Placemark': {
|
||||
out.entities += 1;
|
||||
const name = featureName(node);
|
||||
const style = finalStyle(node, styles);
|
||||
// Only the first geometry of a placemark is drawn.
|
||||
const geometry = [...node.childNodes].find(
|
||||
(kid) => kid.nodeType === 1 && KML_GEOMETRIES.has(kid.localName),
|
||||
);
|
||||
if (geometry) kmlGeometry(geometry, name, style, out);
|
||||
else {
|
||||
// No geometry: an icon with nowhere to stand.
|
||||
const pin = kmlPin(name, style, null, 'absolute');
|
||||
if (pin.image) positionless = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'GroundOverlay':
|
||||
out.entities += 1;
|
||||
kmlOverlay(node, featureName(node), out);
|
||||
return;
|
||||
default:
|
||||
}
|
||||
};
|
||||
let root = doc.documentElement;
|
||||
if (root?.localName === 'kml')
|
||||
root = [...root.childNodes].find(
|
||||
(kid) =>
|
||||
kid.nodeType === 1 &&
|
||||
['Document', 'Folder', 'Placemark', 'GroundOverlay'].includes(
|
||||
kid.localName,
|
||||
),
|
||||
);
|
||||
if (root) visit(root);
|
||||
const entityCount = out.entities;
|
||||
const features = [...out];
|
||||
return {
|
||||
features,
|
||||
entityCount,
|
||||
drawable: positionless || features.some(drawable),
|
||||
};
|
||||
}
|
||||
|
||||
/** The longest step, in degrees, of a rhumb line drawn as a path. */
|
||||
const RHUMB_STEP = 0.5;
|
||||
/**
|
||||
* The most points the steps may add to one file, as many as it may hold
|
||||
* (`MAX_IMPORT_POSITIONS`); past it, the rest are drawn as they are.
|
||||
*/
|
||||
const RHUMB_BUDGET = 250_000;
|
||||
const mercatorY = (lat) =>
|
||||
Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360));
|
||||
const fromMercatorY = (y) => (Math.atan(Math.sinh(y)) * 180) / Math.PI;
|
||||
|
||||
/**
|
||||
* A path along rhumb lines, as GeoJSON is drawn: each long step split at
|
||||
* most `RHUMB_STEP` degrees apart along the line of constant bearing (the
|
||||
* draw port joins points the short way over the globe), the short way
|
||||
* round in longitude. Steps are added while `budget.left` allows.
|
||||
* @param {number[][]} coords `[lon, lat, height]`
|
||||
* @param {{left: number}} [budget] Points it may still add, shared by a file.
|
||||
* @returns {number[][]}
|
||||
*/
|
||||
export function rhumbPath(coords, budget = { left: RHUMB_BUDGET }) {
|
||||
const out = [];
|
||||
for (let i = 0; i < coords.length; i++) {
|
||||
const b = coords[i];
|
||||
const a = coords[i - 1];
|
||||
if (a) {
|
||||
const dLon = ((((b[0] - a[0] + 180) % 360) + 360) % 360) - 180;
|
||||
const steps = Math.ceil(
|
||||
Math.max(Math.abs(dLon), Math.abs(b[1] - a[1])) / RHUMB_STEP,
|
||||
);
|
||||
if (
|
||||
steps > 1 &&
|
||||
steps - 1 <= budget.left &&
|
||||
Math.abs(a[1]) < 89.9 &&
|
||||
Math.abs(b[1]) < 89.9
|
||||
) {
|
||||
budget.left -= steps - 1;
|
||||
const ya = mercatorY(a[1]);
|
||||
const yb = mercatorY(b[1]);
|
||||
for (let k = 1; k < steps; k++) {
|
||||
const f = k / steps;
|
||||
let lon = a[0] + dLon * f;
|
||||
if (lon > 180) lon -= 360;
|
||||
else if (lon < -180) lon += 360;
|
||||
out.push([
|
||||
lon,
|
||||
fromMercatorY(ya + (yb - ya) * f),
|
||||
a[2] + (b[2] - a[2]) * f,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(b);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether a feature draws anything, as the loaders' output is checked. */
|
||||
function drawable(feature) {
|
||||
switch (feature.kind) {
|
||||
case 'pin':
|
||||
return Boolean(feature.image);
|
||||
case 'line':
|
||||
case 'wall':
|
||||
return (feature.coords?.length ?? 0) >= 2;
|
||||
case 'polygon':
|
||||
return (feature.rings[0]?.length ?? 0) >= 3;
|
||||
case 'overlay':
|
||||
// Counted as before even without bounds, though it then draws nothing.
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The features of prepared GeoJSON (names only, two-dimensional
|
||||
* coordinates), drawn in one colour: pins in it standing on the ground,
|
||||
* lines draped in it three pixels wide, polygons filled with it at a
|
||||
* quarter opacity.
|
||||
* @param {object} geojson
|
||||
* @param {string} color A CSS colour.
|
||||
* @returns {{features: object[], entityCount: number, drawable: boolean}}
|
||||
*/
|
||||
export function readGeoJsonFeatures(geojson, color) {
|
||||
const rgba = cssColor(color) ?? [...WHITE];
|
||||
const fill = [rgba[0], rgba[1], rgba[2], 0.25];
|
||||
const pin = plainPin(rgba, GEOJSON_PIN_SIZE);
|
||||
const features = [];
|
||||
let entityCount = 0;
|
||||
const at = (c) => [c[0], c[1], c[2] ?? 0];
|
||||
const geometry = (g, name) => {
|
||||
switch (g?.type) {
|
||||
case 'Point':
|
||||
entityCount += 1;
|
||||
features.push(geoPin(name, g.coordinates));
|
||||
return;
|
||||
case 'MultiPoint':
|
||||
for (const c of g.coordinates) {
|
||||
entityCount += 1;
|
||||
features.push(geoPin(name, c));
|
||||
}
|
||||
return;
|
||||
case 'LineString':
|
||||
entityCount += 1;
|
||||
features.push(geoLine(name, g.coordinates));
|
||||
return;
|
||||
case 'MultiLineString':
|
||||
for (const c of g.coordinates) {
|
||||
entityCount += 1;
|
||||
features.push(geoLine(name, c));
|
||||
}
|
||||
return;
|
||||
case 'Polygon':
|
||||
entityCount += 1;
|
||||
features.push(geoPolygon(name, g.coordinates));
|
||||
return;
|
||||
case 'MultiPolygon':
|
||||
for (const c of g.coordinates) {
|
||||
entityCount += 1;
|
||||
features.push(geoPolygon(name, c));
|
||||
}
|
||||
return;
|
||||
case 'GeometryCollection':
|
||||
for (const part of g.geometries) geometry(part, name);
|
||||
return;
|
||||
default:
|
||||
}
|
||||
};
|
||||
const geoPin = (name, c) => ({
|
||||
kind: 'pin',
|
||||
name,
|
||||
lon: c[0],
|
||||
lat: c[1],
|
||||
height: c[2] ?? 0,
|
||||
mode: c.length > 2 ? 'absolute' : 'clamp',
|
||||
image: pin,
|
||||
size: [GEOJSON_PIN_SIZE, GEOJSON_PIN_SIZE],
|
||||
anchor: 'bottom',
|
||||
});
|
||||
const budget = { left: RHUMB_BUDGET };
|
||||
const geoLine = (name, coords) => ({
|
||||
kind: 'line',
|
||||
name,
|
||||
coords: rhumbPath(coords.map(at), budget),
|
||||
mode: 'draped',
|
||||
color: rgba,
|
||||
width: 3,
|
||||
});
|
||||
const geoPolygon = (name, rings) => ({
|
||||
kind: 'polygon',
|
||||
name,
|
||||
rings: rings.map((ring) => rhumbPath(ring.map(at), budget)),
|
||||
clamp: true,
|
||||
extrude: false,
|
||||
fill,
|
||||
outline: null,
|
||||
});
|
||||
const feature = (f) => {
|
||||
if (f.geometry === null) {
|
||||
// A feature without geometry is a map object that draws nothing.
|
||||
entityCount += 1;
|
||||
return;
|
||||
}
|
||||
geometry(f.geometry, f.properties?.name || undefined);
|
||||
};
|
||||
if (geojson?.type === 'FeatureCollection')
|
||||
for (const f of geojson.features) feature(f);
|
||||
else if (geojson?.type === 'Feature') feature(geojson);
|
||||
else geometry(geojson, undefined);
|
||||
return { features, entityCount, drawable: features.some(drawable) };
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Window } from 'happy-dom';
|
||||
import {
|
||||
readGeoJsonFeatures,
|
||||
readKmlFeatures,
|
||||
rhumbPath,
|
||||
} from './geoImportFeatures.js';
|
||||
|
||||
const { DOMParser } = new Window();
|
||||
|
||||
/** A KML document around `body`, parsed. */
|
||||
const kml = (body) =>
|
||||
new DOMParser().parseFromString(
|
||||
'<?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>`,
|
||||
'application/xml',
|
||||
);
|
||||
|
||||
const point = (coordinates = '1,2,0', extra = '') =>
|
||||
`<Point>${extra}<coordinates>${coordinates}</coordinates></Point>`;
|
||||
|
||||
test('a placemark takes its last inline style over its shared one, property by property', () => {
|
||||
const { features } = readKmlFeatures(
|
||||
kml(`
|
||||
<Style id="shared">
|
||||
<IconStyle><scale>2</scale><color>ff0000ff</color>
|
||||
<Icon><href>data:image/png;base64,AAAA</href></Icon></IconStyle>
|
||||
</Style>
|
||||
<StyleMap id="map">
|
||||
<Pair><key>normal</key><styleUrl>#shared</styleUrl></Pair>
|
||||
<Pair><key>highlight</key><styleUrl>#other</styleUrl></Pair>
|
||||
</StyleMap>
|
||||
<Placemark><name>shared</name><styleUrl>#map</styleUrl>${point()}</Placemark>
|
||||
<Placemark><name>inline</name><styleUrl>#shared</styleUrl>
|
||||
<Style><IconStyle><color>ff00ff00</color></IconStyle></Style>
|
||||
<Style><IconStyle><scale>0.5</scale></IconStyle></Style>
|
||||
${point()}</Placemark>
|
||||
<Placemark><name>none</name><Style><IconStyle><Icon/></IconStyle></Style>${point()}</Placemark>
|
||||
<Placemark><name>default</name>${point()}</Placemark>`),
|
||||
);
|
||||
const [shared, inline, none, fallback] = features;
|
||||
assert.equal(shared.image, 'data:image/png;base64,AAAA');
|
||||
assert.equal(shared.scale, 2);
|
||||
assert.deepEqual(shared.color, [1, 0, 0, 1], 'aabbggrr is red');
|
||||
// Only the last inline style counts; the shared one fills what it leaves.
|
||||
assert.equal(inline.scale, 0.5);
|
||||
assert.deepEqual(inline.color, [1, 0, 0, 1]);
|
||||
assert.equal(inline.image, 'data:image/png;base64,AAAA');
|
||||
assert.equal(none.image, null, 'an empty Icon draws no icon');
|
||||
assert.match(fallback.image.svg, /rgba\(255,255,0,1\)/, 'the yellow pin');
|
||||
for (const f of features) {
|
||||
assert.deepEqual(f.size, [32, 32]);
|
||||
assert.deepEqual(f.scaleByDistance, {
|
||||
near: 2414016,
|
||||
nearValue: 1,
|
||||
far: 1.6093e7,
|
||||
farValue: 0.1,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('an icon hot spot and heading place and turn the icon', () => {
|
||||
const { features } = readKmlFeatures(
|
||||
kml(`
|
||||
<Placemark><Style><IconStyle><scale>0.8</scale><heading>90</heading>
|
||||
<hotSpot x="0.5" y="0" xunits="fraction" yunits="fraction"/>
|
||||
</IconStyle></Style>${point()}</Placemark>
|
||||
<Placemark><Style><IconStyle><heading>0</heading>
|
||||
<hotSpot x="4" y="8" xunits="pixels" yunits="insetPixels"/>
|
||||
</IconStyle></Style>${point()}</Placemark>`),
|
||||
);
|
||||
// Standing on its bottom centre: up by half its 25.6 px height.
|
||||
assert.deepEqual(features[0].pixelOffset, { x: 0, y: -12.8 });
|
||||
assert.equal(features[0].course, 90);
|
||||
assert.deepEqual(features[1].pixelOffset, { x: 12, y: 8 });
|
||||
assert.equal(features[1].course, undefined, 'heading 0 is no heading');
|
||||
});
|
||||
|
||||
test('points, paths and polygons keep their altitude modes', () => {
|
||||
const { features } = readKmlFeatures(
|
||||
kml(`
|
||||
<Style id="s"><LineStyle><color>ff00ffff</color><width>6</width></LineStyle>
|
||||
<PolyStyle><color>66ff0000</color></PolyStyle></Style>
|
||||
<Placemark>${point('1,2,30')}</Placemark>
|
||||
<Placemark>${point('1,2,30', '<altitudeMode>relativeToGround</altitudeMode>')}</Placemark>
|
||||
<Placemark>${point('1,2,30', '<altitudeMode>absolute</altitudeMode>')}</Placemark>
|
||||
<Placemark><styleUrl>#s</styleUrl><LineString><tessellate>1</tessellate>
|
||||
<coordinates>1,2 3,4</coordinates></LineString></Placemark>
|
||||
<Placemark><styleUrl>#s</styleUrl><LineString><tessellate>1</tessellate>
|
||||
<altitudeMode>absolute</altitudeMode><coordinates>1,2,600 3,4,900</coordinates></LineString></Placemark>
|
||||
<Placemark><styleUrl>#s</styleUrl><LineString><extrude>1</extrude>
|
||||
<altitudeMode>relativeToGround</altitudeMode><coordinates>1,2,150 3,4,150</coordinates></LineString></Placemark>
|
||||
<Placemark><styleUrl>#s</styleUrl><Polygon><outerBoundaryIs><LinearRing>
|
||||
<coordinates>0,0 1,0 1,1 0,0</coordinates></LinearRing></outerBoundaryIs>
|
||||
<innerBoundaryIs><LinearRing><coordinates>0.1,0.1 0.2,0.1 0.2,0.2 0.1,0.1</coordinates></LinearRing></innerBoundaryIs>
|
||||
</Polygon></Placemark>
|
||||
<Placemark><Polygon><extrude>1</extrude><altitudeMode>absolute</altitudeMode>
|
||||
<outerBoundaryIs><LinearRing><coordinates>0,0,200 1,0,200 1,1,200 0,0,200</coordinates></LinearRing></outerBoundaryIs>
|
||||
</Polygon></Placemark>
|
||||
<Placemark><Style><PolyStyle><fill>0</fill><outline>0</outline></PolyStyle></Style>
|
||||
<Polygon><outerBoundaryIs><LinearRing><coordinates>0,0 1,0 1,1 0,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>`),
|
||||
);
|
||||
const [
|
||||
clamped,
|
||||
relative,
|
||||
absolute,
|
||||
draped,
|
||||
inAir,
|
||||
wall,
|
||||
ground,
|
||||
block,
|
||||
bare,
|
||||
] = features;
|
||||
assert.deepEqual(
|
||||
[clamped.mode, relative.mode, absolute.mode],
|
||||
['clamp', 'relative', 'absolute'],
|
||||
);
|
||||
assert.equal(relative.height, 30);
|
||||
assert.deepEqual(
|
||||
[draped.mode, draped.width, draped.color],
|
||||
['draped', 6, [1, 1, 0, 1]],
|
||||
);
|
||||
assert.deepEqual([inAir.mode, inAir.coords[1]], ['3d', [3, 4, 900]]);
|
||||
assert.equal(wall.kind, 'wall');
|
||||
assert.deepEqual(wall.fill, [0, 0, 1, 0x66 / 255]);
|
||||
assert.deepEqual(wall.outline, [1, 1, 0, 1], 'outlined in its line colour');
|
||||
assert.equal(wall.outlineWidth, 6);
|
||||
assert.equal(ground.clamp, true);
|
||||
assert.equal(ground.rings.length, 2, 'with its hole');
|
||||
assert.deepEqual(ground.fill, [0, 0, 1, 0x66 / 255]);
|
||||
assert.equal(block.clamp, false);
|
||||
assert.equal(block.extrude, true);
|
||||
assert.deepEqual(block.fill, [1, 1, 1, 1], 'white by default');
|
||||
assert.deepEqual(block.outline, [1, 1, 1, 1]);
|
||||
assert.equal(bare.fill, null);
|
||||
assert.equal(bare.outline, null);
|
||||
});
|
||||
|
||||
test('ground overlays are boxes turned by their rotation, or quads', () => {
|
||||
const { features, drawable } = readKmlFeatures(
|
||||
kml(`
|
||||
<GroundOverlay><name>box</name><Icon><href>blob:packed</href></Icon>
|
||||
<altitudeMode>absolute</altitudeMode><altitude>120</altitude>
|
||||
<LatLonBox><north>2</north><south>1</south><east>200</east><west>-10</west>
|
||||
<rotation>20</rotation></LatLonBox></GroundOverlay>
|
||||
<GroundOverlay><color>80ff0000</color>
|
||||
<gx:LatLonQuad><coordinates>0,0 1,0 1,1 0,1</coordinates></gx:LatLonQuad></GroundOverlay>`),
|
||||
);
|
||||
const [box, quad] = features;
|
||||
assert.equal(drawable, true);
|
||||
assert.deepEqual(box.rect, { west: -10, south: 1, east: -160, north: 2 });
|
||||
assert.ok(Math.abs(box.rotation - (20 * Math.PI) / 180) < 1e-12);
|
||||
assert.equal(box.image, 'blob:packed');
|
||||
assert.equal(box.color, undefined, 'an image is drawn untinted');
|
||||
assert.equal(box.height, 120);
|
||||
assert.equal(quad.quad.length, 4);
|
||||
assert.deepEqual(quad.color, [0, 0, 1, 128 / 255]);
|
||||
assert.equal(quad.height, undefined, 'on the ground');
|
||||
});
|
||||
|
||||
test('map objects are counted as before: folders, placemarks and each part', () => {
|
||||
const read = readKmlFeatures(
|
||||
kml(`
|
||||
<Folder><name>f</name>
|
||||
<Placemark><MultiGeometry>${point()}<LineString><coordinates>1,2 3,4</coordinates></LineString>
|
||||
<MultiGeometry>${point()}</MultiGeometry></MultiGeometry></Placemark>
|
||||
<Placemark><name>only the first geometry</name>${point()}${point('5,6')}</Placemark>
|
||||
</Folder>
|
||||
<Placemark><name>nowhere</name></Placemark>`),
|
||||
);
|
||||
// Folder, two placemarks and the empty one, three parts and one nested.
|
||||
assert.equal(read.entityCount, 8);
|
||||
assert.deepEqual(
|
||||
read.features.map((f) => f.kind),
|
||||
['pin', 'line', 'pin', 'pin'],
|
||||
);
|
||||
assert.deepEqual([read.features[3].lon, read.features[3].lat], [1, 2]);
|
||||
assert.equal(read.drawable, true);
|
||||
assert.equal(
|
||||
readKmlFeatures(
|
||||
kml(
|
||||
'<Placemark><Style><IconStyle><Icon/></IconStyle></Style></Placemark>',
|
||||
),
|
||||
).drawable,
|
||||
false,
|
||||
'a placemark with no icon and nowhere to stand draws nothing',
|
||||
);
|
||||
});
|
||||
|
||||
test('GeoJSON draws in one colour: pins on the ground, draped lines, quarter fills', () => {
|
||||
const read = readGeoJsonFeatures(
|
||||
{
|
||||
type: 'FeatureCollection',
|
||||
features: [
|
||||
{
|
||||
type: 'Feature',
|
||||
properties: { name: 'a' },
|
||||
geometry: {
|
||||
type: 'MultiPoint',
|
||||
coordinates: [
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'Feature',
|
||||
properties: {},
|
||||
geometry: {
|
||||
type: 'LineString',
|
||||
coordinates: [
|
||||
[1, 2],
|
||||
[3, 4],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'Feature',
|
||||
properties: {},
|
||||
geometry: {
|
||||
type: 'MultiPolygon',
|
||||
coordinates: [
|
||||
[
|
||||
[
|
||||
[0, 0],
|
||||
[1, 0],
|
||||
[1, 1],
|
||||
[0, 0],
|
||||
],
|
||||
],
|
||||
[
|
||||
[
|
||||
[2, 2],
|
||||
[3, 2],
|
||||
[3, 3],
|
||||
[2, 2],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'Feature',
|
||||
properties: {},
|
||||
geometry: {
|
||||
type: 'GeometryCollection',
|
||||
geometries: [{ type: 'Point', coordinates: [5, 6] }],
|
||||
},
|
||||
},
|
||||
{ type: 'Feature', properties: {}, geometry: null },
|
||||
],
|
||||
},
|
||||
'#39d0ff',
|
||||
);
|
||||
assert.equal(read.entityCount, 7);
|
||||
const [a, b, line, p1, p2, gc] = read.features;
|
||||
assert.equal(a.name, 'a');
|
||||
assert.deepEqual([a.mode, a.anchor, a.size], ['clamp', 'bottom', [48, 48]]);
|
||||
assert.equal(a.image, b.image, 'one pin image for the file');
|
||||
assert.deepEqual([line.mode, line.width], ['draped', 3]);
|
||||
assert.deepEqual(line.color, [0x39 / 255, 0xd0 / 255, 1, 1]);
|
||||
assert.deepEqual(p1.fill, [0x39 / 255, 0xd0 / 255, 1, 0.25]);
|
||||
assert.equal(p1.outline, null);
|
||||
assert.equal(p2.clamp, true);
|
||||
assert.equal(gc.kind, 'pin');
|
||||
assert.equal(read.drawable, true);
|
||||
});
|
||||
|
||||
test('a ground overlay without bounds, or upside down, draws nowhere', () => {
|
||||
const { features, drawable } = readKmlFeatures(
|
||||
kml(`
|
||||
<GroundOverlay><color>ff00ff00</color></GroundOverlay>
|
||||
<GroundOverlay><color>ff00ff00</color>
|
||||
<LatLonBox><north>1</north><south>2</south><east>3</east><west>4</west></LatLonBox></GroundOverlay>`),
|
||||
);
|
||||
assert.deepEqual(
|
||||
features.map((f) => [f.kind, f.rect, f.quad]),
|
||||
[
|
||||
['overlay', null, undefined],
|
||||
['overlay', null, undefined],
|
||||
],
|
||||
);
|
||||
assert.equal(drawable, true, 'counted as before');
|
||||
});
|
||||
|
||||
test('a hot spot without units is a fraction', () => {
|
||||
const { features } = readKmlFeatures(
|
||||
kml(
|
||||
`<Placemark><Style><IconStyle><hotSpot x="0.5" y="0"/></IconStyle></Style>${point()}</Placemark>`,
|
||||
),
|
||||
);
|
||||
assert.deepEqual(features[0].pixelOffset, { x: 0, y: -16 });
|
||||
});
|
||||
|
||||
test('GeoJSON lines and rings follow rhumb lines, as they were drawn', () => {
|
||||
const path = rhumbPath([
|
||||
[0, 60, 0],
|
||||
[10, 60, 0],
|
||||
]);
|
||||
assert.equal(path.length, 21, 'half a degree apart');
|
||||
assert.ok(
|
||||
path.every(([, lat]) => Math.abs(lat - 60) < 1e-9),
|
||||
'along the parallel',
|
||||
);
|
||||
const across = rhumbPath([
|
||||
[179, 0, 0],
|
||||
[-179, 0, 0],
|
||||
]);
|
||||
assert.deepEqual(
|
||||
across.map(([lon]) => lon),
|
||||
[179, 179.5, 180, -179.5, -179],
|
||||
'the short way over the antimeridian',
|
||||
);
|
||||
const short = rhumbPath([
|
||||
[0, 0, 0],
|
||||
[0.2, 0.2, 0],
|
||||
]);
|
||||
assert.equal(short.length, 2, 'short steps are left alone');
|
||||
const { features } = readGeoJsonFeatures(
|
||||
{
|
||||
type: 'LineString',
|
||||
coordinates: [
|
||||
[0, 60],
|
||||
[10, 60],
|
||||
],
|
||||
},
|
||||
'#39d0ff',
|
||||
);
|
||||
assert.equal(features[0].coords.length, 21);
|
||||
});
|
||||
|
||||
test('rhumb steps stop once a file has added as many points as it may hold', () => {
|
||||
const budget = { left: 30 };
|
||||
const zigzag = Array.from({ length: 6 }, (_, i) => [i % 2 ? 10 : 0, 0, 0]);
|
||||
const path = rhumbPath(zigzag, budget);
|
||||
// Each 10-degree step adds 19 points: one fits, the rest are drawn as given.
|
||||
assert.equal(path.length, 6 + 19);
|
||||
assert.equal(budget.left, 11);
|
||||
});
|
||||
+523
-479
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,256 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createImportedDrawing } from './geoImportPins.js';
|
||||
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
|
||||
import { toLonLatH } from '../geo/ellipsoid.js';
|
||||
|
||||
const FEATURES = [
|
||||
{
|
||||
kind: 'pin',
|
||||
name: 'tower',
|
||||
lon: 1,
|
||||
lat: 2,
|
||||
height: 0,
|
||||
mode: 'absolute',
|
||||
image: 'blob:icon',
|
||||
size: [32, 32],
|
||||
scale: 1.5,
|
||||
color: [1, 0, 0, 1],
|
||||
course: 90,
|
||||
pixelOffset: { x: 0, y: -16 },
|
||||
scaleByDistance: { near: 1, nearValue: 1, far: 2, farValue: 0.1 },
|
||||
},
|
||||
{ kind: 'pin', lon: 3, lat: 4, height: 0, mode: 'clamp', image: null },
|
||||
{
|
||||
kind: 'line',
|
||||
name: 'walk',
|
||||
coords: [
|
||||
[1, 2, 50],
|
||||
[3, 4, 50],
|
||||
],
|
||||
mode: 'draped',
|
||||
color: [1, 1, 0, 1],
|
||||
width: 6,
|
||||
},
|
||||
{
|
||||
kind: 'polygon',
|
||||
rings: [
|
||||
[
|
||||
[0, 0, 200],
|
||||
[1, 0, 200],
|
||||
[1, 1, 200],
|
||||
],
|
||||
],
|
||||
clamp: false,
|
||||
extrude: true,
|
||||
fill: [1, 0, 0, 0.8],
|
||||
outline: [0, 0, 0, 1],
|
||||
outlineWidth: 2,
|
||||
},
|
||||
{
|
||||
kind: 'wall',
|
||||
coords: [
|
||||
[1, 2, 150],
|
||||
[3, 4, 150],
|
||||
],
|
||||
fill: [0, 1, 0, 0.5],
|
||||
outline: [0, 1, 0, 1],
|
||||
},
|
||||
{
|
||||
kind: 'overlay',
|
||||
rect: { west: 0, south: 0, east: 1, north: 1 },
|
||||
rotation: 0.3,
|
||||
image: 'blob:overlay',
|
||||
},
|
||||
];
|
||||
|
||||
/** A drawing of `features` on a renderer double, with double-clicks it is handed. */
|
||||
function drawn(features = FEATURES) {
|
||||
const viewer = {};
|
||||
const ground = bindFakeGroundRenderer(viewer);
|
||||
const clicks = [];
|
||||
const input = {
|
||||
onPointer(type, fn) {
|
||||
if (type === 'dblclick') clicks.push(fn);
|
||||
return () => clicks.splice(clicks.indexOf(fn), 1);
|
||||
},
|
||||
stockEnabled: () => true,
|
||||
};
|
||||
const drawing = createImportedDrawing(viewer, features, {
|
||||
inputFor: () => input,
|
||||
});
|
||||
drawing.mount();
|
||||
const items = (kind) => [
|
||||
...ground.draw.set(drawing.ids[kind]).items.values(),
|
||||
];
|
||||
const doubleClick = (hit) => {
|
||||
ground.setPick(() => hit);
|
||||
for (const fn of clicks) fn({ position: { x: 1, y: 1 } });
|
||||
};
|
||||
return { ground, drawing, items, doubleClick, clicks };
|
||||
}
|
||||
|
||||
test('pins draw as icons with the look their file gave them', (t) => {
|
||||
const { ground, drawing, items } = drawn();
|
||||
t.after(ground.unbind);
|
||||
const [pin, ...others] = items('icons');
|
||||
assert.deepEqual(drawing.items().icons, [pin], 'what it hands the set');
|
||||
assert.equal(others.length, 0, 'a pin with no icon draws nothing');
|
||||
assert.deepEqual(pin.pos, { lon: 1, lat: 2, height: 0 });
|
||||
assert.equal(pin.height, 'absolute');
|
||||
assert.deepEqual(
|
||||
[pin.image, pin.size, pin.scale, pin.color],
|
||||
['blob:icon', [32, 32], 1.5, [1, 0, 0, 1]],
|
||||
);
|
||||
assert.deepEqual([pin.rotationMode, pin.course], ['course', 90]);
|
||||
assert.deepEqual(pin.pixelOffset, { x: 0, y: -16 });
|
||||
assert.equal(pin.scaleByDistance.farValue, 0.1);
|
||||
assert.equal(pin.disableDepthTest, undefined, 'at its own height');
|
||||
assert.deepEqual(pin.meta, { name: 'tower' });
|
||||
});
|
||||
|
||||
test('paths, polygons, walls and overlays draw as lines and shapes', (t) => {
|
||||
const { ground, items } = drawn();
|
||||
t.after(ground.unbind);
|
||||
const [line] = items('lines');
|
||||
assert.equal(line.mode, 'draped');
|
||||
assert.equal(line.widthPx, 6);
|
||||
assert.deepEqual(line.style, { kind: 'solid', color: [1, 1, 0, 1] });
|
||||
assert.ok(
|
||||
line.positions.every((p) => Math.abs(toLonLatH(p).height) < 1e-6),
|
||||
'draped from the surface',
|
||||
);
|
||||
const [polygon, wall, overlay] = items('shapes');
|
||||
assert.equal(polygon.geometry.perPositionHeight, true);
|
||||
assert.equal(polygon.extrudeHeight, 0, 'down to the ellipsoid');
|
||||
assert.deepEqual(polygon.outline, [0, 0, 0, 1]);
|
||||
assert.equal(polygon.outlineWidth, 2);
|
||||
assert.equal(polygon.lit, true);
|
||||
assert.equal(polygon.height, undefined);
|
||||
assert.equal(wall.geometry.kind, 'wall');
|
||||
assert.deepEqual(wall.geometry.positions[0], { lon: 1, lat: 2, height: 150 });
|
||||
assert.equal(overlay.geometry.kind, 'rectangle');
|
||||
assert.equal(overlay.geometry.rotation, 0.3);
|
||||
assert.deepEqual(overlay.fill, { image: 'blob:overlay' });
|
||||
assert.equal(overlay.height, 'clampGround');
|
||||
});
|
||||
|
||||
test('a double-click follows a pin and zooms to a path, until the file goes', (t) => {
|
||||
const { ground, drawing, doubleClick, clicks } = drawn();
|
||||
t.after(ground.unbind);
|
||||
doubleClick({ set: drawing.ids.icons, id: 'p0' });
|
||||
const followed = ground.follows.at(-1);
|
||||
assert.equal(followed.key, `${drawing.ids.icons}:p0`);
|
||||
const at = toLonLatH(followed.position());
|
||||
assert.ok(Math.abs(at.lon - 1) < 1e-9 && Math.abs(at.lat - 2) < 1e-9);
|
||||
doubleClick({ set: drawing.ids.lines, id: 'l2' });
|
||||
assert.ok(ground.flights.at(-1).sphere.radius > 0, 'zoomed to the path');
|
||||
assert.equal(ground.follows.at(-1), null, 'which ends the follow');
|
||||
doubleClick({ set: 'someone-else', id: 'p0' });
|
||||
assert.equal(ground.flights.length, 1, 'other sets are not followed');
|
||||
doubleClick({ set: drawing.ids.icons, id: 'p0' });
|
||||
drawing.destroy();
|
||||
assert.equal(ground.follows.at(-1), null, 'a removed pin is not followed');
|
||||
assert.equal(clicks.length, 0);
|
||||
assert.equal(ground.liveSets().length, 0);
|
||||
assert.deepEqual(drawing.items(), { icons: [], lines: [], shapes: [] });
|
||||
});
|
||||
|
||||
test('hiding a file hides its sets and takes no double-clicks', (t) => {
|
||||
const { ground, drawing, doubleClick } = drawn();
|
||||
t.after(ground.unbind);
|
||||
drawing.show = false;
|
||||
for (const id of Object.values(drawing.ids))
|
||||
assert.equal(ground.draw.set(id).show, false);
|
||||
doubleClick({ set: drawing.ids.icons, id: 'p0' });
|
||||
assert.equal(ground.follows.length, 0);
|
||||
drawing.show = true;
|
||||
assert.equal(ground.draw.set(drawing.ids.icons).show, true);
|
||||
});
|
||||
|
||||
test('a ground pin on the bare ellipsoid stands at 0, not on its sagging tiles', async (t) => {
|
||||
const pin = { kind: 'pin', lon: 1, lat: 2, height: 0, mode: 'clamp' };
|
||||
for (const [source, sag, expected] of [
|
||||
['ellipsoid', -46000, 0],
|
||||
['ellipsoid', -500, 0],
|
||||
['terrain', -30, -30],
|
||||
['terrain', -4000, -4000],
|
||||
]) {
|
||||
const { ground, drawing } = drawn([
|
||||
{ ...pin, image: 'blob:icon' },
|
||||
{ ...pin, lon: 3, image: 'blob:icon' },
|
||||
]);
|
||||
t.after(ground.unbind);
|
||||
ground.globe.terrain = () => sag;
|
||||
const probes = [];
|
||||
ground.renderer.query.sampleHeight = async (points) => {
|
||||
probes.push(points);
|
||||
return points.map(() => ({ height: 0, source }));
|
||||
};
|
||||
await drawing.refreshGround();
|
||||
assert.deepEqual(
|
||||
drawing.items().icons.map((i) => i.pos.height),
|
||||
[expected, expected],
|
||||
`${source} ${sag}`,
|
||||
);
|
||||
assert.equal(probes.length, 2, 'asked once for the file, both ways');
|
||||
assert.deepEqual(probes[0], [{ lon: 1, lat: 2 }]);
|
||||
drawing.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('the ellipsoid is asked about once for each surface', async (t) => {
|
||||
const pin = { kind: 'pin', lon: 1, lat: 2, height: 0, mode: 'clamp' };
|
||||
const { ground, drawing } = drawn([{ ...pin, image: 'blob:icon' }]);
|
||||
t.after(ground.unbind);
|
||||
let version = 1;
|
||||
ground.renderer.globe.surfaceVersion = () => version;
|
||||
ground.globe.terrain = () => -30;
|
||||
let asked = 0;
|
||||
ground.renderer.query.sampleHeight = async (points) => {
|
||||
asked += 1;
|
||||
return points.map(() => ({ height: -30, source: 'terrain' }));
|
||||
};
|
||||
await drawing.refreshGround();
|
||||
await drawing.refreshGround();
|
||||
assert.equal(asked, 2, 'one probe, both ways, for the first surface');
|
||||
version = 2;
|
||||
await drawing.refreshGround();
|
||||
assert.equal(asked, 4, 'and again for the next');
|
||||
assert.equal(drawing.items().icons[0].pos.height, -30);
|
||||
});
|
||||
|
||||
test('nothing draws after destroy, and an overlay without bounds draws nowhere', async (t) => {
|
||||
const { ground, drawing } = drawn([
|
||||
{ kind: 'pin', lon: 1, lat: 2, height: 0, mode: 'clamp', image: 'b' },
|
||||
{ kind: 'overlay', rect: null, color: [1, 1, 1, 1] },
|
||||
]);
|
||||
t.after(ground.unbind);
|
||||
assert.equal(ground.draw.set(drawing.ids.shapes), undefined, 'no shapes');
|
||||
assert.equal(drawing.points().length, 1, 'framed by its pin alone');
|
||||
const pending = drawing.refreshGround();
|
||||
drawing.destroy();
|
||||
await pending;
|
||||
drawing.mount();
|
||||
await drawing.refreshGround();
|
||||
assert.equal(ground.liveSets().length, 0);
|
||||
assert.deepEqual(drawing.items(), { icons: [], lines: [], shapes: [] });
|
||||
});
|
||||
|
||||
test('a turned overlay across the antimeridian frames there', (t) => {
|
||||
const { ground, drawing } = drawn([
|
||||
{
|
||||
kind: 'overlay',
|
||||
rect: { west: 179, south: -1, east: -179, north: 1 },
|
||||
rotation: Math.PI / 4,
|
||||
color: [1, 1, 1, 1],
|
||||
},
|
||||
]);
|
||||
t.after(ground.unbind);
|
||||
const points = drawing.points();
|
||||
assert.equal(points.length, 4);
|
||||
for (const [lon, lat] of points) {
|
||||
assert.ok(Math.abs(lat) < 2, `latitude ${lat}`);
|
||||
assert.ok(Math.abs(lon) > 178 && Math.abs(lon) <= 180, `longitude ${lon}`);
|
||||
}
|
||||
});
|
||||
@@ -80,7 +80,7 @@ test('Directions introduces the shared OSM credit when the requested route draws
|
||||
credits: { showOsmCredit, hideOsmCredit }, input, camera: {},
|
||||
overlays: { setOverlayEntries: noop, setOverlaySourceVisible: noop, clearOverlaySource: noop },
|
||||
render: { governorRequestRender: noop, holdContinuousRender: noop, releaseContinuousRender: noop },
|
||||
sprites: { registerSpriteCollection: noop, unregisterSpriteCollection: noop, restoreSpriteOrder: noop },
|
||||
sprites: {},
|
||||
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
|
||||
ground: { warmGroundFloor: noop, resolveGroundFloorCells: async () => {} },
|
||||
} });
|
||||
|
||||
+12
-91
@@ -1,4 +1,4 @@
|
||||
/** Bottom-to-top order for near-plane-clamped contact sprite collections. */
|
||||
/** Bottom-to-top order of the sprite layers' icon and dot sets. */
|
||||
export const SPRITE_LAYER_ORDER = Object.freeze([
|
||||
'cctv',
|
||||
'firms',
|
||||
@@ -11,97 +11,18 @@ export const SPRITE_LAYER_ORDER = Object.freeze([
|
||||
'flights',
|
||||
]);
|
||||
|
||||
/** @type {Map<string, Object>} */
|
||||
const _collections = new Map();
|
||||
|
||||
/**
|
||||
* Register the current primitive collection for a sprite layer.
|
||||
* The draw order (`SetSpec.drawOrder`) a sprite layer's set is made with:
|
||||
* its place in `SPRITE_LAYER_ORDER`, counted back from -1 for flights, so
|
||||
* flights draw over every other sprite layer and the rest follow the list,
|
||||
* whichever layer was turned on first. Every set at the default order, 0
|
||||
* (selection highlights, route endpoints, the tracked plane and the other
|
||||
* overlays), stays over all of them, as it did when the sprite sets were
|
||||
* raised to the bottom of the scene. A key not in the list gets 0.
|
||||
* @param {string} layerId - Stable sprite-order layer key.
|
||||
* @param {Object} collection - Cesium billboard/point primitive collection.
|
||||
* @returns {void}
|
||||
* @returns {number}
|
||||
*/
|
||||
export function registerSpriteCollection(layerId, collection) {
|
||||
if (!layerId || !collection) return;
|
||||
_collections.set(layerId, collection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a renderer draw set for a sprite layer, by its set id. The
|
||||
* default renderer names each set's host primitive with `drawSetId`; the
|
||||
* restorer raises the host it finds under that name, whichever host the
|
||||
* set draws with now.
|
||||
* @param {string} layerId - Stable sprite-order layer key.
|
||||
* @param {string} setId - The draw set's id.
|
||||
* @returns {object} The registration, for `unregisterSpriteCollection`'s guard.
|
||||
*/
|
||||
export function registerSpriteSet(layerId, setId) {
|
||||
const entry = Object.freeze({ drawSetId: setId });
|
||||
if (layerId && typeof setId === 'string') _collections.set(layerId, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* The primitive `entry` names: itself, or a draw set's host found by its id.
|
||||
* The topmost match wins, so a host still retiring below its replacement is
|
||||
* skipped.
|
||||
*/
|
||||
function resolveSprite(primitives, entry) {
|
||||
if (typeof entry?.drawSetId !== 'string') return entry;
|
||||
for (let i = (primitives.length ?? 0) - 1; i >= 0; i--) {
|
||||
const primitive = primitives.get(i);
|
||||
if (primitive?.drawSetId === entry.drawSetId) return primitive;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a registered collection (primarily useful to lifecycle tests).
|
||||
* @param {string} layerId - Stable sprite-order layer key.
|
||||
* @param {Object} [collection] - Optional identity guard against stale teardown.
|
||||
* @returns {void}
|
||||
*/
|
||||
export function unregisterSpriteCollection(layerId, collection) {
|
||||
if (collection && _collections.get(layerId) !== collection) return;
|
||||
_collections.delete(layerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reassert deterministic sprite stacking after any layer enable/init.
|
||||
* Cesium's stable translucent sort otherwise preserves first-enable primitive
|
||||
* order. Raising bottom-to-top makes flights the final/top collection.
|
||||
* @param {Cesium.Viewer|Object} viewer - Active viewer.
|
||||
* @returns {void}
|
||||
*/
|
||||
export function restoreSpriteOrder(viewer) {
|
||||
if (!viewer || viewer.isDestroyed?.()) return;
|
||||
const scene = viewer.scene;
|
||||
const primitives = scene?.primitives;
|
||||
if (!primitives || scene.isDestroyed?.() || primitives.isDestroyed?.())
|
||||
return;
|
||||
|
||||
for (const layerId of SPRITE_LAYER_ORDER) {
|
||||
const collection = resolveSprite(primitives, _collections.get(layerId));
|
||||
if (!collection || collection.isDestroyed?.()) continue;
|
||||
if (primitives.contains?.(collection) === false) continue;
|
||||
primitives.raiseToTop(collection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicit layer-enable wiring seam. Production callers use the shared
|
||||
* restorer by default; tests inject a spy to pin each enable path without
|
||||
* constructing a WebGL viewer.
|
||||
* @param {string} layerId - Sprite layer whose enable path is restoring order.
|
||||
* @param {Cesium.Viewer|Object} viewer - Active viewer.
|
||||
* @param {(viewer: Object) => void} [restore=restoreSpriteOrder] - Test seam.
|
||||
* @returns {void}
|
||||
*/
|
||||
export function restoreSpriteOrderOnEnable(
|
||||
layerId,
|
||||
viewer,
|
||||
restore = restoreSpriteOrder,
|
||||
) {
|
||||
if (!SPRITE_LAYER_ORDER.includes(layerId) || typeof restore !== 'function')
|
||||
return;
|
||||
restore(viewer);
|
||||
export function spriteDrawOrder(layerId) {
|
||||
const index = SPRITE_LAYER_ORDER.indexOf(layerId);
|
||||
return index < 0 ? 0 : index - SPRITE_LAYER_ORDER.length;
|
||||
}
|
||||
+93
-116
@@ -1,121 +1,98 @@
|
||||
import { createRendering as createFirmsRendering } from '../layers/firms/rendering.js';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
registerSpriteCollection,
|
||||
restoreSpriteOrder,
|
||||
restoreSpriteOrderOnEnable,
|
||||
unregisterSpriteCollection,
|
||||
} from './spriteOrder.js';
|
||||
import flightsLayer from './flights.js';
|
||||
import aisLiveVesselsLayer from './aisLiveVessels.js';
|
||||
import { createFirmsHeatmapLayer } from './firmsHeatmap.js';
|
||||
import * as sprites from './spriteOrder.js';
|
||||
import { SPRITE_LAYER_ORDER, spriteDrawOrder } from './spriteOrder.js';
|
||||
import { createAircraftIcons } from './aircraftIconLayer.js';
|
||||
import { createRendering as createBikeshareRendering } from '../layers/bikeshare/rendering.js';
|
||||
import { createRendering as createCctvRendering } from '../layers/cctv/rendering.js';
|
||||
import { createRendering as createFirmsRendering } from '../layers/firms/rendering.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
const ORDER = ['cctv', 'firms', 'bikeshare', 'ais', 'military', 'flights'];
|
||||
|
||||
function makePrimitives(initial = []) {
|
||||
return {
|
||||
items: [...initial],
|
||||
calls: [],
|
||||
contains(collection) { return this.items.includes(collection); },
|
||||
raiseToTop(collection) {
|
||||
this.calls.push(collection.id);
|
||||
const index = this.items.indexOf(collection);
|
||||
if (index >= 0) this.items.splice(index, 1);
|
||||
this.items.push(collection);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeCollection(id, destroyed = false) {
|
||||
return { id, isDestroyed: () => destroyed };
|
||||
}
|
||||
|
||||
test('restoreSpriteOrder raises live collections bottom-to-top and skips destroyed entries', () => {
|
||||
const collections = Object.fromEntries(ORDER.map((id) => [id, makeCollection(id)]));
|
||||
const destroyedFirms = makeCollection('firms', true);
|
||||
for (const id of ORDER) {
|
||||
registerSpriteCollection(id, id === 'firms' ? destroyedFirms : collections[id]);
|
||||
}
|
||||
const primitives = makePrimitives([
|
||||
collections.flights,
|
||||
collections.ais,
|
||||
collections.cctv,
|
||||
collections.bikeshare,
|
||||
collections.military,
|
||||
]);
|
||||
|
||||
restoreSpriteOrder({ scene: { primitives } });
|
||||
|
||||
assert.deepEqual(primitives.calls, ['cctv', 'bikeshare', 'ais', 'military', 'flights']);
|
||||
assert.deepEqual(primitives.items.map((item) => item.id), [
|
||||
'cctv', 'bikeshare', 'ais', 'military', 'flights',
|
||||
]);
|
||||
|
||||
for (const id of ORDER) unregisterSpriteCollection(id);
|
||||
});
|
||||
|
||||
test('late CCTV registration still restores flights above the ambient collection', () => {
|
||||
const flights = makeCollection('flights');
|
||||
const cctv = makeCollection('cctv');
|
||||
const primitives = makePrimitives([flights]);
|
||||
const viewer = { scene: { primitives } };
|
||||
|
||||
registerSpriteCollection('flights', flights);
|
||||
restoreSpriteOrder(viewer);
|
||||
primitives.items.push(cctv); // CCTV enabled after flights: it starts on top.
|
||||
registerSpriteCollection('cctv', cctv);
|
||||
primitives.calls.length = 0;
|
||||
|
||||
restoreSpriteOrder(viewer);
|
||||
|
||||
assert.deepEqual(primitives.calls, ['cctv', 'flights']);
|
||||
assert.deepEqual(primitives.items.map((item) => item.id), ['cctv', 'flights']);
|
||||
|
||||
unregisterSpriteCollection('cctv', cctv);
|
||||
unregisterSpriteCollection('flights', flights);
|
||||
});
|
||||
|
||||
test('restoreSpriteOrder is inert for destroyed viewers and primitive collections', () => {
|
||||
const flights = makeCollection('flights');
|
||||
const primitives = makePrimitives([flights]);
|
||||
registerSpriteCollection('flights', flights);
|
||||
|
||||
restoreSpriteOrder({ isDestroyed: () => true, scene: { primitives } });
|
||||
restoreSpriteOrder({ scene: { primitives: { ...primitives, isDestroyed: () => true } } });
|
||||
|
||||
assert.deepEqual(primitives.calls, []);
|
||||
unregisterSpriteCollection('flights', flights);
|
||||
});
|
||||
|
||||
test('restoreSpriteOrder never raises a registered collection absent from scene primitives', () => {
|
||||
const flights = makeCollection('flights');
|
||||
const primitives = makePrimitives([]);
|
||||
registerSpriteCollection('flights', flights);
|
||||
|
||||
restoreSpriteOrder({ scene: { primitives } });
|
||||
|
||||
assert.deepEqual(primitives.calls, []);
|
||||
assert.deepEqual(primitives.items, []);
|
||||
unregisterSpriteCollection('flights', flights);
|
||||
});
|
||||
|
||||
test('flights, AIS, and FIRMS enable paths are wired through the shared sprite restorer', () => {
|
||||
const viewer = { id: 'viewer' };
|
||||
const calls = [];
|
||||
const restoreSpy = (value) => calls.push(value);
|
||||
for (const layerId of ['flights', 'ais', 'firms']) {
|
||||
restoreSpriteOrderOnEnable(layerId, viewer, restoreSpy);
|
||||
}
|
||||
assert.deepEqual(calls, [viewer, viewer, viewer]);
|
||||
|
||||
const firmsLayer = createFirmsHeatmapLayer({ id: 'firms', name: 'FIRMS' });
|
||||
assert.match(flightsLayer.enable.toString(), /restoreSpriteOrderOnEnable\('flights', viewer\)/);
|
||||
assert.match(aisLiveVesselsLayer.enable.toString(), /restoreSpriteOrderOnEnable\('ais', activeViewer\)/);
|
||||
assert.match(firmsLayer.enable.toString(), /restoreSpriteOrderOnEnable\('firms', viewer\)/);
|
||||
assert.match(
|
||||
createFirmsRendering.toString(),
|
||||
/spriteEntry = registerSpriteSet\('firms', set\.id\);\s*restoreSpriteOrder\(layerState\._viewer\);/,
|
||||
'lazy FIRMS registration must restore order immediately',
|
||||
test('each sprite layer draws at its place in the order, flights on top', () => {
|
||||
assert.deepEqual(
|
||||
SPRITE_LAYER_ORDER.map(spriteDrawOrder),
|
||||
SPRITE_LAYER_ORDER.map((_, i) => i - SPRITE_LAYER_ORDER.length),
|
||||
);
|
||||
assert.equal(
|
||||
Math.max(...SPRITE_LAYER_ORDER.map(spriteDrawOrder)),
|
||||
spriteDrawOrder('flights'),
|
||||
);
|
||||
assert.ok(spriteDrawOrder('military') > spriteDrawOrder('ais'));
|
||||
assert.ok(spriteDrawOrder('ais') > spriteDrawOrder('transit'));
|
||||
assert.ok(spriteDrawOrder('transit') > spriteDrawOrder('cctv'));
|
||||
// Any other layer stays at the default, over every sprite layer.
|
||||
assert.equal(spriteDrawOrder('flights'), -1);
|
||||
assert.equal(spriteDrawOrder('street-level:marker'), 0);
|
||||
assert.equal(spriteDrawOrder(undefined), 0);
|
||||
});
|
||||
|
||||
/** A viewer double with a fake draw port, unbound after the test. */
|
||||
function drawnViewer(t) {
|
||||
const viewer = {};
|
||||
const { draw, unbind } = bindFakeDraw(viewer);
|
||||
t.after(unbind);
|
||||
return { viewer, draw };
|
||||
}
|
||||
|
||||
test('flights and military make their icon sets at their draw orders', (t) => {
|
||||
const { viewer, draw } = drawnViewer(t);
|
||||
for (const layerId of ['flights', 'military']) {
|
||||
const icons = createAircraftIcons({
|
||||
state: {},
|
||||
services: { focus: { focusPassIsNeeded: () => false }, sprites },
|
||||
parts: {},
|
||||
layerId,
|
||||
renderDelaySec: 0,
|
||||
courseMaxDps: 1,
|
||||
cockpitContactSizePx: 4,
|
||||
});
|
||||
const id = icons._createIcons(viewer);
|
||||
assert.equal(draw.set(id).spec.drawOrder, spriteDrawOrder(layerId));
|
||||
icons._disposeIcons();
|
||||
}
|
||||
});
|
||||
|
||||
test('CCTV, FIRMS and bikeshare make their sprite sets at their draw orders', (t) => {
|
||||
const { viewer, draw } = drawnViewer(t);
|
||||
const cctv = createCctvRendering({
|
||||
state: {},
|
||||
services: { focus: {}, sprites },
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
const cctvId = cctv.createCameraIcons(viewer);
|
||||
assert.equal(draw.set(cctvId).spec.drawOrder, spriteDrawOrder('cctv'));
|
||||
cctv.destroyCameraIcons();
|
||||
|
||||
const layerState = { _viewer: viewer, _enabled: true };
|
||||
const firms = createFirmsRendering({
|
||||
layerState,
|
||||
services: { anchors: {}, sprites },
|
||||
components: {},
|
||||
config: {
|
||||
overlayHost: { setVisible() {}, clearSource() {} },
|
||||
},
|
||||
});
|
||||
firms.ensureDetectionCollections();
|
||||
assert.equal(
|
||||
draw.set(layerState._icons.id).spec.drawOrder,
|
||||
spriteDrawOrder('firms'),
|
||||
);
|
||||
firms.removeDetectionCollections();
|
||||
|
||||
const bikeState = {};
|
||||
const bikeshare = createBikeshareRendering({
|
||||
state: bikeState,
|
||||
services: { render: {}, sprites },
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
bikeshare.attachSets(viewer);
|
||||
assert.equal(
|
||||
draw.set(bikeState._stationSet.id).spec.drawOrder,
|
||||
spriteDrawOrder('bikeshare'),
|
||||
);
|
||||
// The selected station's highlight is not a sprite layer.
|
||||
assert.equal(draw.set(bikeState._selectedSet.id).spec.drawOrder, undefined);
|
||||
bikeshare.detachSets();
|
||||
});
|
||||
@@ -1102,7 +1102,6 @@
|
||||
"That GPX file has no <gpx> document.": "لا يحتوي ملف GPX هذا على مستند <gpx>.",
|
||||
"That {format} file is not valid XML.": "ملف {format} هذا ليس XML صالحًا.",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "يحتوي هذا الملف على صورة غير قابلة للقراءة أو تتجاوز حد 16 ميغابكسل.",
|
||||
"That KML could not be read.": "تعذّرت قراءة ملف KML هذا.",
|
||||
"That file has invalid point coordinates.": "يحتوي هذا الملف على إحداثيات نقاط غير صالحة.",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "ارتفاعات الأرض غير متاحة لهذا الملف. أعد المحاولة بعد تحميل الخريطة.",
|
||||
"That file took too long to read.": "استغرقت قراءة هذا الملف وقتًا طويلًا جدًا.",
|
||||
@@ -1114,7 +1113,6 @@
|
||||
"That {format} file could not be read.": "تعذّرت قراءة ملف {format} هذا.",
|
||||
"That file has {count} map objects; the limit is {limit}.": "عدد عناصر الخريطة في هذا الملف {count}، والحد المسموح {limit}.",
|
||||
"Ground heights could not be read. Try that file again.": "تعذّرت قراءة ارتفاعات الأرض. أعد استيراد الملف.",
|
||||
"That file has invalid point graphics.": "يحتوي هذا الملف على رسومات نقاط غير صالحة.",
|
||||
"Map tiles temporarily unavailable": "بلاطات الخريطة غير متاحة مؤقتًا",
|
||||
"Mapped names temporarily unavailable": "أسماء المواقع المرسومة غير متاحة مؤقتًا",
|
||||
"Military airfield": "مطار عسكري",
|
||||
|
||||
@@ -1070,7 +1070,6 @@
|
||||
"That GPX file has no <gpx> document.": "Diese GPX-Datei hat kein <gpx>-Dokument.",
|
||||
"That {format} file is not valid XML.": "Diese {format}-Datei ist kein gültiges XML.",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "Diese Datei enthält ein unlesbares Bild oder überschreitet das Bildlimit von 16 Megapixeln.",
|
||||
"That KML could not be read.": "Diese KML konnte nicht gelesen werden.",
|
||||
"That file has invalid point coordinates.": "Diese Datei enthält ungültige Punktkoordinaten.",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "Für diese Datei sind keine Geländehöhen verfügbar. Erneut versuchen, wenn die Karte geladen ist.",
|
||||
"That file took too long to read.": "Das Lesen dieser Datei hat zu lange gedauert.",
|
||||
@@ -1082,7 +1081,6 @@
|
||||
"That {format} file could not be read.": "Diese {format}-Datei konnte nicht gelesen werden.",
|
||||
"That file has {count} map objects; the limit is {limit}.": "Diese Datei hat {count} Kartenobjekte; das Limit ist {limit}.",
|
||||
"Ground heights could not be read. Try that file again.": "Geländehöhen konnten nicht gelesen werden. Die Datei erneut laden.",
|
||||
"That file has invalid point graphics.": "Diese Datei enthält ungültige Punktgrafiken.",
|
||||
"Map tiles temporarily unavailable": "Kartenkacheln vorübergehend nicht verfügbar",
|
||||
"Mapped names temporarily unavailable": "Kartierte Namen vorübergehend nicht verfügbar",
|
||||
"Military airfield": "Militärflugplatz",
|
||||
|
||||
@@ -2142,7 +2142,6 @@
|
||||
"That GPX file has no <gpx> document.": "Ese archivo GPX no tiene documento <gpx>.",
|
||||
"That {format} file is not valid XML.": "Ese archivo {format} no es un XML válido.",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "Ese archivo tiene una imagen ilegible o supera el límite de imagen de 16 megapíxeles.",
|
||||
"That KML could not be read.": "No se pudo leer ese KML.",
|
||||
"That file has invalid point coordinates.": "Ese archivo tiene coordenadas de puntos no válidas.",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "Las alturas del terreno no están disponibles para ese archivo. Vuelve a intentarlo cuando el mapa haya cargado.",
|
||||
"That file took too long to read.": "La lectura de ese archivo tardó demasiado.",
|
||||
@@ -2154,7 +2153,6 @@
|
||||
"That {format} file could not be read.": "No se pudo leer ese archivo {format}.",
|
||||
"That file has {count} map objects; the limit is {limit}.": "Ese archivo tiene {count} objetos en el mapa; el límite es {limit}.",
|
||||
"Ground heights could not be read. Try that file again.": "No se pudieron leer las alturas del terreno. Vuelve a intentarlo con ese archivo.",
|
||||
"That file has invalid point graphics.": "Ese archivo tiene gráficos de puntos no válidos.",
|
||||
"Low-accuracy score < 2%": "Índice de baja precisión < 2%",
|
||||
"Low-accuracy score 2–10%": "Índice de baja precisión 2–10%",
|
||||
"Low-accuracy score > 10%": "Índice de baja precisión > 10%",
|
||||
|
||||
@@ -222,7 +222,6 @@
|
||||
"That GPX file has no <gpx> document.": "Ce fichier GPX n'a pas de document <gpx>.",
|
||||
"That {format} file is not valid XML.": "Ce fichier {format} n'est pas un XML valide.",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "Ce fichier contient une image illisible ou dépasse la limite de 16 mégapixels par image.",
|
||||
"That KML could not be read.": "Impossible de lire ce KML.",
|
||||
"That file has invalid point coordinates.": "Ce fichier contient des coordonnées de points non valides.",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "Les altitudes du sol ne sont pas disponibles pour ce fichier. Réessayez une fois la carte chargée.",
|
||||
"That file took too long to read.": "La lecture de ce fichier a pris trop de temps.",
|
||||
@@ -234,7 +233,6 @@
|
||||
"That {format} file could not be read.": "Impossible de lire ce fichier {format}.",
|
||||
"That file has {count} map objects; the limit is {limit}.": "Ce fichier contient {count} objets cartographiques ; la limite est de {limit}.",
|
||||
"Ground heights could not be read. Try that file again.": "Impossible de lire les altitudes du sol. Réessayez avec ce fichier.",
|
||||
"That file has invalid point graphics.": "Ce fichier contient des symboles de points non valides.",
|
||||
"Overpass rate-limited": "Overpass : limite de requêtes atteinte",
|
||||
"Overpass timed out": "Délai Overpass dépassé",
|
||||
"Overpass could not complete the query": "Overpass n'a pas pu terminer la requête",
|
||||
|
||||
@@ -222,7 +222,6 @@
|
||||
"That GPX file has no <gpx> document.": "Quel file GPX non ha un documento <gpx>.",
|
||||
"That {format} file is not valid XML.": "Quel file {format} non è un XML valido.",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "Quel file ha un'immagine illeggibile o supera il limite di 16 megapixel per immagine.",
|
||||
"That KML could not be read.": "Impossibile leggere quel KML.",
|
||||
"That file has invalid point coordinates.": "Quel file ha coordinate dei punti non valide.",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "Le quote del terreno non sono disponibili per quel file. Riprova quando la mappa è caricata.",
|
||||
"That file took too long to read.": "La lettura di quel file ha richiesto troppo tempo.",
|
||||
@@ -234,7 +233,6 @@
|
||||
"That {format} file could not be read.": "Impossibile leggere quel file {format}.",
|
||||
"That file has {count} map objects; the limit is {limit}.": "Quel file ha {count} oggetti sulla mappa; il limite è {limit}.",
|
||||
"Ground heights could not be read. Try that file again.": "Impossibile leggere le quote del terreno. Riprova con quel file.",
|
||||
"That file has invalid point graphics.": "Quel file ha simboli dei punti non validi.",
|
||||
"Overpass rate-limited": "Overpass ha limitato le richieste",
|
||||
"Overpass timed out": "Overpass è andato in timeout",
|
||||
"Overpass could not complete the query": "Overpass non ha potuto completare la query",
|
||||
|
||||
@@ -216,7 +216,6 @@
|
||||
"That GPX file has no <gpx> document.": "このGPXファイルには<gpx>ドキュメントがありません。",
|
||||
"That {format} file is not valid XML.": "この{format}ファイルは有効なXMLではありません。",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "このファイルには読み取れない画像があるか、画像が1,600万画素の上限を超えています。",
|
||||
"That KML could not be read.": "このKMLを読み取れませんでした。",
|
||||
"That file has invalid point coordinates.": "このファイルには無効な点座標があります。",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "このファイルの地表高を取得できません。地図の読み込み後にもう一度お試しください。",
|
||||
"That file took too long to read.": "ファイルの読み取りに時間がかかりすぎました。",
|
||||
@@ -228,7 +227,6 @@
|
||||
"That {format} file could not be read.": "この{format}ファイルを読み取れませんでした。",
|
||||
"That file has {count} map objects; the limit is {limit}.": "このファイルの地図オブジェクトは{count}個です。上限は{limit}個です。",
|
||||
"Ground heights could not be read. Try that file again.": "地表高を読み取れませんでした。もう一度このファイルをお試しください。",
|
||||
"That file has invalid point graphics.": "このファイルには無効なポイントグラフィックがあります。",
|
||||
"Overpass rate-limited": "Overpassがレート制限中",
|
||||
"Overpass timed out": "Overpassがタイムアウトしました",
|
||||
"Overpass could not complete the query": "Overpassがクエリを完了できませんでした",
|
||||
|
||||
@@ -222,7 +222,6 @@
|
||||
"That GPX file has no <gpx> document.": "Esse arquivo GPX não tem documento <gpx>.",
|
||||
"That {format} file is not valid XML.": "Esse arquivo {format} não é um XML válido.",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "Esse arquivo tem uma imagem ilegível ou ultrapassa o limite de imagem de 16 megapixels.",
|
||||
"That KML could not be read.": "Não foi possível ler esse KML.",
|
||||
"That file has invalid point coordinates.": "Esse arquivo tem coordenadas de pontos inválidas.",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "As altitudes do terreno não estão disponíveis para esse arquivo. Tente de novo quando o mapa tiver carregado.",
|
||||
"That file took too long to read.": "A leitura desse arquivo demorou demais.",
|
||||
@@ -234,7 +233,6 @@
|
||||
"That {format} file could not be read.": "Não foi possível ler esse arquivo {format}.",
|
||||
"That file has {count} map objects; the limit is {limit}.": "Esse arquivo tem {count} objetos no mapa; o limite é {limit}.",
|
||||
"Ground heights could not be read. Try that file again.": "Não foi possível ler as altitudes do terreno. Tente esse arquivo de novo.",
|
||||
"That file has invalid point graphics.": "Esse arquivo tem gráficos de pontos inválidos.",
|
||||
"Overpass rate-limited": "Overpass: limite de requisições atingido",
|
||||
"Overpass timed out": "Tempo esgotado no Overpass",
|
||||
"Overpass could not complete the query": "Overpass não conseguiu concluir a consulta",
|
||||
|
||||
@@ -2176,7 +2176,6 @@
|
||||
"That GPX file has no <gpx> document.": "В этом файле GPX нет документа <gpx>.",
|
||||
"That {format} file is not valid XML.": "Этот файл {format} — некорректный XML.",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "В файле есть нечитаемое изображение или изображение больше лимита в 16 мегапикселей.",
|
||||
"That KML could not be read.": "Не удалось прочитать этот KML.",
|
||||
"That file has invalid point coordinates.": "В файле некорректные координаты точек.",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "Высоты рельефа для этого файла недоступны. Попробуйте ещё раз, когда карта загрузится.",
|
||||
"That file took too long to read.": "Файл читался слишком долго.",
|
||||
@@ -2188,7 +2187,6 @@
|
||||
"That {format} file could not be read.": "Не удалось прочитать этот файл {format}.",
|
||||
"That file has {count} map objects; the limit is {limit}.": "Объектов на карте в файле: {count}; лимит: {limit}.",
|
||||
"Ground heights could not be read. Try that file again.": "Не удалось получить высоты рельефа. Попробуйте импортировать файл ещё раз.",
|
||||
"That file has invalid point graphics.": "В файле некорректное оформление точек.",
|
||||
"Low-accuracy score < 2%": "Доля неточных < 2%",
|
||||
"Low-accuracy score 2–10%": "Доля неточных 2–10%",
|
||||
"Low-accuracy score > 10%": "Доля неточных > 10%",
|
||||
|
||||
@@ -225,7 +225,6 @@
|
||||
"That GPX file has no <gpx> document.": "У цьому файлі GPX немає документа <gpx>.",
|
||||
"That {format} file is not valid XML.": "Цей файл {format} — некоректний XML.",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "У файлі є непридатне для читання зображення або зображення, більше за ліміт 16 мегапікселів.",
|
||||
"That KML could not be read.": "Не вдалося прочитати цей KML.",
|
||||
"That file has invalid point coordinates.": "У файлі некоректні координати точок.",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "Висоти рельєфу для цього файлу недоступні. Спробуйте ще раз, коли карта завантажиться.",
|
||||
"That file took too long to read.": "Файл читався надто довго.",
|
||||
@@ -237,7 +236,6 @@
|
||||
"That {format} file could not be read.": "Не вдалося прочитати цей файл {format}.",
|
||||
"That file has {count} map objects; the limit is {limit}.": "Обʼєктів на карті у файлі: {count}; ліміт: {limit}.",
|
||||
"Ground heights could not be read. Try that file again.": "Не вдалося отримати висоти рельєфу. Спробуйте імпортувати файл ще раз.",
|
||||
"That file has invalid point graphics.": "У файлі некоректне оформлення точок.",
|
||||
"Overpass rate-limited": "Overpass обмежує частоту запитів",
|
||||
"Overpass timed out": "Минув час очікування Overpass",
|
||||
"Overpass could not complete the query": "Overpass не зміг завершити запит",
|
||||
|
||||
@@ -216,7 +216,6 @@
|
||||
"That GPX file has no <gpx> document.": "该 GPX 文件没有 <gpx> 文档。",
|
||||
"That {format} file is not valid XML.": "该 {format} 文件不是有效的 XML。",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "该文件包含无法读取的图像,或图像超过 1600 万像素上限。",
|
||||
"That KML could not be read.": "无法读取该 KML。",
|
||||
"That file has invalid point coordinates.": "该文件的点坐标无效。",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "无法获取该文件的地面高度。请在地图加载完成后重试。",
|
||||
"That file took too long to read.": "读取该文件耗时过长。",
|
||||
@@ -228,7 +227,6 @@
|
||||
"That {format} file could not be read.": "无法读取该 {format} 文件。",
|
||||
"That file has {count} map objects; the limit is {limit}.": "该文件有 {count} 个地图对象,上限为 {limit} 个。",
|
||||
"Ground heights could not be read. Try that file again.": "无法读取地面高度。请重新导入该文件。",
|
||||
"That file has invalid point graphics.": "该文件的点样式无效。",
|
||||
"Overpass rate-limited": "Overpass 已被限流",
|
||||
"Overpass timed out": "Overpass 超时",
|
||||
"Overpass could not complete the query": "Overpass 无法完成查询",
|
||||
|
||||
@@ -216,7 +216,6 @@
|
||||
"That GPX file has no <gpx> document.": "該 GPX 文件沒有 <gpx> 文檔。",
|
||||
"That {format} file is not valid XML.": "該 {format} 文件不是有效的 XML。",
|
||||
"That file has an unreadable image or exceeds the 16-megapixel image limit.": "該文件包含無法讀取的圖像,或圖像超過 1600 萬像素上限。",
|
||||
"That KML could not be read.": "無法讀取該 KML。",
|
||||
"That file has invalid point coordinates.": "該文件的點座標無效。",
|
||||
"Ground heights are not available for that file. Try again when the map has loaded.": "無法獲取該文件的地面高度。請在地圖加載完成後重試。",
|
||||
"That file took too long to read.": "讀取該文件耗時過長。",
|
||||
@@ -228,7 +227,6 @@
|
||||
"That {format} file could not be read.": "無法讀取該 {format} 文件。",
|
||||
"That file has {count} map objects; the limit is {limit}.": "該文件有 {count} 個地圖對象,上限為 {limit} 個。",
|
||||
"Ground heights could not be read. Try that file again.": "無法讀取地面高度。請重新導入該文件。",
|
||||
"That file has invalid point graphics.": "該文件的點樣式無效。",
|
||||
"Overpass rate-limited": "Overpass 已被限流",
|
||||
"Overpass timed out": "Overpass 超時",
|
||||
"Overpass could not complete the query": "Overpass 無法完成查詢",
|
||||
|
||||
@@ -176,7 +176,7 @@ function makeLiveLayer() {
|
||||
setOverlaySourceVisible() {},
|
||||
clearOverlaySource() {},
|
||||
},
|
||||
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
|
||||
sprites: {},
|
||||
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
|
||||
};
|
||||
const state = createState({ services });
|
||||
|
||||
@@ -11,7 +11,6 @@ export function createLifecycle({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
const { restoreSpriteOrder } = services.sprites;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
|
||||
/** Stop listening to the camera, if the layer is. */
|
||||
@@ -62,8 +61,6 @@ export function createLifecycle({
|
||||
|
||||
parts.selection._installClickHandler(viewer);
|
||||
|
||||
restoreSpriteOrder(viewer);
|
||||
|
||||
console.log(
|
||||
`[Data:Bikeshare] Initialized with ${GBFS_CITY_REGISTRY.length} cities`,
|
||||
);
|
||||
@@ -98,7 +95,6 @@ export function createLifecycle({
|
||||
}
|
||||
|
||||
void parts.viewport.runProximityCheck();
|
||||
restoreSpriteOrder(viewer);
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -48,27 +48,18 @@ export function createRendering({
|
||||
id: `${prefix}:stations`,
|
||||
blend: 'translucent',
|
||||
show: false,
|
||||
drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0,
|
||||
});
|
||||
layerState._selectedSet = draw.points({ id: `${prefix}:selected` });
|
||||
// Drawn from the start, empty, so both take their place in the scene
|
||||
// now, as the layer's collections did; the stations' place among the
|
||||
// other sprite layers is the sprite order's (`restoreSpriteOrder`).
|
||||
// other sprite layers is their draw order (`spriteDrawOrder`).
|
||||
layerState._stationSet.set([]);
|
||||
layerState._selectedSet.set([]);
|
||||
layerState._spriteEntry = services.sprites?.registerSpriteSet?.(
|
||||
'bikeshare',
|
||||
layerState._stationSet.id,
|
||||
);
|
||||
}
|
||||
|
||||
/** Let the layer's draw sets go. */
|
||||
function detachSets() {
|
||||
if (layerState._spriteEntry)
|
||||
services.sprites?.unregisterSpriteCollection?.(
|
||||
'bikeshare',
|
||||
layerState._spriteEntry,
|
||||
);
|
||||
layerState._spriteEntry = null;
|
||||
layerState._stationSet?.dispose();
|
||||
layerState._selectedSet?.dispose();
|
||||
layerState._stationSet = null;
|
||||
|
||||
@@ -27,10 +27,6 @@ export function createState({ services }) {
|
||||
|
||||
layerState._selectedSet = null;
|
||||
|
||||
/** The station set's sprite-order registration, while it has one. */
|
||||
|
||||
layerState._spriteEntry = null;
|
||||
|
||||
/** Whether the bikeshare layer is currently enabled. */
|
||||
|
||||
layerState._enabled = false;
|
||||
|
||||
@@ -22,7 +22,6 @@ export function createLifecycle({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
const { registerSpriteSet, restoreSpriteOrder } = services.sprites;
|
||||
const { activateCctvCameraFromWorldClick } = services.activation;
|
||||
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
|
||||
services.picking;
|
||||
@@ -205,10 +204,7 @@ export function createLifecycle({
|
||||
layerState._lastViewContext = '';
|
||||
layerState._calibrationById = parts.calibration.loadCalibrationStore();
|
||||
|
||||
// A host without the sprite order still draws the icons, in the
|
||||
// order they were added.
|
||||
const iconSetId = parts.rendering.createCameraIcons(layerState._viewer);
|
||||
registerSpriteSet?.('cctv', iconSetId);
|
||||
parts.rendering.createCameraIcons(layerState._viewer);
|
||||
|
||||
const sources = await parts.catalog.loadCameraSources();
|
||||
const catalogFromSources = parts.catalog.buildCatalogFromSources(sources);
|
||||
@@ -457,7 +453,6 @@ export function createLifecycle({
|
||||
}
|
||||
parts.rendering.refreshCoverageStyles();
|
||||
parts.presentation.notifyListeners();
|
||||
restoreSpriteOrder(layerState._viewer);
|
||||
console.log('[Data:CCTV] Initialized with', layerState._count, 'cameras');
|
||||
},
|
||||
|
||||
@@ -519,7 +514,6 @@ export function createLifecycle({
|
||||
parts.cards.startCardFrameLoop();
|
||||
parts.cards.refreshAmbientCards();
|
||||
parts.presentation.notifyListeners();
|
||||
restoreSpriteOrder(layerState._viewer);
|
||||
},
|
||||
|
||||
/** Disables the layer: hides entities, stops the projection loop and load queue. */
|
||||
|
||||
@@ -118,8 +118,9 @@ export function createRendering({
|
||||
* far-LOD Google-3D mesh sits above the true ground and swallowed
|
||||
* ground-anchored icons); the set culls the far side of the globe and
|
||||
* refreshHorizonCulling thins the rest.
|
||||
* The set stacks under the other sprite layers (`spriteDrawOrder`).
|
||||
* @param {object} viewer The layer's viewer.
|
||||
* @returns {string} The icon set's id, for the sprite order.
|
||||
* @returns {string} The icon set's id.
|
||||
*/
|
||||
function createCameraIcons(viewer) {
|
||||
// A re-init against a new viewer replaces the icons; the old ones go.
|
||||
@@ -127,9 +128,10 @@ export function createRendering({
|
||||
const set = drawOf(viewer).icons({
|
||||
id: `cctv:${++iconSets}:icons`,
|
||||
horizonCull: true,
|
||||
drawOrder: services.sprites?.spriteDrawOrder?.('cctv') ?? 0,
|
||||
});
|
||||
// Columns of no rows put the set's host in the scene now, where the
|
||||
// sprite order finds it, rather than with its first camera.
|
||||
// Columns of no rows put the set's host in the scene now, rather than
|
||||
// with its first camera.
|
||||
set.setColumns?.({ ids: [] });
|
||||
layerState._icons = createIconBook(set);
|
||||
return set.id;
|
||||
|
||||
@@ -111,7 +111,7 @@ test('camera construction is inert and destruction cancels a pending catalog and
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
},
|
||||
sprites: { registerSpriteSet: noop },
|
||||
sprites: {},
|
||||
activation: {},
|
||||
locations: {},
|
||||
picking: { unregisterPickOwner: noop },
|
||||
|
||||
@@ -957,8 +957,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
* @type {{markers: object, steps: object, route: object}|null}
|
||||
*/
|
||||
let _sets = null;
|
||||
/** The registration of the dots in the shared sprite order. */
|
||||
let _spriteEntry = null;
|
||||
/** Whether a route is drawn. */
|
||||
let _routeDrawn = false;
|
||||
/**
|
||||
@@ -1002,9 +1000,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
|
||||
/** Let the layer's draw sets go. */
|
||||
function detachSets() {
|
||||
if (_spriteEntry)
|
||||
services.sprites.unregisterSpriteCollection?.('directions', _spriteEntry);
|
||||
_spriteEntry = null;
|
||||
if (!_sets) return;
|
||||
for (const set of Object.values(_sets)) set.dispose();
|
||||
_sets = null;
|
||||
@@ -1275,7 +1270,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
_anchorStartedAt = Date.now();
|
||||
anchorStepPoints();
|
||||
syncRenderHold();
|
||||
services.sprites.restoreSpriteOrder(_viewer);
|
||||
services.render.governorRequestRender('directions-route');
|
||||
}
|
||||
|
||||
@@ -1719,16 +1713,14 @@ export function createDirectionsLayer({ services, source }) {
|
||||
id: `${prefix}:steps`,
|
||||
blend: 'translucent',
|
||||
show: false,
|
||||
drawOrder: services.sprites.spriteDrawOrder?.('directions') ?? 0,
|
||||
}),
|
||||
route: draw.lines({ id: `${prefix}:route` }),
|
||||
};
|
||||
// Drawn from the start, empty, so the dots take their place in the
|
||||
// scene now, as their collection did; their place among the other
|
||||
// sprite layers is the sprite order's.
|
||||
// sprite layers is their draw order.
|
||||
_sets.steps.set([]);
|
||||
_spriteEntry =
|
||||
services.sprites.registerSpriteSet?.('directions', _sets.steps.id) ??
|
||||
null;
|
||||
_enabled = false;
|
||||
_mode = DEFAULT_DIRECTIONS_MODE;
|
||||
disarm();
|
||||
@@ -1740,7 +1732,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
_flightStep = null;
|
||||
_overlayHost.setVisible(DIRECTIONS_STEP_OVERLAY_SOURCE_ID, false);
|
||||
_overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, false);
|
||||
services.sprites.restoreSpriteOrder(viewer);
|
||||
console.log('[Data:Directions] Initialized');
|
||||
},
|
||||
|
||||
@@ -1761,7 +1752,6 @@ export function createDirectionsLayer({ services, source }) {
|
||||
typeof pickedId === 'string' && pickedId.startsWith('directions:'),
|
||||
);
|
||||
syncRenderHold();
|
||||
services.sprites.restoreSpriteOrder(viewer);
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,6 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFirmsHeatmapLayer } from '../../data/firmsHeatmap.js';
|
||||
import { unregisterSpriteCollection } from '../../data/spriteOrder.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
|
||||
@@ -110,7 +109,6 @@ function harness(fires, heightM, { sceneFromViewer = false } = {}) {
|
||||
cells,
|
||||
cleanup() {
|
||||
layer.destroy(viewer);
|
||||
unregisterSpriteCollection('firms');
|
||||
input.destroy();
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = saved.project;
|
||||
for (const key of ['window', 'document'])
|
||||
|
||||
@@ -16,7 +16,6 @@ export function createLifecycle({
|
||||
feed,
|
||||
}) {
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
const { restoreSpriteOrderOnEnable } = services.sprites;
|
||||
const { clearSelectedEntityContextForLayer } = services.context;
|
||||
const { id, overlayHost } = config;
|
||||
|
||||
@@ -49,12 +48,6 @@ export function createLifecycle({
|
||||
);
|
||||
if (!layerState._fires.length && !layerState._loading)
|
||||
await components.ingestion.loadHeatmap();
|
||||
if (
|
||||
layerState._enabled &&
|
||||
!layerState._destroyed &&
|
||||
layerState._viewer === viewer
|
||||
)
|
||||
restoreSpriteOrderOnEnable('firms', viewer);
|
||||
},
|
||||
|
||||
disable() {
|
||||
|
||||
@@ -14,8 +14,7 @@ export function createRendering({
|
||||
feed,
|
||||
}) {
|
||||
const { warmFireAnchorFloors } = services.anchors;
|
||||
const { registerSpriteSet, unregisterSpriteCollection, restoreSpriteOrder } =
|
||||
services.sprites;
|
||||
const { spriteDrawOrder } = services.sprites;
|
||||
const { overlayHost } = config;
|
||||
|
||||
/**
|
||||
@@ -340,22 +339,18 @@ export function createRendering({
|
||||
};
|
||||
}
|
||||
|
||||
/** The sprite order's entry for the glow set. */
|
||||
let spriteEntry = null;
|
||||
|
||||
function ensureDetectionCollections() {
|
||||
if (!layerState._viewer || layerState._icons) return;
|
||||
const set = drawOf(layerState._viewer).icons({
|
||||
id: `firms:${++iconSets}:icons`,
|
||||
horizonCull: true,
|
||||
show: layerState._enabled,
|
||||
drawOrder: spriteDrawOrder?.('firms') ?? 0,
|
||||
});
|
||||
// Columns of no rows put the set's host in the scene now, where the
|
||||
// sprite order finds it, rather than with its first fire.
|
||||
// Columns of no rows put the set's host in the scene now, rather than
|
||||
// with its first fire.
|
||||
set.setColumns?.({ ids: [] });
|
||||
layerState._icons = set;
|
||||
spriteEntry = registerSpriteSet('firms', set.id);
|
||||
restoreSpriteOrder(layerState._viewer);
|
||||
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, layerState._enabled);
|
||||
}
|
||||
|
||||
@@ -364,8 +359,6 @@ export function createRendering({
|
||||
* renderer takes it out of the scene it draws in.
|
||||
*/
|
||||
function removeDetectionCollections() {
|
||||
if (spriteEntry) unregisterSpriteCollection('firms', spriteEntry);
|
||||
spriteEntry = null;
|
||||
layerState._icons?.dispose();
|
||||
layerState._icons = null;
|
||||
drawnGlows.clear();
|
||||
|
||||
@@ -9,8 +9,6 @@ export function createLifecycle({
|
||||
resolveAsset,
|
||||
}) {
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { registerSpriteSet, restoreSpriteOrder, restoreSpriteOrderOnEnable } =
|
||||
services.sprites;
|
||||
const { onMilitaryLayerActiveChange } = services.militaryRegistry;
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { ensureGeoidReady } = services.geoid;
|
||||
@@ -45,7 +43,7 @@ export function createLifecycle({
|
||||
clearFocusTarget('flights');
|
||||
flightState._focusEvidenceIds.clear();
|
||||
flightState._viewer = viewer;
|
||||
registerSpriteSet('flights', parts.icons._createIcons(viewer));
|
||||
parts.icons._createIcons(viewer);
|
||||
// The models' draw sets; a hidden item keeps the tracked asset loaded so
|
||||
// the tracked plane's model draws as soon as it is wanted.
|
||||
parts.rendering._createModelSets(viewer, {
|
||||
@@ -98,8 +96,6 @@ export function createLifecycle({
|
||||
);
|
||||
}
|
||||
|
||||
restoreSpriteOrder(viewer);
|
||||
|
||||
console.log('[Data:Flights] Initialized with GPU icons');
|
||||
},
|
||||
|
||||
@@ -152,7 +148,6 @@ export function createLifecycle({
|
||||
flightState._lastFleetTickMs = 0;
|
||||
});
|
||||
}
|
||||
restoreSpriteOrderOnEnable('flights', viewer);
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -9,7 +9,6 @@ export function createLifecycle({
|
||||
resolveAsset,
|
||||
}) {
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { registerSpriteSet, restoreSpriteOrder } = services.sprites;
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const { ensureGeoidReady } = services.geoid;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
@@ -42,7 +41,7 @@ export function createLifecycle({
|
||||
flightState.lifetime = new AbortController();
|
||||
clearFocusTarget('militaryFlights');
|
||||
flightState._viewer = viewer;
|
||||
registerSpriteSet('military', parts.icons._createIcons(viewer));
|
||||
parts.icons._createIcons(viewer);
|
||||
// The models' draw sets; a hidden item keeps the tracked asset loaded so
|
||||
// the tracked plane's model draws as soon as it is wanted.
|
||||
parts.rendering._createModelSets(viewer, {
|
||||
@@ -78,8 +77,6 @@ export function createLifecycle({
|
||||
|
||||
parts.tracking._installClickHandler(viewer);
|
||||
|
||||
restoreSpriteOrder(viewer);
|
||||
|
||||
console.log('[Data:Military] Initialized with GPU icons');
|
||||
},
|
||||
|
||||
@@ -134,7 +131,6 @@ export function createLifecycle({
|
||||
flightState._lastFleetTickMs = 0;
|
||||
});
|
||||
}
|
||||
restoreSpriteOrder(viewer);
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createHorizonCull } from './view.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
|
||||
const SPRITE_ID = 'street-level:marker';
|
||||
const SET_ID = 'street-level:marker';
|
||||
|
||||
/** Draw-set ids of the markers made so far, so every layer instance has its own. */
|
||||
let markerSets = 0;
|
||||
@@ -45,7 +45,7 @@ function markerIcon(position, bearing, look) {
|
||||
|
||||
/** On-globe marker for the open image, clamped to the ground. */
|
||||
export function createMarker({ state }) {
|
||||
const { render, sprites } = state.services;
|
||||
const { render } = state.services;
|
||||
|
||||
function requestRender() {
|
||||
render?.governorRequestRender?.('street-level-marker');
|
||||
@@ -69,13 +69,11 @@ export function createMarker({ state }) {
|
||||
function ensure(viewer) {
|
||||
if (state.marker.set) return;
|
||||
state.marker.set = drawOf(viewer).icons({
|
||||
id: `${SPRITE_ID}:${++markerSets}`,
|
||||
id: `${SET_ID}:${++markerSets}`,
|
||||
});
|
||||
// Drawn from now, empty: the marker keeps its place under the cones
|
||||
// (made after it), whichever is first given something to draw.
|
||||
// Drawn from now, empty: the marker keeps its place by when it was made
|
||||
// (before the cones), whichever is first given something to draw.
|
||||
state.marker.set.set([]);
|
||||
state.marker.sprite =
|
||||
sprites?.registerSpriteSet?.(SPRITE_ID, state.marker.set.id) ?? null;
|
||||
}
|
||||
|
||||
/** Move (or create) the marker; null removes it. `style`: the provider's `marker`. */
|
||||
@@ -112,10 +110,8 @@ export function createMarker({ state }) {
|
||||
horizon.stop();
|
||||
const markers = state.marker.set;
|
||||
if (!markers) return;
|
||||
sprites?.unregisterSpriteCollection?.(SPRITE_ID, state.marker.sprite);
|
||||
markers.dispose();
|
||||
state.marker.set = null;
|
||||
state.marker.sprite = null;
|
||||
state.marker.placed = null;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,23 +27,10 @@ function setup() {
|
||||
};
|
||||
const draw = fakeDrawPort();
|
||||
bindRenderer(viewer, streetPorts(viewer, { camera: true, draw }));
|
||||
/** Sprite-order registrations: setId → the entry handed out. */
|
||||
const sprites = new Map();
|
||||
const state = {
|
||||
services: {
|
||||
sprites: {
|
||||
registerSpriteSet(layerId, setId) {
|
||||
const entry = { layerId, setId };
|
||||
sprites.set(setId, entry);
|
||||
return entry;
|
||||
},
|
||||
unregisterSpriteCollection(layerId, entry) {
|
||||
if (sprites.get(entry?.setId) === entry) sprites.delete(entry.setId);
|
||||
},
|
||||
},
|
||||
},
|
||||
services: {},
|
||||
viewer,
|
||||
marker: { set: null, sprite: null, placed: null, look: null },
|
||||
marker: { set: null, placed: null, look: null },
|
||||
};
|
||||
const marker = createMarker({ state });
|
||||
marker.ensure(viewer);
|
||||
@@ -52,7 +39,7 @@ function setup() {
|
||||
};
|
||||
/** The marker's drawn icon, or undefined. */
|
||||
const icon = () => draw.find('street-level:marker:')?.items.get('sl:pos');
|
||||
return { state, viewer, view, preRender, marker, frame, draw, icon, sprites };
|
||||
return { state, viewer, view, preRender, marker, frame, draw, icon };
|
||||
}
|
||||
|
||||
test('the photo marker is hidden behind the globe, and shows from its side', () => {
|
||||
@@ -138,16 +125,14 @@ test('each placement is one write, culled before it is sent', () => {
|
||||
assert.equal(set.writes, before + 2);
|
||||
});
|
||||
|
||||
test('a marker destroyed and made again draws in a new set, registered once', () => {
|
||||
const { marker, viewer, draw, sprites, icon } = setup();
|
||||
test('a marker destroyed and made again draws in a new set', () => {
|
||||
const { marker, viewer, draw, icon } = setup();
|
||||
const first = draw.find('street-level:marker:').spec.id;
|
||||
assert.deepEqual([...sprites.keys()], [first]);
|
||||
marker.destroy();
|
||||
assert.equal(sprites.size, 0, 'its sprite order entry goes with it');
|
||||
assert.equal(draw.set(first), undefined, 'its set goes with it');
|
||||
marker.ensure(viewer);
|
||||
const second = draw.find('street-level:marker:').spec.id;
|
||||
assert.notEqual(second, first);
|
||||
assert.deepEqual([...sprites.keys()], [second]);
|
||||
marker.set(SPOT, 30);
|
||||
assert.equal(icon().course, 30);
|
||||
});
|
||||
@@ -100,7 +100,6 @@ export function createKartaViewProvider({
|
||||
selectedId: null,
|
||||
images: [],
|
||||
set: null,
|
||||
sprite: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
abort: null,
|
||||
|
||||
@@ -46,7 +46,6 @@ function createProviderState(context) {
|
||||
selectedId: null,
|
||||
images: [],
|
||||
set: null,
|
||||
sprite: null,
|
||||
loading: false,
|
||||
/** Why the selected sequence's images could not load, until it goes. */
|
||||
error: null,
|
||||
|
||||
@@ -171,7 +171,6 @@ export function createPanoramaxProvider({
|
||||
selectedId: null,
|
||||
images: [],
|
||||
set: null,
|
||||
sprite: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
abort: null,
|
||||
|
||||
@@ -27,7 +27,7 @@ export function filtersOf(provider) {
|
||||
* @property {(context: ProviderContext) => ProviderInstance} create
|
||||
*
|
||||
* @typedef {object} ProviderContext Handed to `create()` once by the core.
|
||||
* @property {object} services Scene services: picking, input, render, sprites (a `scenePick` given is not read).
|
||||
* @property {object} services Scene services: picking, input, render (a `scenePick` given is not read).
|
||||
* @property {() => {pano: string, sinceMs: number|null}} getFilter Filter resolved against now; read it on every use so "since N days" keeps up.
|
||||
* @property {() => boolean} isActive Layer enabled and this provider switched on.
|
||||
* @property {() => void} notify Ask the core to publish a new UI snapshot.
|
||||
|
||||
@@ -54,7 +54,7 @@ export function thinImages(images, spacingM = IMAGE_CONE_MIN_SPACING_M) {
|
||||
* The sequence's images in capture order, thinned (see `thinImages`).
|
||||
* @param {{coverage: string}} options.colors
|
||||
* @param {string} options.pickPrefix Pick-id prefix of the cones.
|
||||
* @param {string} options.spriteId Sprite-order id of the cone set (and its draw-set id's stem).
|
||||
* @param {string} options.spriteId Stem of the cone set's draw-set id.
|
||||
* @param {string} options.renderKey Render-governor reason.
|
||||
* @param {(sequenceId: string|null) => void} [options.onHighlight]
|
||||
* Highlight the sequence's coverage line (null: none).
|
||||
@@ -71,7 +71,7 @@ export function createSequenceCones({
|
||||
onHighlight = () => {},
|
||||
passes = passesImageryFilter,
|
||||
}) {
|
||||
const { render, sprites } = state.services;
|
||||
const { render } = state.services;
|
||||
|
||||
function requestRender() {
|
||||
render?.governorRequestRender?.(renderKey);
|
||||
@@ -101,10 +101,9 @@ export function createSequenceCones({
|
||||
state.sequence.set = drawOf(viewer).icons({
|
||||
id: `${spriteId}:${++coneSets}`,
|
||||
});
|
||||
// Drawn from now, empty: the cones keep their place over the marker.
|
||||
// Drawn from now, empty: the cones keep their place by when they were
|
||||
// made (after the marker).
|
||||
state.sequence.set.set([]);
|
||||
state.sequence.sprite =
|
||||
sprites?.registerSpriteSet?.(spriteId, state.sequence.set.id) ?? null;
|
||||
}
|
||||
|
||||
function clearCones() {
|
||||
@@ -232,10 +231,8 @@ export function createSequenceCones({
|
||||
cones = [];
|
||||
const set = state.sequence.set;
|
||||
if (set) {
|
||||
sprites?.unregisterSpriteCollection?.(spriteId, state.sequence.sprite);
|
||||
set.dispose();
|
||||
state.sequence.set = null;
|
||||
state.sequence.sprite = null;
|
||||
}
|
||||
state.sequence.images = [];
|
||||
state.sequence.selectedId = null;
|
||||
|
||||
@@ -55,8 +55,8 @@ export function createState({ services }) {
|
||||
/** Whether the camera is low enough for a ground click to open an image. */
|
||||
groundClickReady: false,
|
||||
|
||||
/** The open image's marker: its draw set, sprite registration and drawn icon. */
|
||||
marker: { set: null, sprite: null, placed: null, look: null },
|
||||
/** The open image's marker: its draw set and drawn icon. */
|
||||
marker: { set: null, placed: null, look: null },
|
||||
clickSubscription: null,
|
||||
};
|
||||
}
|
||||
@@ -4,13 +4,12 @@ import { TRANSIT_ENABLED_FEEDS } from '../../data/transitFeeds.js';
|
||||
|
||||
/**
|
||||
* Init / enable / disable / update / destroy for one Transit layer instance.
|
||||
* Everything acquired here is released here — primitives, listeners, the sprite
|
||||
* registration, the pick owner, the render hold, and the camera listener.
|
||||
* Everything acquired here is released here — primitives, listeners, the
|
||||
* pick owner, the render hold, and the camera listener.
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createLifecycle({ state, services, parts }) {
|
||||
const { restoreSpriteOrder } = services.sprites;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
const { releaseContinuousRender } = services.render;
|
||||
|
||||
@@ -112,7 +111,6 @@ export function createLifecycle({ state, services, parts }) {
|
||||
state._rotationPose = null;
|
||||
state._rotationDirty = false;
|
||||
state._overlayHost.setVisible(TRANSIT_SELECTED_OVERLAY_SOURCE_ID, false);
|
||||
restoreSpriteOrder(viewer);
|
||||
bindStyleEvents();
|
||||
console.log(
|
||||
`[Data:Transit] Initialized with ${TRANSIT_ENABLED_FEEDS.length} GTFS-RT feeds`,
|
||||
@@ -143,7 +141,6 @@ export function createLifecycle({ state, services, parts }) {
|
||||
}
|
||||
parts.rendering.startFrames(viewer);
|
||||
parts.viewport.runProximityCheck();
|
||||
restoreSpriteOrder(viewer);
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createTransitLayer } from './index.js';
|
||||
import { spriteDrawOrder } from '../../data/spriteOrder.js';
|
||||
import {
|
||||
FEED_EVICT_AFTER_MS,
|
||||
FEED_STALE_AFTER_MS,
|
||||
@@ -240,7 +241,6 @@ function harness(
|
||||
const originalFetch = globalThis.fetch;
|
||||
const originalDocument = globalThis.document;
|
||||
const primitives = [];
|
||||
const sprites = new Map();
|
||||
const pickOwners = new Map();
|
||||
const overlaySources = new Map();
|
||||
const credits = [];
|
||||
@@ -306,7 +306,6 @@ function harness(
|
||||
get length() {
|
||||
return primitives.length;
|
||||
},
|
||||
raiseToTop() {},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -343,17 +342,7 @@ function harness(
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
},
|
||||
sprites: {
|
||||
registerSpriteCollection: (id, collection) =>
|
||||
sprites.set(id, collection),
|
||||
registerSpriteSet: (id, setId) => {
|
||||
const entry = { drawSetId: setId };
|
||||
sprites.set(id, entry);
|
||||
return entry;
|
||||
},
|
||||
unregisterSpriteCollection: (id) => sprites.delete(id),
|
||||
restoreSpriteOrder() {},
|
||||
},
|
||||
sprites: { spriteDrawOrder },
|
||||
picking: {
|
||||
registerPickOwner: (id, predicate) => pickOwners.set(id, predicate),
|
||||
unregisterPickOwner: (id) => pickOwners.delete(id),
|
||||
@@ -524,7 +513,6 @@ function harness(
|
||||
cameraThresholds: () => [...cameraListeners].map((l) => l.threshold),
|
||||
input,
|
||||
primitives,
|
||||
sprites,
|
||||
pickOwners,
|
||||
overlaySources,
|
||||
credits,
|
||||
@@ -1108,7 +1096,6 @@ test('destroy releases every shared registration this layer took', async (t) =>
|
||||
}));
|
||||
app.layer.enable(app.viewer);
|
||||
await app.layer.update();
|
||||
assert.ok(app.sprites.has('transit'));
|
||||
assert.ok(app.pickOwners.has('transit'));
|
||||
const ids = app.layer._transitSetIdsForTest();
|
||||
assert.deepEqual(
|
||||
@@ -1119,11 +1106,6 @@ test('destroy releases every shared registration this layer took', async (t) =>
|
||||
|
||||
app.layer.destroy(app.viewer);
|
||||
assert.deepEqual(app.cameraThresholds(), [], 'the camera listener goes');
|
||||
assert.equal(
|
||||
app.sprites.has('transit'),
|
||||
false,
|
||||
'the sprite collection is unregistered',
|
||||
);
|
||||
assert.equal(
|
||||
app.pickOwners.has('transit'),
|
||||
false,
|
||||
@@ -1149,11 +1131,7 @@ test('two layers built from the factory share no state', async (t) => {
|
||||
holdContinuousRender,
|
||||
releaseContinuousRender,
|
||||
},
|
||||
sprites: {
|
||||
registerSpriteCollection() {},
|
||||
unregisterSpriteCollection() {},
|
||||
restoreSpriteOrder() {},
|
||||
},
|
||||
sprites: { spriteDrawOrder },
|
||||
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
|
||||
overlays: {
|
||||
setOverlayEntries() {},
|
||||
@@ -3846,7 +3824,7 @@ test('the actual Transit lifecycle keeps exactly its own camera listener in ever
|
||||
_failedCityIds: new Set(),
|
||||
},
|
||||
services: {
|
||||
sprites: { restoreSpriteOrder: noop },
|
||||
sprites: { spriteDrawOrder },
|
||||
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
|
||||
},
|
||||
source: {},
|
||||
@@ -3946,60 +3924,19 @@ test('the actual Transit lifecycle keeps exactly its own camera listener in ever
|
||||
}
|
||||
});
|
||||
|
||||
test('moving and stationary transit stay adjacent above CCTV and Bikeshare during migration', async (t) => {
|
||||
const {
|
||||
registerSpriteCollection,
|
||||
unregisterSpriteCollection,
|
||||
restoreSpriteOrder,
|
||||
} = await import('../../data/spriteOrder.js');
|
||||
test('moving and stationary transit draw next to each other, above CCTV and Bikeshare and under flights', (t) => {
|
||||
const app = harness(t);
|
||||
app.layer.enable(app.viewer);
|
||||
app.layer._loadTransitFleetForTest(1, BOSTON, 70);
|
||||
const cctv = {},
|
||||
bike = {},
|
||||
flights = {};
|
||||
// The marker sets' hosts, named by their set ids as the draw port names
|
||||
// them, between the others.
|
||||
const [stillId, movingId] = app.layer._transitSetIdsForTest();
|
||||
const still = { drawSetId: stillId },
|
||||
moving = { drawSetId: movingId };
|
||||
app.primitives.push(cctv, still, bike, moving, flights);
|
||||
app.viewer.scene.primitives.raiseToTop = (c) => {
|
||||
app.primitives.splice(app.primitives.indexOf(c), 1);
|
||||
app.primitives.push(c);
|
||||
};
|
||||
const collections = new Map([
|
||||
...app.sprites,
|
||||
['cctv', cctv],
|
||||
['bikeshare', bike],
|
||||
['flights', flights],
|
||||
]);
|
||||
for (const [id, collection] of collections)
|
||||
registerSpriteCollection(id, collection);
|
||||
t.after(() => {
|
||||
for (const [id, c] of collections) unregisterSpriteCollection(id, c);
|
||||
});
|
||||
const entry = app.vehicles()[0],
|
||||
parts = app.layer._transitPartsForTest();
|
||||
const stillHost = still,
|
||||
movingHost = moving;
|
||||
for (const moving of [true, false, true]) {
|
||||
entry.sample.phase = moving ? 'playing' : 'held';
|
||||
entry.sample.segmentSpeedMps = moving ? 1 : 0;
|
||||
entry.sample.segmentCourseDeg = NaN;
|
||||
parts.rendering.schedulePlayback(entry);
|
||||
restoreSpriteOrder(app.viewer);
|
||||
parts.rendering.flushMarkers();
|
||||
assert.ok(app.markers(moving ? 'moving' : 'still').has(entry.key));
|
||||
const active = app.primitives.indexOf(moving ? movingHost : stillHost);
|
||||
assert.ok(active > app.primitives.indexOf(cctv));
|
||||
assert.ok(active > app.primitives.indexOf(bike));
|
||||
assert.ok(active < app.primitives.indexOf(flights));
|
||||
assert.equal(
|
||||
app.primitives.indexOf(movingHost) - app.primitives.indexOf(stillHost),
|
||||
1,
|
||||
);
|
||||
}
|
||||
const [still, moving] = app.layer
|
||||
._transitSetIdsForTest()
|
||||
.map((id) => app.draw.set(id).spec.drawOrder);
|
||||
assert.equal(still, spriteDrawOrder('transit'));
|
||||
assert.equal(moving, spriteDrawOrder('transit-motion'));
|
||||
assert.equal(moving - still, 1, 'adjacent, the moving ones over the still');
|
||||
for (const under of ['cctv', 'bikeshare'])
|
||||
assert.ok(still > spriteDrawOrder(under), `over ${under}`);
|
||||
assert.ok(moving < spriteDrawOrder('flights'), 'under flights');
|
||||
});
|
||||
|
||||
test('transit polls the supplied source and cancels it when disabled', async (t) => {
|
||||
|
||||
@@ -77,32 +77,30 @@ export function createRendering({ state, services, parts }) {
|
||||
|
||||
/**
|
||||
* The two icon sets, still and moving, hidden, in the scene now (with no
|
||||
* items) and in the shared sprite order. A viewer of the layer's own
|
||||
* draws through `./render/cesium/unbound`, which its owner loads.
|
||||
* items), each at its place in the shared sprite order. A viewer of the
|
||||
* layer's own draws through `./render/cesium/unbound`, which its owner loads.
|
||||
* @param {object} viewer
|
||||
*/
|
||||
function createMarkers(viewer) {
|
||||
destroyMarkers(viewer);
|
||||
const draw = drawOf(viewer);
|
||||
const drawOrder = (layerId) =>
|
||||
services.sprites?.spriteDrawOrder?.(layerId) ?? 0;
|
||||
state._stillIcons = draw.icons({
|
||||
id: `transit:${instance}:still`,
|
||||
blend: 'translucent',
|
||||
show: false,
|
||||
drawOrder: drawOrder('transit'),
|
||||
});
|
||||
state._movingIcons = draw.icons({
|
||||
id: `transit:${instance}:moving`,
|
||||
blend: 'translucent',
|
||||
show: false,
|
||||
drawOrder: drawOrder('transit-motion'),
|
||||
});
|
||||
// Emptied, they are drawn now: the sprite order finds them at once.
|
||||
// Emptied, they are drawn now: in the scene at once.
|
||||
state._stillIcons.set([]);
|
||||
state._movingIcons.set([]);
|
||||
const { registerSpriteSet } = services.sprites;
|
||||
state._stillSprite = registerSpriteSet?.('transit', state._stillIcons.id);
|
||||
state._movingSprite = registerSpriteSet?.(
|
||||
'transit-motion',
|
||||
state._movingIcons.id,
|
||||
);
|
||||
state._markersShown = false;
|
||||
}
|
||||
|
||||
@@ -127,27 +125,20 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Let both sets go and take them out of the sprite order.
|
||||
* Let both sets go.
|
||||
* @param {object|null|undefined} _viewer
|
||||
*/
|
||||
function destroyMarkers(_viewer) {
|
||||
dirty.clear();
|
||||
stillRemovals.length = 0;
|
||||
movingRemovals.length = 0;
|
||||
const { unregisterSpriteCollection } = services.sprites;
|
||||
if (state._stillIcons) {
|
||||
if (state._stillSprite)
|
||||
unregisterSpriteCollection?.('transit', state._stillSprite);
|
||||
state._stillIcons.dispose();
|
||||
state._stillIcons = null;
|
||||
state._stillSprite = null;
|
||||
}
|
||||
if (state._movingIcons) {
|
||||
if (state._movingSprite)
|
||||
unregisterSpriteCollection?.('transit-motion', state._movingSprite);
|
||||
state._movingIcons.dispose();
|
||||
state._movingIcons = null;
|
||||
state._movingSprite = null;
|
||||
}
|
||||
state._markersShown = false;
|
||||
}
|
||||
|
||||
@@ -26,9 +26,6 @@ export function createState({ services }) {
|
||||
/** The still markers' icon draw set, and the moving ones', or null. */
|
||||
state._stillIcons = null;
|
||||
state._movingIcons = null;
|
||||
/** Their sprite-order registrations. */
|
||||
state._stillSprite = null;
|
||||
state._movingSprite = null;
|
||||
/** Whether the markers are shown (the layer is on). */
|
||||
state._markersShown = false;
|
||||
state._visible = new Set();
|
||||
|
||||
@@ -10,7 +10,6 @@ export function createLifecycle({
|
||||
options,
|
||||
}) {
|
||||
const { state } = vesselState;
|
||||
const { restoreSpriteOrder, restoreSpriteOrderOnEnable } = services.sprites;
|
||||
const { releaseContinuousRender } = services.render;
|
||||
const { ensureGeoidReady } = services.geoid;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
@@ -157,7 +156,6 @@ export function createLifecycle({
|
||||
);
|
||||
components.selection.installInteraction(viewer);
|
||||
components.rendering.installRuntime(viewer);
|
||||
restoreSpriteOrder(viewer);
|
||||
},
|
||||
|
||||
enable(viewer) {
|
||||
@@ -190,7 +188,6 @@ export function createLifecycle({
|
||||
registerPickOwner('ais-live-vessels', (pickedId) =>
|
||||
state.records.byMmsi.has(pickedId),
|
||||
);
|
||||
restoreSpriteOrderOnEnable('ais', activeViewer);
|
||||
// Vessels are asked for by view, so ask again when the view moves away.
|
||||
removeViewListener();
|
||||
const moveEnd = activeViewer?.camera?.moveEnd;
|
||||
|
||||
@@ -32,7 +32,7 @@ function services() {
|
||||
clearOverlaySource: noop,
|
||||
},
|
||||
geoid: {},
|
||||
sprites: { registerSpriteSet: noop },
|
||||
sprites: {},
|
||||
focus: {
|
||||
focusNowMs: (now) => now,
|
||||
getFocusTarget: () => null,
|
||||
|
||||
@@ -34,7 +34,7 @@ function setup({ focusPassIsNeeded = () => false } = {}) {
|
||||
clearOverlaySource: noop,
|
||||
},
|
||||
geoid: {},
|
||||
sprites: { registerSpriteSet: noop },
|
||||
sprites: {},
|
||||
focus: {
|
||||
focusNowMs: () => clock,
|
||||
getFocusTarget: () => null,
|
||||
|
||||
@@ -92,8 +92,7 @@ export function createRendering({
|
||||
visualRecords = new WeakMap();
|
||||
}
|
||||
|
||||
const { registerSpriteSet } = services.sprites;
|
||||
let warnedNoSpriteOrder = false;
|
||||
const { spriteDrawOrder } = services.sprites;
|
||||
const {
|
||||
forgetSpriteFocus,
|
||||
focusNowMs,
|
||||
@@ -138,20 +137,13 @@ export function createRendering({
|
||||
const set = drawOf(viewer).icons({
|
||||
id: `ais-vessels:${++instances}`,
|
||||
horizonCull: true,
|
||||
drawOrder: spriteDrawOrder?.('ais') ?? 0,
|
||||
});
|
||||
// Columns of no rows put the set's host in the scene now, where the
|
||||
// sprite order finds it, rather than with its first vessel.
|
||||
// Columns of no rows put the set's host in the scene now, rather than
|
||||
// with its first vessel.
|
||||
set.setColumns?.({ ids: [] });
|
||||
state.icons = createVesselIconBook(set);
|
||||
state.icons.show = state.feed.enabled;
|
||||
if (registerSpriteSet) registerSpriteSet('ais', set.id);
|
||||
else if (!warnedNoSpriteOrder) {
|
||||
// Drawn still, but not raised over the other sprite layers.
|
||||
warnedNoSpriteOrder = true;
|
||||
console.warn(
|
||||
'[Data:ais-live-vessels] the host has no registerSpriteSet; ships keep their draw order',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Let the icon draw set go (the layer is destroyed). */
|
||||
|
||||
+51
-15
@@ -224,6 +224,23 @@ const DEPTH_BIASED_STATE = Object.freeze({
|
||||
blending: Cesium.BlendingState.ALPHA_BLEND,
|
||||
});
|
||||
|
||||
/**
|
||||
* An image fill's material. The image carries its own alpha, so it draws in
|
||||
* the translucent pass whatever its colour, as the entities' image
|
||||
* materials did.
|
||||
*/
|
||||
function imageMaterial(image, repeat = [1, 1]) {
|
||||
// Typed first and given its uniforms after, as `Material.fromType` does:
|
||||
// the image loads when first drawn, not here.
|
||||
const material = new Cesium.Material({
|
||||
fabric: { type: 'Image' },
|
||||
translucent: true,
|
||||
});
|
||||
material.uniforms.image = image;
|
||||
material.uniforms.repeat = new Cesium.Cartesian2(...repeat);
|
||||
return material;
|
||||
}
|
||||
|
||||
/** A `radialRim` fill's material. */
|
||||
function radialRimMaterial(fill) {
|
||||
const uniforms = {
|
||||
@@ -722,7 +739,8 @@ export function createCesiumDraw({
|
||||
slot >= 0 && slot + 1 < scene.primitives.length
|
||||
? scene.primitives.get(slot + 1)
|
||||
: null;
|
||||
// Named for code that orders the scene's primitives (`spriteOrder.js`).
|
||||
// Named for code that finds a set's host among the scene's primitives
|
||||
// (`uploadProbe.js`).
|
||||
host.drawSetId = record.spec.id;
|
||||
// Only old ground primitives wait for the new ones: the rest of the old
|
||||
// host goes now, as the new host's own parts draw at once.
|
||||
@@ -765,9 +783,8 @@ export function createCesiumDraw({
|
||||
* higher order goes earlier; of one order, in the order they were made.
|
||||
* The hosts trade places among the slots they hold, so nothing else in
|
||||
* the scene moves. Nothing moves while every set is at 0 (unless an order
|
||||
* just changed, `changed`), so sets at 0 stack as they were first drawn
|
||||
* (and as the sprite order raises them); nor while the hosts are already
|
||||
* in order.
|
||||
* just changed, `changed`), so sets at 0 stack as they were first drawn;
|
||||
* nor while the hosts are already in order.
|
||||
* Translucent ones blend order-independently, whatever their order, and
|
||||
* items in different view frustums stack nearer frustum first.
|
||||
* @param {boolean} [changed]
|
||||
@@ -1024,6 +1041,11 @@ export function createCesiumDraw({
|
||||
// The defaults, so a restyle in place puts back what an item dropped.
|
||||
rotation: 0,
|
||||
alignedAxis: Cesium.Cartesian3.ZERO,
|
||||
// CSS pixels, y down, as the billboard takes them.
|
||||
pixelOffset: new Cesium.Cartesian2(
|
||||
item.pixelOffset?.x ?? 0,
|
||||
item.pixelOffset?.y ?? 0,
|
||||
),
|
||||
};
|
||||
if (item.rotationMode === 'screen') look.rotation = item.rotation ?? 0;
|
||||
if (item.rotationMode === 'course') {
|
||||
@@ -1066,6 +1088,9 @@ export function createCesiumDraw({
|
||||
rotationMode: item.rotationMode,
|
||||
rotation: item.rotation,
|
||||
course: item.course,
|
||||
pixelOffset: item.pixelOffset
|
||||
? [item.pixelOffset.x ?? 0, item.pixelOffset.y ?? 0]
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1112,7 +1137,11 @@ export function createCesiumDraw({
|
||||
sameCurve(style.fadeByDistance, item.fadeByDistance) &&
|
||||
style.rotationMode === item.rotationMode &&
|
||||
(item.rotationMode === 'screen' || style.rotation === item.rotation) &&
|
||||
style.course === item.course
|
||||
style.course === item.course &&
|
||||
(item.pixelOffset
|
||||
? style.pixelOffset?.[0] === (item.pixelOffset.x ?? 0) &&
|
||||
style.pixelOffset[1] === (item.pixelOffset.y ?? 0)
|
||||
: style.pixelOffset === undefined)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3255,6 +3284,21 @@ export function createCesiumDraw({
|
||||
),
|
||||
};
|
||||
}
|
||||
case 'wall': {
|
||||
// Up from `minimumHeights` (the ellipsoid) to `maximumHeights` (the
|
||||
// positions' own), as the entities' walls draw.
|
||||
const wall = {
|
||||
positions: g.positions.map(toCartesian),
|
||||
minimumHeights: g.minimumHeights,
|
||||
maximumHeights: g.maximumHeights,
|
||||
};
|
||||
return {
|
||||
fill: new Cesium.WallGeometry({ ...wall, vertexFormat }),
|
||||
outline: item.outline
|
||||
? new Cesium.WallOutlineGeometry(wall)
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`the Cesium renderer has no ${g.kind} shapes`);
|
||||
}
|
||||
@@ -3523,12 +3567,7 @@ export function createCesiumDraw({
|
||||
: UnpickableGroundPrimitive;
|
||||
const grounds = batches.map((batch) => {
|
||||
const material = batch.imageFill
|
||||
? Cesium.Material.fromType('Image', {
|
||||
image: batch.image,
|
||||
repeat: new Cesium.Cartesian2(
|
||||
...(batch.imageFill.repeat ?? [1, 1]),
|
||||
),
|
||||
})
|
||||
? imageMaterial(batch.image, batch.imageFill.repeat)
|
||||
: batch.rimFill
|
||||
? radialRimMaterial(batch.rimFill)
|
||||
: null;
|
||||
@@ -4147,10 +4186,7 @@ export function createCesiumDraw({
|
||||
);
|
||||
} else if (imageFill && !item.outlineOnly) {
|
||||
const material = ownMaterial(
|
||||
Cesium.Material.fromType('Image', {
|
||||
image: toImage(imageFill.image),
|
||||
repeat: new Cesium.Cartesian2(...(imageFill.repeat ?? [1, 1])),
|
||||
}),
|
||||
imageMaterial(toImage(imageFill.image), imageFill.repeat),
|
||||
);
|
||||
host.add(
|
||||
new Cesium.Primitive({
|
||||
|
||||
+133
-98
@@ -13,6 +13,7 @@ import {
|
||||
} from './draw.js';
|
||||
import { drawHitOf } from './drawHit.js';
|
||||
import { MODEL_RETRY_MS } from './drawModels.js';
|
||||
import { spriteDrawOrder } from '../../data/spriteOrder.js';
|
||||
|
||||
// Node has no WebGL context to report line-width limits.
|
||||
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
|
||||
@@ -1669,13 +1670,7 @@ test('the traffic layer draws its dots as one point collection moved, added to a
|
||||
assert.equal(scene.added.length, 0);
|
||||
});
|
||||
|
||||
test('a rebuilt set keeps its place among the scene primitives, and names its host', async () => {
|
||||
const {
|
||||
registerSpriteSet,
|
||||
registerSpriteCollection,
|
||||
restoreSpriteOrder,
|
||||
unregisterSpriteCollection,
|
||||
} = await import('../../data/spriteOrder.js');
|
||||
test('a rebuilt set keeps its place among the scene primitives, and names its host', () => {
|
||||
const scene = fakeScene();
|
||||
scene.primitives = new Cesium.PrimitiveCollection();
|
||||
const { draw } = drawOver(scene);
|
||||
@@ -1702,17 +1697,6 @@ test('a rebuilt set keeps its place among the scene primitives, and names its ho
|
||||
'not raised by updates',
|
||||
);
|
||||
|
||||
// The sprite order finds the set's host by its id, whichever host it is.
|
||||
const cctv = registerSpriteCollection('cctv', below);
|
||||
const flights = registerSpriteCollection('flights', above);
|
||||
const entry = registerSpriteSet('bikeshare', 'kept');
|
||||
scene.primitives.raiseToTop(below);
|
||||
assert.deepEqual(order(), ['kept', 'above', 'below']);
|
||||
restoreSpriteOrder({ scene });
|
||||
assert.deepEqual(order(), ['below', 'kept', 'above']);
|
||||
unregisterSpriteCollection('bikeshare', entry);
|
||||
unregisterSpriteCollection('cctv', cctv);
|
||||
unregisterSpriteCollection('flights', flights);
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
@@ -1784,6 +1768,54 @@ test('reordering by drawOrder leaves the other primitives where they are', () =>
|
||||
for (const set of [a, b, c]) set.dispose();
|
||||
});
|
||||
|
||||
test('sprite layers stack flights on top, all under a set at the default order', () => {
|
||||
const scene = fakeScene();
|
||||
scene.primitives = new Cesium.PrimitiveCollection();
|
||||
const { draw } = drawOver(scene);
|
||||
const dot = { id: 'a', pos: { lon: 0, lat: 0 }, pixelSize: 4, color: '#fff' };
|
||||
// Made before every sprite set, and again after them.
|
||||
const highlight = draw.points({ id: 'highlight' });
|
||||
highlight.set([dot]);
|
||||
const sets = ['flights', 'cctv', 'ais', 'transit'].map((layerId) => {
|
||||
const set = draw.points({
|
||||
id: layerId,
|
||||
drawOrder: spriteDrawOrder(layerId),
|
||||
});
|
||||
set.set([dot]);
|
||||
return set;
|
||||
});
|
||||
const endpoint = draw.points({ id: 'endpoint' });
|
||||
endpoint.set([dot]);
|
||||
const order = [];
|
||||
for (let i = 0; i < scene.primitives.length; i++) {
|
||||
order.push(scene.primitives.get(i).drawSetId);
|
||||
}
|
||||
// Earlier draws on top.
|
||||
assert.deepEqual(order, [
|
||||
'highlight',
|
||||
'endpoint',
|
||||
'flights',
|
||||
'ais',
|
||||
'transit',
|
||||
'cctv',
|
||||
]);
|
||||
// Raised above flights in place, CCTV keeps every other set's slot.
|
||||
sets[1].setOptions({ drawOrder: spriteDrawOrder('flights') + 0.5 });
|
||||
const after = [];
|
||||
for (let i = 0; i < scene.primitives.length; i++) {
|
||||
after.push(scene.primitives.get(i).drawSetId);
|
||||
}
|
||||
assert.deepEqual(after, [
|
||||
'highlight',
|
||||
'endpoint',
|
||||
'cctv',
|
||||
'flights',
|
||||
'ais',
|
||||
'transit',
|
||||
]);
|
||||
for (const set of [highlight, endpoint, ...sets]) set.dispose();
|
||||
});
|
||||
|
||||
test('changing an option rebuilds only the kinds that build it in, in their place', () => {
|
||||
const scene = fakeScene();
|
||||
scene.primitives = new Cesium.PrimitiveCollection();
|
||||
@@ -2252,17 +2284,12 @@ test('the GNSS layer draws its cells as ground fills that stay out of the pick p
|
||||
test('the fires layer draws its heat cells as ground fills through the Cesium draw port', async (t) => {
|
||||
const { createFirmsHeatmapLayer } =
|
||||
await import('../../data/firmsHeatmap.js');
|
||||
const { unregisterSpriteCollection } =
|
||||
await import('../../data/spriteOrder.js');
|
||||
const { fakeInput } = await import('../../input/testDoubles.mjs');
|
||||
const { bindFakeCesiumScene } =
|
||||
await import('../../testSupport/fakeCesiumScene.mjs');
|
||||
const saved = globalThis.window;
|
||||
globalThis.window = new EventTarget();
|
||||
const scene = fakeScene();
|
||||
// The layer keeps its detection icons over other sprites.
|
||||
scene.primitives.contains = (p) => scene.added.includes(p);
|
||||
scene.primitives.raiseToTop = () => {};
|
||||
// Far out, where the layer draws heat cells rather than detections.
|
||||
const viewer = {
|
||||
scene,
|
||||
@@ -2302,7 +2329,6 @@ test('the fires layer draws its heat cells as ground fills through the Cesium dr
|
||||
t.after(() => {
|
||||
input.destroy();
|
||||
unbind();
|
||||
unregisterSpriteCollection('firms');
|
||||
if (saved === undefined) delete globalThis.window;
|
||||
else globalThis.window = saved;
|
||||
});
|
||||
@@ -3330,6 +3356,59 @@ test('a draped line shown after it is ready keeps that show through the swap', (
|
||||
set.dispose();
|
||||
}));
|
||||
|
||||
test('an icon stands off its position by its pixel offset, and back when it has none', () => {
|
||||
const { scene, draw } = drawOver();
|
||||
const set = draw.icons({ id: 'offset-pins' });
|
||||
const icon = (pixelOffset) => ({
|
||||
id: 'a',
|
||||
pos: { lon: 0, lat: 0 },
|
||||
image: 'pin.png',
|
||||
size: [8, 8],
|
||||
...(pixelOffset ? { pixelOffset } : {}),
|
||||
});
|
||||
set.set([icon({ x: 3, y: -4 })]);
|
||||
const pin = () => scene.added[0].get(0);
|
||||
assert.deepEqual([pin().pixelOffset.x, pin().pixelOffset.y], [3, -4]);
|
||||
set.upsert([icon({ x: 0, y: 6 })]);
|
||||
assert.deepEqual([pin().pixelOffset.x, pin().pixelOffset.y], [0, 6]);
|
||||
set.upsert([icon()]);
|
||||
assert.deepEqual([pin().pixelOffset.x, pin().pixelOffset.y], [0, 0]);
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
test('a wall stands up from the ellipsoid to its positions, with or without a fill', () => {
|
||||
const { scene, draw } = drawOver();
|
||||
const set = draw.shapes({ id: 'walls' });
|
||||
const wall = (id, fill) => ({
|
||||
id,
|
||||
geometry: {
|
||||
kind: 'wall',
|
||||
positions: [
|
||||
{ lon: 0, lat: 0, height: 100 },
|
||||
{ lon: 0.01, lat: 0, height: 150 },
|
||||
],
|
||||
},
|
||||
fill,
|
||||
outline: [1, 1, 0, 1],
|
||||
});
|
||||
set.set([wall('filled', [0, 0, 1, 0.5]), wall('outline', null)]);
|
||||
const geometries = [];
|
||||
const walk = (primitive) => {
|
||||
if (!primitive) return;
|
||||
if (primitive instanceof Cesium.PrimitiveCollection)
|
||||
for (let i = 0; i < primitive.length; i++) walk(primitive.get(i));
|
||||
for (const instance of [primitive.geometryInstances ?? []].flat())
|
||||
geometries.push([instance.id?.id, instance.geometry.constructor.name]);
|
||||
};
|
||||
scene.added.forEach(walk);
|
||||
assert.deepEqual(geometries.sort(), [
|
||||
['filled', 'WallGeometry'],
|
||||
['filled', 'WallOutlineGeometry'],
|
||||
['outline', 'WallOutlineGeometry'],
|
||||
]);
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
test('icons blend as their set says', () => {
|
||||
const { scene, draw } = drawOver();
|
||||
const set = draw.icons({ id: 'pins', blend: 'translucent' });
|
||||
@@ -3648,14 +3727,10 @@ test('the vessels layer draws its ships as one GPU icon set that holds them on c
|
||||
await import('../../data/iconSet.js');
|
||||
const spriteOrder = await import('../../data/spriteOrder.js');
|
||||
const scene = fakeScene();
|
||||
const registered = [];
|
||||
const { layer, viewer, part, unbind } = await vesselLayerOver(scene, {
|
||||
registerSpriteSet(layerId, setId) {
|
||||
registered.push([layerId, setId]);
|
||||
return spriteOrder.registerSpriteSet(layerId, setId);
|
||||
},
|
||||
});
|
||||
const military = { name: 'military' };
|
||||
const { layer, viewer, part, unbind } = await vesselLayerOver(
|
||||
scene,
|
||||
spriteOrder,
|
||||
);
|
||||
try {
|
||||
layer.testing._setVesselStateForTest({ viewer, icons: null });
|
||||
layer.testing._reconcileVesselsForTest(viewer, [
|
||||
@@ -3696,34 +3771,11 @@ test('the vessels layer draws its ships as one GPU icon set that holds them on c
|
||||
assert.equal(set.count, 1);
|
||||
assert.equal(set.course(set.row('244000001'), tau), 95);
|
||||
|
||||
// The sprite order finds the host by its set id and stacks it under the
|
||||
// military sprites.
|
||||
assert.deepEqual(registered, [['ais', host.drawSetId]]);
|
||||
spriteOrder.registerSpriteCollection('military', military);
|
||||
const stack = (list) => ({
|
||||
scene: {
|
||||
primitives: {
|
||||
get: (i) => list[i],
|
||||
get length() {
|
||||
return list.length;
|
||||
},
|
||||
contains: (p) => list.includes(p),
|
||||
raiseToTop(p) {
|
||||
list.splice(list.indexOf(p), 1);
|
||||
list.push(p);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const order = [military, host, { name: 'other' }];
|
||||
spriteOrder.restoreSpriteOrder(stack(order));
|
||||
assert.deepEqual(
|
||||
order.map((p) => p.name ?? p.drawSetId),
|
||||
['other', host.drawSetId, 'military'],
|
||||
);
|
||||
// The set stacks at the vessels' place in the sprite order.
|
||||
assert.equal(record.spec.drawOrder, spriteOrder.spriteDrawOrder('ais'));
|
||||
|
||||
// Torn down and drawn again: a new set, registered in the old one's
|
||||
// place, with the old host gone from the scene.
|
||||
// Torn down and drawn again: a new set at the same draw order, with
|
||||
// the old host gone from the scene.
|
||||
layer.destroy(viewer);
|
||||
assert.equal(scene.added.length, 0, 'destroyed: the set goes');
|
||||
layer.testing._setVesselStateForTest({ viewer, icons: null });
|
||||
@@ -3735,16 +3787,13 @@ test('the vessels layer draws its ships as one GPU icon set that holds them on c
|
||||
assert.notEqual(again, host);
|
||||
assert.notEqual(again.drawSetId, host.drawSetId, 'a new set id');
|
||||
assert.equal(part.sets.has(host.drawSetId), false);
|
||||
assert.deepEqual(registered.at(-1), ['ais', again.drawSetId]);
|
||||
const stray = { name: 'stray' };
|
||||
const next = [military, again, stray];
|
||||
spriteOrder.restoreSpriteOrder(stack(next));
|
||||
assert.deepEqual(next, [stray, again, military], 'the new host is raised');
|
||||
assert.equal(
|
||||
part.sets.get(again.drawSetId).spec.drawOrder,
|
||||
spriteOrder.spriteDrawOrder('ais'),
|
||||
);
|
||||
layer.destroy(viewer);
|
||||
assert.equal(scene.added.length, 0);
|
||||
} finally {
|
||||
spriteOrder.unregisterSpriteCollection('military', military);
|
||||
spriteOrder.unregisterSpriteCollection('ais');
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
@@ -3790,12 +3839,10 @@ test('the FIRMS layer draws its fire glows as one GPU icon set on a viewer of it
|
||||
warmFireAnchorFloors: async () => false,
|
||||
},
|
||||
sprites: {
|
||||
registerSpriteSet: (layerId, setId) => {
|
||||
sprites.push([layerId, setId]);
|
||||
return { drawSetId: setId };
|
||||
spriteDrawOrder: (layerId) => {
|
||||
sprites.push(layerId);
|
||||
return spriteDrawOrder(layerId);
|
||||
},
|
||||
unregisterSpriteCollection: noop,
|
||||
restoreSpriteOrder: noop,
|
||||
},
|
||||
};
|
||||
const config = {
|
||||
@@ -3826,7 +3873,7 @@ test('the FIRMS layer draws its fire glows as one GPU icon set on a viewer of it
|
||||
|
||||
const [host] = scene.added;
|
||||
assert.ok(host instanceof IconSetPrimitive, 'one GPU icon set');
|
||||
assert.deepEqual(sprites, [['firms', host.drawSetId]]);
|
||||
assert.deepEqual(sprites, ['firms'], 'at the fires’ draw order');
|
||||
const set = host.set;
|
||||
assert.equal(set.count, 2);
|
||||
const strong = set.row('firms-0');
|
||||
@@ -3980,20 +4027,14 @@ test('the Radio layer draws its stations, clusters and selected marker as point
|
||||
assert.equal(scene.added.length, 0, 'gone with the layer');
|
||||
});
|
||||
|
||||
test('vessels on a host with no sprite-set registry still draw, and say so once', async (t) => {
|
||||
const warnings = [];
|
||||
t.mock.method(console, 'warn', (...args) => warnings.push(args.join(' ')));
|
||||
test('vessels on a host without the sprite order still draw, at the default draw order', async () => {
|
||||
const scene = fakeScene();
|
||||
const { layer, viewer, unbind } = await vesselLayerOver(scene, {});
|
||||
const { layer, viewer, part, unbind } = await vesselLayerOver(scene, {});
|
||||
const ship = { mmsi: '244000001', lat: 51.95, lon: 4.1, heading: 90 };
|
||||
layer.testing._setVesselStateForTest({ viewer, icons: null });
|
||||
layer.testing._reconcileVesselsForTest(viewer, [ship]);
|
||||
assert.equal(scene.added.length, 1, 'drawn');
|
||||
layer.destroy(viewer);
|
||||
layer.testing._setVesselStateForTest({ viewer, icons: null });
|
||||
layer.testing._reconcileVesselsForTest(viewer, [ship]);
|
||||
const said = warnings.filter((w) => w.includes('registerSpriteSet'));
|
||||
assert.equal(said.length, 1, 'once, not per set');
|
||||
assert.equal(part.sets.get(scene.added[0].drawSetId).spec.drawOrder, 0);
|
||||
layer.destroy(viewer);
|
||||
unbind();
|
||||
});
|
||||
@@ -4241,6 +4282,7 @@ test('an unclamped shape filled with an image draws a textured primitive and fre
|
||||
assert.ok(appearance instanceof Cesium.MaterialAppearance);
|
||||
assert.equal(appearance.material.type, 'Image');
|
||||
assert.equal(appearance.material.uniforms.image, 'picture.png');
|
||||
assert.equal(appearance.isTranslucent(), true, 'its own alpha blends');
|
||||
assert.deepEqual(
|
||||
appearance.material.uniforms.repeat,
|
||||
new Cesium.Cartesian2(2, 3),
|
||||
@@ -4840,12 +4882,10 @@ test('the directions layer draws its markers, flowing route and maneuver dots on
|
||||
releaseContinuousRender: noop,
|
||||
},
|
||||
sprites: {
|
||||
registerSpriteSet: (layerId, setId) => {
|
||||
sprites.push([layerId, setId]);
|
||||
return { drawSetId: setId };
|
||||
spriteDrawOrder: (layerId) => {
|
||||
sprites.push(layerId);
|
||||
return spriteDrawOrder(layerId);
|
||||
},
|
||||
unregisterSpriteCollection: noop,
|
||||
restoreSpriteOrder: noop,
|
||||
},
|
||||
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
|
||||
overlays: {
|
||||
@@ -4902,12 +4942,12 @@ test('the directions layer draws its markers, flowing route and maneuver dots on
|
||||
[flow.repeat, flow.duty, flow.speed, flow.color.alpha],
|
||||
[64, 0.46, 0.55, 0.95],
|
||||
);
|
||||
// One maneuver dot, at its junction on the ground floor, in the sprite
|
||||
// order.
|
||||
// One maneuver dot, at its junction on the ground floor, at the
|
||||
// directions' draw order.
|
||||
const steps = hostOf(':steps');
|
||||
assert.ok(steps instanceof Cesium.PointPrimitiveCollection);
|
||||
assert.equal(steps.blendOption, Cesium.BlendOption.TRANSLUCENT);
|
||||
assert.deepEqual(sprites, [['directions', steps.drawSetId]]);
|
||||
assert.deepEqual(sprites, ['directions']);
|
||||
assert.equal(steps.length, 1);
|
||||
const dot = steps.get(0);
|
||||
assert.equal(dot.id.id, 'directions:step:1');
|
||||
@@ -7513,12 +7553,10 @@ test('the transit layer draws its vehicles as two icon sets, moving a marker bet
|
||||
releaseContinuousRender: noop,
|
||||
},
|
||||
sprites: {
|
||||
registerSpriteSet: (layerId, setId) => {
|
||||
const entry = { drawSetId: setId };
|
||||
registered.push([layerId, setId]);
|
||||
return entry;
|
||||
spriteDrawOrder: (layerId) => {
|
||||
registered.push(layerId);
|
||||
return spriteDrawOrder(layerId);
|
||||
},
|
||||
unregisterSpriteCollection: noop,
|
||||
},
|
||||
};
|
||||
const state = createState({ services });
|
||||
@@ -7530,10 +7568,7 @@ test('the transit layer draws its vehicles as two icon sets, moving a marker bet
|
||||
});
|
||||
rendering.createMarkers(viewer);
|
||||
const [stillId, movingId] = rendering.setIds();
|
||||
assert.deepEqual(registered, [
|
||||
['transit', stillId],
|
||||
['transit-motion', movingId],
|
||||
]);
|
||||
assert.deepEqual(registered, ['transit', 'transit-motion']);
|
||||
const hostOf = (setId) => scene.added.find((h) => h.drawSetId === setId);
|
||||
assert.ok(hostOf(stillId) instanceof Cesium.BillboardCollection);
|
||||
assert.ok(hostOf(movingId) instanceof Cesium.BillboardCollection);
|
||||
|
||||
@@ -83,7 +83,7 @@ test('a moving item takes its icon set onto the GPU, in its billboards’ place'
|
||||
assert.equal(scene.added.length, 1, 'one host');
|
||||
const host = scene.added[0];
|
||||
assert.ok(host instanceof IconSetPrimitive, 'drawn by the GPU icon set');
|
||||
assert.equal(host.drawSetId, 'gpu:switch', 'named for sprite ordering');
|
||||
assert.equal(host.drawSetId, 'gpu:switch', 'named for finding its host');
|
||||
const { set: rowsOf, course } = rows(part, 'gpu:switch');
|
||||
assert.equal(rowsOf.count, 2, 'the items it had are rows too');
|
||||
assert.equal(set.size(), 2);
|
||||
|
||||
@@ -1 +1 @@
|
||||
["src/data/geoImportPins.js"]
|
||||
[]
|
||||
@@ -255,6 +255,40 @@ test('only allow-listed files outside the Cesium adapter reach Cesium', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('the scan still recognises each way of reaching Cesium', () => {
|
||||
// With the list empty, the check above passes vacuously unless the scan
|
||||
// still sees Cesium; these are the forms the header lists.
|
||||
const reaches = (code, file = 'src/x/y.js') => {
|
||||
const { imports, takesNamespace } = scan(code);
|
||||
return takesNamespace || imports.some((s) => reachesCesium(file, s));
|
||||
};
|
||||
for (const code of [
|
||||
"import * as C from 'cesium';",
|
||||
"import { Viewer } from '@cesium/engine';",
|
||||
"import x from '../../node_modules/cesium/Source/Cesium.js';",
|
||||
"import x from '/node_modules/cesium/index.js?v=1';",
|
||||
"import { draw } from '../render/cesium/draw.js';",
|
||||
"export * from '../render/cesium/draw.js';",
|
||||
"const m = import('cesium');",
|
||||
'function f(Cesium) {}',
|
||||
'const { cesium } = deps;',
|
||||
'const c = window.Cesium;',
|
||||
'Cesium.Color.RED;',
|
||||
])
|
||||
assert.ok(reaches(code), code);
|
||||
for (const code of [
|
||||
"import { drawOf } from '../render/rendererOf.js';",
|
||||
'const cesiumLike = 1; Cesium2.x;',
|
||||
])
|
||||
assert.ok(!reaches(code), code);
|
||||
assert.ok(
|
||||
vueScript(
|
||||
'a.vue',
|
||||
'<script src="../render/cesium/draw.js"></script>',
|
||||
).external.some((s) => reachesCesium('src/ui/a.vue', s)),
|
||||
);
|
||||
});
|
||||
|
||||
test('every allow-listed file still reaches Cesium', () => {
|
||||
const present = new Set(runtimeFiles);
|
||||
const stale = allowList.filter(
|
||||
|
||||
@@ -139,9 +139,8 @@ const DRAW_FROM_CALLER = new Set([
|
||||
// eye and shade the globe through the ports alone.
|
||||
'./application/layers',
|
||||
'./standalone/catalog',
|
||||
// The application's tools (scene director, annotations, embed views):
|
||||
// they draw, fly and take clicks through the ports; only Import's pins
|
||||
// (`src/data/geoImportPins.js`, still on the Cesium list) drive Cesium.
|
||||
// The application's tools (scene director, annotations, embed views,
|
||||
// Import): they draw, fly and take clicks through the ports.
|
||||
'./application/tools',
|
||||
]);
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
"src/celestialRing.js": 1,
|
||||
"src/data/bhoteKoshiEmbeddedMedia.js": 1,
|
||||
"src/data/followed.js": 5,
|
||||
"src/data/spriteOrder.js": 2,
|
||||
"src/layers/flights/motion.js": 1,
|
||||
"src/layers/military/motion.js": 1,
|
||||
"src/layers/streetLevel/view.js": 1,
|
||||
|
||||
@@ -411,12 +411,11 @@ test('the imported files render what the file import publishes and keep focus',
|
||||
const viewer = {
|
||||
container: document.createElement('div'),
|
||||
scene: { requestRender() {} },
|
||||
dataSources: { add: async (ds) => ds, remove: () => true },
|
||||
};
|
||||
const tool = initGeoFileImport({
|
||||
viewer,
|
||||
load: async (file) => ({
|
||||
dataSource: { show: true },
|
||||
drawing: { show: true, destroy() {} },
|
||||
name: file.name,
|
||||
format: file.name.endsWith('.kml') ? 'kml' : 'geojson',
|
||||
entityCount: 2,
|
||||
|
||||
@@ -9,7 +9,7 @@ import { findCamera } from '../render/rendererOf.js';
|
||||
|
||||
/**
|
||||
* Fly synchronously to a footprint, `[lon, lat, height]` points (degrees,
|
||||
* metres) such as a file's (`dataSourcePoints`); later navigation always
|
||||
* metres) such as a file's (`importedDrawingPoints`); later navigation always
|
||||
* owns its camera. False when there is nothing to frame or no camera.
|
||||
*/
|
||||
export function flyToFootprint(
|
||||
|
||||
@@ -5,44 +5,66 @@ import {
|
||||
cancelCameraArrival,
|
||||
ownCameraArrival,
|
||||
} from '../data/cameraArrival.js';
|
||||
import { dataSourcePoints } from '../data/geoImportPins.js';
|
||||
import {
|
||||
createImportedDrawing,
|
||||
importedDrawingPoints,
|
||||
} from '../data/geoImportPins.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeSceneQuery } from '../testSupport/fakeCesiumScene.mjs';
|
||||
import { flyToFootprint } from './flyToDataSource.js';
|
||||
|
||||
/** As the file import flies to one of its files. */
|
||||
const flyToDataSource = (viewer, dataSource) =>
|
||||
flyToFootprint(viewer, dataSourcePoints(dataSource));
|
||||
const flyToDataSource = (viewer, drawing) =>
|
||||
flyToFootprint(viewer, importedDrawingPoints(drawing));
|
||||
|
||||
/** An imported file's drawing of `features`, not drawn. */
|
||||
const drawingOf = (features) => createImportedDrawing({}, features);
|
||||
const pin = (lon, lat, height = 0, mode = 'absolute') => ({
|
||||
kind: 'pin',
|
||||
lon,
|
||||
lat,
|
||||
height,
|
||||
mode,
|
||||
image: 'pin.png',
|
||||
size: [32, 32],
|
||||
});
|
||||
const line = (coords, mode = 'draped') => ({
|
||||
kind: 'line',
|
||||
coords,
|
||||
mode,
|
||||
color: [1, 1, 1, 1],
|
||||
width: 1,
|
||||
});
|
||||
|
||||
/** A Cesium-shaped viewer double, bound to the camera and query ports. */
|
||||
const bound = (viewer) =>
|
||||
bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) });
|
||||
|
||||
function source() {
|
||||
const ds = new Cesium.CustomDataSource('t');
|
||||
ds.entities.add({
|
||||
position: Cesium.Cartesian3.fromDegrees(-122.4862, 37.7694, -2667),
|
||||
billboard: { heightReference: Cesium.HeightReference.CLAMP_TO_GROUND },
|
||||
});
|
||||
ds.entities.add({
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([
|
||||
-122.49, 37.77, -122.48, 37.771,
|
||||
]),
|
||||
return drawingOf([
|
||||
pin(-122.4862, 37.7694, 0, 'clamp'),
|
||||
line([
|
||||
[-122.49, 37.77, 0],
|
||||
[-122.48, 37.771, 0],
|
||||
]),
|
||||
{
|
||||
kind: 'polygon',
|
||||
rings: [
|
||||
[
|
||||
[-122.5, 37.76, 0],
|
||||
[-122.49, 37.76, 0],
|
||||
[-122.49, 37.765, 0],
|
||||
],
|
||||
],
|
||||
clamp: true,
|
||||
fill: [1, 1, 1, 0.25],
|
||||
outline: null,
|
||||
},
|
||||
});
|
||||
ds.entities.add({
|
||||
polygon: {
|
||||
hierarchy: Cesium.Cartesian3.fromDegreesArray([
|
||||
-122.5, 37.76, -122.49, 37.76, -122.49, 37.765,
|
||||
]),
|
||||
},
|
||||
});
|
||||
return ds;
|
||||
]);
|
||||
}
|
||||
|
||||
test('points come from positions, lines and polygons, as lon/lat only', () => {
|
||||
const points = dataSourcePoints(source());
|
||||
const points = importedDrawingPoints(source());
|
||||
assert.equal(points.length, 6);
|
||||
assert.ok(Math.abs(points[0][0] + 122.4862) < 1e-6);
|
||||
assert.ok(Math.abs(points[0][1] - 37.7694) < 1e-6);
|
||||
@@ -71,10 +93,7 @@ test('the camera frames the footprint at the surface, never a buried center', ()
|
||||
calls[0].options.complete();
|
||||
assert.equal(handedOver, true, 'the ground guard runs on landing');
|
||||
cancelCameraArrival(viewer);
|
||||
assert.equal(
|
||||
flyToDataSource(viewer, new Cesium.CustomDataSource('empty')),
|
||||
false,
|
||||
);
|
||||
assert.equal(flyToDataSource(viewer, drawingOf([])), false);
|
||||
assert.equal(
|
||||
calls.length,
|
||||
1,
|
||||
@@ -86,13 +105,11 @@ test('a very long track is framed without spreading it into a call', () => {
|
||||
// 400k vertices: `push(...line)` throws RangeError (too many arguments)
|
||||
// well below this; the walk keeps a bounded sample and both ends.
|
||||
const n = 400_000;
|
||||
const line = new Array(n);
|
||||
for (let i = 0; i < n; i++)
|
||||
line[i] = Cesium.Cartesian3.fromDegrees(-120 + (i / n) * 2, 40);
|
||||
const ds = new Cesium.CustomDataSource('long');
|
||||
ds.entities.add({ polyline: { positions: line } });
|
||||
ds.entities.add({ position: Cesium.Cartesian3.fromDegrees(-110, 41) });
|
||||
const points = dataSourcePoints(ds);
|
||||
const coords = new Array(n);
|
||||
for (let i = 0; i < n; i++) coords[i] = [-120 + (i / n) * 2, 40, 0];
|
||||
const points = importedDrawingPoints(
|
||||
drawingOf([line(coords), pin(-110, 41)]),
|
||||
);
|
||||
assert.equal(points.length, n + 1, 'every vertex contributes to framing');
|
||||
const lons = points.map(([lon]) => lon);
|
||||
assert.ok(
|
||||
@@ -103,34 +120,37 @@ test('a very long track is framed without spreading it into a call', () => {
|
||||
});
|
||||
|
||||
test('framing includes a sparse interior outlier, walls and rotated overlays', () => {
|
||||
const ds = new Cesium.CustomDataSource('bounds');
|
||||
const line = Array.from({ length: 200031 }, () =>
|
||||
Cesium.Cartesian3.fromDegrees(0, 0),
|
||||
const coords = Array.from({ length: 200031 }, () => [0, 0, 0]);
|
||||
coords[12345] = [20, 10, 0];
|
||||
const points = importedDrawingPoints(
|
||||
drawingOf([
|
||||
line(coords),
|
||||
{
|
||||
kind: 'wall',
|
||||
coords: [
|
||||
[30, 10, 0],
|
||||
[31, 11, 0],
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'overlay',
|
||||
rect: { west: 40, south: 0, east: 41, north: 1 },
|
||||
rotation: Math.PI / 4,
|
||||
},
|
||||
]),
|
||||
);
|
||||
line[12345] = Cesium.Cartesian3.fromDegrees(20, 10);
|
||||
ds.entities.add({ polyline: { positions: line } });
|
||||
ds.entities.add({
|
||||
wall: { positions: Cesium.Cartesian3.fromDegreesArray([30, 10, 31, 11]) },
|
||||
});
|
||||
ds.entities.add({
|
||||
rectangle: {
|
||||
coordinates: Cesium.Rectangle.fromDegrees(40, 0, 41, 1),
|
||||
rotation: Math.PI / 4,
|
||||
},
|
||||
});
|
||||
const points = dataSourcePoints(ds);
|
||||
assert.ok(points.some(([lon]) => Math.abs(lon - 20) < 1e-6));
|
||||
assert.ok(points.some(([lon]) => Math.abs(lon - 31) < 1e-6));
|
||||
assert.ok(points.some(([lon]) => lon > 41));
|
||||
});
|
||||
|
||||
test('portrait framing accounts for FOV, high ground and symmetric extents', () => {
|
||||
const ds = new Cesium.CustomDataSource('view');
|
||||
ds.entities.add({
|
||||
polyline: {
|
||||
positions: Cesium.Cartesian3.fromDegreesArray([-105, 39, -104.9, 39]),
|
||||
},
|
||||
});
|
||||
const ds = drawingOf([
|
||||
line([
|
||||
[-105, 39, 0],
|
||||
[-104.9, 39, 0],
|
||||
]),
|
||||
]);
|
||||
const calls = [];
|
||||
const viewer = bound({
|
||||
scene: { globe: { getHeight: () => 2600 } },
|
||||
@@ -149,34 +169,17 @@ test('portrait framing accounts for FOV, high ground and symmetric extents', ()
|
||||
viewer.camera.frustum.aspectRatio = 16 / 9;
|
||||
flyToDataSource(viewer, ds);
|
||||
assert.ok(calls[0].options.offset.range > calls[1].options.offset.range);
|
||||
const symmetric = {
|
||||
entities: {
|
||||
values: [
|
||||
{ position: { getValue: () => new Cesium.Cartesian3(6378137, 0, 0) } },
|
||||
{ position: { getValue: () => new Cesium.Cartesian3(-6378137, 0, 0) } },
|
||||
],
|
||||
},
|
||||
};
|
||||
const symmetric = drawingOf([pin(0, 0), pin(180, 0)]);
|
||||
assert.doesNotThrow(() => flyToDataSource(viewer, symmetric));
|
||||
assert.ok(Number.isFinite(calls.at(-1).options.offset.range));
|
||||
assert.doesNotThrow(() => calls.at(-1).options.complete());
|
||||
cancelCameraArrival(viewer);
|
||||
});
|
||||
|
||||
test('non-finite positions and hidden features never enter the camera footprint', () => {
|
||||
const position = (p) => ({ position: { getValue: () => p } });
|
||||
const points = dataSourcePoints({
|
||||
entities: {
|
||||
values: [
|
||||
position(new Cesium.Cartesian3(NaN, 1, 2)),
|
||||
{
|
||||
...position(Cesium.Cartesian3.fromDegrees(10, 10)),
|
||||
isShowing: false,
|
||||
},
|
||||
position(Cesium.Cartesian3.fromDegrees(20, 20)),
|
||||
],
|
||||
},
|
||||
});
|
||||
assert.equal(points.length, 1);
|
||||
assert.ok(Math.abs(points[0][0] - 20) < 1e-6);
|
||||
test('non-finite positions are refused and a hidden file has no footprint', () => {
|
||||
assert.throws(() => drawingOf([pin(Number.NaN, 1)]), /invalid point/);
|
||||
const drawing = drawingOf([pin(20, 20)]);
|
||||
assert.equal(importedDrawingPoints(drawing).length, 1);
|
||||
drawing.show = false;
|
||||
assert.deepEqual(importedDrawingPoints(drawing), []);
|
||||
});
|
||||
+35
-21
@@ -5,10 +5,9 @@ import {
|
||||
loadGeoFile,
|
||||
} from '../data/geoFileImport.js';
|
||||
import {
|
||||
addImportedSource,
|
||||
dataSourcePoints,
|
||||
removeImportedSource,
|
||||
showImportedSource,
|
||||
importedDrawingPoints,
|
||||
removeImportedDrawing,
|
||||
showImportedDrawing,
|
||||
} from '../data/geoImportPins.js';
|
||||
import { formatNumber, t, tn, translateKnown } from '../i18n/index.js';
|
||||
import { flyToFootprint } from './flyToDataSource.js';
|
||||
@@ -19,9 +18,9 @@ import {
|
||||
findGlobe,
|
||||
} from '../render/rendererOf.js';
|
||||
|
||||
/** Fly to the whole footprint of one imported file's data source. */
|
||||
const flyToDataSource = (viewer, dataSource, options) =>
|
||||
flyToFootprint(viewer, dataSourcePoints(dataSource), options);
|
||||
/** Fly to the whole footprint of one imported file's drawing. */
|
||||
const flyToDrawing = (viewer, drawing, options) =>
|
||||
flyToFootprint(viewer, importedDrawingPoints(drawing), options);
|
||||
|
||||
// One color per file, in import order, from the whiteboard palette.
|
||||
const COLORS = ['#39d0ff', '#ffb547', '#5dff9f', '#ff6b6b', '#8be9ff'];
|
||||
@@ -45,14 +44,14 @@ function localizedValues(values) {
|
||||
* renders them. `connect(actions)` answers the view's pick and row buttons
|
||||
* and returns their disconnect.
|
||||
* @returns {{destroy: Function, importFiles: Function, list: Function,
|
||||
* setVisible: Function, flyTo: Function, remove: Function,
|
||||
* setVisible: Function, flyTo: Function, remove: Function, drawn: Function,
|
||||
* diagnostics: Function}|null}
|
||||
*/
|
||||
export function initGeoFileImport({
|
||||
viewer,
|
||||
load = loadGeoFile,
|
||||
document: doc = globalThis.document,
|
||||
flyToSource = flyToDataSource,
|
||||
flyToSource = flyToDrawing,
|
||||
navigation = null,
|
||||
ground = null,
|
||||
subscribeMapSource = null,
|
||||
@@ -188,7 +187,7 @@ export function initGeoFileImport({
|
||||
const item = find(id);
|
||||
if (!item) return false;
|
||||
item.visible = Boolean(visible);
|
||||
showImportedSource(item.dataSource, item.visible);
|
||||
showImportedDrawing(item.drawing, item.visible);
|
||||
if (item.visible) scheduleGround();
|
||||
present();
|
||||
render();
|
||||
@@ -199,7 +198,7 @@ export function initGeoFileImport({
|
||||
// destination's terrain has loaded (see ./flyToDataSource.js).
|
||||
const fly = (item) => {
|
||||
if (!item.visible) setVisible(item.id, true);
|
||||
flyToSource(viewer, item.dataSource, { ground });
|
||||
flyToSource(viewer, item.drawing, { ground });
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -236,7 +235,7 @@ export function initGeoFileImport({
|
||||
const at = imports.findIndex((item) => item.id === id);
|
||||
if (at < 0) return false;
|
||||
const [item] = imports.splice(at, 1);
|
||||
removeImportedSource(viewer, item.dataSource);
|
||||
removeImportedDrawing(item.drawing);
|
||||
item.revoke?.();
|
||||
present();
|
||||
render();
|
||||
@@ -300,6 +299,18 @@ export function initGeoFileImport({
|
||||
loaded.revoke?.();
|
||||
break;
|
||||
}
|
||||
try {
|
||||
loaded.mount?.();
|
||||
} catch {
|
||||
// Something in it the renderer would not draw: refused whole.
|
||||
loaded.revoke?.();
|
||||
outcomes.push({
|
||||
name: fileName,
|
||||
ok: false,
|
||||
error: t('That file could not be read.'),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
colorAt += 1;
|
||||
seq += 1;
|
||||
const item = {
|
||||
@@ -311,17 +322,10 @@ export function initGeoFileImport({
|
||||
removed: loaded.removed || 0,
|
||||
color,
|
||||
visible: true,
|
||||
dataSource: loaded.dataSource,
|
||||
drawing: loaded.drawing,
|
||||
revoke: loaded.revoke,
|
||||
refreshGround: loaded.refreshGround,
|
||||
};
|
||||
await addImportedSource(viewer, item.dataSource);
|
||||
if (destroyed) {
|
||||
removeImportedSource(viewer, item.dataSource);
|
||||
item.revoke?.();
|
||||
break;
|
||||
}
|
||||
loaded.mount?.();
|
||||
imports.push(item);
|
||||
present();
|
||||
render();
|
||||
@@ -409,6 +413,16 @@ export function initGeoFileImport({
|
||||
setVisible,
|
||||
flyTo,
|
||||
remove,
|
||||
/** What a file drew: its sets' ids, whether shown, and their items. */
|
||||
drawn: (id) => {
|
||||
const item = imports.find((entry) => entry.id === id);
|
||||
if (!item?.drawing) return null;
|
||||
return {
|
||||
sets: { ...item.drawing.ids },
|
||||
show: item.drawing.show,
|
||||
...item.drawing.items?.(),
|
||||
};
|
||||
},
|
||||
diagnostics: () => ({
|
||||
files: imports.length,
|
||||
entities: imports.reduce((n, item) => n + item.entityCount, 0),
|
||||
@@ -424,7 +438,7 @@ export function initGeoFileImport({
|
||||
clearTimeout(groundTimer);
|
||||
for (const remove of groundRemovers) remove();
|
||||
for (const item of imports.splice(0)) {
|
||||
removeImportedSource(viewer, item.dataSource);
|
||||
removeImportedDrawing(item.drawing);
|
||||
item.revoke?.();
|
||||
}
|
||||
for (const [target, type, listener, options] of listeners.splice(0))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Behavioral tests for DISPLAY ▸ Import: the controller is driven against
|
||||
// fake DOM and viewer doubles with an injected loader, and its observable
|
||||
// effects are asserted — data sources added and removed, the rows and hint it
|
||||
// effects are asserted — drawings mounted and removed, the rows and hint it
|
||||
// publishes, drop handling, the file limit, and what destroy() gives back.
|
||||
// The Display panel renders the published list (`displayPanel.test.mjs`);
|
||||
// real parsing and rendering run in `scripts/qa-geo-import.mjs`.
|
||||
@@ -85,16 +85,6 @@ function setup({
|
||||
const viewer = {
|
||||
container: new FakeElement('div', 'cesiumContainer'),
|
||||
scene: { requestRender: () => (renders += 1) },
|
||||
dataSources: {
|
||||
add: async (ds) => {
|
||||
added.push(ds);
|
||||
return ds;
|
||||
},
|
||||
remove: (ds, destroy) => {
|
||||
removed.push({ ds, destroy });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
flyTo: (target) => flights.push(target),
|
||||
};
|
||||
// The renderer's ports, when the test gives them, bound before the import
|
||||
@@ -107,7 +97,7 @@ function setup({
|
||||
if (file.fail) throw new GeoImportError(file.fail);
|
||||
if (file.crash) throw new Error('boom');
|
||||
return {
|
||||
dataSource: { show: true },
|
||||
drawing: { show: true },
|
||||
name: file.name,
|
||||
format: 'geojson',
|
||||
entityCount: 3,
|
||||
@@ -115,9 +105,24 @@ function setup({
|
||||
revoke: () => revoked.push(file.name),
|
||||
};
|
||||
};
|
||||
// Each loaded file's drawing, recorded when the import mounts it and when
|
||||
// it takes it off the globe.
|
||||
const recorded = async (file, opts) => {
|
||||
const loaded = await (load || defaultLoad)(file, opts);
|
||||
const drawing = loaded.drawing ?? {};
|
||||
drawing.destroy = () => removed.push({ ds: drawing, destroy: true });
|
||||
return {
|
||||
...loaded,
|
||||
drawing,
|
||||
mount() {
|
||||
loaded.mount?.();
|
||||
added.push(drawing);
|
||||
},
|
||||
};
|
||||
};
|
||||
const tool = initGeoFileImport({
|
||||
viewer,
|
||||
load: load || defaultLoad,
|
||||
load: recorded,
|
||||
document,
|
||||
...(navigation ? { navigation } : {}),
|
||||
...(subscribeMapSource ? { subscribeMapSource } : {}),
|
||||
@@ -201,10 +206,19 @@ test('row buttons hide, show, fly to and remove a file', async () => {
|
||||
await t.tool.importFiles([file('a.gpx')]);
|
||||
const [{ id }] = t.tool.list();
|
||||
const ds = t.added[0];
|
||||
ds.ids = { icons: 'i', lines: 'l', shapes: 's' };
|
||||
ds.items = () => ({ icons: [{ id: 'p0' }], lines: [], shapes: [] });
|
||||
const glyphClick = (name) => press(t, rows(t)[0], name);
|
||||
assert.equal(ds.show, true);
|
||||
glyphClick('toggle');
|
||||
assert.equal(ds.show, false);
|
||||
assert.deepEqual(t.tool.drawn(id), {
|
||||
sets: { icons: 'i', lines: 'l', shapes: 's' },
|
||||
show: false,
|
||||
icons: [{ id: 'p0' }],
|
||||
lines: [],
|
||||
shapes: [],
|
||||
});
|
||||
assert.equal(t.tool.list()[0].visible, false);
|
||||
assert.equal(action(rows(t)[0], 'toggle').pressed, 'false');
|
||||
assert.equal(action(rows(t)[0], 'toggle').icon, 'visibility_off');
|
||||
@@ -217,6 +231,7 @@ test('row buttons hide, show, fly to and remove a file', async () => {
|
||||
assert.deepEqual(t.revoked, ['a.gpx']);
|
||||
assert.equal(t.tool.list().length, 0);
|
||||
assert.deepEqual(rows(t), []);
|
||||
assert.equal(t.tool.drawn(id), null);
|
||||
assert.equal(t.tool.remove(id), false);
|
||||
});
|
||||
|
||||
@@ -240,6 +255,32 @@ test('a refused file says why and does not stop the rest of the batch', async ()
|
||||
assert.equal(t.tool.list().length, 1);
|
||||
});
|
||||
|
||||
test('a file the renderer will not draw is refused and released, and the batch goes on', async () => {
|
||||
const t = setup({
|
||||
load: async (file) => ({
|
||||
drawing: { show: true },
|
||||
name: file.name,
|
||||
format: 'kml',
|
||||
entityCount: 1,
|
||||
revoke: () => t.revoked.push(file.name),
|
||||
mount() {
|
||||
if (file.name === 'odd.kml') throw new Error('refused');
|
||||
},
|
||||
}),
|
||||
});
|
||||
const out = await t.tool.importFiles([file('odd.kml'), file('good.kml')]);
|
||||
assert.deepEqual(
|
||||
out.map((o) => o.ok),
|
||||
[false, true],
|
||||
);
|
||||
assert.match(out[0].error, /could not be read\./);
|
||||
assert.deepEqual(t.revoked, ['odd.kml']);
|
||||
assert.deepEqual(
|
||||
t.tool.list().map((f) => f.name),
|
||||
['good.kml'],
|
||||
);
|
||||
});
|
||||
|
||||
test('the number of files on the globe is bounded', async () => {
|
||||
const t = setup();
|
||||
const many = Array.from({ length: MAX_IMPORTED_FILES + 2 }, (_, i) =>
|
||||
@@ -314,7 +355,7 @@ test('a file that finishes loading after destroy is released, not added', async
|
||||
load: async () => {
|
||||
await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: 'late',
|
||||
format: 'kml',
|
||||
entityCount: 1,
|
||||
@@ -418,7 +459,7 @@ test('a direct camera gesture cancels the fly-to of a file still being read', as
|
||||
name: 'slow.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -464,7 +505,7 @@ test('ground refresh coalesces map changes and releases its subscription on tear
|
||||
name: 'point.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
refreshGround: async () => refreshed++,
|
||||
}),
|
||||
});
|
||||
@@ -500,7 +541,7 @@ test('the camera settling and the terrain queue running dry refresh the ground,
|
||||
name: 'point.geojson',
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
refreshGround: async () => refreshed++,
|
||||
}),
|
||||
});
|
||||
@@ -569,7 +610,7 @@ test('a slow import does not fly once something newer took the camera', async ()
|
||||
load: async (f) => {
|
||||
await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
@@ -603,7 +644,7 @@ test('a queued import cannot fly over navigation that happened while it waited',
|
||||
load: async (f) => {
|
||||
if (f.name === 'first.geojson') await gate;
|
||||
return {
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 1,
|
||||
@@ -638,7 +679,7 @@ test('a refused deferred stamp (Cockpit) imports without flying', async () => {
|
||||
test('KML and KMZ rows say they keep their own styles instead of showing a color', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: f.name,
|
||||
format: f.name.endsWith('.kml') ? 'kml' : 'gpx',
|
||||
entityCount: 2,
|
||||
@@ -657,7 +698,7 @@ test('KML and KMZ rows say they keep their own styles instead of showing a color
|
||||
test('the map-object count in a row title keeps digit grouping', async () => {
|
||||
const t = setup({
|
||||
load: async (f) => ({
|
||||
dataSource: {},
|
||||
drawing: {},
|
||||
name: f.name,
|
||||
format: 'geojson',
|
||||
entityCount: 12345,
|
||||
|
||||
Reference in new issue
Block a user