@xgis/xgis3d 0.3.58 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Map3D.d.ts +2 -2
- package/dist/cameraBoundsGuard.d.ts +5 -2
- package/dist/index.js +48 -20
- package/dist/index.js.map +1 -1
- package/dist/reconcilers/useCesiumViewBounds.d.ts +4 -1
- package/dist/utils/createKMLLayer.d.ts +2 -2
- package/dist/utils/createWMSLayer.d.ts +2 -2
- package/dist/utils/createWMTSLayer.d.ts +2 -1
- package/dist/utils/kmlEntityStyle.d.ts +2 -2
- package/dist/utils/layerCreation.d.ts +2 -2
- package/dist/utils/topicRectangle.d.ts +3 -0
- package/package.json +4 -6
- package/dist/reconcilers/useCesiumLayerReconciler.d.ts +0 -2
package/dist/Map3D.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import 'cesium/Build/Cesium/Widgets/widgets.css';
|
|
2
|
-
import type {
|
|
2
|
+
import type { IEngineRegistration, IMapEngine } from '@xgis/xgis-common';
|
|
3
3
|
import type { Viewer as CesiumViewer } from 'cesium';
|
|
4
4
|
export declare function applyRotationPermission(viewer: CesiumViewer, rotationAllowed: boolean): void;
|
|
5
5
|
export declare function releaseWebglContext(canvas: HTMLCanvasElement): void;
|
|
6
6
|
interface Map3DProps {
|
|
7
|
-
onEngineReady: (engine: IMapEngine) =>
|
|
7
|
+
onEngineReady: (engine: IMapEngine) => IEngineRegistration;
|
|
8
8
|
}
|
|
9
9
|
export declare function Map3D({ onEngineReady }: Map3DProps): import("react/jsx-runtime").JSX.Element;
|
|
10
10
|
export {};
|
|
@@ -2,5 +2,8 @@ import type { EpsgCode, MapExtent, ZoomLevel } from '@xgis/xgis-common';
|
|
|
2
2
|
import type { Viewer as CesiumViewer } from 'cesium';
|
|
3
3
|
/** Zoom at which `bounds` just fills the canvas — the furthest this camera may pull back. */
|
|
4
4
|
export declare function boundsFloor(viewer: CesiumViewer, bounds: MapExtent): ZoomLevel;
|
|
5
|
-
/**
|
|
6
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Cesium has no extent constraint, so the camera is pulled back each frame after it moves: out of
|
|
7
|
+
* anywhere past `bounds`, and back from any closer than `zoomCeiling`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createCameraBoundsGuard(viewer: CesiumViewer, bounds: MapExtent, projection: EpsgCode, zoomCeiling: ZoomLevel): () => void;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { jsx } from 'react/jsx-runtime';
|
|
2
2
|
import 'cesium/Build/Cesium/Widgets/widgets.css';
|
|
3
|
-
import { toWgs84, resolutionForZoom, fromWgs84, wrapToRange, TWO_PI, ZOOM_0_RESOLUTION, RADIANS_TO_DEGREES, extentCenter, zoomForExtent, asMapExtent, createEngineErrorChannel, WEBGL_CONTEXT_LOST_ERROR_NAME, zoomToFit, clampExtentToBounds, MIN_ZOOM, SHALLOWEST_PITCH, platformModifierOnly, KML_DEFAULT_COLOR, KML_LABEL_OUTLINE_COLOR, kmlExtractStyles, KML_LABEL_FONT, KML_MARKER_SIZE_PX, KML_LABEL_OUTLINE_PX, KML_LABEL_FONT_SIZE_PX, ogcMapsCesiumCrs, withQuery, ogcMapsMapUrl, ogcMapsQuery, stringifyParams, parseTmsTileMap, tmsCesiumSchemeFor, tmsLevelRange, tmsTileBase, tmsTileSuffix, parseWmsCaps, parseWmtsCapabilities, toAlpha, useBasemapStore, useActiveBasemapPlan,
|
|
3
|
+
import { toWgs84, resolutionForZoom, fromWgs84, wrapToRange, TWO_PI, ZOOM_0_RESOLUTION, RADIANS_TO_DEGREES, extentCenter, zoomForExtent, asMapExtent, createEngineErrorChannel, WEBGL_CONTEXT_LOST_ERROR_NAME, zoomToFit, clampExtentToBounds, MIN_ZOOM, SHALLOWEST_PITCH, platformModifierOnly, KML_DEFAULT_COLOR, KML_LABEL_OUTLINE_COLOR, kmlExtractStyles, KML_LABEL_FONT, KML_MARKER_SIZE_PX, KML_LABEL_OUTLINE_PX, KML_LABEL_FONT_SIZE_PX, ogcMapsCesiumCrs, withQuery, ogcMapsMapUrl, ogcMapsQuery, stringifyParams, parseTmsTileMap, tmsCesiumSchemeFor, tmsLevelRange, tmsTileBase, tmsTileSuffix, parseWmsCaps, parseWmtsCapabilities, fallbackTileTemplate, toAlpha, useBasemapStore, useActiveBasemapPlan, useMapViewStore, useProjectionStore, bus, translate, useTerrainStore, useUserMarkerStore, useTranslate, MAX_ZOOM } from '@xgis/xgis-common';
|
|
4
4
|
import { Cartesian3, Matrix4, BoundingSphere, HeadingPitchRange, Rectangle, Cartesian2, Transforms, Matrix3, Math as Math$1, EllipsoidTerrainProvider, Ellipsoid, Cartographic, sampleTerrainMostDetailed, CameraEventType, KeyboardEventModifier, Cesium3DTileStyle, I3SDataProvider, Cesium3DTileset, Color, ImageMaterialProperty, ColorMaterialProperty, ConstantProperty, Iso8601, ArcType, PointGraphics, Resource, HeightReference, PolygonHierarchy, KmlDataSource, UrlTemplateImageryProvider, WebMercatorTilingScheme, GeographicTilingScheme, WebMercatorProjection, WebMapServiceImageryProvider, WebMapTileServiceImageryProvider, CesiumTerrainProvider, ConstantPositionProperty } from 'cesium';
|
|
5
5
|
import { useRef, useMemo, useEffect, useState, useCallback } from 'react';
|
|
6
6
|
import { Viewer } from 'resium';
|
|
@@ -526,7 +526,7 @@ function boundsFloor(viewer, bounds) {
|
|
|
526
526
|
const canvas = viewer.scene.canvas;
|
|
527
527
|
return zoomToFit(bounds, { width: canvas.clientWidth, height: canvas.clientHeight });
|
|
528
528
|
}
|
|
529
|
-
function createCameraBoundsGuard(viewer, bounds, projection) {
|
|
529
|
+
function createCameraBoundsGuard(viewer, bounds, projection, zoomCeiling) {
|
|
530
530
|
let lastPosition;
|
|
531
531
|
let lastCanvasKey = "";
|
|
532
532
|
function clampToBounds() {
|
|
@@ -545,7 +545,7 @@ function createCameraBoundsGuard(viewer, bounds, projection) {
|
|
|
545
545
|
const viewport = { width: canvas.clientWidth, height: canvas.clientHeight };
|
|
546
546
|
const currentRange = focus ? focus.range : camera.positionCartographic.height * MAX_FOCUS_RANGE_FACTOR;
|
|
547
547
|
const range = Math.min(
|
|
548
|
-
currentRange,
|
|
548
|
+
Math.max(currentRange, rangeForZoom(viewer, zoomCeiling, metresPerUnit)),
|
|
549
549
|
rangeForZoom(viewer, boundsFloor(viewer, bounds), metresPerUnit)
|
|
550
550
|
);
|
|
551
551
|
const footprint = asMapExtent(
|
|
@@ -560,7 +560,7 @@ function createCameraBoundsGuard(viewer, bounds, projection) {
|
|
|
560
560
|
);
|
|
561
561
|
const [x, y] = wgs84ToMap(projection, lon, lat);
|
|
562
562
|
const [targetX, targetY] = extentCenter(clampExtentToBounds(footprint, bounds));
|
|
563
|
-
if (Math.abs(targetX - x) < MOVE_EPSILON_METERS && Math.abs(targetY - y) < MOVE_EPSILON_METERS && currentRange - range < MOVE_EPSILON_METERS) {
|
|
563
|
+
if (Math.abs(targetX - x) < MOVE_EPSILON_METERS && Math.abs(targetY - y) < MOVE_EPSILON_METERS && Math.abs(currentRange - range) < MOVE_EPSILON_METERS) {
|
|
564
564
|
return;
|
|
565
565
|
}
|
|
566
566
|
const [targetLon, targetLat] = mapToWgs84(projection, targetX, targetY);
|
|
@@ -589,6 +589,9 @@ function createCesiumViewLimitsCapability(viewer) {
|
|
|
589
589
|
return MIN_ZOOM;
|
|
590
590
|
}
|
|
591
591
|
return reportedZoomGrid(boundsFloor(viewer, bounds));
|
|
592
|
+
},
|
|
593
|
+
getZoomCeiling(zoomCeiling) {
|
|
594
|
+
return reportedZoomGrid(zoomCeiling);
|
|
592
595
|
}
|
|
593
596
|
};
|
|
594
597
|
}
|
|
@@ -1268,7 +1271,7 @@ function createTMS(source, presentation, capabilitiesText) {
|
|
|
1268
1271
|
});
|
|
1269
1272
|
}
|
|
1270
1273
|
|
|
1271
|
-
function createWMS(source, presentation, capabilities) {
|
|
1274
|
+
function createWMS(source, presentation, capabilities, rectangle) {
|
|
1272
1275
|
if (!capabilities) {
|
|
1273
1276
|
return null;
|
|
1274
1277
|
}
|
|
@@ -1288,53 +1291,61 @@ function createWMS(source, presentation, capabilities) {
|
|
|
1288
1291
|
crs: request.crs,
|
|
1289
1292
|
srs: request.crs,
|
|
1290
1293
|
tilingScheme: request.projection === "webMercator" ? new WebMercatorTilingScheme() : new GeographicTilingScheme(),
|
|
1294
|
+
rectangle,
|
|
1291
1295
|
credit: presentation.copyright
|
|
1292
1296
|
});
|
|
1293
1297
|
}
|
|
1294
1298
|
|
|
1295
|
-
|
|
1296
|
-
function coarsestLevel(tilingScheme, minimumLevel) {
|
|
1299
|
+
function coarsestLevel(tilingScheme, rectangle, minimumLevel) {
|
|
1297
1300
|
if (minimumLevel === void 0) {
|
|
1298
1301
|
return void 0;
|
|
1299
1302
|
}
|
|
1300
|
-
return safeMinimumLevel(tilingScheme,
|
|
1303
|
+
return safeMinimumLevel(tilingScheme, rectangle ?? tilingScheme.rectangle, minimumLevel);
|
|
1304
|
+
}
|
|
1305
|
+
function layerRectangle(bbox, topic) {
|
|
1306
|
+
if (!bbox) {
|
|
1307
|
+
return topic;
|
|
1308
|
+
}
|
|
1309
|
+
return Rectangle.fromDegrees(...bbox);
|
|
1301
1310
|
}
|
|
1302
|
-
function createWMTS(source, presentation, capabilitiesText) {
|
|
1303
|
-
const parsed = parseWmtsCapabilities(capabilitiesText, source.layer);
|
|
1311
|
+
function createWMTS(source, presentation, capabilitiesText, rectangle) {
|
|
1312
|
+
const parsed = parseWmtsCapabilities(capabilitiesText, source.layer, source.format);
|
|
1304
1313
|
if (!parsed) {
|
|
1305
1314
|
return null;
|
|
1306
1315
|
}
|
|
1307
1316
|
const style = source.styles ?? "default";
|
|
1308
|
-
const url =
|
|
1317
|
+
const url = parsed.tileTemplate ?? fallbackTileTemplate(source.href, source.layer, style);
|
|
1309
1318
|
const tilingScheme = parsed.tilingScheme === "geographic" ? new GeographicTilingScheme() : new WebMercatorTilingScheme();
|
|
1319
|
+
const extent = layerRectangle(parsed.wgs84BoundingBox, rectangle);
|
|
1310
1320
|
return new WebMapTileServiceImageryProvider({
|
|
1311
1321
|
url: withQuery(url, stringifyParams(source.params)),
|
|
1312
1322
|
layer: source.layer,
|
|
1313
1323
|
style,
|
|
1314
1324
|
tileMatrixSetID: parsed.tileMatrixSetID,
|
|
1325
|
+
dimensions: parsed.dimensions,
|
|
1315
1326
|
tileMatrixLabels: parsed.tileMatrixLabels.length > 0 ? parsed.tileMatrixLabels : void 0,
|
|
1316
1327
|
format: source.format,
|
|
1317
1328
|
tilingScheme,
|
|
1318
1329
|
maximumLevel: parsed.maximumLevel,
|
|
1319
|
-
minimumLevel: coarsestLevel(tilingScheme, parsed.minimumLevel),
|
|
1330
|
+
minimumLevel: coarsestLevel(tilingScheme, extent, parsed.minimumLevel),
|
|
1320
1331
|
credit: presentation.copyright,
|
|
1321
|
-
rectangle:
|
|
1332
|
+
rectangle: extent
|
|
1322
1333
|
});
|
|
1323
1334
|
}
|
|
1324
1335
|
|
|
1325
|
-
function createCesiumBaseLayer(entry, viewer) {
|
|
1336
|
+
function createCesiumBaseLayer(entry, viewer, rectangle) {
|
|
1326
1337
|
const { layer, capabilities, tileset } = entry;
|
|
1327
1338
|
const { source } = layer;
|
|
1328
1339
|
switch (source.kind) {
|
|
1329
1340
|
case "wms": {
|
|
1330
|
-
const provider = createWMS(source, layer, capabilities);
|
|
1341
|
+
const provider = createWMS(source, layer, capabilities, rectangle);
|
|
1331
1342
|
return provider ? { kind: "imagery", provider } : null;
|
|
1332
1343
|
}
|
|
1333
1344
|
case "wmts": {
|
|
1334
1345
|
if (!capabilities) {
|
|
1335
1346
|
return null;
|
|
1336
1347
|
}
|
|
1337
|
-
const provider = createWMTS(source, layer, capabilities);
|
|
1348
|
+
const provider = createWMTS(source, layer, capabilities, rectangle);
|
|
1338
1349
|
return provider ? { kind: "imagery", provider } : null;
|
|
1339
1350
|
}
|
|
1340
1351
|
case "ogcMaps": {
|
|
@@ -1361,6 +1372,16 @@ function createCesiumBaseLayer(entry, viewer) {
|
|
|
1361
1372
|
}
|
|
1362
1373
|
}
|
|
1363
1374
|
|
|
1375
|
+
function topicRectangle(bbox, projection) {
|
|
1376
|
+
if (!bbox) {
|
|
1377
|
+
return void 0;
|
|
1378
|
+
}
|
|
1379
|
+
const [minX, minY, maxX, maxY] = bbox;
|
|
1380
|
+
const [west, south] = mapToWgs84(projection, minX, minY);
|
|
1381
|
+
const [east, north] = mapToWgs84(projection, maxX, maxY);
|
|
1382
|
+
return Rectangle.fromDegrees(west, south, east, north);
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1364
1385
|
function errorStatus(error) {
|
|
1365
1386
|
const cause = error.error;
|
|
1366
1387
|
if (typeof cause !== "object" || cause === null || !("statusCode" in cause)) {
|
|
@@ -1435,6 +1456,12 @@ function useCesiumBasemapAttachments(viewer) {
|
|
|
1435
1456
|
function useCesiumBasemapReconciler(viewer) {
|
|
1436
1457
|
const basemapOpacity = useBasemapStore((s) => s.opacity3d);
|
|
1437
1458
|
const { entries, ready } = useActiveBasemapPlan("3d");
|
|
1459
|
+
const constraintBbox = useMapViewStore((s) => s.constraintBbox);
|
|
1460
|
+
const projection = useProjectionStore((s) => s.projection);
|
|
1461
|
+
const rectangle = useMemo(
|
|
1462
|
+
() => topicRectangle(constraintBbox, projection),
|
|
1463
|
+
[constraintBbox, projection]
|
|
1464
|
+
);
|
|
1438
1465
|
const attachments = useCesiumBasemapAttachments(viewer);
|
|
1439
1466
|
useEffect(() => {
|
|
1440
1467
|
attachments.setOpacity(basemapOpacity);
|
|
@@ -1462,7 +1489,7 @@ function useCesiumBasemapReconciler(viewer) {
|
|
|
1462
1489
|
})();
|
|
1463
1490
|
};
|
|
1464
1491
|
for (const entry of entries) {
|
|
1465
|
-
const created = createCesiumBaseLayer(entry, viewer);
|
|
1492
|
+
const created = createCesiumBaseLayer(entry, viewer, rectangle);
|
|
1466
1493
|
if (!created) {
|
|
1467
1494
|
continue;
|
|
1468
1495
|
}
|
|
@@ -1482,7 +1509,7 @@ function useCesiumBasemapReconciler(viewer) {
|
|
|
1482
1509
|
return () => {
|
|
1483
1510
|
cancelled = true;
|
|
1484
1511
|
};
|
|
1485
|
-
}, [viewer, attachments, entries, ready]);
|
|
1512
|
+
}, [viewer, attachments, entries, ready, rectangle]);
|
|
1486
1513
|
useEffect(() => attachments.detachAll, [attachments]);
|
|
1487
1514
|
}
|
|
1488
1515
|
|
|
@@ -1666,13 +1693,14 @@ function useCesiumUserMarker(viewer) {
|
|
|
1666
1693
|
|
|
1667
1694
|
function useCesiumViewBounds(viewer) {
|
|
1668
1695
|
const constraintBbox = useMapViewStore((s) => s.constraintBbox);
|
|
1696
|
+
const zoomCeiling = useMapViewStore((s) => s.zoomCeiling);
|
|
1669
1697
|
const projection = useProjectionStore((s) => s.projection);
|
|
1670
1698
|
useEffect(() => {
|
|
1671
1699
|
if (!constraintBbox) {
|
|
1672
1700
|
return;
|
|
1673
1701
|
}
|
|
1674
|
-
return createCameraBoundsGuard(viewer, constraintBbox, projection);
|
|
1675
|
-
}, [viewer, constraintBbox, projection]);
|
|
1702
|
+
return createCameraBoundsGuard(viewer, constraintBbox, projection, zoomCeiling);
|
|
1703
|
+
}, [viewer, constraintBbox, projection, zoomCeiling]);
|
|
1676
1704
|
}
|
|
1677
1705
|
|
|
1678
1706
|
const currentProjection = () => useProjectionStore.getState().projection;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/cesiumBaseUrl.ts","../src/projection.ts","../src/cameraScale.ts","../src/lookAtTarget.ts","../src/pickGroundPoint.ts","../src/capabilities/cesiumMoving.ts","../src/capabilities/cesiumCamera.ts","../src/capabilities/cesiumEngineHealth.ts","../src/cameraBoundsGuard.ts","../src/capabilities/cesiumViewLimits.ts","../src/entryCamera.ts","../src/interactions/canvasPressRelay.ts","../src/interactions/centroidTilt.ts","../src/interactions/cesiumKeyboardHandler.ts","../src/interactions/nadirLimit.ts","../src/utils/create3DTilesetLayer.ts","../src/utils/kmlEntityOpacity.ts","../src/utils/kmlEntityStyle.ts","../src/utils/createKMLLayer.ts","../src/utils/createOGCMapsLayer.ts","../src/utils/createOGCTilesLayer.ts","../src/utils/safeMinimumLevel.ts","../src/utils/createTMSLayer.ts","../src/utils/createWMSLayer.ts","../src/utils/createWMTSLayer.ts","../src/utils/layerCreation.ts","../src/reconcilers/useCesiumBasemapAttachments.ts","../src/reconcilers/useCesiumBasemapReconciler.ts","../src/reconcilers/useCesiumEntryCamera.ts","../src/reconcilers/useCesiumTerrainReconciler.ts","../src/reconcilers/userMarkerCone.ts","../src/reconcilers/useCesiumUserMarker.ts","../src/reconcilers/useCesiumViewBounds.ts","../src/Map3D.tsx"],"sourcesContent":["declare global {\n interface Window {\n CESIUM_BASE_URL?: string\n }\n}\n\n// Substituted at build time by both vite configs. A `cesium/package.json` import would be the\n// obvious alternative, but the library build strips its `with { type: 'json' }` attribute, which\n// makes the published module unloadable in Node.\ndeclare const __CESIUM_VERSION__: string\n\nconst META_NAME = 'xgis-cesium-base-url'\n\nlet resolved: string | undefined\n\n// Module-scope read of a build-time contract, not a component reaching into the DOM. `content` is\n// '' for a missing or empty attribute, never undefined, so an empty tag must not win.\nfunction fromMeta(): string {\n return document.querySelector<HTMLMetaElement>(`meta[name=\"${META_NAME}\"]`)?.content.trim() ?? ''\n}\n\n/**\n * Under Module Federation the base URL is baked in by a `define`. An npm consumer gets the meta tag\n * from the cesiumAssets build plugin. This default is the remaining case: assets copied to the\n * conventional path without the plugin.\n */\nexport function ensureCesiumBaseUrl(): void {\n // Importing this package under SSR or in a plain Node process must not throw; Cesium only ever\n // reads the value in a browser, so there is nothing to set anywhere else.\n if (typeof window === 'undefined') {\n return\n }\n\n // Memoised because Map3D calls this during render.\n if (resolved === undefined) {\n resolved = fromMeta() || `/cesium-${__CESIUM_VERSION__}`\n }\n\n window.CESIUM_BASE_URL = resolved\n}\n\n// Runs on import so the default travels with this module rather than depending on index.ts being\n// the entry point. Map3D calls it again before constructing the Viewer, which is what actually\n// guarantees the value is set before Cesium resolves its first asset URL.\nensureCesiumBaseUrl()\n","import type { EpsgCode } from '@xgis/xgis-common'\nimport {\n fromWgs84,\n resolutionForZoom,\n toWgs84,\n TWO_PI,\n wrapToRange,\n ZOOM_0_RESOLUTION,\n} from '@xgis/xgis-common'\nimport { Cartesian3 } from 'cesium'\n\n// Loose lon/lat pairs, which is what this package's callers work in.\nexport function mapToWgs84(projection: EpsgCode, x: number, y: number): [number, number] {\n const { lon, lat } = toWgs84(projection, [x, y])\n\n return [lon, lat]\n}\n\nexport function wgs84ToMap(projection: EpsgCode, lon: number, lat: number): [number, number] {\n return fromWgs84(projection, { lon, lat })\n}\n\nfunction ellipsoidPoint(projection: EpsgCode, x: number, y: number): Cartesian3 {\n const [lon, lat] = mapToWgs84(projection, x, y)\n\n return Cartesian3.fromDegrees(lon, lat)\n}\n\n// Zoom is in map units, the camera in metres.\nexport function metresPerMapUnit(projection: EpsgCode, lon: number, lat: number): number {\n const [x, y] = wgs84ToMap(projection, lon, lat)\n const east = Cartesian3.distance(\n ellipsoidPoint(projection, x - 0.5, y),\n ellipsoidPoint(projection, x + 0.5, y),\n )\n const north = Cartesian3.distance(\n ellipsoidPoint(projection, x, y - 0.5),\n ellipsoidPoint(projection, x, y + 0.5),\n )\n\n return (east + north) / 2\n}\n\n// Cesium's fov covers the canvas's longer side.\nexport function fovSpanPx(viewportWidthPx: number, viewportHeightPx: number): number {\n return Math.max(viewportWidthPx, viewportHeightPx)\n}\n\n// Camera range showing the same area as 2D at `zoom`, so a 2D↔3D switch keeps the scale.\n// Depends on the canvas size, unlike the 2D resolution.\nexport function zoomToRange(\n zoom: number,\n spanPx: number,\n fov: number,\n metresPerUnit: number,\n): number {\n return (resolutionForZoom(zoom) * metresPerUnit * spanPx) / (2 * Math.tan(fov / 2))\n}\n\nexport function rangeToZoom(\n range: number,\n spanPx: number,\n fov: number,\n metresPerUnit: number,\n): number {\n const resolution = (2 * range * Math.tan(fov / 2)) / spanPx / metresPerUnit\n return Math.max(0, Math.log2(ZOOM_0_RESOLUTION / resolution))\n}\n\n// A tilted 3D view covers more ground, so 2D zooms out with it, up to a cap. Looking above the\n// horizon holds the cap instead of snapping 2D back in.\nexport function focusRangeForZoom(\n height: number,\n focusRange: number | undefined,\n maxRangeFactor: number,\n): number {\n const maxRange = height * maxRangeFactor\n\n if (focusRange === undefined) {\n return maxRange\n }\n\n return Math.min(focusRange, maxRange)\n}\n\n// Cesium heading turns the view, store rotation turns the map: opposite directions.\nfunction flipAngleDirection(radians: number): number {\n return wrapToRange(-radians, TWO_PI)\n}\n\nexport const cesiumHeadingToRotation = flipAngleDirection\nexport const rotationToCesiumHeading = flipAngleDirection\n\n// Approximate visible area as if looking straight down; undercounts a tilted view.\nexport function cameraFootprint(\n projection: EpsgCode,\n centerLon: number,\n centerLat: number,\n zoom: number,\n viewportWidthPx: number,\n viewportHeightPx: number,\n): [number, number, number, number] {\n const [cx, cy] = wgs84ToMap(projection, centerLon, centerLat)\n const resolution = resolutionForZoom(zoom)\n const halfWidth = (resolution * viewportWidthPx) / 2\n const halfHeight = (resolution * viewportHeightPx) / 2\n return [cx - halfWidth, cy - halfHeight, cx + halfWidth, cy + halfHeight]\n}\n","import type { ZoomLevel } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\n\nimport { fovSpanPx, rangeToZoom, zoomToRange } from './projection'\n\n// Cesium's PerspectiveFrustum default. Only an orthographic frustum lacks `fov`, and `scene3DOnly`\n// never selects one — so this is a type guard, not a real fallback.\nconst DEFAULT_FOV = Math.PI / 3\n\n// Stand-in span for a canvas with no layout yet (a host that mounts xgis into a hidden or\n// zero-sized container). A zero span would make the range 0, parking the camera on the ellipsoid\n// and reporting a non-finite zoom back. This value is the reference the conversion assumed before\n// it became viewport-aware, so the degenerate case simply behaves as it always did.\nconst FALLBACK_SPAN_PX = 1000\n\ninterface ViewportOptics {\n readonly spanPx: number\n readonly fov: number\n}\n\n// Read fresh on every call: the canvas resizes with the window and with the parallel-view split, and\n// a stale span is exactly the bug this module exists to prevent.\nfunction opticsOf(viewer: CesiumViewer): ViewportOptics {\n const canvas = viewer.scene.canvas\n const frustum = viewer.camera.frustum\n const fov = 'fov' in frustum && frustum.fov !== undefined ? frustum.fov : DEFAULT_FOV\n const spanPx = fovSpanPx(canvas.clientWidth, canvas.clientHeight)\n\n return { spanPx: spanPx > 0 ? spanPx : FALLBACK_SPAN_PX, fov }\n}\n\n/** Camera→focus range that renders `zoom` at the same ground scale as the 2D map. */\nexport function rangeForZoom(viewer: CesiumViewer, zoom: number, metresPerUnit: number): number {\n const { spanPx, fov } = opticsOf(viewer)\n return zoomToRange(zoom, spanPx, fov, metresPerUnit)\n}\n\n/** The 2D zoom whose resolution matches the ground scale at `range` — inverse of `rangeForZoom`. */\nexport function zoomForRange(viewer: CesiumViewer, range: number, metresPerUnit: number): number {\n const { spanPx, fov } = opticsOf(viewer)\n return rangeToZoom(range, spanPx, fov, metresPerUnit)\n}\n\n// The one-decimal grid cesiumCamera reports zoom on, or a comparison against it (the zoom-out\n// button's floor included) never meets and never resolves.\nexport function reportedZoomGrid(zoom: number): ZoomLevel {\n return (Math.round(zoom * 10) / 10) as ZoomLevel\n}\n","import type { Camera, Cartesian3, HeadingPitchRange } from 'cesium'\nimport { Matrix4 } from 'cesium'\n\n// Cesium's EPSILON10 threshold on |direction × up-axis|², which equals cos²(pitch).\nconst DEGENERATE_RIGHT_EPSILON = 1e-10\n\nfunction looksStraightDown(pitch: number): boolean {\n return Math.cos(pitch) ** 2 < DEGENERATE_RIGHT_EPSILON\n}\n\n// Straight down, `lookAt` has no right vector to derive and falls back to east, facing north whatever\n// the heading. A twist about the view direction restores it; `setView` would also move the pitch.\nexport function lookAtTarget(camera: Camera, target: Cartesian3, offset: HeadingPitchRange): void {\n camera.lookAt(target, offset)\n camera.lookAtTransform(Matrix4.IDENTITY)\n\n if (!looksStraightDown(offset.pitch)) {\n return\n }\n\n camera.twistRight(offset.heading)\n}\n","import type { Cartesian2, Cartesian3, Viewer as CesiumViewer } from 'cesium'\n\n// Terrain first, ellipsoid as fallback: an ellipsoid-only pick reports a longer range than the\n// terrain actually on screen, understating how close the camera really is.\nexport function pickGroundPoint(\n viewer: CesiumViewer,\n pixel: Cartesian2,\n): { point: Cartesian3; onTerrain: boolean } | undefined {\n const scene = viewer.scene\n const pickRay = viewer.camera.getPickRay(pixel)\n const terrainPoint = pickRay ? scene.globe.pick(pickRay, scene) : undefined\n const point = terrainPoint ?? viewer.camera.pickEllipsoid(pixel, scene.globe.ellipsoid)\n\n return point ? { point, onTerrain: terrainPoint !== undefined } : undefined\n}\n","import type { Viewer as CesiumViewer } from 'cesium'\n\n// Cesium raises moveEnd mid-drag once the camera stands still, so a held pointer extends the move.\nexport function watchCesiumMoving(\n viewer: CesiumViewer,\n callback: (moving: boolean) => void,\n): () => void {\n const canvas = viewer.scene.canvas\n let cameraMoving = false\n let pressed: number[] = []\n let reported = false\n\n function report(): void {\n const moving = cameraMoving || pressed.length > 0\n\n if (moving === reported) {\n return\n }\n\n reported = moving\n callback(moving)\n }\n\n const press = (event: PointerEvent): void => {\n pressed = [...pressed, event.pointerId]\n report()\n }\n\n const release = (event: PointerEvent): void => {\n pressed = pressed.filter((id) => id !== event.pointerId)\n report()\n }\n\n const releaseAll = (): void => {\n pressed = []\n report()\n }\n\n const removeMoveStart = viewer.camera.moveStart.addEventListener(() => {\n cameraMoving = true\n report()\n })\n const removeMoveEnd = viewer.camera.moveEnd.addEventListener(() => {\n cameraMoving = false\n report()\n })\n\n canvas.addEventListener('pointerdown', press)\n canvas.addEventListener('lostpointercapture', release)\n window.addEventListener('pointerup', release)\n window.addEventListener('pointercancel', release)\n window.addEventListener('blur', releaseAll)\n\n return () => {\n removeMoveStart()\n removeMoveEnd()\n canvas.removeEventListener('pointerdown', press)\n canvas.removeEventListener('lostpointercapture', release)\n window.removeEventListener('pointerup', release)\n window.removeEventListener('pointercancel', release)\n window.removeEventListener('blur', releaseAll)\n }\n}\n","import type { EpsgCode, ICameraCapability, MapExtent, Radians, ViewChange } from '@xgis/xgis-common'\nimport { asMapExtent, extentCenter, RADIANS_TO_DEGREES, zoomForExtent } from '@xgis/xgis-common'\nimport type { Camera, TerrainProvider, Viewer as CesiumViewer } from 'cesium'\nimport {\n BoundingSphere,\n Cartesian2,\n Cartesian3,\n Cartographic,\n Ellipsoid,\n EllipsoidTerrainProvider,\n HeadingPitchRange,\n Math as CesiumMath,\n Matrix3,\n Matrix4,\n Rectangle,\n sampleTerrainMostDetailed,\n Transforms,\n} from 'cesium'\n\nimport { rangeForZoom, reportedZoomGrid, zoomForRange } from '../cameraScale'\nimport { lookAtTarget } from '../lookAtTarget'\nimport { pickGroundPoint } from '../pickGroundPoint'\nimport {\n cameraFootprint,\n cesiumHeadingToRotation,\n focusRangeForZoom,\n mapToWgs84,\n metresPerMapUnit,\n rotationToCesiumHeading,\n} from '../projection'\nimport { watchCesiumMoving } from './cesiumMoving'\n\ninterface CameraFocus {\n readonly lon: number\n readonly lat: number\n // Elevation of the point above the ellipsoid. Carried so a re-target lands on the surface the\n // focus was measured against rather than dropping back to ellipsoid height.\n readonly height: number\n readonly range: number\n // False when the pick fell back to the ellipsoid, leaving height and range wrong by the terrain\n // elevation.\n readonly onTerrain: boolean\n}\n\n// Cap how far the camera->focus slant range may exceed the vertical height when deriving the synced\n// 2D zoom. A grazing (near-horizon) tilt otherwise pushes the focus point arbitrarily far, zooming\n// the 2D view out toward the whole map\nexport const MAX_FOCUS_RANGE_FACTOR = 10\n\n// Elevation to aim a jump at, when the destination is somewhere the camera cannot see yet. Its own\n// terrain cannot be sampled: `globe.getHeight` reads whichever tile level happens to be loaded, and\n// from a far camera that coarse heightmap reports -443 m over Estonia — enough to fly the camera\n// underground. The surface currently on screen is the closest honestly measurable stand-in, and\n// once the destination is centred `fireChange` reports the true zoom from it.\nfunction jumpTargetHeight(focus: CameraFocus | undefined): number {\n return focus?.height ?? 0\n}\n\nfunction cameraFocusFromPoint(\n viewer: CesiumViewer,\n point: Cartesian3,\n onTerrain: boolean,\n): CameraFocus {\n const carto = Cartographic.fromCartesian(point)\n return {\n lon: carto.longitude * RADIANS_TO_DEGREES,\n lat: carto.latitude * RADIANS_TO_DEGREES,\n height: carto.height,\n range: Cartesian3.distance(viewer.camera.position, point),\n onTerrain,\n }\n}\n\n// Screen-centre ground point (degrees) plus the camera->point slant range, or undefined when the\n// screen centre is above the horizon. `createCentroidTilt` orbits the camera about this very point,\n// so it is invariant under the tilt gesture, and anchoring the 2D footprint here keeps the 2D map from\n// drifting toward the horizon as the 3D view tilts. The slant range grows as the view tilts, so\n// basing the 2D zoom on it (not the vertical height) keeps the 2D extent matched to the area the 3D\n// view covers.\nexport function screenCenterGroundFocus(viewer: CesiumViewer): CameraFocus | undefined {\n const canvas = viewer.scene.canvas\n const centerPx = new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2)\n const picked = pickGroundPoint(viewer, centerPx)\n\n return picked ? cameraFocusFromPoint(viewer, picked.point, picked.onTerrain) : undefined\n}\n\n// Whether the focus is an ellipsoid fallback standing in for terrain that has not rendered yet,\n// rather than ground that genuinely is not there. Reporting the first writes a zoom wrong by the\n// terrain elevation into the shared store.\n//\n// `camera.changed` is raised at the end of `Scene.initializeFrame`, before the quadtree refills its\n// load queues, so `globe.tilesLoaded` still describes the previous frame and cannot be consulted\n// here. Assume unrendered; `postRender` is where that question can be answered.\nfunction focusIsUnmeasurable(viewer: CesiumViewer, focus: CameraFocus | undefined): boolean {\n if (!focus || focus.onTerrain) {\n return false\n }\n\n return !(viewer.terrainProvider instanceof EllipsoidTerrainProvider)\n}\n\n// Cesium's camera.heading/camera.pitch getters always measure against the ENU frame at the\n// camera's OWN position, not the frame `lookAt` actually orients the camera against (the ENU frame\n// at the look-at target). The two frames coincide at nadir but tilt apart as the camera->target\n// range grows relative to Earth's radius, so a `setPitch`/`setRotation` round-trip drifts once\n// zoomed out far enough (e.g. at MIN_ZOOM). Re-deriving heading/pitch against the SAME focus point\n// used to position the camera keeps the reported value equal to what was set, at any range.\nexport function headingPitchAtFocus(\n camera: Camera,\n lon: number,\n lat: number,\n): { heading: number; pitch: number } {\n const enuRotation = Matrix4.getMatrix3(\n Transforms.eastNorthUpToFixedFrame(Cartesian3.fromDegrees(lon, lat)),\n new Matrix3(),\n )\n const localRotation = Matrix3.transpose(enuRotation, new Matrix3())\n\n const localDirection = Matrix3.multiplyByVector(\n localRotation,\n camera.directionWC,\n new Cartesian3(),\n )\n const localUp = Matrix3.multiplyByVector(localRotation, camera.upWC, new Cartesian3())\n\n const pitch = CesiumMath.PI_OVER_TWO - CesiumMath.acosClamped(localDirection.z)\n\n const nearVertical = CesiumMath.equalsEpsilon(\n Math.abs(localDirection.z),\n 1.0,\n CesiumMath.EPSILON3,\n )\n const rawHeading = nearVertical\n ? Math.atan2(localUp.y, localUp.x) - CesiumMath.PI_OVER_TWO\n : Math.atan2(localDirection.y, localDirection.x) - CesiumMath.PI_OVER_TWO\n const heading = CesiumMath.TWO_PI - CesiumMath.zeroToTwoPi(rawHeading)\n\n return { heading, pitch }\n}\n\n// The orientation to hand a `lookAt`/`flyTo` that is about to re-apply the camera's current tilt and\n// bearing. Both orient against the ENU frame at their TARGET, while the `camera.heading`/\n// `camera.pitch` getters measure against the frame at the camera's OWN position; the two differ by\n// the angle the camera's `range · cos(pitch)` stand-off subtends at Earth's centre. Feeding a getter\n// back into `lookAt` therefore loses that angle on every call — 0.14° of tilt at zoom 6, 2.17° at\n// MIN_ZOOM — and a parallel-view divider drag replays it ~180 times a second, walking the camera to\n// nadir. With no focus point the value is applied at the camera's own position, where the two frames\n// already coincide, so the getters are the correct read there.\nfunction orientationAtFocus(\n camera: Camera,\n focus: CameraFocus | undefined,\n): { heading: number; pitch: number } {\n if (!focus) {\n return { heading: camera.heading, pitch: camera.pitch }\n }\n\n return headingPitchAtFocus(camera, focus.lon, focus.lat)\n}\n\n// The screen-centre point at `height`, picked along the same ray rather than raised off the\n// ellipsoid one. Raising it instead leaves the target off the view ray, so its lon/lat and range\n// disagree and a `lookAt` relocates the camera on every call.\nfunction focusAtHeight(viewer: CesiumViewer, height: number): CameraFocus | undefined {\n const scene = viewer.scene\n const canvas = scene.canvas\n const centerPx = new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2)\n const base = scene.globe.ellipsoid ?? Ellipsoid.default\n\n const point = viewer.camera.pickEllipsoid(\n centerPx,\n new Ellipsoid(base.radii.x + height, base.radii.y + height, base.radii.z + height),\n )\n\n if (!point) {\n return undefined\n }\n\n const carto = Cartographic.fromCartesian(point)\n\n return {\n lon: carto.longitude * RADIANS_TO_DEGREES,\n lat: carto.latitude * RADIANS_TO_DEGREES,\n height,\n range: Cartesian3.distance(viewer.camera.position, point),\n onTerrain: false,\n }\n}\n\n// Shared by flyToPosition and useCesiumEntryCamera. Rejects on a failed tile request so\n// `undefined` means only \"no terrain here\" (an ellipsoid provider, or a point terrain does not\n// cover), never a transient failure worth retrying as if it were an answer.\nexport async function sampleTerrainHeight(\n provider: TerrainProvider,\n position: { lon: number; lat: number },\n): Promise<number | undefined> {\n if (provider instanceof EllipsoidTerrainProvider) {\n return undefined\n }\n\n const [sampled] = await sampleTerrainMostDetailed(\n provider,\n [Cartographic.fromDegrees(position.lon, position.lat)],\n true,\n )\n\n return sampled?.height\n}\n\nasync function destinationTerrainHeight(\n viewer: CesiumViewer,\n lon: number,\n lat: number,\n): Promise<number> {\n try {\n return (await sampleTerrainHeight(viewer.terrainProvider, { lon, lat })) ?? 0\n } catch {\n return 0\n }\n}\n\n// The focus point, which does not move when the camera tilts (ADR 0006); the camera sub-point\n// when the horizon is in view.\nexport function viewCenter(viewer: CesiumViewer, focus: CameraFocus | undefined): [number, number] {\n const carto = viewer.camera.positionCartographic\n\n return focus\n ? [focus.lon, focus.lat]\n : [carto.longitude * RADIANS_TO_DEGREES, carto.latitude * RADIANS_TO_DEGREES]\n}\n\nconst ROTATION_EPSILON = 0.0001\n\nexport function createCesiumCameraCapability(\n viewer: CesiumViewer,\n getProjection: () => EpsgCode,\n): ICameraCapability {\n const listeners = new Set<(change: ViewChange) => void>()\n const rotationListeners = new Set<(rotation: number) => void>()\n\n viewer.camera.percentageChanged = 0.01\n\n let lastRotation: number | undefined\n\n // Last elevation measured against rendered terrain, so placement has something better than the\n // ellipsoid while tiles stream.\n let lastTerrainHeight: number | undefined\n\n // Placement only: reporting needs the raw measurement to keep `onTerrain` honest.\n function focusForPlacement(): CameraFocus | undefined {\n const focus = screenCenterGroundFocus(viewer)\n\n if (!focus) {\n return undefined\n }\n\n if (focus.onTerrain) {\n lastTerrainHeight = focus.height\n return focus\n }\n\n if (lastTerrainHeight === undefined) {\n return focus\n }\n\n return focusAtHeight(viewer, lastTerrainHeight) ?? focus\n }\n\n // A settle was dropped as unmeasurable and is waiting to be re-issued.\n let settleDropped = false\n\n // Cesium's camera.changed already fires live during a gesture (throttled by percentageChanged),\n // so the compass rides the same event on its own channel — kept separate from onViewChange so\n // the contract matches the 2D capability (ADR 0006 pipeline stays on settle reporting only).\n function fireRotation(rotation: number): void {\n if (lastRotation !== undefined && Math.abs(rotation - lastRotation) < ROTATION_EPSILON) {\n return\n }\n\n lastRotation = rotation\n rotationListeners.forEach((cb) => cb(rotation))\n }\n\n function metresPerUnitAt([lon, lat]: [number, number]): number {\n return metresPerMapUnit(getProjection(), lon, lat)\n }\n\n function reportedZoom(focus: CameraFocus | undefined): number {\n // Slant range, so the 2D extent grows as the 3D view tilts; capped near the horizon.\n const height = viewer.camera.positionCartographic.height\n const range = focusRangeForZoom(height, focus?.range, MAX_FOCUS_RANGE_FACTOR)\n\n return reportedZoomGrid(zoomForRange(viewer, range, metresPerUnitAt(viewCenter(viewer, focus))))\n }\n\n function footprint(focus: CameraFocus | undefined, zoom: number): MapExtent {\n const canvas = viewer.scene.canvas\n const [centerLon, centerLat] = viewCenter(viewer, focus)\n\n return asMapExtent(\n cameraFootprint(\n getProjection(),\n centerLon,\n centerLat,\n zoom,\n canvas.clientWidth,\n canvas.clientHeight,\n ),\n )\n }\n\n // Pure reporter (ADR 0006): emit the settled view on every camera change, including the result\n // of a programmatic command. The coordinator owns loop-breaking, so the capability never\n // suppresses its own changes.\n function emitChange(focus: CameraFocus | undefined, heading: number, pitch: number): void {\n const zoom = reportedZoom(focus)\n\n // A camera sitting on the ellipsoid (range 0) drives the zoom to infinity. The coordinator\n // writes reported zoom straight to the store without clamping, so drop the whole degenerate\n // report rather than poison the shared view state — the bbox is derived from this zoom too.\n if (!Number.isFinite(zoom)) {\n return\n }\n\n const change: ViewChange = {\n zoom,\n rotation: cesiumHeadingToRotation(heading),\n pitch: pitch as Radians,\n bbox: footprint(focus, zoom),\n }\n\n settleDropped = false\n listeners.forEach((cb) => cb(change))\n }\n\n function fireChange(focus: CameraFocus | undefined, heading: number, pitch: number): void {\n if (focusIsUnmeasurable(viewer, focus)) {\n settleDropped = true\n return\n }\n\n emitChange(focus, heading, pitch)\n }\n\n function currentView(): { focus: CameraFocus | undefined; heading: number; pitch: number } {\n const camera = viewer.camera\n const focus = screenCenterGroundFocus(viewer)\n const { heading, pitch } = focus\n ? headingPitchAtFocus(camera, focus.lon, focus.lat)\n : { heading: camera.heading, pitch: camera.pitch }\n\n return { focus, heading, pitch }\n }\n\n viewer.camera.changed.addEventListener(() => {\n const { focus, heading, pitch } = currentView()\n\n fireRotation(cesiumHeadingToRotation(heading))\n fireChange(focus, heading, pitch)\n })\n\n // Tiles finishing does not move the camera, so `camera.changed` will not fire; without this a\n // dropped settle would stand until the user next moves the map.\n viewer.scene.postRender.addEventListener(() => {\n if (!settleDropped || !viewer.scene.globe.tilesLoaded) {\n return\n }\n\n // Tiles are genuinely all in: an ellipsoid fallback here is real ground, not a gap.\n const { focus, heading, pitch } = currentView()\n emitChange(focus, heading, pitch)\n })\n\n return {\n flyTo(extent) {\n const projection = getProjection()\n const [west, south] = mapToWgs84(projection, extent[0], extent[1])\n const [east, north] = mapToWgs84(projection, extent[2], extent[3])\n viewer.camera.flyTo({\n destination: Rectangle.fromDegrees(west, south, east, north),\n duration: 0,\n })\n },\n fitExtent(extent) {\n const camera = viewer.camera\n const canvas = viewer.scene.canvas\n const [cx, cy] = extentCenter(extent)\n const projection = getProjection()\n const [lon, lat] = mapToWgs84(projection, cx, cy)\n const focus = focusForPlacement()\n const { heading, pitch } = orientationAtFocus(camera, focus)\n\n // Match the 2D ground scale at the focus point rather than containing the rectangle. (BBOX is not nicely transferable\n // onto a 3D map)\n const zoom = zoomForExtent(extent, canvas.clientWidth, canvas.clientHeight)\n const range = rangeForZoom(viewer, zoom, metresPerUnitAt([lon, lat]))\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(lon, lat, jumpTargetHeight(focus)),\n new HeadingPitchRange(heading, pitch, range),\n )\n },\n setExtent(extent) {\n const camera = viewer.camera\n const [cx, cy] = extentCenter(extent)\n const [lon, lat] = mapToWgs84(getProjection(), cx, cy)\n const focus = focusForPlacement()\n const { heading, pitch } = orientationAtFocus(camera, focus)\n\n // Recenter the camera's focus on the 2D centre, preserving the current tilt, heading and\n // range (setZoom refines the range next). A Rectangle destination would reset to nadir.\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(lon, lat, jumpTargetHeight(focus)),\n new HeadingPitchRange(heading, pitch, focus?.range ?? camera.positionCartographic.height),\n )\n },\n setZoom(zoom) {\n const camera = viewer.camera\n const focus = focusForPlacement()\n const range = rangeForZoom(viewer, zoom, metresPerUnitAt(viewCenter(viewer, focus)))\n\n if (!focus) {\n // Above the horizon — no focus point; set the vertical height in place.\n camera.setView({\n destination: Cartesian3.fromRadians(\n camera.positionCartographic.longitude,\n camera.positionCartographic.latitude,\n range,\n ),\n orientation: { heading: camera.heading, pitch: camera.pitch, roll: camera.roll },\n })\n return\n }\n\n // Set the camera->focus slant range (inverse of the zoomForRange(range) used in 3D->2D),\n // keeping the focus point, heading and pitch.\n const { heading, pitch } = orientationAtFocus(camera, focus)\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(focus.lon, focus.lat, focus.height),\n new HeadingPitchRange(heading, pitch, range),\n )\n },\n setRotation(rotation) {\n const camera = viewer.camera\n const heading = rotationToCesiumHeading(rotation)\n const focus = focusForPlacement()\n\n if (!focus) {\n // Above the horizon — rotate heading in place.\n camera.setView({ orientation: { heading, pitch: camera.pitch, roll: 0 } })\n return\n }\n\n // Orbit the focus point to the new heading, keeping the focus, range and pitch.\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(focus.lon, focus.lat, focus.height),\n new HeadingPitchRange(heading, orientationAtFocus(camera, focus).pitch, focus.range),\n )\n },\n setPitch(pitch) {\n const camera = viewer.camera\n const focus = focusForPlacement()\n\n if (!focus) {\n // Above the horizon — no focus point; tilt in place.\n camera.setView({\n destination: camera.position,\n orientation: { heading: camera.heading, pitch, roll: 0 },\n })\n return\n }\n\n // Orbit the focus point to the new tilt, keeping the focus, heading and range — the same pivot\n // the native CTRL-drag tilt uses. Tilting about the camera position instead swings the\n // screen-centre ground point downrange, which fireChange then reports as a new 2D centre.\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(focus.lon, focus.lat, focus.height),\n new HeadingPitchRange(orientationAtFocus(camera, focus).heading, pitch, focus.range),\n )\n },\n zoomTo(coord, zoom) {\n const camera = viewer.camera\n const [lon, lat] = mapToWgs84(getProjection(), coord[0], coord[1])\n const focus = focusForPlacement()\n const { heading, pitch } = orientationAtFocus(camera, focus)\n const range = rangeForZoom(viewer, zoom, metresPerUnitAt([lon, lat]))\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(lon, lat, jumpTargetHeight(focus)),\n new HeadingPitchRange(heading, pitch, range),\n )\n },\n async flyToPosition(position, zoom) {\n const camera = viewer.camera\n const focus = focusForPlacement()\n const { heading, pitch } = orientationAtFocus(camera, focus)\n const terrainHeight = await destinationTerrainHeight(viewer, position.lon, position.lat)\n const range = rangeForZoom(viewer, zoom, metresPerUnitAt([position.lon, position.lat]))\n\n // flyTo's `destination` places the camera itself there, not a look-at target, so off nadir\n // the centred point drifts.\n camera.flyToBoundingSphere(\n new BoundingSphere(Cartesian3.fromDegrees(position.lon, position.lat, terrainHeight), 0),\n {\n offset: new HeadingPitchRange(heading, pitch, range),\n duration: 1.0,\n },\n )\n },\n getCenter() {\n const carto = viewer.camera.positionCartographic\n return [carto.longitude * RADIANS_TO_DEGREES, carto.latitude * RADIANS_TO_DEGREES]\n },\n getBbox() {\n const { focus } = currentView()\n\n return footprint(focus, reportedZoom(focus))\n },\n getRotation() {\n return cesiumHeadingToRotation(currentView().heading)\n },\n onViewChange(callback) {\n listeners.add(callback)\n return () => {\n listeners.delete(callback)\n }\n },\n onRotationChange(callback) {\n rotationListeners.add(callback)\n return () => {\n rotationListeners.delete(callback)\n }\n },\n onMovingChange(callback) {\n return watchCesiumMoving(viewer, callback)\n },\n }\n}\n","import {\n createEngineErrorChannel,\n type EngineErrorChannel,\n WEBGL_CONTEXT_LOST_ERROR_NAME,\n} from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\n\nexport interface CesiumEngineHealth extends EngineErrorChannel {\n dispose(): void\n}\n\nexport function createCesiumEngineHealth(viewer: CesiumViewer): CesiumEngineHealth {\n const channel = createEngineErrorChannel()\n\n function handleContextLost(): void {\n const error = new Error('WebGL context lost')\n error.name = WEBGL_CONTEXT_LOST_ERROR_NAME\n channel.reportError(error, { severity: 'fatal' })\n }\n\n function handleRenderError(_scene: unknown, error: unknown): void {\n channel.reportError(error instanceof Error ? error : new Error(String(error)), {\n severity: 'fatal',\n })\n }\n\n viewer.canvas.addEventListener('webglcontextlost', handleContextLost)\n viewer.scene.renderError.addEventListener(handleRenderError)\n\n return {\n reportError: channel.reportError,\n onError: channel.onError,\n dispose() {\n viewer.canvas.removeEventListener('webglcontextlost', handleContextLost)\n viewer.scene.renderError.removeEventListener(handleRenderError)\n },\n }\n}\n","import type { EpsgCode, MapExtent, ZoomLevel } from '@xgis/xgis-common'\nimport { asMapExtent, clampExtentToBounds, extentCenter, zoomToFit } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { Cartesian3, HeadingPitchRange } from 'cesium'\n\nimport { rangeForZoom, zoomForRange } from './cameraScale'\nimport {\n headingPitchAtFocus,\n MAX_FOCUS_RANGE_FACTOR,\n screenCenterGroundFocus,\n viewCenter,\n} from './capabilities/cesiumCamera'\nimport { lookAtTarget } from './lookAtTarget'\nimport { cameraFootprint, mapToWgs84, metresPerMapUnit, wgs84ToMap } from './projection'\n\n// Below this the correction would feed cameraSync's report -> store -> mirror loop (ADR 0006).\nconst MOVE_EPSILON_METERS = 1\n\n/** Zoom at which `bounds` just fills the canvas — the furthest this camera may pull back. */\nexport function boundsFloor(viewer: CesiumViewer, bounds: MapExtent): ZoomLevel {\n const canvas = viewer.scene.canvas\n\n return zoomToFit(bounds, { width: canvas.clientWidth, height: canvas.clientHeight })\n}\n\n/** Cesium has no extent constraint, so the camera is pulled back each frame after it moves. */\nexport function createCameraBoundsGuard(\n viewer: CesiumViewer,\n bounds: MapExtent,\n projection: EpsgCode,\n): () => void {\n let lastPosition: Cartesian3 | undefined\n let lastCanvasKey = ''\n\n function clampToBounds(): void {\n const camera = viewer.camera\n const canvas = viewer.scene.canvas\n // The footprint is derived from the canvas as well, so a resize alone can put it out of bounds\n // even though the camera itself never moved.\n const canvasKey = `${canvas.clientWidth}x${canvas.clientHeight}`\n const settled =\n lastPosition &&\n Cartesian3.equals(camera.position, lastPosition) &&\n canvasKey === lastCanvasKey\n\n if (settled) {\n return\n }\n\n lastPosition = Cartesian3.clone(camera.position, lastPosition)\n lastCanvasKey = canvasKey\n\n const focus = screenCenterGroundFocus(viewer)\n const [lon, lat] = viewCenter(viewer, focus)\n // Taken where the capability takes it, or the guard's zoom floor and the reported zoom disagree.\n const metresPerUnit = metresPerMapUnit(projection, lon, lat)\n\n const viewport = { width: canvas.clientWidth, height: canvas.clientHeight }\n\n // Tilted toward the horizon nothing is under the screen centre, so the camera's height stands\n // in for its distance. A tilted camera can be far out while staying low, so the height is\n // scaled to stay comparable with the distance limit below.\n const currentRange = focus\n ? focus.range\n : camera.positionCartographic.height * MAX_FOCUS_RANGE_FACTOR\n\n // Scale is corrected before position: a view covering more ground than the topic shows the\n // outside however it is centred, and the pulled-in footprint is what the centre then clamps\n // against.\n const range = Math.min(\n currentRange,\n rangeForZoom(viewer, boundsFloor(viewer, bounds), metresPerUnit),\n )\n\n const footprint = asMapExtent(\n cameraFootprint(\n projection,\n lon,\n lat,\n zoomForRange(viewer, range, metresPerUnit),\n viewport.width,\n viewport.height,\n ),\n )\n\n const [x, y] = wgs84ToMap(projection, lon, lat)\n const [targetX, targetY] = extentCenter(clampExtentToBounds(footprint, bounds))\n\n if (\n Math.abs(targetX - x) < MOVE_EPSILON_METERS &&\n Math.abs(targetY - y) < MOVE_EPSILON_METERS &&\n currentRange - range < MOVE_EPSILON_METERS\n ) {\n return\n }\n\n const [targetLon, targetLat] = mapToWgs84(projection, targetX, targetY)\n\n if (focus) {\n // camera.heading/pitch measure against the ENU frame at the camera's OWN position, but\n // lookAt orients against the frame at its TARGET — re-deriving them at the focus point\n // avoids baking that mismatch into the correction (see headingPitchAtFocus).\n const { heading, pitch } = headingPitchAtFocus(camera, focus.lon, focus.lat)\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(targetLon, targetLat),\n new HeadingPitchRange(heading, pitch, range),\n )\n } else {\n // Back from the scaled stand-in to the height setView expects.\n camera.setView({\n destination: Cartesian3.fromDegrees(targetLon, targetLat, range / MAX_FOCUS_RANGE_FACTOR),\n orientation: { heading: camera.heading, pitch: camera.pitch, roll: camera.roll },\n })\n }\n\n lastPosition = Cartesian3.clone(camera.position, lastPosition)\n }\n\n return viewer.scene.preRender.addEventListener(clampToBounds)\n}\n","import type { IViewLimitsCapability } from '@xgis/xgis-common'\nimport { MIN_ZOOM } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\n\nimport { boundsFloor } from '../cameraBoundsGuard'\nimport { reportedZoomGrid } from '../cameraScale'\n\nexport function createCesiumViewLimitsCapability(viewer: CesiumViewer): IViewLimitsCapability {\n return {\n getZoomFloor(bounds) {\n if (!bounds) {\n return MIN_ZOOM\n }\n\n return reportedZoomGrid(boundsFloor(viewer, bounds))\n },\n }\n}\n","import {\n type EpsgCode,\n extentCenter,\n type MapExtent,\n type Radians,\n SHALLOWEST_PITCH,\n type ZoomLevel,\n} from '@xgis/xgis-common'\nimport { Cartesian3, HeadingPitchRange, type Viewer as CesiumViewer } from 'cesium'\n\nimport { rangeForZoom } from './cameraScale'\nimport { headingPitchAtFocus } from './capabilities/cesiumCamera'\nimport { lookAtTarget } from './lookAtTarget'\nimport { mapToWgs84, metresPerMapUnit, rotationToCesiumHeading } from './projection'\n\n// Assumed ground elevation until terrain can be sampled; `useCesiumEntryCamera` corrects it.\nexport const ELLIPSOID_HEIGHT = 0\n\nexport interface EntryView {\n readonly bbox: MapExtent\n readonly zoom: ZoomLevel\n readonly rotation: Radians\n readonly pitch: Radians\n}\n\nexport interface EntryTarget {\n readonly lon: number\n readonly lat: number\n readonly heading: number\n readonly pitch: number\n readonly range: number\n}\n\nexport function entryTarget(\n viewer: CesiumViewer,\n view: EntryView,\n projection: EpsgCode,\n): EntryTarget {\n const [centerX, centerY] = extentCenter(view.bbox)\n const [lon, lat] = mapToWgs84(projection, centerX, centerY)\n\n return {\n lon,\n lat,\n heading: rotationToCesiumHeading(view.rotation),\n // `lookAt` offsets the camera by -range*sin(pitch), so a pitch at or above the horizon would\n // place it on or under the ground plane. Free-look (SHIFT-drag) can leave the store's pitch\n // there and it survives a mode switch, so entry clamps to the same tilt the gestures stop at.\n pitch: Math.min(view.pitch, SHALLOWEST_PITCH),\n range: rangeForZoom(viewer, view.zoom, metresPerMapUnit(projection, lon, lat)),\n }\n}\n\n// `height` is the ground elevation under the target; the camera stands off from that.\nexport function placeEntryCamera(viewer: CesiumViewer, target: EntryTarget, height: number): void {\n lookAtTarget(\n viewer.camera,\n Cartesian3.fromDegrees(target.lon, target.lat, height),\n new HeadingPitchRange(target.heading, target.pitch, target.range),\n )\n}\n\n// Lifts the camera by the ground elevation under its target, leaving where it looks, how far and\n// how steeply it is tilted exactly as they were. The range and orientation are measured off the\n// camera rather than rebuilt, so whatever moved it last is not overridden.\nexport function raiseEntryCameraToTerrain(\n viewer: CesiumViewer,\n target: EntryTarget,\n height: number,\n): void {\n const camera = viewer.camera\n const ellipsoidPoint = Cartesian3.fromDegrees(target.lon, target.lat, ELLIPSOID_HEIGHT)\n const range = Cartesian3.distance(camera.position, ellipsoidPoint)\n const { heading, pitch } = headingPitchAtFocus(camera, target.lon, target.lat)\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(target.lon, target.lat, height),\n new HeadingPitchRange(heading, pitch, range),\n )\n}\n","import type { Viewer as CesiumViewer } from 'cesium'\n\n// Cesium's ScreenSpaceEventHandler cancels `pointerdown` on the canvas whenever an input action is\n// registered for the pressed button — which the default camera controller always is — and a\n// cancelled `pointerdown` suppresses the compatibility `mousedown` event. TEDI overlays opened by\n// click (the basemap picker's Popover, every tooltip on a touch device) detect an outside press by\n// listening for `mousedown` on the document, so pressing the 3D canvas never dismisses them, while\n// the same press over the 2D map does. Re-dispatching the suppressed event restores the symmetry.\n//\n// Remove once TEDI's Overlay dismisses on `pointerdown` (floating-ui's default) instead.\nexport function createCanvasPressRelay(viewer: CesiumViewer): () => void {\n const canvas = viewer.canvas\n\n function relayAsMouseDown(event: PointerEvent): void {\n if (!event.defaultPrevented) {\n return\n }\n\n canvas.dispatchEvent(\n new MouseEvent('mousedown', {\n bubbles: true,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n }),\n )\n }\n\n canvas.addEventListener('pointerdown', relayAsMouseDown)\n\n return () => {\n canvas.removeEventListener('pointerdown', relayAsMouseDown)\n }\n}\n","import { platformModifierOnly, SHALLOWEST_PITCH } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport {\n CameraEventType,\n Cartesian2,\n KeyboardEventModifier,\n Math as CesiumMath,\n Matrix4,\n Transforms,\n} from 'cesium'\n\nimport { pickGroundPoint } from '../pickGroundPoint'\n\n// Heading turns at the 2D interaction's rate, against canvas width rather than an absolute\n// rad/px, so the same drag turns both panes together in parallel view.\nexport const ROTATE_RATE = 1.77\n// Pitch has no 2D counterpart to match, and Cesium's own altitude-dependent tilt rate is private.\nexport const RADIANS_PER_PIXEL = 0.0025\nconst LEFT_BUTTON = 0\nconst MIDDLE_BUTTON = 1\nconst LEFT_BUTTON_MASK = 1\nconst MIDDLE_BUTTON_MASK = 4\n\ninterface TiltEventTypeEntry {\n eventType: CameraEventType\n modifier?: KeyboardEventModifier\n}\n\n// Every mouse tilt gesture Cesium binds, including its Ctrl+right-drag: all of them pivot on the\n// cursor, which is what this replaces. Pinch-tilt is left to Cesium.\nfunction isReplacedTilt(entry: CameraEventType | TiltEventTypeEntry): boolean {\n if (entry === CameraEventType.MIDDLE_DRAG) {\n return true\n }\n\n return (\n typeof entry === 'object' &&\n (entry.eventType === CameraEventType.LEFT_DRAG ||\n entry.eventType === CameraEventType.RIGHT_DRAG) &&\n entry.modifier === KeyboardEventModifier.CTRL\n )\n}\n\nfunction buttonMaskFor(button: number): number {\n return button === MIDDLE_BUTTON ? MIDDLE_BUTTON_MASK : LEFT_BUTTON_MASK\n}\n\nfunction startsGesture(event: PointerEvent): boolean {\n if (event.button === MIDDLE_BUTTON) {\n return !event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey\n }\n\n return event.button === LEFT_BUTTON && platformModifierOnly(event)\n}\n\n/**\n * Orbits the camera about the ground point under the canvas centre, on terrain where terrain has\n * rendered. That is the same point `screenCenterGroundFocus` reports as the view centre, so the\n * synced 2D pane holds still while the 3D view turns.\n *\n * Cesium's own tilt cannot do this: it picks its pivot from the mouse position, and splits the two\n * mouse axes across two different pivots — see ADR 0024.\n */\nexport function createCentroidTilt(viewer: CesiumViewer): () => void {\n const { scene, camera } = viewer\n const controller = scene.screenSpaceCameraController\n const canvas = scene.canvas\n const originalTiltEventTypes = controller.tiltEventTypes\n const entries = Array.isArray(originalTiltEventTypes)\n ? originalTiltEventTypes\n : originalTiltEventTypes === undefined\n ? []\n : [originalTiltEventTypes]\n controller.tiltEventTypes = entries.filter((entry) => !isReplacedTilt(entry))\n\n let anchorTransform: Matrix4 | undefined\n let activePointerId: number | undefined\n let activeButtonMask = LEFT_BUTTON_MASK\n let suspendedRotate: boolean | undefined\n let lastX = 0\n let lastY = 0\n\n function finishGesture(): void {\n const pointerId = activePointerId\n activePointerId = undefined\n anchorTransform = undefined\n if (suspendedRotate !== undefined) {\n controller.enableRotate = suspendedRotate\n suspendedRotate = undefined\n }\n if (pointerId !== undefined && canvas.hasPointerCapture(pointerId)) {\n canvas.releasePointerCapture(pointerId)\n }\n }\n\n function handlePointerDown(event: PointerEvent): void {\n if (\n activePointerId !== undefined ||\n event.pointerType !== 'mouse' ||\n !startsGesture(event) ||\n !controller.enableInputs ||\n !controller.enableTilt\n ) {\n return\n }\n\n // Picked once per gesture: the camera keeps looking at the pivot, so it stays under the canvas\n // centre by itself. Re-picking every frame would walk it across the terrain instead.\n const picked = pickGroundPoint(\n viewer,\n new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2),\n )\n if (!picked) {\n return\n }\n\n anchorTransform = Transforms.eastNorthUpToFixedFrame(picked.point)\n activePointerId = event.pointerId\n activeButtonMask = buttonMaskFor(event.button)\n // `KeyboardEventModifier` has no Meta, so on macOS Cesium sees this drag as an unmodified\n // left-drag, matches its own `rotateEventTypes` and spins the globe under the orbit. Measured\n // 152 px of pivot drift before this suspension.\n suspendedRotate = controller.enableRotate\n controller.enableRotate = false\n lastX = event.clientX\n lastY = event.clientY\n canvas.setPointerCapture(event.pointerId)\n }\n\n function handlePointerMove(event: PointerEvent): void {\n if (!anchorTransform || event.pointerId !== activePointerId) {\n return\n }\n if (!(event.buttons & activeButtonMask) || !controller.enableInputs || !controller.enableTilt) {\n finishGesture()\n return\n }\n const dx = event.clientX - lastX\n const dy = event.clientY - lastY\n lastX = event.clientX\n lastY = event.clientY\n if (dx === 0 && dy === 0) {\n return\n }\n\n const previousTransform = Matrix4.clone(camera.transform)\n try {\n camera.lookAtTransform(anchorTransform)\n // Rotating about the frame's vertical axis leaves the tilt untouched, so the heading half of\n // a diagonal drag always applies in full — including while the tilt sits at its limit.\n camera.rotateLeft(ROTATE_RATE * (dx / canvas.clientWidth) * Math.PI * 2)\n\n // The horizon end of the tilt; `createNadirLimit` bounds the overhead end the same way, and\n // neither covers the other. The camera looks at the frame's origin, so the vertical component\n // of its direction is the sine of the tilt. Clamping the angle rather than rejecting the\n // whole step is what keeps the gesture from stalling sideways once the tilt is pinned.\n // Cesium's native controller derives vertical tilt from startY - endY: dragging down must\n // pass a negative angle to rotateUp.\n const tilt = CesiumMath.asinClamped(camera.direction.z)\n const allowedUp = Math.min(-dy * RADIANS_PER_PIXEL, SHALLOWEST_PITCH - tilt)\n\n if (allowedUp !== 0) {\n camera.rotateUp(allowedUp)\n }\n } finally {\n camera.lookAtTransform(previousTransform)\n }\n scene.requestRender()\n }\n\n function handlePointerEnd(event: PointerEvent): void {\n if (event.pointerId !== activePointerId) {\n return\n }\n finishGesture()\n }\n\n canvas.addEventListener('pointerdown', handlePointerDown)\n canvas.addEventListener('pointermove', handlePointerMove)\n canvas.addEventListener('pointerup', handlePointerEnd)\n canvas.addEventListener('pointercancel', handlePointerEnd)\n canvas.addEventListener('lostpointercapture', handlePointerEnd)\n window.addEventListener('blur', finishGesture)\n\n return () => {\n finishGesture()\n controller.tiltEventTypes = originalTiltEventTypes\n canvas.removeEventListener('pointerdown', handlePointerDown)\n canvas.removeEventListener('pointermove', handlePointerMove)\n canvas.removeEventListener('pointerup', handlePointerEnd)\n canvas.removeEventListener('pointercancel', handlePointerEnd)\n canvas.removeEventListener('lostpointercapture', handlePointerEnd)\n window.removeEventListener('blur', finishGesture)\n }\n}\n","import type { Viewer as CesiumViewer } from 'cesium'\nimport { Cartesian2, Cartesian3 } from 'cesium'\n\nimport { pickGroundPoint } from '../pickGroundPoint'\n\nconst KEYBOARD_PAN_DIVISOR = 10\n\n// One zoom level is a factor of two in the camera->focus range, as in the synced 2D view.\nconst ZOOM_IN_RANGE_FRACTION = 0.5\nconst ZOOM_OUT_RANGE_FRACTION = 1\n\ntype Vec3 = [number, number, number]\n\n// Horizontal component of `vec` (projection onto the plane with the given normal), normalized.\n// null when `vec` is parallel to the normal — then there is no horizontal direction.\nexport function horizontalDirection(vec: Vec3, normal: Vec3): Vec3 | null {\n const [vecX, vecY, vecZ] = vec\n const [normalX, normalY, normalZ] = normal\n\n const dot = vecX * normalX + vecY * normalY + vecZ * normalZ\n const hX = vecX - dot * normalX\n const hY = vecY - dot * normalY\n const hZ = vecZ - dot * normalZ\n const len = Math.hypot(hX, hY, hZ)\n\n if (len < 1e-6) {\n return null\n }\n\n return [hX / len, hY / len, hZ / len]\n}\n\nexport function createCesiumKeyboardHandler(viewer: CesiumViewer, label: string): () => void {\n const canvas = viewer.canvas\n canvas.setAttribute('tabindex', '0')\n canvas.setAttribute('role', 'application')\n canvas.setAttribute('aria-label', label)\n\n function focusCanvas(): void {\n canvas.focus()\n }\n\n function panForward(amount: number): void {\n const camera = viewer.camera\n const normal = viewer.scene.globe.ellipsoid.geodeticSurfaceNormal(\n camera.positionWC,\n new Cartesian3(),\n )\n const forward = horizontalDirection(\n [camera.up.x, camera.up.y, camera.up.z],\n [normal.x, normal.y, normal.z],\n )\n\n if (!forward) {\n return\n }\n\n const [forwardX, forwardY, forwardZ] = forward\n camera.move(new Cartesian3(forwardX, forwardY, forwardZ), amount)\n }\n\n function screenCenterRange(): number {\n const camera = viewer.camera\n const canvas = viewer.scene.canvas\n const picked = pickGroundPoint(\n viewer,\n new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2),\n )\n\n if (!picked) {\n return camera.positionCartographic.height\n }\n\n return Cartesian3.distance(camera.positionWC, picked.point)\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n const camera = viewer.camera\n const moveRate = camera.positionCartographic.height / KEYBOARD_PAN_DIVISOR\n\n switch (event.key) {\n case 'ArrowUp':\n panForward(moveRate)\n break\n case 'ArrowDown':\n panForward(-moveRate)\n break\n case 'ArrowLeft':\n camera.moveLeft(moveRate)\n break\n case 'ArrowRight':\n camera.moveRight(moveRate)\n break\n case '+':\n case '=':\n camera.zoomIn(screenCenterRange() * ZOOM_IN_RANGE_FRACTION)\n break\n case '-':\n camera.zoomOut(screenCenterRange() * ZOOM_OUT_RANGE_FRACTION)\n break\n default:\n return\n }\n\n event.preventDefault()\n }\n\n canvas.addEventListener('click', focusCanvas)\n canvas.addEventListener('keydown', onKeyDown)\n\n return () => {\n canvas.removeEventListener('click', focusCanvas)\n canvas.removeEventListener('keydown', onKeyDown)\n }\n}\n","import type { Camera, Viewer as CesiumViewer } from 'cesium'\nimport { Cartesian3, Math as CesiumMath, Matrix4 } from 'cesium'\n\nconst DOWN = new Cartesian3(0, 0, -1)\n\n// Negative once the view has turned past straight down: the up vector tips below the frame's\n// horizontal exactly as it crosses.\nfunction angleToNadir(camera: Camera): number {\n const angle = CesiumMath.acosClamped(Cartesian3.dot(camera.direction, DOWN))\n\n return camera.up.z >= 0 ? angle : -angle\n}\n\n/**\n * Cesium clamps its tilt by the camera's POSITION against the pivot it orbits, never by where the\n * camera looks. The two differ by the angle between the drag row and the canvas midline, so the\n * view crosses straight down — upside down in 3D, and a heading flipped 180 degrees into the synced\n * 2D view. The tilt reaches the pitch only through `rotateUp`, so the limit goes there.\n */\nexport function createNadirLimit(viewer: CesiumViewer): () => void {\n const camera = viewer.camera\n const rotateUp = camera.rotateUp.bind(camera)\n\n camera.rotateUp = (angle?: number) => {\n const requested = angle ?? camera.defaultRotateAmount\n\n // `pan3D` finishes with a rotateUp of its own, about the Earth's centre, which does not change\n // the tilt at all. Only the tilt gesture rotates inside a reference frame.\n if (Matrix4.equals(camera.transform, Matrix4.IDENTITY)) {\n rotateUp(requested)\n return\n }\n\n const allowed = Math.max(requested, -angleToNadir(camera))\n\n if (allowed !== 0) {\n rotateUp(allowed)\n }\n }\n\n return () => {\n Reflect.deleteProperty(camera, 'rotateUp')\n }\n}\n","import type { I3DSource, RgbaColor } from '@xgis/xgis-common'\nimport { Cesium3DTileset, Cesium3DTileStyle, I3SDataProvider } from 'cesium'\n\nexport type Cesium3DPrimitive = Cesium3DTileset | I3SDataProvider\n\nexport interface Created3DTileset {\n primitive: Cesium3DPrimitive\n styleable?: Cesium3DTileset\n source: I3DSource\n}\n\nconst MEGABYTE = 1024 * 1024\nconst DEFAULT_MEM_USAGE = 512\nconst DEFAULT_FILL_COLOR: RgbaColor = [234, 231, 221, 1]\nconst DEFAULT_SCREENSPACE_ERROR = 16\n\nfunction colorExpression([red, green, blue, alpha]: RgbaColor, opacity: number): string {\n return `rgba(${red}, ${green}, ${blue}, ${alpha * opacity})`\n}\n\nfunction tilesetOptions(source: I3DSource): Cesium3DTileset.ConstructorOptions {\n return {\n maximumScreenSpaceError: source.maximumScreenSpaceError ?? DEFAULT_SCREENSPACE_ERROR,\n skipLevelOfDetail: source.skipLevelOfDetail ?? true,\n cullWithChildrenBounds: source.cullWithChildrenBounds ?? true,\n dynamicScreenSpaceError: source.dynamicScreenSpaceError ?? true,\n dynamicScreenSpaceErrorDensity: 0.99,\n cacheBytes: source.maximumMemoryUsage\n ? source.maximumMemoryUsage * MEGABYTE\n : DEFAULT_MEM_USAGE * MEGABYTE,\n cullRequestsWhileMoving: true,\n cullRequestsWhileMovingMultiplier: 300,\n foveatedScreenSpaceError: true,\n }\n}\n\nfunction i3sUrl(source: I3DSource): string {\n const withLayer =\n source.layerId === undefined || /\\/layers\\/\\d+\\/?$/.test(source.url)\n ? source.url\n : `${source.url.replace(/\\/+$/, '')}/layers/${source.layerId}`\n\n if (!source.token) {\n return withLayer\n }\n\n return `${withLayer}${withLayer.includes('?') ? '&' : '?'}token=${encodeURIComponent(source.token)}`\n}\n\nexport async function create3DTileset(source: I3DSource): Promise<Created3DTileset | null> {\n if (!source.url) {\n return null\n }\n\n if (source.type === 'i3s') {\n const provider = await I3SDataProvider.fromUrl(i3sUrl(source), {\n cesium3dTilesetOptions: tilesetOptions(source),\n })\n\n return { primitive: provider, source }\n }\n\n const tileset = await Cesium3DTileset.fromUrl(source.url, tilesetOptions(source))\n\n return { primitive: tileset, styleable: tileset, source }\n}\n\nexport function apply3DTilesetOpacity(created: Created3DTileset, opacity: number): void {\n const tileset = created.styleable\n\n if (!tileset) {\n return\n }\n\n tileset.style = new Cesium3DTileStyle({\n color: colorExpression(created.source.fillColor ?? DEFAULT_FILL_COLOR, opacity),\n })\n}\n","import type { Entity, EntityCollection, MaterialProperty, Property } from 'cesium'\nimport {\n Color,\n ColorMaterialProperty,\n ConstantProperty,\n ImageMaterialProperty,\n Iso8601,\n} from 'cesium'\n\n/**\n * One colour-bearing property of one entity, paired with the colour it shows at full opacity.\n *\n * Cesium has no per-DataSource alpha the way imagery layers and 3D tilesets have, so basemap\n * opacity has to be written into every entity individually. Recomputing from `base` rather\n * than from whatever is currently on the entity is what stops a dragged slider from compounding.\n */\nexport interface KmlOpacitySlot {\n base: Color\n property: ConstantProperty\n}\n\ntype Filled = { material: MaterialProperty }\ntype Outlined = { outlineColor: Property | undefined }\ntype Tinted = { color: Property | undefined }\n\nfunction constantColor(property: Property | undefined, fallback: Color): Color {\n const value: unknown = property?.getValue(Iso8601.MINIMUM_VALUE)\n\n return value instanceof Color ? value : fallback\n}\n\n// Replacing a property makes the geometry visualizer rebuild the primitive, where calling setValue\n// on the one the graphic already holds lets the static colour batch update an attribute instead.\n// The slider is dragged, so this is the hot path.\nfunction colorSlot(\n current: Property | undefined,\n fallback: Color,\n install: (property: ConstantProperty) => void,\n): KmlOpacitySlot {\n const base = constantColor(current, fallback)\n\n if (current instanceof ConstantProperty) {\n return { base, property: current }\n }\n\n const property = new ConstantProperty(base)\n install(property)\n\n return { base, property }\n}\n\n// Targets the colour inside the material rather than the material itself, which would be the\n// rebuild colorSlot is avoiding.\nfunction materialSlot(graphic: Filled): KmlOpacitySlot {\n const material = graphic.material\n\n if (material instanceof ImageMaterialProperty || material instanceof ColorMaterialProperty) {\n return colorSlot(material.color, Color.WHITE, (property) => {\n material.color = property\n })\n }\n\n // An unstyled KML polygon or polyline has no material at all — the white it draws in comes from\n // the visualizer's default, so there is nothing to read and one has to be created.\n const created = new ColorMaterialProperty(Color.WHITE)\n graphic.material = created\n\n return colorSlot(created.color, Color.WHITE, (property) => {\n created.color = property\n })\n}\n\nfunction fillSlots(graphic: Filled | undefined): KmlOpacitySlot[] {\n return graphic ? [materialSlot(graphic)] : []\n}\n\n// Cesium's GeometryUpdater draws an absent outline colour black, so capturing white here would\n// repaint unstyled geometry the moment the slots were collected.\nfunction outlineSlots(graphic: Outlined | undefined): KmlOpacitySlot[] {\n if (!graphic) {\n return []\n }\n\n return [\n colorSlot(graphic.outlineColor, Color.BLACK, (property) => {\n graphic.outlineColor = property\n }),\n ]\n}\n\n// White as the fallback leaves the image or disc uncoloured, so only the alpha ever moves.\nfunction tintSlots(graphic: Tinted | undefined): KmlOpacitySlot[] {\n if (!graphic) {\n return []\n }\n\n return [\n colorSlot(graphic.color, Color.WHITE, (property) => {\n graphic.color = property\n }),\n ]\n}\n\nfunction entitySlots(entity: Entity): KmlOpacitySlot[] {\n const { polygon, polyline, wall, rectangle, path, billboard, point } = entity\n\n return [\n ...fillSlots(polygon),\n ...outlineSlots(polygon),\n ...fillSlots(polyline),\n ...fillSlots(wall),\n ...outlineSlots(wall),\n ...fillSlots(rectangle),\n ...fillSlots(path),\n ...tintSlots(billboard),\n ...tintSlots(point),\n ...outlineSlots(point),\n ]\n}\n\nexport function collectKmlOpacitySlots(entities: EntityCollection): KmlOpacitySlot[] {\n return entities.values.flatMap(entitySlots)\n}\n\n// ConstantProperty.setValue clones into the Color it already holds, so one scratch can carry every\n// write without ever being retained — and it skips its change event when the colour has not moved.\nconst scratchColor = new Color()\n\nexport function applyKmlOpacity(slots: readonly KmlOpacitySlot[], opacity: number): void {\n for (const slot of slots) {\n slot.property.setValue(Color.fromAlpha(slot.base, slot.base.alpha * opacity, scratchColor))\n }\n}\n","import type { KmlParams } from '@xgis/xgis-common'\nimport {\n KML_DEFAULT_COLOR,\n KML_LABEL_FONT,\n KML_LABEL_FONT_SIZE_PX,\n KML_LABEL_OUTLINE_COLOR,\n KML_LABEL_OUTLINE_PX,\n KML_MARKER_SIZE_PX,\n kmlExtractStyles,\n} from '@xgis/xgis-common'\nimport type {\n Cartesian3,\n Entity,\n EntityCollection,\n LabelGraphics,\n MaterialProperty,\n PolygonGraphics,\n PolylineGraphics,\n Property,\n} from 'cesium'\nimport {\n ArcType,\n Color,\n ColorMaterialProperty,\n ConstantProperty,\n HeightReference,\n Iso8601,\n PointGraphics,\n PolygonHierarchy,\n Resource,\n} from 'cesium'\n\nconst DEFAULT_COLOR = Color.fromCssColorString(KML_DEFAULT_COLOR)\nconst LABEL_OUTLINE_COLOR = Color.fromCssColorString(KML_LABEL_OUTLINE_COLOR)\n\nconst SDF_FONT_SIZE_PX = 48\n\nconst LABEL_OUTLINE_WIDTH = (KML_LABEL_OUTLINE_PX * SDF_FONT_SIZE_PX) / KML_LABEL_FONT_SIZE_PX\n\n// Cesium draws a polygon outline with a WebGL line width, clamped to\n// ContextLimits.maximumAliasedLineWidth — 1 on Chrome/ANGLE and most desktop GPUs. Anything wider\n// has to be drawn as a polyline, which goes through a shader that honours width.\nconst MIN_DRAWN_OUTLINE_WIDTH = 1\n\nfunction constantValue(property: Property | undefined): unknown {\n return property?.getValue(Iso8601.MINIMUM_VALUE)\n}\n\nfunction markerHeightReference(clampToGround: boolean): HeightReference {\n return clampToGround ? HeightReference.CLAMP_TO_GROUND : HeightReference.NONE\n}\n\nfunction makeLabelReadable(label: LabelGraphics): void {\n label.font = new ConstantProperty(KML_LABEL_FONT)\n label.outlineColor = new ConstantProperty(LABEL_OUTLINE_COLOR)\n label.outlineWidth = new ConstantProperty(LABEL_OUTLINE_WIDTH)\n}\n\nexport function normaliseKmlEntities(entities: EntityCollection, clampToGround: boolean): void {\n for (const entity of entities.values) {\n if (entity.label) {\n makeLabelReadable(entity.label)\n }\n\n // Cesium only drapes a KML line carrying <tessellate>1</tessellate> and leaves every other one\n // at ArcType.NONE — a straight chord through the ellipsoid, buried under any terrain.\n if (entity.polyline && clampToGround) {\n entity.polyline.clampToGround = new ConstantProperty(true)\n entity.polyline.arcType = new ConstantProperty(ArcType.GEODESIC)\n }\n }\n}\n\nfunction ringPositions(polygon: PolygonGraphics): Cartesian3[][] {\n const hierarchy = constantValue(polygon.hierarchy)\n\n if (!(hierarchy instanceof PolygonHierarchy)) {\n return []\n }\n\n return [hierarchy.positions, ...hierarchy.holes.map((hole) => hole.positions)]\n}\n\n// Cesium gives every KML polygon a white outline whether the document asked for one or not, so an\n// untouched white cannot be told from a deliberate one. xgis2d defaults an unnamed stroke to black,\n// and matching that matters more here: a white border disappears on a light basemap.\nfunction boundaryColor(polygon: PolygonGraphics, stroke: Color | undefined): Color {\n if (stroke) {\n return stroke\n }\n\n const outlineColor = constantValue(polygon.outlineColor)\n\n if (outlineColor instanceof Color && !Color.equals(outlineColor, Color.WHITE)) {\n return outlineColor\n }\n\n return DEFAULT_COLOR\n}\n\nfunction boundaryEntities(\n entity: Entity,\n polygon: PolygonGraphics,\n stroke: Color | undefined,\n width: number,\n clampToGround: boolean,\n): Entity.ConstructorOptions[] {\n const rings = ringPositions(polygon)\n\n if (rings.length === 0) {\n return []\n }\n\n const color = boundaryColor(polygon, stroke)\n\n // The 1px outline would otherwise sit just under the polyline, showing through as a fringe.\n polygon.outline = new ConstantProperty(false)\n\n return rings.map((positions) => ({\n parent: entity,\n polyline: {\n positions,\n width,\n material: new ColorMaterialProperty(color),\n clampToGround,\n arcType: clampToGround ? ArcType.GEODESIC : ArcType.NONE,\n },\n }))\n}\n\ntype FilledGraphic = {\n material: MaterialProperty\n outline: Property | undefined\n outlineColor: Property | undefined\n}\n\nfunction styleFilled(\n graphic: FilledGraphic | undefined,\n fill: Color | undefined,\n stroke: Color | undefined,\n): void {\n if (!graphic) {\n return\n }\n\n if (fill) {\n graphic.material = new ColorMaterialProperty(fill)\n }\n\n if (stroke) {\n graphic.outline = new ConstantProperty(true)\n graphic.outlineColor = new ConstantProperty(stroke)\n }\n}\n\nfunction stylePolyline(\n polyline: PolylineGraphics | undefined,\n stroke: Color | undefined,\n width: number | undefined,\n): void {\n if (!polyline) {\n return\n }\n\n if (stroke) {\n polyline.material = new ColorMaterialProperty(stroke)\n }\n\n if (width !== undefined) {\n polyline.width = new ConstantProperty(width)\n }\n}\n\n// Cesium renders a KML point as a billboard, defaulting to a yellow pushpin PinBuilder draws onto a\n// canvas. An <IconStyle><Icon><href> arrives as a Resource — a deliberate choice by the KML author,\n// so only an explicit `symbol` overrides it. Testing for a string would miss every real KML icon.\nfunction hasAuthoredIcon(entity: Entity): boolean {\n const image = constantValue(entity.billboard?.image)\n\n return image instanceof Resource || typeof image === 'string'\n}\n\nfunction stylePoint(\n entity: Entity,\n params: KmlParams,\n markerColor: Color | undefined,\n clampToGround: boolean,\n): void {\n const billboard = entity.billboard\n\n if (!billboard) {\n return\n }\n\n if (params.symbol) {\n billboard.image = new ConstantProperty(params.symbol)\n // Cesium sized and placed the billboard for whatever icon it is replacing — its own 32x32\n // default, or an <IconStyle> scale, hotSpot and sprite region. None of that describes the\n // configured image, and a leftover offset puts it metres off the placemark.\n billboard.width = undefined\n billboard.height = undefined\n billboard.scale = undefined\n billboard.pixelOffset = undefined\n billboard.imageSubRegion = undefined\n\n return\n }\n\n if (!markerColor || hasAuthoredIcon(entity)) {\n return\n }\n\n entity.billboard = undefined\n entity.point = new PointGraphics({\n pixelSize: KML_MARKER_SIZE_PX,\n color: markerColor,\n heightReference: markerHeightReference(clampToGround),\n })\n}\n\nexport function applyKmlStyle(\n entities: EntityCollection,\n params: KmlParams,\n clampToGround: boolean,\n): void {\n const stroke = params.lineColor ? Color.fromCssColorString(params.lineColor) : undefined\n const fill = params.fillColor ? Color.fromCssColorString(params.fillColor) : undefined\n const width = params.lineThickness\n\n // xgis2d draws a marker whenever the config names any style field, falling back to black when it\n // names no colour. Resolving the same way keeps a point the same shape and colour in both engines.\n const markerColor = kmlExtractStyles(params) ? undefined : (fill ?? stroke ?? DEFAULT_COLOR)\n\n const boundaries: Entity.ConstructorOptions[] = []\n\n for (const entity of entities.values) {\n styleFilled(entity.polygon, fill, stroke)\n styleFilled(entity.wall, fill, stroke)\n stylePolyline(entity.polyline, stroke, width)\n stylePoint(entity, params, markerColor, clampToGround)\n\n const polygon = entity.polygon\n\n if (polygon && width !== undefined && width > MIN_DRAWN_OUTLINE_WIDTH) {\n boundaries.push(...boundaryEntities(entity, polygon, stroke, width, clampToGround))\n }\n }\n\n // Added after the walk, so the loop cannot reach the entities it is producing.\n for (const boundary of boundaries) {\n entities.add(boundary)\n }\n}\n","import type { KmlParams } from '@xgis/xgis-common'\nimport type { Camera } from 'cesium'\nimport { KmlDataSource } from 'cesium'\n\nimport type { KmlOpacitySlot } from './kmlEntityOpacity'\nimport { collectKmlOpacitySlots } from './kmlEntityOpacity'\nimport { applyKmlStyle, normaliseKmlEntities } from './kmlEntityStyle'\n\nexport interface CreatedKml {\n dataSource: KmlDataSource\n opacitySlots: KmlOpacitySlot[]\n}\n\nconst CLAMPED_ALTITUDE_MODE = 'clampToGround'\n\n// Only these carry an altitudeMode that decides how geometry is drawn. KML puts the same element on\n// <LookAt>, <Camera> and <Region> too, where it describes a viewpoint — and Google Earth writes a\n// <LookAt> into almost everything it exports, so reading those would un-drape a whole document that\n// never asked for it.\nconst GEOMETRY_TAGS = ['Point', 'LineString', 'LinearRing', 'Polygon', 'Track', 'MultiTrack']\n\nfunction declaresOwnAltitude(geometry: Element): boolean {\n return Array.from(geometry.children).some((child) => {\n if (child.localName !== 'altitudeMode') {\n return false\n }\n\n const mode = (child.textContent ?? '').trim()\n\n // Cesium falls back to clampToGround for a mode it does not recognise, empty included.\n return mode !== '' && mode !== CLAMPED_ALTITUDE_MODE\n })\n}\n\n// Geometry that names an altitude keeps it — draping something its author placed at a height would\n// throw that height away. Everything else Cesium draws flat on the ellipsoid, which puts it under\n// the terrain. Cesium decides this per placemark, but nothing on the loaded entity records the\n// choice, so it has to be read off the document before the load.\nfunction shouldClampToGround(kmlDocument: Document): boolean {\n return !GEOMETRY_TAGS.some((tag) =>\n Array.from(kmlDocument.getElementsByTagNameNS('*', tag)).some(declaresOwnAltitude),\n )\n}\n\nexport async function createKML(\n params: KmlParams,\n camera: Camera,\n canvas: HTMLCanvasElement,\n): Promise<CreatedKml> {\n const kmlDocument = new DOMParser().parseFromString(params.objects, 'application/xml')\n const clampToGround = shouldClampToGround(kmlDocument)\n\n const dataSource = await KmlDataSource.load(kmlDocument, { camera, canvas, clampToGround })\n\n normaliseKmlEntities(dataSource.entities, clampToGround)\n applyKmlStyle(dataSource.entities, params, clampToGround)\n\n return { dataSource, opacitySlots: collectKmlOpacitySlots(dataSource.entities) }\n}\n","import type {\n CesiumTilingScheme,\n CrsAxisOrder,\n LayerPresentation,\n OgcMapsSource,\n} from '@xgis/xgis-common'\nimport { ogcMapsCesiumCrs, ogcMapsMapUrl, ogcMapsQuery, withQuery } from '@xgis/xgis-common'\nimport type { ImageryProvider } from 'cesium'\nimport { GeographicTilingScheme, UrlTemplateImageryProvider, WebMercatorTilingScheme } from 'cesium'\n\nconst TILE_SIZE = 256\n\nconst BBOX_TEMPLATE: Record<CesiumTilingScheme, Record<CrsAxisOrder, string>> = {\n geographic: {\n eastingFirst: '{westDegrees},{southDegrees},{eastDegrees},{northDegrees}',\n northingFirst: '{southDegrees},{westDegrees},{northDegrees},{eastDegrees}',\n },\n webMercator: {\n eastingFirst: '{westProjected},{southProjected},{eastProjected},{northProjected}',\n northingFirst: '{southProjected},{westProjected},{northProjected},{eastProjected}',\n },\n}\n\nexport function createOGCMaps(\n source: OgcMapsSource,\n presentation: LayerPresentation,\n capabilities?: string,\n): ImageryProvider | null {\n if (!capabilities) {\n return null\n }\n\n const resolved = ogcMapsCesiumCrs(capabilities)\n\n if (!resolved) {\n return null\n }\n\n const { projection, crs, axisOrder } = resolved\n\n return new UrlTemplateImageryProvider({\n url: withQuery(ogcMapsMapUrl(source), {\n ...ogcMapsQuery(source),\n crs,\n 'bbox-crs': crs,\n bbox: BBOX_TEMPLATE[projection][axisOrder],\n width: '{width}',\n height: '{height}',\n }),\n tilingScheme:\n projection === 'webMercator' ? new WebMercatorTilingScheme() : new GeographicTilingScheme(),\n tileWidth: TILE_SIZE,\n tileHeight: TILE_SIZE,\n credit: presentation.copyright,\n })\n}\n","import type { LayerPresentation, OgcTilesSource, ResolvedOgcTileset } from '@xgis/xgis-common'\nimport { stringifyParams, withQuery } from '@xgis/xgis-common'\nimport type { ImageryProvider } from 'cesium'\nimport { GeographicTilingScheme, UrlTemplateImageryProvider, WebMercatorTilingScheme } from 'cesium'\n\nexport function createOGCTiles(\n source: OgcTilesSource,\n presentation: LayerPresentation,\n tileset: ResolvedOgcTileset,\n): ImageryProvider | null {\n const { cesium } = tileset\n\n if (!cesium) {\n return null\n }\n\n const labels = cesium.tileMatrixLabels\n\n return new UrlTemplateImageryProvider({\n url: withQuery(cesium.url, stringifyParams(source.params)),\n tilingScheme:\n cesium.tilingScheme === 'webMercator'\n ? new WebMercatorTilingScheme()\n : new GeographicTilingScheme(),\n tileWidth: cesium.tileWidth,\n tileHeight: cesium.tileHeight,\n minimumLevel: cesium.minimumLevel,\n maximumLevel: cesium.maximumLevel,\n customTags: labels\n ? {\n tileMatrix: (\n _provider: UrlTemplateImageryProvider,\n _x: number,\n _y: number,\n level: number,\n ) => labels[level] ?? '',\n }\n : undefined,\n credit: presentation.copyright,\n })\n}\n","import type { TilingScheme } from 'cesium'\nimport { Rectangle } from 'cesium'\n\n//copy of Cesium's TileMapServiceImageryProvider calculateSafeMinimumDetailLevel\nexport function safeMinimumLevel(\n scheme: TilingScheme,\n rectangle: Rectangle,\n minimumLevel: number,\n): number {\n const southwest = scheme.positionToTileXY(Rectangle.southwest(rectangle), minimumLevel)\n const northeast = scheme.positionToTileXY(Rectangle.northeast(rectangle), minimumLevel)\n\n if (!southwest || !northeast) {\n return 0\n }\n\n const tiles =\n (Math.abs(northeast.x - southwest.x) + 1) * (Math.abs(northeast.y - southwest.y) + 1)\n\n return tiles > 4 ? 0 : minimumLevel\n}\n","import type { LayerPresentation, ParsedTmsTileMap, TmsSource } from '@xgis/xgis-common'\nimport {\n parseTmsTileMap,\n tmsCesiumSchemeFor,\n tmsLevelRange,\n tmsTileBase,\n tmsTileSuffix,\n} from '@xgis/xgis-common'\nimport type { ImageryProvider, TilingScheme } from 'cesium'\nimport {\n Cartesian3,\n GeographicTilingScheme,\n Rectangle,\n UrlTemplateImageryProvider,\n WebMercatorProjection,\n WebMercatorTilingScheme,\n} from 'cesium'\n\nimport { safeMinimumLevel } from './safeMinimumLevel'\n\nfunction tilesetRectangle(tileMap: ParsedTmsTileMap, geographic: boolean): Rectangle {\n const [minX, minY, maxX, maxY] = tileMap.extent\n\n if (geographic) {\n return Rectangle.fromDegrees(minX, minY, maxX, maxY)\n }\n\n const projection = new WebMercatorProjection()\n const southwest = projection.unproject(new Cartesian3(minX, minY, 0))\n const northeast = projection.unproject(new Cartesian3(maxX, maxY, 0))\n\n return new Rectangle(\n southwest.longitude,\n southwest.latitude,\n northeast.longitude,\n northeast.latitude,\n )\n}\n\nfunction confineToScheme(rectangle: Rectangle, scheme: TilingScheme): Rectangle {\n return Rectangle.intersection(rectangle, scheme.rectangle) ?? scheme.rectangle\n}\n\nexport function createTMS(\n source: TmsSource,\n presentation: LayerPresentation,\n capabilitiesText: string,\n): ImageryProvider | null {\n const tileMap = parseTmsTileMap(capabilitiesText)\n const scheme = tileMap ? tmsCesiumSchemeFor(tileMap) : undefined\n\n if (!tileMap || !scheme) {\n return null\n }\n\n const geographic = scheme === 'geographic'\n const tilingScheme = geographic ? new GeographicTilingScheme() : new WebMercatorTilingScheme()\n const rectangle = confineToScheme(tilesetRectangle(tileMap, geographic), tilingScheme)\n const { minimum, maximum } = tmsLevelRange(tileMap)\n\n return new UrlTemplateImageryProvider({\n url: `${tmsTileBase(source.href)}{z}/{x}/{reverseY}${tmsTileSuffix(tileMap.extension)}`,\n tilingScheme,\n rectangle,\n tileWidth: tileMap.tileWidth,\n tileHeight: tileMap.tileHeight,\n minimumLevel: safeMinimumLevel(tilingScheme, rectangle, minimum),\n maximumLevel: maximum,\n credit: presentation.copyright,\n })\n}\n","import type { LayerPresentation, WmsSource } from '@xgis/xgis-common'\nimport { parseWmsCaps } from '@xgis/xgis-common'\nimport type { ImageryProvider } from 'cesium'\nimport {\n GeographicTilingScheme,\n WebMapServiceImageryProvider,\n WebMercatorTilingScheme,\n} from 'cesium'\n\nexport function createWMS(\n source: WmsSource,\n presentation: LayerPresentation,\n capabilities?: string,\n): ImageryProvider | null {\n if (!capabilities) {\n return null\n }\n\n const request = parseWmsCaps(capabilities, source.layers, source.version)\n\n if (!request) {\n return null\n }\n\n return new WebMapServiceImageryProvider({\n url: source.href,\n layers: source.layers.join(','),\n parameters: {\n ...source.params,\n format: source.format ?? 'image/png',\n styles: source.styles ?? '',\n version: request.version,\n },\n crs: request.crs,\n srs: request.crs,\n tilingScheme:\n request.projection === 'webMercator'\n ? new WebMercatorTilingScheme()\n : new GeographicTilingScheme(),\n credit: presentation.copyright,\n })\n}\n","import type { LayerPresentation, WmtsSource } from '@xgis/xgis-common'\nimport { parseWmtsCapabilities, stringifyParams, withQuery } from '@xgis/xgis-common'\nimport type { ImageryProvider, TilingScheme } from 'cesium'\nimport {\n GeographicTilingScheme,\n Rectangle,\n WebMapTileServiceImageryProvider,\n WebMercatorTilingScheme,\n} from 'cesium'\n\nimport { safeMinimumLevel } from './safeMinimumLevel'\n\nconst ESTONIA_RECTANGLE = Rectangle.fromDegrees(10.11, 53.26, 35.2, 63.3)\n\nfunction coarsestLevel(\n tilingScheme: TilingScheme,\n minimumLevel: number | undefined,\n): number | undefined {\n if (minimumLevel === undefined) {\n return undefined\n }\n\n return safeMinimumLevel(tilingScheme, ESTONIA_RECTANGLE, minimumLevel)\n}\n\nexport function createWMTS(\n source: WmtsSource,\n presentation: LayerPresentation,\n capabilitiesText: string,\n): ImageryProvider | null {\n const parsed = parseWmtsCapabilities(capabilitiesText, source.layer)\n\n if (!parsed) {\n return null\n }\n\n const style = source.styles ?? 'default'\n const url = `${source.href}/1.0.0/${source.layer}/${style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}`\n const tilingScheme =\n parsed.tilingScheme === 'geographic'\n ? new GeographicTilingScheme()\n : new WebMercatorTilingScheme()\n\n return new WebMapTileServiceImageryProvider({\n url: withQuery(url, stringifyParams(source.params)),\n layer: source.layer,\n style,\n tileMatrixSetID: parsed.tileMatrixSetID,\n tileMatrixLabels: parsed.tileMatrixLabels.length > 0 ? parsed.tileMatrixLabels : undefined,\n format: source.format,\n tilingScheme,\n maximumLevel: parsed.maximumLevel,\n minimumLevel: coarsestLevel(tilingScheme, parsed.minimumLevel),\n credit: presentation.copyright,\n rectangle: ESTONIA_RECTANGLE,\n })\n}\n","import type { BasemapPlanEntry } from '@xgis/xgis-common'\nimport { ImageryProvider, Viewer as CesiumViewer } from 'cesium'\n\nimport type { Created3DTileset } from './create3DTilesetLayer'\nimport { create3DTileset } from './create3DTilesetLayer'\nimport type { CreatedKml } from './createKMLLayer'\nimport { createKML } from './createKMLLayer'\nimport { createOGCMaps } from './createOGCMapsLayer'\nimport { createOGCTiles } from './createOGCTilesLayer'\nimport { createTMS } from './createTMSLayer'\nimport { createWMS } from './createWMSLayer'\nimport { createWMTS } from './createWMTSLayer'\n\nexport type CesiumBaseLayer =\n | { kind: 'imagery'; provider: ImageryProvider }\n | { kind: 'kml'; kml: Promise<CreatedKml> }\n | { kind: 'tileset'; tileset: Promise<Created3DTileset | null> }\n\nexport function createCesiumBaseLayer(\n entry: BasemapPlanEntry,\n viewer: CesiumViewer,\n): CesiumBaseLayer | null {\n const { layer, capabilities, tileset } = entry\n const { source } = layer\n\n switch (source.kind) {\n case 'wms': {\n const provider = createWMS(source, layer, capabilities)\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'wmts': {\n if (!capabilities) {\n return null\n }\n\n const provider = createWMTS(source, layer, capabilities)\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'ogcMaps': {\n const provider = createOGCMaps(source, layer, capabilities)\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'ogcTiles': {\n const provider = tileset ? createOGCTiles(source, layer, tileset) : null\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'tms': {\n const provider = capabilities ? createTMS(source, layer, capabilities) : null\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'tileset3d':\n return { kind: 'tileset', tileset: create3DTileset(source.tileset) }\n case 'kml':\n return {\n kind: 'kml',\n kml: createKML(source.params, viewer.scene.camera, viewer.scene.canvas),\n }\n default:\n return source satisfies never\n }\n}\n","import { toAlpha } from '@xgis/xgis-common'\nimport type {\n ImageryLayer,\n ImageryProvider,\n TileProviderError,\n Viewer as CesiumViewer,\n} from 'cesium'\nimport { useMemo, useRef } from 'react'\n\nimport type { Created3DTileset } from '../utils/create3DTilesetLayer'\nimport { apply3DTilesetOpacity } from '../utils/create3DTilesetLayer'\nimport type { CreatedKml } from '../utils/createKMLLayer'\nimport { applyKmlOpacity } from '../utils/kmlEntityOpacity'\n\nexport interface CesiumBasemapAttachments {\n addImagery: (provider: ImageryProvider) => void\n addTileset: (tileset: Created3DTileset) => void\n addKml: (kml: CreatedKml) => void\n detachAll: () => void\n setOpacity: (opacity: number) => void\n}\n\nfunction errorStatus(error: TileProviderError): number | undefined {\n const cause: unknown = error.error\n\n if (typeof cause !== 'object' || cause === null || !('statusCode' in cause)) {\n return undefined\n }\n\n return typeof cause.statusCode === 'number' ? cause.statusCode : undefined\n}\n\nfunction logImageryErrors(provider: ImageryProvider): void {\n provider.errorEvent.addEventListener((error: TileProviderError) => {\n const status = errorStatus(error)\n\n console.warn(`Base map imagery request failed (${status ?? 'no status'}): ${error.message}`)\n })\n}\n\nexport function useCesiumBasemapAttachments(viewer: CesiumViewer): CesiumBasemapAttachments {\n const imageryRef = useRef<ImageryLayer[]>([])\n const kmlRef = useRef<CreatedKml[]>([])\n const tilesetRef = useRef<Created3DTileset[]>([])\n\n const opacityRef = useRef(100)\n\n return useMemo(\n () => ({\n addImagery(provider: ImageryProvider) {\n logImageryErrors(provider)\n\n const layer = viewer.imageryLayers.addImageryProvider(provider, 0)\n layer.alpha = toAlpha(opacityRef.current)\n imageryRef.current.push(layer)\n viewer.scene.requestRender()\n },\n\n addTileset(tileset: Created3DTileset) {\n tilesetRef.current.push(tileset)\n viewer.scene.primitives.add(tileset.primitive)\n apply3DTilesetOpacity(tileset, toAlpha(opacityRef.current))\n viewer.scene.requestRender()\n },\n\n addKml(kml: CreatedKml) {\n kmlRef.current.push(kml)\n viewer.dataSources.add(kml.dataSource)\n applyKmlOpacity(kml.opacitySlots, toAlpha(opacityRef.current))\n viewer.scene.requestRender()\n },\n\n detachAll() {\n for (const layer of imageryRef.current) {\n viewer.imageryLayers.remove(layer)\n }\n imageryRef.current = []\n\n for (const kml of kmlRef.current) {\n viewer.dataSources.remove(kml.dataSource, true)\n }\n kmlRef.current = []\n\n for (const tileset of tilesetRef.current) {\n viewer.scene.primitives.remove(tileset.primitive)\n }\n tilesetRef.current = []\n },\n\n setOpacity(opacity: number) {\n opacityRef.current = opacity\n\n for (const layer of imageryRef.current) {\n layer.alpha = toAlpha(opacity)\n }\n\n for (const tileset of tilesetRef.current) {\n apply3DTilesetOpacity(tileset, toAlpha(opacity))\n }\n\n // Cesium has no per-DataSource alpha, so a KML basemap fades entity by entity.\n for (const kml of kmlRef.current) {\n applyKmlOpacity(kml.opacitySlots, toAlpha(opacity))\n }\n\n viewer.scene.requestRender()\n },\n }),\n [viewer],\n )\n}\n","import { bus, translate, useActiveBasemapPlan, useBasemapStore } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { useEffect } from 'react'\n\nimport { createCesiumBaseLayer } from '../utils/layerCreation'\nimport { useCesiumBasemapAttachments } from './useCesiumBasemapAttachments'\n\nexport function useCesiumBasemapReconciler(viewer: CesiumViewer): void {\n const basemapOpacity = useBasemapStore((s) => s.opacity3d)\n const { entries, ready } = useActiveBasemapPlan('3d')\n\n const attachments = useCesiumBasemapAttachments(viewer)\n\n useEffect(() => {\n attachments.setOpacity(basemapOpacity)\n }, [attachments, basemapOpacity])\n\n useEffect(() => {\n if (!ready) {\n return\n }\n\n attachments.detachAll()\n\n let cancelled = false\n\n const attachAsync = <T>(\n load: Promise<T | null>,\n attach: (value: T) => void,\n failure: string,\n toastKey?: string,\n ) => {\n void (async () => {\n try {\n const value = await load\n\n if (!cancelled && value) {\n attach(value)\n }\n } catch (error) {\n console.warn(failure, error)\n\n if (!toastKey || cancelled) {\n return\n }\n\n bus.emit('showToast', { message: translate(toastKey), severity: 'error' })\n }\n })()\n }\n\n for (const entry of entries) {\n const created = createCesiumBaseLayer(entry, viewer)\n\n if (!created) {\n continue\n }\n\n if (created.kind === 'imagery') {\n attachments.addImagery(created.provider)\n } else if (created.kind === 'tileset') {\n attachAsync(\n created.tileset,\n attachments.addTileset,\n 'Failed to load 3D tileset basemap',\n 'error.basemap.tileset3dFailed',\n )\n } else {\n attachAsync(created.kml, attachments.addKml, 'Failed to load KML basemap')\n }\n }\n\n return () => {\n cancelled = true\n }\n }, [viewer, attachments, entries, ready])\n\n useEffect(() => attachments.detachAll, [attachments])\n}\n","import type { MapExtent } from '@xgis/xgis-common'\nimport { extentCenter, useMapViewStore, useProjectionStore } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { useEffect } from 'react'\n\nimport { sampleTerrainHeight } from '../capabilities/cesiumCamera'\nimport type { EntryView } from '../entryCamera'\nimport { entryTarget, raiseEntryCameraToTerrain } from '../entryCamera'\n\n// Canvas input that means the user has taken over.\nconst TAKEOVER_EVENTS = ['pointerdown', 'wheel'] as const\n\n// How far the shared view's centre may drift before the entry view counts as superseded.\nconst CENTRE_TOLERANCE_METRES = 1\n\n// Distance rather than equality on the store's fields: `fireChange` rounds zoom, wraps rotation and\n// rebuilds the bbox, so none of them compare reliably. Only the centre carries intent.\nfunction viewRecentred(entryBbox: MapExtent, currentBbox: MapExtent): boolean {\n const [entryX, entryY] = extentCenter(entryBbox)\n const [currentX, currentY] = extentCenter(currentBbox)\n\n return Math.hypot(currentX - entryX, currentY - entryY) >= CENTRE_TOLERANCE_METRES\n}\n\n/**\n * Re-places the entry camera against terrain once a provider arrives.\n *\n * `Map3D` has to place it synchronously, before any provider exists, so it stands off from the\n * ellipsoid instead — too close to the ground for the zoom it claims. See ADR 0020.\n */\nexport function useCesiumEntryCamera(viewer: CesiumViewer, view: EntryView): void {\n useEffect(() => {\n // Read once: the entry view is in the projection Map3D mounted with, and a later topic in\n // another projection fits itself.\n const projection = useProjectionStore.getState().projection\n const canvas = viewer.scene.canvas\n let done = false\n let userTookOver = false\n let stopListening = (): void => {}\n\n function noteTakeover(): void {\n userTookOver = true\n }\n\n function finish(): void {\n done = true\n stopListening()\n TAKEOVER_EVENTS.forEach((event) => canvas.removeEventListener(event, noteTakeover))\n }\n\n async function refine(): Promise<void> {\n if (done) {\n return\n }\n\n try {\n const height = await sampleTerrainHeight(\n viewer.terrainProvider,\n entryTarget(viewer, view, projection),\n )\n\n // No terrain yet — keep listening for the provider that brings some.\n if (done || height === undefined) {\n return\n }\n\n if (userTookOver || viewRecentred(view.bbox, useMapViewStore.getState().bbox)) {\n finish()\n return\n }\n\n raiseEntryCameraToTerrain(viewer, entryTarget(viewer, view, projection), height)\n finish()\n } catch (error) {\n // A failed tile request, not an answer. The subscription stays up so a later provider\n // change retries; until then the ellipsoid placement stands — too low, but usable.\n console.error('Failed to sample terrain for the entry camera', error)\n }\n }\n\n TAKEOVER_EVENTS.forEach((event) => canvas.addEventListener(event, noteTakeover))\n\n stopListening = viewer.scene.globe.terrainProviderChanged.addEventListener(() => {\n refine()\n })\n\n // Covers a provider already in place, which will fire no change event.\n refine()\n\n return finish\n }, [viewer, view])\n}\n","import { useTerrainStore } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { CesiumTerrainProvider, EllipsoidTerrainProvider } from 'cesium'\nimport { useEffect } from 'react'\n\nexport function useCesiumTerrainReconciler(viewer: CesiumViewer): void {\n const terrainUrl = useTerrainStore((s) => s.terrainUrl)\n\n useEffect(() => {\n if (!terrainUrl) {\n return\n }\n\n let cancelled = false\n\n async function loadTerrain(url: string) {\n try {\n const provider = await CesiumTerrainProvider.fromUrl(url)\n\n if (!cancelled) {\n viewer.terrainProvider = provider\n }\n } catch (err) {\n console.error('Failed to load terrain provider', err)\n }\n }\n\n loadTerrain(terrainUrl)\n\n return () => {\n cancelled = true\n viewer.terrainProvider = new EllipsoidTerrainProvider()\n }\n }, [viewer, terrainUrl])\n}\n","import type { Radians } from '@xgis/xgis-common'\nimport { Cartesian3, Matrix4, PolygonHierarchy, Transforms } from 'cesium'\n\nconst HALF_SPAN: Radians = (35 * Math.PI) / 180\nconst ARC_SEGMENTS = 16\n\nexport const CONE_SCREEN_RADIUS_PX = 40\n\nconst MIN_RADIUS_METERS = 1\n\nexport function coneRadiusForScreenSize(range: number, fov: number, spanPx: number): number {\n const metersPerPixel = (2 * range * Math.tan(fov / 2)) / spanPx\n return Math.max(MIN_RADIUS_METERS, metersPerPixel * CONE_SCREEN_RADIUS_PX)\n}\n\nexport function coneHierarchy(\n lon: number,\n lat: number,\n heading: Radians,\n radiusMeters: number,\n): PolygonHierarchy {\n const origin = Cartesian3.fromDegrees(lon, lat)\n const enuFrame = Transforms.eastNorthUpToFixedFrame(origin)\n const positions = [origin]\n\n for (let i = 0; i <= ARC_SEGMENTS; i++) {\n const angle = heading - HALF_SPAN + (2 * HALF_SPAN * i) / ARC_SEGMENTS\n const local = new Cartesian3(radiusMeters * Math.sin(angle), radiusMeters * Math.cos(angle), 0)\n positions.push(Matrix4.multiplyByPoint(enuFrame, local, new Cartesian3()))\n }\n\n return new PolygonHierarchy(positions)\n}\n","import { useUserMarkerStore } from '@xgis/xgis-common'\nimport type { Entity, Viewer as CesiumViewer } from 'cesium'\nimport {\n Cartesian3,\n Color,\n ConstantPositionProperty,\n ConstantProperty,\n HeightReference,\n} from 'cesium'\nimport { useEffect, useRef } from 'react'\n\nimport { fovSpanPx } from '../projection'\nimport { coneHierarchy, coneRadiusForScreenSize } from './userMarkerCone'\n\n// Matches cameraScale.ts's own fallback for a non-perspective frustum.\nconst DEFAULT_FOV = Math.PI / 3\n\nexport function useCesiumUserMarker(viewer: CesiumViewer): void {\n const marker = useUserMarkerStore((s) => s.marker)\n const heading = useUserMarkerStore((s) => s.heading)\n const entityRef = useRef<Entity | null>(null)\n const coneEntityRef = useRef<Entity | null>(null)\n const markerRef = useRef(marker)\n const headingRef = useRef(heading)\n markerRef.current = marker\n headingRef.current = heading\n const updateConeRef = useRef<(() => void) | null>(null)\n\n useEffect(() => {\n const entity = viewer.entities.add({\n point: {\n pixelSize: 12,\n color: Color.fromCssColorString('#2563EB'),\n outlineColor: Color.WHITE,\n outlineWidth: 2,\n heightReference: HeightReference.CLAMP_TO_GROUND,\n disableDepthTestDistance: Number.POSITIVE_INFINITY,\n },\n show: false,\n })\n entityRef.current = entity\n\n const coneEntity = viewer.entities.add({\n polygon: {\n material: Color.fromCssColorString('#2563EB').withAlpha(0.35),\n },\n show: false,\n })\n coneEntityRef.current = coneEntity\n\n function updateCone(): void {\n const currentMarker = markerRef.current\n const currentHeading = headingRef.current\n\n if (currentMarker === null || currentHeading === null || !coneEntity.polygon) {\n return\n }\n\n const camera = viewer.camera\n const markerPosition = Cartesian3.fromDegrees(currentMarker.lon, currentMarker.lat)\n const range = Cartesian3.distance(camera.position, markerPosition)\n const frustum = camera.frustum\n const fov = 'fov' in frustum && frustum.fov !== undefined ? frustum.fov : DEFAULT_FOV\n const canvas = viewer.scene.canvas\n const spanPx = fovSpanPx(canvas.clientWidth, canvas.clientHeight)\n\n const radius = coneRadiusForScreenSize(range, fov, spanPx)\n coneEntity.polygon.hierarchy = new ConstantProperty(\n coneHierarchy(currentMarker.lon, currentMarker.lat, currentHeading, radius),\n )\n }\n\n updateConeRef.current = updateCone\n const removeCameraListener = viewer.camera.changed.addEventListener(updateCone)\n\n return () => {\n removeCameraListener()\n viewer.entities.remove(entity)\n viewer.entities.remove(coneEntity)\n entityRef.current = null\n coneEntityRef.current = null\n updateConeRef.current = null\n }\n }, [viewer])\n\n useEffect(() => {\n const entity = entityRef.current\n const coneEntity = coneEntityRef.current\n if (!entity || !coneEntity) {\n return\n }\n\n if (marker === null) {\n entity.show = false\n coneEntity.show = false\n } else {\n entity.position = new ConstantPositionProperty(Cartesian3.fromDegrees(marker.lon, marker.lat))\n entity.show = true\n coneEntity.show = heading !== null\n updateConeRef.current?.()\n }\n\n viewer.scene.requestRender()\n }, [marker, heading, viewer])\n}\n","import { useMapViewStore, useProjectionStore } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { useEffect } from 'react'\n\nimport { createCameraBoundsGuard } from '../cameraBoundsGuard'\n\n/** Cesium has no extent constraint, so the topic bbox is enforced by a per-frame camera guard. */\nexport function useCesiumViewBounds(viewer: CesiumViewer): void {\n const constraintBbox = useMapViewStore((s) => s.constraintBbox)\n const projection = useProjectionStore((s) => s.projection)\n\n useEffect(() => {\n if (!constraintBbox) {\n return\n }\n\n return createCameraBoundsGuard(viewer, constraintBbox, projection)\n }, [viewer, constraintBbox, projection])\n}\n","// MF remotes have no HTML of their own — CSS must be imported explicitly.\nimport 'cesium/Build/Cesium/Widgets/widgets.css'\n\nimport type { EngineRegistration, EpsgCode, IMapEngine } from '@xgis/xgis-common'\nimport {\n MAX_ZOOM,\n MIN_ZOOM,\n RADIANS_TO_DEGREES,\n useMapViewStore,\n useProjectionStore,\n useTranslate,\n} from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { Color } from 'cesium'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { CesiumComponentRef } from 'resium'\nimport { Viewer } from 'resium'\n\nimport { rangeForZoom } from './cameraScale'\nimport { createCesiumCameraCapability } from './capabilities/cesiumCamera'\nimport { createCesiumEngineHealth } from './capabilities/cesiumEngineHealth'\nimport { createCesiumViewLimitsCapability } from './capabilities/cesiumViewLimits'\nimport { ensureCesiumBaseUrl } from './cesiumBaseUrl'\nimport type { EntryView } from './entryCamera'\nimport { ELLIPSOID_HEIGHT, entryTarget, placeEntryCamera } from './entryCamera'\nimport { createCanvasPressRelay } from './interactions/canvasPressRelay'\nimport { createCentroidTilt } from './interactions/centroidTilt'\nimport { createCesiumKeyboardHandler } from './interactions/cesiumKeyboardHandler'\nimport { createNadirLimit } from './interactions/nadirLimit'\nimport { metresPerMapUnit } from './projection'\nimport { useCesiumBasemapReconciler } from './reconcilers/useCesiumBasemapReconciler'\nimport { useCesiumEntryCamera } from './reconcilers/useCesiumEntryCamera'\nimport { useCesiumTerrainReconciler } from './reconcilers/useCesiumTerrainReconciler'\nimport { useCesiumUserMarker } from './reconcilers/useCesiumUserMarker'\nimport { useCesiumViewBounds } from './reconcilers/useCesiumViewBounds'\n\nconst currentProjection = (): EpsgCode => useProjectionStore.getState().projection\n\n// Keep camera input deterministic: gestures stop when input stops, without inertial movement.\nconst CAMERA_INERTIA = 0\n\n// Gesture guard only — mapViewStore.setZoom remains the authority on the zoom borders. Cesium\n// compares these against the camera's height above the ellipsoid while rangeForZoom yields a slant\n// range, so at a tilt the clamp is loose by 1/sin(-pitch); close enough for a backstop. The scale\n// is taken where the camera stands when the limits are applied, not as it moves.\nfunction applyZoomDistanceLimits(viewer: CesiumViewer, projection: EpsgCode): void {\n const { longitude, latitude } = viewer.camera.positionCartographic\n const metresPerUnit = metresPerMapUnit(\n projection,\n longitude * RADIANS_TO_DEGREES,\n latitude * RADIANS_TO_DEGREES,\n )\n const controller = viewer.scene.screenSpaceCameraController\n\n controller.maximumZoomDistance = rangeForZoom(viewer, MIN_ZOOM, metresPerUnit)\n controller.minimumZoomDistance = rangeForZoom(viewer, MAX_ZOOM, metresPerUnit)\n}\n\n// enableRotate is left alone — it also drives ordinary panning, not just rotation. enableTilt and\n// enableLook both fold a heading change into the same gesture that changes pitch, so a topic that\n// forbids rotating loses tilt along with it — Cesium has no input that changes only one.\nexport function applyRotationPermission(viewer: CesiumViewer, rotationAllowed: boolean): void {\n viewer.scene.screenSpaceCameraController.enableTilt = rotationAllowed\n viewer.scene.screenSpaceCameraController.enableLook = rotationAllowed\n}\n\n// Cesium's destroy() never releases the context itself.\nexport function releaseWebglContext(canvas: HTMLCanvasElement): void {\n const gl = canvas.getContext('webgl2') ?? canvas.getContext('webgl')\n\n gl?.getExtension('WEBGL_lose_context')?.loseContext()\n}\n\nconst MSAA = 1\n\nfunction applyGlobeSettings(viewer: CesiumViewer): void {\n const globe = viewer.scene.globe\n\n globe.baseColor = Color.WHITE\n globe.showGroundAtmosphere = false\n globe.maximumScreenSpaceError = 2.2\n globe.depthTestAgainstTerrain = true\n}\n\ninterface CesiumLayerSyncProps {\n viewer: CesiumViewer\n entry: EntryView\n}\n\n// useCesiumEntryCamera must follow useCesiumTerrainReconciler so the fetch is in flight before it\n// subscribes.\nfunction CesiumLayerSync({ viewer, entry }: CesiumLayerSyncProps) {\n useCesiumBasemapReconciler(viewer)\n useCesiumTerrainReconciler(viewer)\n useCesiumEntryCamera(viewer, entry)\n useCesiumUserMarker(viewer)\n useCesiumViewBounds(viewer)\n return null\n}\n\ninterface Map3DProps {\n onEngineReady: (engine: IMapEngine) => EngineRegistration\n}\n\nexport function Map3D({ onEngineReady }: Map3DProps) {\n // Cesium builds worker and asset URLs lazily, first doing so when the Viewer below is\n // constructed. Setting the base URL here as well as at module scope keeps that guarantee\n // independent of how a bundler orders this package's own imports, which flattening can change.\n ensureCesiumBaseUrl()\n\n const [cesiumViewer, setCesiumViewer] = useState<CesiumViewer | null>(null)\n const [entry, setEntry] = useState<EntryView | null>(null)\n const rotationAllowed = useMapViewStore((s) => s.rotationAllowed)\n const projection = useProjectionStore((s) => s.projection)\n const t = useTranslate()\n const canvasLabel = t('map.3d.aria')\n\n const onViewerInit = useCallback((ref: CesiumComponentRef<CesiumViewer> | null) => {\n if (!ref?.cesiumElement) {\n return\n }\n\n const viewer = ref.cesiumElement\n const view = useMapViewStore.getState()\n\n // Against the ellipsoid: no terrain provider exists yet. useCesiumEntryCamera re-places it.\n placeEntryCamera(viewer, entryTarget(viewer, view, currentProjection()), ELLIPSOID_HEIGHT)\n\n applyGlobeSettings(viewer)\n applyRotationPermission(viewer, view.rotationAllowed)\n viewer.scene.screenSpaceCameraController.inertiaSpin = CAMERA_INERTIA\n viewer.scene.screenSpaceCameraController.inertiaZoom = CAMERA_INERTIA\n viewer.scene.screenSpaceCameraController.minimumCollisionTerrainHeight =\n Number.POSITIVE_INFINITY\n\n setEntry(view)\n setCesiumViewer(viewer)\n }, [])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n const health = createCesiumEngineHealth(cesiumViewer)\n\n const engine: IMapEngine = {\n type: '3d',\n capabilities: {\n camera: createCesiumCameraCapability(cesiumViewer, currentProjection),\n viewLimits: createCesiumViewLimitsCapability(cesiumViewer),\n },\n destroy() {},\n reportError: health.reportError,\n onError: health.onError,\n }\n\n const { unregister } = onEngineReady(engine)\n\n return () => {\n health.dispose()\n unregister()\n }\n }, [cesiumViewer, onEngineReady])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n const canvas = cesiumViewer.canvas\n\n return () => {\n releaseWebglContext(canvas)\n }\n }, [cesiumViewer])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n return createCesiumKeyboardHandler(cesiumViewer, canvasLabel)\n }, [cesiumViewer, canvasLabel])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n return createCanvasPressRelay(cesiumViewer)\n }, [cesiumViewer])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n return createNadirLimit(cesiumViewer)\n }, [cesiumViewer])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n return createCentroidTilt(cesiumViewer)\n }, [cesiumViewer])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n // The zoom<->range mapping depends on the viewport and, as zoom is in map units, on the topic\n // projection. A window resize or a parallel-view divider drag does not remount this component.\n applyZoomDistanceLimits(cesiumViewer, projection)\n\n const observer = new ResizeObserver(() => applyZoomDistanceLimits(cesiumViewer, projection))\n observer.observe(cesiumViewer.scene.canvas)\n\n return () => {\n observer.disconnect()\n }\n }, [cesiumViewer, projection])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n applyRotationPermission(cesiumViewer, rotationAllowed)\n }, [cesiumViewer, rotationAllowed])\n\n return (\n <Viewer\n ref={onViewerInit}\n full\n animation={false}\n baseLayerPicker={false}\n fullscreenButton={false}\n geocoder={false}\n homeButton={false}\n infoBox={false}\n sceneModePicker={false}\n selectionIndicator={false}\n timeline={false}\n navigationHelpButton={false}\n baseLayer={false}\n requestRenderMode\n maximumRenderTimeChange={Infinity}\n scene3DOnly\n useBrowserRecommendedResolution={false}\n msaaSamples={MSAA}\n showRenderLoopErrors={false}\n >\n {cesiumViewer && entry && <CesiumLayerSync viewer={cesiumViewer} entry={entry} />}\n </Viewer>\n )\n}\n"],"names":["DEFAULT_FOV","CesiumMath","canvas"],"mappings":";;;;;;;AAWA,MAAM,SAAA,GAAY,sBAAA;AAElB,IAAI,QAAA;AAIJ,SAAS,QAAA,GAAmB;AAC1B,EAAA,OAAO,QAAA,CAAS,cAA+B,CAAA,WAAA,EAAc,SAAS,IAAI,CAAA,EAAG,OAAA,CAAQ,MAAK,IAAK,EAAA;AACjG;AAOO,SAAS,mBAAA,GAA4B;AAG1C,EAAA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,IAAA;AAAA,EACF;AAGA,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,QAA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F;AAEA,IAAA,uBAAA,CAAwB,cAAc,eAAe,CAAA;AAAA,EACvD,CAAA,EAAG,CAAC,YAAA,EAAc,eAAe,CAAC,CAAA;AAElC,EAAA,uBACE,GAAA;AAAA,IAAC,MAAA;AAAA,IAAA;AAAA,MACC,GAAA,EAAK,YAAA;AAAA,MACL,IAAA,EAAI,IAAA;AAAA,MACJ,SAAA,EAAW,KAAA;AAAA,MACX,eAAA,EAAiB,KAAA;AAAA,MACjB,gBAAA,EAAkB,KAAA;AAAA,MAClB,QAAA,EAAU,KAAA;AAAA,MACV,UAAA,EAAY,KAAA;AAAA,MACZ,OAAA,EAAS,KAAA;AAAA,MACT,eAAA,EAAiB,KAAA;AAAA,MACjB,kBAAA,EAAoB,KAAA;AAAA,MACpB,QAAA,EAAU,KAAA;AAAA,MACV,oBAAA,EAAsB,KAAA;AAAA,MACtB,SAAA,EAAW,KAAA;AAAA,MACX,iBAAA,EAAiB,IAAA;AAAA,MACjB,uBAAA,EAAyB,QAAA;AAAA,MACzB,WAAA,EAAW,IAAA;AAAA,MACX,+BAAA,EAAiC,KAAA;AAAA,MACjC,WAAA,EAAa,IAAA;AAAA,MACb,oBAAA,EAAsB,KAAA;AAAA,MAErB,0BAAgB,KAAA,oBAAS,GAAA,CAAC,eAAA,EAAA,EAAgB,MAAA,EAAQ,cAAc,KAAA,EAAc;AAAA;AAAA,GACjF;AAEJ;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/cesiumBaseUrl.ts","../src/projection.ts","../src/cameraScale.ts","../src/lookAtTarget.ts","../src/pickGroundPoint.ts","../src/capabilities/cesiumMoving.ts","../src/capabilities/cesiumCamera.ts","../src/capabilities/cesiumEngineHealth.ts","../src/cameraBoundsGuard.ts","../src/capabilities/cesiumViewLimits.ts","../src/entryCamera.ts","../src/interactions/canvasPressRelay.ts","../src/interactions/centroidTilt.ts","../src/interactions/cesiumKeyboardHandler.ts","../src/interactions/nadirLimit.ts","../src/utils/create3DTilesetLayer.ts","../src/utils/kmlEntityOpacity.ts","../src/utils/kmlEntityStyle.ts","../src/utils/createKMLLayer.ts","../src/utils/createOGCMapsLayer.ts","../src/utils/createOGCTilesLayer.ts","../src/utils/safeMinimumLevel.ts","../src/utils/createTMSLayer.ts","../src/utils/createWMSLayer.ts","../src/utils/createWMTSLayer.ts","../src/utils/layerCreation.ts","../src/utils/topicRectangle.ts","../src/reconcilers/useCesiumBasemapAttachments.ts","../src/reconcilers/useCesiumBasemapReconciler.ts","../src/reconcilers/useCesiumEntryCamera.ts","../src/reconcilers/useCesiumTerrainReconciler.ts","../src/reconcilers/userMarkerCone.ts","../src/reconcilers/useCesiumUserMarker.ts","../src/reconcilers/useCesiumViewBounds.ts","../src/Map3D.tsx"],"sourcesContent":["declare global {\n interface Window {\n CESIUM_BASE_URL?: string\n }\n}\n\n// Substituted at build time by both vite configs. A `cesium/package.json` import would be the\n// obvious alternative, but the library build strips its `with { type: 'json' }` attribute, which\n// makes the published module unloadable in Node.\ndeclare const __CESIUM_VERSION__: string\n\nconst META_NAME = 'xgis-cesium-base-url'\n\nlet resolved: string | undefined\n\n// Module-scope read of a build-time contract, not a component reaching into the DOM. `content` is\n// '' for a missing or empty attribute, never undefined, so an empty tag must not win.\nfunction fromMeta(): string {\n return document.querySelector<HTMLMetaElement>(`meta[name=\"${META_NAME}\"]`)?.content.trim() ?? ''\n}\n\n/**\n * Under Module Federation the base URL is baked in by a `define`. An npm consumer gets the meta tag\n * from the cesiumAssets build plugin. This default is the remaining case: assets copied to the\n * conventional path without the plugin.\n */\nexport function ensureCesiumBaseUrl(): void {\n // Importing this package under SSR or in a plain Node process must not throw; Cesium only ever\n // reads the value in a browser, so there is nothing to set anywhere else.\n if (typeof window === 'undefined') {\n return\n }\n\n // Memoised because Map3D calls this during render.\n if (resolved === undefined) {\n resolved = fromMeta() || `/cesium-${__CESIUM_VERSION__}`\n }\n\n window.CESIUM_BASE_URL = resolved\n}\n\n// Runs on import so the default travels with this module rather than depending on index.ts being\n// the entry point. Map3D calls it again before constructing the Viewer, which is what actually\n// guarantees the value is set before Cesium resolves its first asset URL.\nensureCesiumBaseUrl()\n","import type { EpsgCode } from '@xgis/xgis-common'\nimport {\n fromWgs84,\n resolutionForZoom,\n toWgs84,\n TWO_PI,\n wrapToRange,\n ZOOM_0_RESOLUTION,\n} from '@xgis/xgis-common'\nimport { Cartesian3 } from 'cesium'\n\n// Loose lon/lat pairs, which is what this package's callers work in.\nexport function mapToWgs84(projection: EpsgCode, x: number, y: number): [number, number] {\n const { lon, lat } = toWgs84(projection, [x, y])\n\n return [lon, lat]\n}\n\nexport function wgs84ToMap(projection: EpsgCode, lon: number, lat: number): [number, number] {\n return fromWgs84(projection, { lon, lat })\n}\n\nfunction ellipsoidPoint(projection: EpsgCode, x: number, y: number): Cartesian3 {\n const [lon, lat] = mapToWgs84(projection, x, y)\n\n return Cartesian3.fromDegrees(lon, lat)\n}\n\n// Zoom is in map units, the camera in metres.\nexport function metresPerMapUnit(projection: EpsgCode, lon: number, lat: number): number {\n const [x, y] = wgs84ToMap(projection, lon, lat)\n const east = Cartesian3.distance(\n ellipsoidPoint(projection, x - 0.5, y),\n ellipsoidPoint(projection, x + 0.5, y),\n )\n const north = Cartesian3.distance(\n ellipsoidPoint(projection, x, y - 0.5),\n ellipsoidPoint(projection, x, y + 0.5),\n )\n\n return (east + north) / 2\n}\n\n// Cesium's fov covers the canvas's longer side.\nexport function fovSpanPx(viewportWidthPx: number, viewportHeightPx: number): number {\n return Math.max(viewportWidthPx, viewportHeightPx)\n}\n\n// Camera range showing the same area as 2D at `zoom`, so a 2D↔3D switch keeps the scale.\n// Depends on the canvas size, unlike the 2D resolution.\nexport function zoomToRange(\n zoom: number,\n spanPx: number,\n fov: number,\n metresPerUnit: number,\n): number {\n return (resolutionForZoom(zoom) * metresPerUnit * spanPx) / (2 * Math.tan(fov / 2))\n}\n\nexport function rangeToZoom(\n range: number,\n spanPx: number,\n fov: number,\n metresPerUnit: number,\n): number {\n const resolution = (2 * range * Math.tan(fov / 2)) / spanPx / metresPerUnit\n return Math.max(0, Math.log2(ZOOM_0_RESOLUTION / resolution))\n}\n\n// A tilted 3D view covers more ground, so 2D zooms out with it, up to a cap. Looking above the\n// horizon holds the cap instead of snapping 2D back in.\nexport function focusRangeForZoom(\n height: number,\n focusRange: number | undefined,\n maxRangeFactor: number,\n): number {\n const maxRange = height * maxRangeFactor\n\n if (focusRange === undefined) {\n return maxRange\n }\n\n return Math.min(focusRange, maxRange)\n}\n\n// Cesium heading turns the view, store rotation turns the map: opposite directions.\nfunction flipAngleDirection(radians: number): number {\n return wrapToRange(-radians, TWO_PI)\n}\n\nexport const cesiumHeadingToRotation = flipAngleDirection\nexport const rotationToCesiumHeading = flipAngleDirection\n\n// Approximate visible area as if looking straight down; undercounts a tilted view.\nexport function cameraFootprint(\n projection: EpsgCode,\n centerLon: number,\n centerLat: number,\n zoom: number,\n viewportWidthPx: number,\n viewportHeightPx: number,\n): [number, number, number, number] {\n const [cx, cy] = wgs84ToMap(projection, centerLon, centerLat)\n const resolution = resolutionForZoom(zoom)\n const halfWidth = (resolution * viewportWidthPx) / 2\n const halfHeight = (resolution * viewportHeightPx) / 2\n return [cx - halfWidth, cy - halfHeight, cx + halfWidth, cy + halfHeight]\n}\n","import type { ZoomLevel } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\n\nimport { fovSpanPx, rangeToZoom, zoomToRange } from './projection'\n\n// Cesium's PerspectiveFrustum default. Only an orthographic frustum lacks `fov`, and `scene3DOnly`\n// never selects one — so this is a type guard, not a real fallback.\nconst DEFAULT_FOV = Math.PI / 3\n\n// Stand-in span for a canvas with no layout yet (a host that mounts xgis into a hidden or\n// zero-sized container). A zero span would make the range 0, parking the camera on the ellipsoid\n// and reporting a non-finite zoom back. This value is the reference the conversion assumed before\n// it became viewport-aware, so the degenerate case simply behaves as it always did.\nconst FALLBACK_SPAN_PX = 1000\n\ninterface ViewportOptics {\n readonly spanPx: number\n readonly fov: number\n}\n\n// Read fresh on every call: the canvas resizes with the window and with the parallel-view split, and\n// a stale span is exactly the bug this module exists to prevent.\nfunction opticsOf(viewer: CesiumViewer): ViewportOptics {\n const canvas = viewer.scene.canvas\n const frustum = viewer.camera.frustum\n const fov = 'fov' in frustum && frustum.fov !== undefined ? frustum.fov : DEFAULT_FOV\n const spanPx = fovSpanPx(canvas.clientWidth, canvas.clientHeight)\n\n return { spanPx: spanPx > 0 ? spanPx : FALLBACK_SPAN_PX, fov }\n}\n\n/** Camera→focus range that renders `zoom` at the same ground scale as the 2D map. */\nexport function rangeForZoom(viewer: CesiumViewer, zoom: number, metresPerUnit: number): number {\n const { spanPx, fov } = opticsOf(viewer)\n return zoomToRange(zoom, spanPx, fov, metresPerUnit)\n}\n\n/** The 2D zoom whose resolution matches the ground scale at `range` — inverse of `rangeForZoom`. */\nexport function zoomForRange(viewer: CesiumViewer, range: number, metresPerUnit: number): number {\n const { spanPx, fov } = opticsOf(viewer)\n return rangeToZoom(range, spanPx, fov, metresPerUnit)\n}\n\n// The one-decimal grid cesiumCamera reports zoom on, or a comparison against it (the zoom-out\n// button's floor included) never meets and never resolves.\nexport function reportedZoomGrid(zoom: number): ZoomLevel {\n return (Math.round(zoom * 10) / 10) as ZoomLevel\n}\n","import type { Camera, Cartesian3, HeadingPitchRange } from 'cesium'\nimport { Matrix4 } from 'cesium'\n\n// Cesium's EPSILON10 threshold on |direction × up-axis|², which equals cos²(pitch).\nconst DEGENERATE_RIGHT_EPSILON = 1e-10\n\nfunction looksStraightDown(pitch: number): boolean {\n return Math.cos(pitch) ** 2 < DEGENERATE_RIGHT_EPSILON\n}\n\n// Straight down, `lookAt` has no right vector to derive and falls back to east, facing north whatever\n// the heading. A twist about the view direction restores it; `setView` would also move the pitch.\nexport function lookAtTarget(camera: Camera, target: Cartesian3, offset: HeadingPitchRange): void {\n camera.lookAt(target, offset)\n camera.lookAtTransform(Matrix4.IDENTITY)\n\n if (!looksStraightDown(offset.pitch)) {\n return\n }\n\n camera.twistRight(offset.heading)\n}\n","import type { Cartesian2, Cartesian3, Viewer as CesiumViewer } from 'cesium'\n\n// Terrain first, ellipsoid as fallback: an ellipsoid-only pick reports a longer range than the\n// terrain actually on screen, understating how close the camera really is.\nexport function pickGroundPoint(\n viewer: CesiumViewer,\n pixel: Cartesian2,\n): { point: Cartesian3; onTerrain: boolean } | undefined {\n const scene = viewer.scene\n const pickRay = viewer.camera.getPickRay(pixel)\n const terrainPoint = pickRay ? scene.globe.pick(pickRay, scene) : undefined\n const point = terrainPoint ?? viewer.camera.pickEllipsoid(pixel, scene.globe.ellipsoid)\n\n return point ? { point, onTerrain: terrainPoint !== undefined } : undefined\n}\n","import type { Viewer as CesiumViewer } from 'cesium'\n\n// Cesium raises moveEnd mid-drag once the camera stands still, so a held pointer extends the move.\nexport function watchCesiumMoving(\n viewer: CesiumViewer,\n callback: (moving: boolean) => void,\n): () => void {\n const canvas = viewer.scene.canvas\n let cameraMoving = false\n let pressed: number[] = []\n let reported = false\n\n function report(): void {\n const moving = cameraMoving || pressed.length > 0\n\n if (moving === reported) {\n return\n }\n\n reported = moving\n callback(moving)\n }\n\n const press = (event: PointerEvent): void => {\n pressed = [...pressed, event.pointerId]\n report()\n }\n\n const release = (event: PointerEvent): void => {\n pressed = pressed.filter((id) => id !== event.pointerId)\n report()\n }\n\n const releaseAll = (): void => {\n pressed = []\n report()\n }\n\n const removeMoveStart = viewer.camera.moveStart.addEventListener(() => {\n cameraMoving = true\n report()\n })\n const removeMoveEnd = viewer.camera.moveEnd.addEventListener(() => {\n cameraMoving = false\n report()\n })\n\n canvas.addEventListener('pointerdown', press)\n canvas.addEventListener('lostpointercapture', release)\n window.addEventListener('pointerup', release)\n window.addEventListener('pointercancel', release)\n window.addEventListener('blur', releaseAll)\n\n return () => {\n removeMoveStart()\n removeMoveEnd()\n canvas.removeEventListener('pointerdown', press)\n canvas.removeEventListener('lostpointercapture', release)\n window.removeEventListener('pointerup', release)\n window.removeEventListener('pointercancel', release)\n window.removeEventListener('blur', releaseAll)\n }\n}\n","import type {\n EpsgCode,\n ICameraCapability,\n IViewChange,\n MapExtent,\n Radians,\n} from '@xgis/xgis-common'\nimport { asMapExtent, extentCenter, RADIANS_TO_DEGREES, zoomForExtent } from '@xgis/xgis-common'\nimport type { Camera, TerrainProvider, Viewer as CesiumViewer } from 'cesium'\nimport {\n BoundingSphere,\n Cartesian2,\n Cartesian3,\n Cartographic,\n Ellipsoid,\n EllipsoidTerrainProvider,\n HeadingPitchRange,\n Math as CesiumMath,\n Matrix3,\n Matrix4,\n Rectangle,\n sampleTerrainMostDetailed,\n Transforms,\n} from 'cesium'\n\nimport { rangeForZoom, reportedZoomGrid, zoomForRange } from '../cameraScale'\nimport { lookAtTarget } from '../lookAtTarget'\nimport { pickGroundPoint } from '../pickGroundPoint'\nimport {\n cameraFootprint,\n cesiumHeadingToRotation,\n focusRangeForZoom,\n mapToWgs84,\n metresPerMapUnit,\n rotationToCesiumHeading,\n} from '../projection'\nimport { watchCesiumMoving } from './cesiumMoving'\n\ninterface CameraFocus {\n readonly lon: number\n readonly lat: number\n // Elevation of the point above the ellipsoid. Carried so a re-target lands on the surface the\n // focus was measured against rather than dropping back to ellipsoid height.\n readonly height: number\n readonly range: number\n // False when the pick fell back to the ellipsoid, leaving height and range wrong by the terrain\n // elevation.\n readonly onTerrain: boolean\n}\n\n// Cap how far the camera->focus slant range may exceed the vertical height when deriving the synced\n// 2D zoom. A grazing (near-horizon) tilt otherwise pushes the focus point arbitrarily far, zooming\n// the 2D view out toward the whole map\nexport const MAX_FOCUS_RANGE_FACTOR = 10\n\n// Elevation to aim a jump at, when the destination is somewhere the camera cannot see yet. Its own\n// terrain cannot be sampled: `globe.getHeight` reads whichever tile level happens to be loaded, and\n// from a far camera that coarse heightmap reports -443 m over Estonia — enough to fly the camera\n// underground. The surface currently on screen is the closest honestly measurable stand-in, and\n// once the destination is centred `fireChange` reports the true zoom from it.\nfunction jumpTargetHeight(focus: CameraFocus | undefined): number {\n return focus?.height ?? 0\n}\n\nfunction cameraFocusFromPoint(\n viewer: CesiumViewer,\n point: Cartesian3,\n onTerrain: boolean,\n): CameraFocus {\n const carto = Cartographic.fromCartesian(point)\n return {\n lon: carto.longitude * RADIANS_TO_DEGREES,\n lat: carto.latitude * RADIANS_TO_DEGREES,\n height: carto.height,\n range: Cartesian3.distance(viewer.camera.position, point),\n onTerrain,\n }\n}\n\n// Screen-centre ground point (degrees) plus the camera->point slant range, or undefined when the\n// screen centre is above the horizon. `createCentroidTilt` orbits the camera about this very point,\n// so it is invariant under the tilt gesture, and anchoring the 2D footprint here keeps the 2D map from\n// drifting toward the horizon as the 3D view tilts. The slant range grows as the view tilts, so\n// basing the 2D zoom on it (not the vertical height) keeps the 2D extent matched to the area the 3D\n// view covers.\nexport function screenCenterGroundFocus(viewer: CesiumViewer): CameraFocus | undefined {\n const canvas = viewer.scene.canvas\n const centerPx = new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2)\n const picked = pickGroundPoint(viewer, centerPx)\n\n return picked ? cameraFocusFromPoint(viewer, picked.point, picked.onTerrain) : undefined\n}\n\n// Whether the focus is an ellipsoid fallback standing in for terrain that has not rendered yet,\n// rather than ground that genuinely is not there. Reporting the first writes a zoom wrong by the\n// terrain elevation into the shared store.\n//\n// `camera.changed` is raised at the end of `Scene.initializeFrame`, before the quadtree refills its\n// load queues, so `globe.tilesLoaded` still describes the previous frame and cannot be consulted\n// here. Assume unrendered; `postRender` is where that question can be answered.\nfunction focusIsUnmeasurable(viewer: CesiumViewer, focus: CameraFocus | undefined): boolean {\n if (!focus || focus.onTerrain) {\n return false\n }\n\n return !(viewer.terrainProvider instanceof EllipsoidTerrainProvider)\n}\n\n// Cesium's camera.heading/camera.pitch getters always measure against the ENU frame at the\n// camera's OWN position, not the frame `lookAt` actually orients the camera against (the ENU frame\n// at the look-at target). The two frames coincide at nadir but tilt apart as the camera->target\n// range grows relative to Earth's radius, so a `setPitch`/`setRotation` round-trip drifts once\n// zoomed out far enough (e.g. at MIN_ZOOM). Re-deriving heading/pitch against the SAME focus point\n// used to position the camera keeps the reported value equal to what was set, at any range.\nexport function headingPitchAtFocus(\n camera: Camera,\n lon: number,\n lat: number,\n): { heading: number; pitch: number } {\n const enuRotation = Matrix4.getMatrix3(\n Transforms.eastNorthUpToFixedFrame(Cartesian3.fromDegrees(lon, lat)),\n new Matrix3(),\n )\n const localRotation = Matrix3.transpose(enuRotation, new Matrix3())\n\n const localDirection = Matrix3.multiplyByVector(\n localRotation,\n camera.directionWC,\n new Cartesian3(),\n )\n const localUp = Matrix3.multiplyByVector(localRotation, camera.upWC, new Cartesian3())\n\n const pitch = CesiumMath.PI_OVER_TWO - CesiumMath.acosClamped(localDirection.z)\n\n const nearVertical = CesiumMath.equalsEpsilon(\n Math.abs(localDirection.z),\n 1.0,\n CesiumMath.EPSILON3,\n )\n const rawHeading = nearVertical\n ? Math.atan2(localUp.y, localUp.x) - CesiumMath.PI_OVER_TWO\n : Math.atan2(localDirection.y, localDirection.x) - CesiumMath.PI_OVER_TWO\n const heading = CesiumMath.TWO_PI - CesiumMath.zeroToTwoPi(rawHeading)\n\n return { heading, pitch }\n}\n\n// The orientation to hand a `lookAt`/`flyTo` that is about to re-apply the camera's current tilt and\n// bearing. Both orient against the ENU frame at their TARGET, while the `camera.heading`/\n// `camera.pitch` getters measure against the frame at the camera's OWN position; the two differ by\n// the angle the camera's `range · cos(pitch)` stand-off subtends at Earth's centre. Feeding a getter\n// back into `lookAt` therefore loses that angle on every call — 0.14° of tilt at zoom 6, 2.17° at\n// MIN_ZOOM — and a parallel-view divider drag replays it ~180 times a second, walking the camera to\n// nadir. With no focus point the value is applied at the camera's own position, where the two frames\n// already coincide, so the getters are the correct read there.\nfunction orientationAtFocus(\n camera: Camera,\n focus: CameraFocus | undefined,\n): { heading: number; pitch: number } {\n if (!focus) {\n return { heading: camera.heading, pitch: camera.pitch }\n }\n\n return headingPitchAtFocus(camera, focus.lon, focus.lat)\n}\n\n// The screen-centre point at `height`, picked along the same ray rather than raised off the\n// ellipsoid one. Raising it instead leaves the target off the view ray, so its lon/lat and range\n// disagree and a `lookAt` relocates the camera on every call.\nfunction focusAtHeight(viewer: CesiumViewer, height: number): CameraFocus | undefined {\n const scene = viewer.scene\n const canvas = scene.canvas\n const centerPx = new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2)\n const base = scene.globe.ellipsoid ?? Ellipsoid.default\n\n const point = viewer.camera.pickEllipsoid(\n centerPx,\n new Ellipsoid(base.radii.x + height, base.radii.y + height, base.radii.z + height),\n )\n\n if (!point) {\n return undefined\n }\n\n const carto = Cartographic.fromCartesian(point)\n\n return {\n lon: carto.longitude * RADIANS_TO_DEGREES,\n lat: carto.latitude * RADIANS_TO_DEGREES,\n height,\n range: Cartesian3.distance(viewer.camera.position, point),\n onTerrain: false,\n }\n}\n\n// Shared by flyToPosition and useCesiumEntryCamera. Rejects on a failed tile request so\n// `undefined` means only \"no terrain here\" (an ellipsoid provider, or a point terrain does not\n// cover), never a transient failure worth retrying as if it were an answer.\nexport async function sampleTerrainHeight(\n provider: TerrainProvider,\n position: { lon: number; lat: number },\n): Promise<number | undefined> {\n if (provider instanceof EllipsoidTerrainProvider) {\n return undefined\n }\n\n const [sampled] = await sampleTerrainMostDetailed(\n provider,\n [Cartographic.fromDegrees(position.lon, position.lat)],\n true,\n )\n\n return sampled?.height\n}\n\nasync function destinationTerrainHeight(\n viewer: CesiumViewer,\n lon: number,\n lat: number,\n): Promise<number> {\n try {\n return (await sampleTerrainHeight(viewer.terrainProvider, { lon, lat })) ?? 0\n } catch {\n return 0\n }\n}\n\n// The focus point, which does not move when the camera tilts (ADR 0006); the camera sub-point\n// when the horizon is in view.\nexport function viewCenter(viewer: CesiumViewer, focus: CameraFocus | undefined): [number, number] {\n const carto = viewer.camera.positionCartographic\n\n return focus\n ? [focus.lon, focus.lat]\n : [carto.longitude * RADIANS_TO_DEGREES, carto.latitude * RADIANS_TO_DEGREES]\n}\n\nconst ROTATION_EPSILON = 0.0001\n\nexport function createCesiumCameraCapability(\n viewer: CesiumViewer,\n getProjection: () => EpsgCode,\n): ICameraCapability {\n const listeners = new Set<(change: IViewChange) => void>()\n const rotationListeners = new Set<(rotation: number) => void>()\n\n viewer.camera.percentageChanged = 0.01\n\n let lastRotation: number | undefined\n\n // Last elevation measured against rendered terrain, so placement has something better than the\n // ellipsoid while tiles stream.\n let lastTerrainHeight: number | undefined\n\n // Placement only: reporting needs the raw measurement to keep `onTerrain` honest.\n function focusForPlacement(): CameraFocus | undefined {\n const focus = screenCenterGroundFocus(viewer)\n\n if (!focus) {\n return undefined\n }\n\n if (focus.onTerrain) {\n lastTerrainHeight = focus.height\n return focus\n }\n\n if (lastTerrainHeight === undefined) {\n return focus\n }\n\n return focusAtHeight(viewer, lastTerrainHeight) ?? focus\n }\n\n // A settle was dropped as unmeasurable and is waiting to be re-issued.\n let settleDropped = false\n\n // Cesium's camera.changed already fires live during a gesture (throttled by percentageChanged),\n // so the compass rides the same event on its own channel — kept separate from onViewChange so\n // the contract matches the 2D capability (ADR 0006 pipeline stays on settle reporting only).\n function fireRotation(rotation: number): void {\n if (lastRotation !== undefined && Math.abs(rotation - lastRotation) < ROTATION_EPSILON) {\n return\n }\n\n lastRotation = rotation\n rotationListeners.forEach((cb) => cb(rotation))\n }\n\n function metresPerUnitAt([lon, lat]: [number, number]): number {\n return metresPerMapUnit(getProjection(), lon, lat)\n }\n\n function reportedZoom(focus: CameraFocus | undefined): number {\n // Slant range, so the 2D extent grows as the 3D view tilts; capped near the horizon.\n const height = viewer.camera.positionCartographic.height\n const range = focusRangeForZoom(height, focus?.range, MAX_FOCUS_RANGE_FACTOR)\n\n return reportedZoomGrid(zoomForRange(viewer, range, metresPerUnitAt(viewCenter(viewer, focus))))\n }\n\n function footprint(focus: CameraFocus | undefined, zoom: number): MapExtent {\n const canvas = viewer.scene.canvas\n const [centerLon, centerLat] = viewCenter(viewer, focus)\n\n return asMapExtent(\n cameraFootprint(\n getProjection(),\n centerLon,\n centerLat,\n zoom,\n canvas.clientWidth,\n canvas.clientHeight,\n ),\n )\n }\n\n // Pure reporter (ADR 0006): emit the settled view on every camera change, including the result\n // of a programmatic command. The coordinator owns loop-breaking, so the capability never\n // suppresses its own changes.\n function emitChange(focus: CameraFocus | undefined, heading: number, pitch: number): void {\n const zoom = reportedZoom(focus)\n\n // A camera sitting on the ellipsoid (range 0) drives the zoom to infinity. The coordinator\n // writes reported zoom straight to the store without clamping, so drop the whole degenerate\n // report rather than poison the shared view state — the bbox is derived from this zoom too.\n if (!Number.isFinite(zoom)) {\n return\n }\n\n const change: IViewChange = {\n zoom,\n rotation: cesiumHeadingToRotation(heading),\n pitch: pitch as Radians,\n bbox: footprint(focus, zoom),\n }\n\n settleDropped = false\n listeners.forEach((cb) => cb(change))\n }\n\n function fireChange(focus: CameraFocus | undefined, heading: number, pitch: number): void {\n if (focusIsUnmeasurable(viewer, focus)) {\n settleDropped = true\n return\n }\n\n emitChange(focus, heading, pitch)\n }\n\n function currentView(): { focus: CameraFocus | undefined; heading: number; pitch: number } {\n const camera = viewer.camera\n const focus = screenCenterGroundFocus(viewer)\n const { heading, pitch } = focus\n ? headingPitchAtFocus(camera, focus.lon, focus.lat)\n : { heading: camera.heading, pitch: camera.pitch }\n\n return { focus, heading, pitch }\n }\n\n viewer.camera.changed.addEventListener(() => {\n const { focus, heading, pitch } = currentView()\n\n fireRotation(cesiumHeadingToRotation(heading))\n fireChange(focus, heading, pitch)\n })\n\n // Tiles finishing does not move the camera, so `camera.changed` will not fire; without this a\n // dropped settle would stand until the user next moves the map.\n viewer.scene.postRender.addEventListener(() => {\n if (!settleDropped || !viewer.scene.globe.tilesLoaded) {\n return\n }\n\n // Tiles are genuinely all in: an ellipsoid fallback here is real ground, not a gap.\n const { focus, heading, pitch } = currentView()\n emitChange(focus, heading, pitch)\n })\n\n return {\n flyTo(extent) {\n const projection = getProjection()\n const [west, south] = mapToWgs84(projection, extent[0], extent[1])\n const [east, north] = mapToWgs84(projection, extent[2], extent[3])\n viewer.camera.flyTo({\n destination: Rectangle.fromDegrees(west, south, east, north),\n duration: 0,\n })\n },\n fitExtent(extent) {\n const camera = viewer.camera\n const canvas = viewer.scene.canvas\n const [cx, cy] = extentCenter(extent)\n const projection = getProjection()\n const [lon, lat] = mapToWgs84(projection, cx, cy)\n const focus = focusForPlacement()\n const { heading, pitch } = orientationAtFocus(camera, focus)\n\n // Match the 2D ground scale at the focus point rather than containing the rectangle. (BBOX is not nicely transferable\n // onto a 3D map)\n const zoom = zoomForExtent(extent, canvas.clientWidth, canvas.clientHeight)\n const range = rangeForZoom(viewer, zoom, metresPerUnitAt([lon, lat]))\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(lon, lat, jumpTargetHeight(focus)),\n new HeadingPitchRange(heading, pitch, range),\n )\n },\n setExtent(extent) {\n const camera = viewer.camera\n const [cx, cy] = extentCenter(extent)\n const [lon, lat] = mapToWgs84(getProjection(), cx, cy)\n const focus = focusForPlacement()\n const { heading, pitch } = orientationAtFocus(camera, focus)\n\n // Recenter the camera's focus on the 2D centre, preserving the current tilt, heading and\n // range (setZoom refines the range next). A Rectangle destination would reset to nadir.\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(lon, lat, jumpTargetHeight(focus)),\n new HeadingPitchRange(heading, pitch, focus?.range ?? camera.positionCartographic.height),\n )\n },\n setZoom(zoom) {\n const camera = viewer.camera\n const focus = focusForPlacement()\n const range = rangeForZoom(viewer, zoom, metresPerUnitAt(viewCenter(viewer, focus)))\n\n if (!focus) {\n // Above the horizon — no focus point; set the vertical height in place.\n camera.setView({\n destination: Cartesian3.fromRadians(\n camera.positionCartographic.longitude,\n camera.positionCartographic.latitude,\n range,\n ),\n orientation: { heading: camera.heading, pitch: camera.pitch, roll: camera.roll },\n })\n return\n }\n\n // Set the camera->focus slant range (inverse of the zoomForRange(range) used in 3D->2D),\n // keeping the focus point, heading and pitch.\n const { heading, pitch } = orientationAtFocus(camera, focus)\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(focus.lon, focus.lat, focus.height),\n new HeadingPitchRange(heading, pitch, range),\n )\n },\n setRotation(rotation) {\n const camera = viewer.camera\n const heading = rotationToCesiumHeading(rotation)\n const focus = focusForPlacement()\n\n if (!focus) {\n // Above the horizon — rotate heading in place.\n camera.setView({ orientation: { heading, pitch: camera.pitch, roll: 0 } })\n return\n }\n\n // Orbit the focus point to the new heading, keeping the focus, range and pitch.\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(focus.lon, focus.lat, focus.height),\n new HeadingPitchRange(heading, orientationAtFocus(camera, focus).pitch, focus.range),\n )\n },\n setPitch(pitch) {\n const camera = viewer.camera\n const focus = focusForPlacement()\n\n if (!focus) {\n // Above the horizon — no focus point; tilt in place.\n camera.setView({\n destination: camera.position,\n orientation: { heading: camera.heading, pitch, roll: 0 },\n })\n return\n }\n\n // Orbit the focus point to the new tilt, keeping the focus, heading and range — the same pivot\n // the native CTRL-drag tilt uses. Tilting about the camera position instead swings the\n // screen-centre ground point downrange, which fireChange then reports as a new 2D centre.\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(focus.lon, focus.lat, focus.height),\n new HeadingPitchRange(orientationAtFocus(camera, focus).heading, pitch, focus.range),\n )\n },\n zoomTo(coord, zoom) {\n const camera = viewer.camera\n const [lon, lat] = mapToWgs84(getProjection(), coord[0], coord[1])\n const focus = focusForPlacement()\n const { heading, pitch } = orientationAtFocus(camera, focus)\n const range = rangeForZoom(viewer, zoom, metresPerUnitAt([lon, lat]))\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(lon, lat, jumpTargetHeight(focus)),\n new HeadingPitchRange(heading, pitch, range),\n )\n },\n async flyToPosition(position, zoom) {\n const camera = viewer.camera\n const focus = focusForPlacement()\n const { heading, pitch } = orientationAtFocus(camera, focus)\n const terrainHeight = await destinationTerrainHeight(viewer, position.lon, position.lat)\n const range = rangeForZoom(viewer, zoom, metresPerUnitAt([position.lon, position.lat]))\n\n // flyTo's `destination` places the camera itself there, not a look-at target, so off nadir\n // the centred point drifts.\n camera.flyToBoundingSphere(\n new BoundingSphere(Cartesian3.fromDegrees(position.lon, position.lat, terrainHeight), 0),\n {\n offset: new HeadingPitchRange(heading, pitch, range),\n duration: 1.0,\n },\n )\n },\n getCenter() {\n const carto = viewer.camera.positionCartographic\n return [carto.longitude * RADIANS_TO_DEGREES, carto.latitude * RADIANS_TO_DEGREES]\n },\n getBbox() {\n const { focus } = currentView()\n\n return footprint(focus, reportedZoom(focus))\n },\n getRotation() {\n return cesiumHeadingToRotation(currentView().heading)\n },\n onViewChange(callback) {\n listeners.add(callback)\n return () => {\n listeners.delete(callback)\n }\n },\n onRotationChange(callback) {\n rotationListeners.add(callback)\n return () => {\n rotationListeners.delete(callback)\n }\n },\n onMovingChange(callback) {\n return watchCesiumMoving(viewer, callback)\n },\n }\n}\n","import {\n createEngineErrorChannel,\n type EngineErrorChannel,\n WEBGL_CONTEXT_LOST_ERROR_NAME,\n} from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\n\nexport interface CesiumEngineHealth extends EngineErrorChannel {\n dispose(): void\n}\n\nexport function createCesiumEngineHealth(viewer: CesiumViewer): CesiumEngineHealth {\n const channel = createEngineErrorChannel()\n\n function handleContextLost(): void {\n const error = new Error('WebGL context lost')\n error.name = WEBGL_CONTEXT_LOST_ERROR_NAME\n channel.reportError(error, { severity: 'fatal' })\n }\n\n function handleRenderError(_scene: unknown, error: unknown): void {\n channel.reportError(error instanceof Error ? error : new Error(String(error)), {\n severity: 'fatal',\n })\n }\n\n viewer.canvas.addEventListener('webglcontextlost', handleContextLost)\n viewer.scene.renderError.addEventListener(handleRenderError)\n\n return {\n reportError: channel.reportError,\n onError: channel.onError,\n dispose() {\n viewer.canvas.removeEventListener('webglcontextlost', handleContextLost)\n viewer.scene.renderError.removeEventListener(handleRenderError)\n },\n }\n}\n","import type { EpsgCode, MapExtent, ZoomLevel } from '@xgis/xgis-common'\nimport { asMapExtent, clampExtentToBounds, extentCenter, zoomToFit } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { Cartesian3, HeadingPitchRange } from 'cesium'\n\nimport { rangeForZoom, zoomForRange } from './cameraScale'\nimport {\n headingPitchAtFocus,\n MAX_FOCUS_RANGE_FACTOR,\n screenCenterGroundFocus,\n viewCenter,\n} from './capabilities/cesiumCamera'\nimport { lookAtTarget } from './lookAtTarget'\nimport { cameraFootprint, mapToWgs84, metresPerMapUnit, wgs84ToMap } from './projection'\n\n// Below this the correction would feed cameraSync's report -> store -> mirror loop (ADR 0006).\nconst MOVE_EPSILON_METERS = 1\n\n/** Zoom at which `bounds` just fills the canvas — the furthest this camera may pull back. */\nexport function boundsFloor(viewer: CesiumViewer, bounds: MapExtent): ZoomLevel {\n const canvas = viewer.scene.canvas\n\n return zoomToFit(bounds, { width: canvas.clientWidth, height: canvas.clientHeight })\n}\n\n/**\n * Cesium has no extent constraint, so the camera is pulled back each frame after it moves: out of\n * anywhere past `bounds`, and back from any closer than `zoomCeiling`.\n */\nexport function createCameraBoundsGuard(\n viewer: CesiumViewer,\n bounds: MapExtent,\n projection: EpsgCode,\n zoomCeiling: ZoomLevel,\n): () => void {\n let lastPosition: Cartesian3 | undefined\n let lastCanvasKey = ''\n\n function clampToBounds(): void {\n const camera = viewer.camera\n const canvas = viewer.scene.canvas\n // The footprint is derived from the canvas as well, so a resize alone can put it out of bounds\n // even though the camera itself never moved.\n const canvasKey = `${canvas.clientWidth}x${canvas.clientHeight}`\n const settled =\n lastPosition &&\n Cartesian3.equals(camera.position, lastPosition) &&\n canvasKey === lastCanvasKey\n\n if (settled) {\n return\n }\n\n lastPosition = Cartesian3.clone(camera.position, lastPosition)\n lastCanvasKey = canvasKey\n\n const focus = screenCenterGroundFocus(viewer)\n const [lon, lat] = viewCenter(viewer, focus)\n // Taken where the capability takes it, or the guard's zoom floor and the reported zoom disagree.\n const metresPerUnit = metresPerMapUnit(projection, lon, lat)\n\n const viewport = { width: canvas.clientWidth, height: canvas.clientHeight }\n\n // Tilted toward the horizon nothing is under the screen centre, so the camera's height stands\n // in for its distance. A tilted camera can be far out while staying low, so the height is\n // scaled to stay comparable with the distance limit below.\n const currentRange = focus\n ? focus.range\n : camera.positionCartographic.height * MAX_FOCUS_RANGE_FACTOR\n\n // Scale is corrected before position: a view covering more ground than the topic shows the\n // outside however it is centred, and the pulled-in footprint is what the centre then clamps\n // against. The floor is applied last so it wins over the ceiling, as OpenLayers' own clamp\n // does, should a topic set the two past each other.\n const range = Math.min(\n Math.max(currentRange, rangeForZoom(viewer, zoomCeiling, metresPerUnit)),\n rangeForZoom(viewer, boundsFloor(viewer, bounds), metresPerUnit),\n )\n\n const footprint = asMapExtent(\n cameraFootprint(\n projection,\n lon,\n lat,\n zoomForRange(viewer, range, metresPerUnit),\n viewport.width,\n viewport.height,\n ),\n )\n\n const [x, y] = wgs84ToMap(projection, lon, lat)\n const [targetX, targetY] = extentCenter(clampExtentToBounds(footprint, bounds))\n\n if (\n Math.abs(targetX - x) < MOVE_EPSILON_METERS &&\n Math.abs(targetY - y) < MOVE_EPSILON_METERS &&\n Math.abs(currentRange - range) < MOVE_EPSILON_METERS\n ) {\n return\n }\n\n const [targetLon, targetLat] = mapToWgs84(projection, targetX, targetY)\n\n if (focus) {\n // camera.heading/pitch measure against the ENU frame at the camera's OWN position, but\n // lookAt orients against the frame at its TARGET — re-deriving them at the focus point\n // avoids baking that mismatch into the correction (see headingPitchAtFocus).\n const { heading, pitch } = headingPitchAtFocus(camera, focus.lon, focus.lat)\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(targetLon, targetLat),\n new HeadingPitchRange(heading, pitch, range),\n )\n } else {\n // Back from the scaled stand-in to the height setView expects.\n camera.setView({\n destination: Cartesian3.fromDegrees(targetLon, targetLat, range / MAX_FOCUS_RANGE_FACTOR),\n orientation: { heading: camera.heading, pitch: camera.pitch, roll: camera.roll },\n })\n }\n\n lastPosition = Cartesian3.clone(camera.position, lastPosition)\n }\n\n return viewer.scene.preRender.addEventListener(clampToBounds)\n}\n","import type { IViewLimitsCapability } from '@xgis/xgis-common'\nimport { MIN_ZOOM } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\n\nimport { boundsFloor } from '../cameraBoundsGuard'\nimport { reportedZoomGrid } from '../cameraScale'\n\nexport function createCesiumViewLimitsCapability(viewer: CesiumViewer): IViewLimitsCapability {\n return {\n getZoomFloor(bounds) {\n if (!bounds) {\n return MIN_ZOOM\n }\n\n return reportedZoomGrid(boundsFloor(viewer, bounds))\n },\n\n getZoomCeiling(zoomCeiling) {\n return reportedZoomGrid(zoomCeiling)\n },\n }\n}\n","import {\n type EpsgCode,\n extentCenter,\n type MapExtent,\n type Radians,\n SHALLOWEST_PITCH,\n type ZoomLevel,\n} from '@xgis/xgis-common'\nimport { Cartesian3, HeadingPitchRange, type Viewer as CesiumViewer } from 'cesium'\n\nimport { rangeForZoom } from './cameraScale'\nimport { headingPitchAtFocus } from './capabilities/cesiumCamera'\nimport { lookAtTarget } from './lookAtTarget'\nimport { mapToWgs84, metresPerMapUnit, rotationToCesiumHeading } from './projection'\n\n// Assumed ground elevation until terrain can be sampled; `useCesiumEntryCamera` corrects it.\nexport const ELLIPSOID_HEIGHT = 0\n\nexport interface EntryView {\n readonly bbox: MapExtent\n readonly zoom: ZoomLevel\n readonly rotation: Radians\n readonly pitch: Radians\n}\n\nexport interface EntryTarget {\n readonly lon: number\n readonly lat: number\n readonly heading: number\n readonly pitch: number\n readonly range: number\n}\n\nexport function entryTarget(\n viewer: CesiumViewer,\n view: EntryView,\n projection: EpsgCode,\n): EntryTarget {\n const [centerX, centerY] = extentCenter(view.bbox)\n const [lon, lat] = mapToWgs84(projection, centerX, centerY)\n\n return {\n lon,\n lat,\n heading: rotationToCesiumHeading(view.rotation),\n // `lookAt` offsets the camera by -range*sin(pitch), so a pitch at or above the horizon would\n // place it on or under the ground plane. Free-look (SHIFT-drag) can leave the store's pitch\n // there and it survives a mode switch, so entry clamps to the same tilt the gestures stop at.\n pitch: Math.min(view.pitch, SHALLOWEST_PITCH),\n range: rangeForZoom(viewer, view.zoom, metresPerMapUnit(projection, lon, lat)),\n }\n}\n\n// `height` is the ground elevation under the target; the camera stands off from that.\nexport function placeEntryCamera(viewer: CesiumViewer, target: EntryTarget, height: number): void {\n lookAtTarget(\n viewer.camera,\n Cartesian3.fromDegrees(target.lon, target.lat, height),\n new HeadingPitchRange(target.heading, target.pitch, target.range),\n )\n}\n\n// Lifts the camera by the ground elevation under its target, leaving where it looks, how far and\n// how steeply it is tilted exactly as they were. The range and orientation are measured off the\n// camera rather than rebuilt, so whatever moved it last is not overridden.\nexport function raiseEntryCameraToTerrain(\n viewer: CesiumViewer,\n target: EntryTarget,\n height: number,\n): void {\n const camera = viewer.camera\n const ellipsoidPoint = Cartesian3.fromDegrees(target.lon, target.lat, ELLIPSOID_HEIGHT)\n const range = Cartesian3.distance(camera.position, ellipsoidPoint)\n const { heading, pitch } = headingPitchAtFocus(camera, target.lon, target.lat)\n\n lookAtTarget(\n camera,\n Cartesian3.fromDegrees(target.lon, target.lat, height),\n new HeadingPitchRange(heading, pitch, range),\n )\n}\n","import type { Viewer as CesiumViewer } from 'cesium'\n\n// Cesium's ScreenSpaceEventHandler cancels `pointerdown` on the canvas whenever an input action is\n// registered for the pressed button — which the default camera controller always is — and a\n// cancelled `pointerdown` suppresses the compatibility `mousedown` event. TEDI overlays opened by\n// click (the basemap picker's Popover, every tooltip on a touch device) detect an outside press by\n// listening for `mousedown` on the document, so pressing the 3D canvas never dismisses them, while\n// the same press over the 2D map does. Re-dispatching the suppressed event restores the symmetry.\n//\n// Remove once TEDI's Overlay dismisses on `pointerdown` (floating-ui's default) instead.\nexport function createCanvasPressRelay(viewer: CesiumViewer): () => void {\n const canvas = viewer.canvas\n\n function relayAsMouseDown(event: PointerEvent): void {\n if (!event.defaultPrevented) {\n return\n }\n\n canvas.dispatchEvent(\n new MouseEvent('mousedown', {\n bubbles: true,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n }),\n )\n }\n\n canvas.addEventListener('pointerdown', relayAsMouseDown)\n\n return () => {\n canvas.removeEventListener('pointerdown', relayAsMouseDown)\n }\n}\n","import { platformModifierOnly, SHALLOWEST_PITCH } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport {\n CameraEventType,\n Cartesian2,\n KeyboardEventModifier,\n Math as CesiumMath,\n Matrix4,\n Transforms,\n} from 'cesium'\n\nimport { pickGroundPoint } from '../pickGroundPoint'\n\n// Heading turns at the 2D interaction's rate, against canvas width rather than an absolute\n// rad/px, so the same drag turns both panes together in parallel view.\nexport const ROTATE_RATE = 1.77\n// Pitch has no 2D counterpart to match, and Cesium's own altitude-dependent tilt rate is private.\nexport const RADIANS_PER_PIXEL = 0.0025\nconst LEFT_BUTTON = 0\nconst MIDDLE_BUTTON = 1\nconst LEFT_BUTTON_MASK = 1\nconst MIDDLE_BUTTON_MASK = 4\n\ninterface TiltEventTypeEntry {\n eventType: CameraEventType\n modifier?: KeyboardEventModifier\n}\n\n// Every mouse tilt gesture Cesium binds, including its Ctrl+right-drag: all of them pivot on the\n// cursor, which is what this replaces. Pinch-tilt is left to Cesium.\nfunction isReplacedTilt(entry: CameraEventType | TiltEventTypeEntry): boolean {\n if (entry === CameraEventType.MIDDLE_DRAG) {\n return true\n }\n\n return (\n typeof entry === 'object' &&\n (entry.eventType === CameraEventType.LEFT_DRAG ||\n entry.eventType === CameraEventType.RIGHT_DRAG) &&\n entry.modifier === KeyboardEventModifier.CTRL\n )\n}\n\nfunction buttonMaskFor(button: number): number {\n return button === MIDDLE_BUTTON ? MIDDLE_BUTTON_MASK : LEFT_BUTTON_MASK\n}\n\nfunction startsGesture(event: PointerEvent): boolean {\n if (event.button === MIDDLE_BUTTON) {\n return !event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey\n }\n\n return event.button === LEFT_BUTTON && platformModifierOnly(event)\n}\n\n/**\n * Orbits the camera about the ground point under the canvas centre, on terrain where terrain has\n * rendered. That is the same point `screenCenterGroundFocus` reports as the view centre, so the\n * synced 2D pane holds still while the 3D view turns.\n *\n * Cesium's own tilt cannot do this: it picks its pivot from the mouse position, and splits the two\n * mouse axes across two different pivots — see ADR 0024.\n */\nexport function createCentroidTilt(viewer: CesiumViewer): () => void {\n const { scene, camera } = viewer\n const controller = scene.screenSpaceCameraController\n const canvas = scene.canvas\n const originalTiltEventTypes = controller.tiltEventTypes\n const entries = Array.isArray(originalTiltEventTypes)\n ? originalTiltEventTypes\n : originalTiltEventTypes === undefined\n ? []\n : [originalTiltEventTypes]\n controller.tiltEventTypes = entries.filter((entry) => !isReplacedTilt(entry))\n\n let anchorTransform: Matrix4 | undefined\n let activePointerId: number | undefined\n let activeButtonMask = LEFT_BUTTON_MASK\n let suspendedRotate: boolean | undefined\n let lastX = 0\n let lastY = 0\n\n function finishGesture(): void {\n const pointerId = activePointerId\n activePointerId = undefined\n anchorTransform = undefined\n if (suspendedRotate !== undefined) {\n controller.enableRotate = suspendedRotate\n suspendedRotate = undefined\n }\n if (pointerId !== undefined && canvas.hasPointerCapture(pointerId)) {\n canvas.releasePointerCapture(pointerId)\n }\n }\n\n function handlePointerDown(event: PointerEvent): void {\n if (\n activePointerId !== undefined ||\n event.pointerType !== 'mouse' ||\n !startsGesture(event) ||\n !controller.enableInputs ||\n !controller.enableTilt\n ) {\n return\n }\n\n // Picked once per gesture: the camera keeps looking at the pivot, so it stays under the canvas\n // centre by itself. Re-picking every frame would walk it across the terrain instead.\n const picked = pickGroundPoint(\n viewer,\n new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2),\n )\n if (!picked) {\n return\n }\n\n anchorTransform = Transforms.eastNorthUpToFixedFrame(picked.point)\n activePointerId = event.pointerId\n activeButtonMask = buttonMaskFor(event.button)\n // `KeyboardEventModifier` has no Meta, so on macOS Cesium sees this drag as an unmodified\n // left-drag, matches its own `rotateEventTypes` and spins the globe under the orbit. Measured\n // 152 px of pivot drift before this suspension.\n suspendedRotate = controller.enableRotate\n controller.enableRotate = false\n lastX = event.clientX\n lastY = event.clientY\n canvas.setPointerCapture(event.pointerId)\n }\n\n function handlePointerMove(event: PointerEvent): void {\n if (!anchorTransform || event.pointerId !== activePointerId) {\n return\n }\n if (!(event.buttons & activeButtonMask) || !controller.enableInputs || !controller.enableTilt) {\n finishGesture()\n return\n }\n const dx = event.clientX - lastX\n const dy = event.clientY - lastY\n lastX = event.clientX\n lastY = event.clientY\n if (dx === 0 && dy === 0) {\n return\n }\n\n const previousTransform = Matrix4.clone(camera.transform)\n try {\n camera.lookAtTransform(anchorTransform)\n // Rotating about the frame's vertical axis leaves the tilt untouched, so the heading half of\n // a diagonal drag always applies in full — including while the tilt sits at its limit.\n camera.rotateLeft(ROTATE_RATE * (dx / canvas.clientWidth) * Math.PI * 2)\n\n // The horizon end of the tilt; `createNadirLimit` bounds the overhead end the same way, and\n // neither covers the other. The camera looks at the frame's origin, so the vertical component\n // of its direction is the sine of the tilt. Clamping the angle rather than rejecting the\n // whole step is what keeps the gesture from stalling sideways once the tilt is pinned.\n // Cesium's native controller derives vertical tilt from startY - endY: dragging down must\n // pass a negative angle to rotateUp.\n const tilt = CesiumMath.asinClamped(camera.direction.z)\n const allowedUp = Math.min(-dy * RADIANS_PER_PIXEL, SHALLOWEST_PITCH - tilt)\n\n if (allowedUp !== 0) {\n camera.rotateUp(allowedUp)\n }\n } finally {\n camera.lookAtTransform(previousTransform)\n }\n scene.requestRender()\n }\n\n function handlePointerEnd(event: PointerEvent): void {\n if (event.pointerId !== activePointerId) {\n return\n }\n finishGesture()\n }\n\n canvas.addEventListener('pointerdown', handlePointerDown)\n canvas.addEventListener('pointermove', handlePointerMove)\n canvas.addEventListener('pointerup', handlePointerEnd)\n canvas.addEventListener('pointercancel', handlePointerEnd)\n canvas.addEventListener('lostpointercapture', handlePointerEnd)\n window.addEventListener('blur', finishGesture)\n\n return () => {\n finishGesture()\n controller.tiltEventTypes = originalTiltEventTypes\n canvas.removeEventListener('pointerdown', handlePointerDown)\n canvas.removeEventListener('pointermove', handlePointerMove)\n canvas.removeEventListener('pointerup', handlePointerEnd)\n canvas.removeEventListener('pointercancel', handlePointerEnd)\n canvas.removeEventListener('lostpointercapture', handlePointerEnd)\n window.removeEventListener('blur', finishGesture)\n }\n}\n","import type { Viewer as CesiumViewer } from 'cesium'\nimport { Cartesian2, Cartesian3 } from 'cesium'\n\nimport { pickGroundPoint } from '../pickGroundPoint'\n\nconst KEYBOARD_PAN_DIVISOR = 10\n\n// One zoom level is a factor of two in the camera->focus range, as in the synced 2D view.\nconst ZOOM_IN_RANGE_FRACTION = 0.5\nconst ZOOM_OUT_RANGE_FRACTION = 1\n\ntype Vec3 = [number, number, number]\n\n// Horizontal component of `vec` (projection onto the plane with the given normal), normalized.\n// null when `vec` is parallel to the normal — then there is no horizontal direction.\nexport function horizontalDirection(vec: Vec3, normal: Vec3): Vec3 | null {\n const [vecX, vecY, vecZ] = vec\n const [normalX, normalY, normalZ] = normal\n\n const dot = vecX * normalX + vecY * normalY + vecZ * normalZ\n const hX = vecX - dot * normalX\n const hY = vecY - dot * normalY\n const hZ = vecZ - dot * normalZ\n const len = Math.hypot(hX, hY, hZ)\n\n if (len < 1e-6) {\n return null\n }\n\n return [hX / len, hY / len, hZ / len]\n}\n\nexport function createCesiumKeyboardHandler(viewer: CesiumViewer, label: string): () => void {\n const canvas = viewer.canvas\n canvas.setAttribute('tabindex', '0')\n canvas.setAttribute('role', 'application')\n canvas.setAttribute('aria-label', label)\n\n function focusCanvas(): void {\n canvas.focus()\n }\n\n function panForward(amount: number): void {\n const camera = viewer.camera\n const normal = viewer.scene.globe.ellipsoid.geodeticSurfaceNormal(\n camera.positionWC,\n new Cartesian3(),\n )\n const forward = horizontalDirection(\n [camera.up.x, camera.up.y, camera.up.z],\n [normal.x, normal.y, normal.z],\n )\n\n if (!forward) {\n return\n }\n\n const [forwardX, forwardY, forwardZ] = forward\n camera.move(new Cartesian3(forwardX, forwardY, forwardZ), amount)\n }\n\n function screenCenterRange(): number {\n const camera = viewer.camera\n const canvas = viewer.scene.canvas\n const picked = pickGroundPoint(\n viewer,\n new Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2),\n )\n\n if (!picked) {\n return camera.positionCartographic.height\n }\n\n return Cartesian3.distance(camera.positionWC, picked.point)\n }\n\n function onKeyDown(event: KeyboardEvent): void {\n const camera = viewer.camera\n const moveRate = camera.positionCartographic.height / KEYBOARD_PAN_DIVISOR\n\n switch (event.key) {\n case 'ArrowUp':\n panForward(moveRate)\n break\n case 'ArrowDown':\n panForward(-moveRate)\n break\n case 'ArrowLeft':\n camera.moveLeft(moveRate)\n break\n case 'ArrowRight':\n camera.moveRight(moveRate)\n break\n case '+':\n case '=':\n camera.zoomIn(screenCenterRange() * ZOOM_IN_RANGE_FRACTION)\n break\n case '-':\n camera.zoomOut(screenCenterRange() * ZOOM_OUT_RANGE_FRACTION)\n break\n default:\n return\n }\n\n event.preventDefault()\n }\n\n canvas.addEventListener('click', focusCanvas)\n canvas.addEventListener('keydown', onKeyDown)\n\n return () => {\n canvas.removeEventListener('click', focusCanvas)\n canvas.removeEventListener('keydown', onKeyDown)\n }\n}\n","import type { Camera, Viewer as CesiumViewer } from 'cesium'\nimport { Cartesian3, Math as CesiumMath, Matrix4 } from 'cesium'\n\nconst DOWN = new Cartesian3(0, 0, -1)\n\n// Negative once the view has turned past straight down: the up vector tips below the frame's\n// horizontal exactly as it crosses.\nfunction angleToNadir(camera: Camera): number {\n const angle = CesiumMath.acosClamped(Cartesian3.dot(camera.direction, DOWN))\n\n return camera.up.z >= 0 ? angle : -angle\n}\n\n/**\n * Cesium clamps its tilt by the camera's POSITION against the pivot it orbits, never by where the\n * camera looks. The two differ by the angle between the drag row and the canvas midline, so the\n * view crosses straight down — upside down in 3D, and a heading flipped 180 degrees into the synced\n * 2D view. The tilt reaches the pitch only through `rotateUp`, so the limit goes there.\n */\nexport function createNadirLimit(viewer: CesiumViewer): () => void {\n const camera = viewer.camera\n const rotateUp = camera.rotateUp.bind(camera)\n\n camera.rotateUp = (angle?: number) => {\n const requested = angle ?? camera.defaultRotateAmount\n\n // `pan3D` finishes with a rotateUp of its own, about the Earth's centre, which does not change\n // the tilt at all. Only the tilt gesture rotates inside a reference frame.\n if (Matrix4.equals(camera.transform, Matrix4.IDENTITY)) {\n rotateUp(requested)\n return\n }\n\n const allowed = Math.max(requested, -angleToNadir(camera))\n\n if (allowed !== 0) {\n rotateUp(allowed)\n }\n }\n\n return () => {\n Reflect.deleteProperty(camera, 'rotateUp')\n }\n}\n","import type { I3DSource, RgbaColor } from '@xgis/xgis-common'\nimport { Cesium3DTileset, Cesium3DTileStyle, I3SDataProvider } from 'cesium'\n\nexport type Cesium3DPrimitive = Cesium3DTileset | I3SDataProvider\n\nexport interface Created3DTileset {\n primitive: Cesium3DPrimitive\n styleable?: Cesium3DTileset\n source: I3DSource\n}\n\nconst MEGABYTE = 1024 * 1024\nconst DEFAULT_MEM_USAGE = 512\nconst DEFAULT_FILL_COLOR: RgbaColor = [234, 231, 221, 1]\nconst DEFAULT_SCREENSPACE_ERROR = 16\n\nfunction colorExpression([red, green, blue, alpha]: RgbaColor, opacity: number): string {\n return `rgba(${red}, ${green}, ${blue}, ${alpha * opacity})`\n}\n\nfunction tilesetOptions(source: I3DSource): Cesium3DTileset.ConstructorOptions {\n return {\n maximumScreenSpaceError: source.maximumScreenSpaceError ?? DEFAULT_SCREENSPACE_ERROR,\n skipLevelOfDetail: source.skipLevelOfDetail ?? true,\n cullWithChildrenBounds: source.cullWithChildrenBounds ?? true,\n dynamicScreenSpaceError: source.dynamicScreenSpaceError ?? true,\n dynamicScreenSpaceErrorDensity: 0.99,\n cacheBytes: source.maximumMemoryUsage\n ? source.maximumMemoryUsage * MEGABYTE\n : DEFAULT_MEM_USAGE * MEGABYTE,\n cullRequestsWhileMoving: true,\n cullRequestsWhileMovingMultiplier: 300,\n foveatedScreenSpaceError: true,\n }\n}\n\nfunction i3sUrl(source: I3DSource): string {\n const withLayer =\n source.layerId === undefined || /\\/layers\\/\\d+\\/?$/.test(source.url)\n ? source.url\n : `${source.url.replace(/\\/+$/, '')}/layers/${source.layerId}`\n\n if (!source.token) {\n return withLayer\n }\n\n return `${withLayer}${withLayer.includes('?') ? '&' : '?'}token=${encodeURIComponent(source.token)}`\n}\n\nexport async function create3DTileset(source: I3DSource): Promise<Created3DTileset | null> {\n if (!source.url) {\n return null\n }\n\n if (source.type === 'i3s') {\n const provider = await I3SDataProvider.fromUrl(i3sUrl(source), {\n cesium3dTilesetOptions: tilesetOptions(source),\n })\n\n return { primitive: provider, source }\n }\n\n const tileset = await Cesium3DTileset.fromUrl(source.url, tilesetOptions(source))\n\n return { primitive: tileset, styleable: tileset, source }\n}\n\nexport function apply3DTilesetOpacity(created: Created3DTileset, opacity: number): void {\n const tileset = created.styleable\n\n if (!tileset) {\n return\n }\n\n tileset.style = new Cesium3DTileStyle({\n color: colorExpression(created.source.fillColor ?? DEFAULT_FILL_COLOR, opacity),\n })\n}\n","import type { Entity, EntityCollection, MaterialProperty, Property } from 'cesium'\nimport {\n Color,\n ColorMaterialProperty,\n ConstantProperty,\n ImageMaterialProperty,\n Iso8601,\n} from 'cesium'\n\n/**\n * One colour-bearing property of one entity, paired with the colour it shows at full opacity.\n *\n * Cesium has no per-DataSource alpha the way imagery layers and 3D tilesets have, so basemap\n * opacity has to be written into every entity individually. Recomputing from `base` rather\n * than from whatever is currently on the entity is what stops a dragged slider from compounding.\n */\nexport interface KmlOpacitySlot {\n base: Color\n property: ConstantProperty\n}\n\ntype Filled = { material: MaterialProperty }\ntype Outlined = { outlineColor: Property | undefined }\ntype Tinted = { color: Property | undefined }\n\nfunction constantColor(property: Property | undefined, fallback: Color): Color {\n const value: unknown = property?.getValue(Iso8601.MINIMUM_VALUE)\n\n return value instanceof Color ? value : fallback\n}\n\n// Replacing a property makes the geometry visualizer rebuild the primitive, where calling setValue\n// on the one the graphic already holds lets the static colour batch update an attribute instead.\n// The slider is dragged, so this is the hot path.\nfunction colorSlot(\n current: Property | undefined,\n fallback: Color,\n install: (property: ConstantProperty) => void,\n): KmlOpacitySlot {\n const base = constantColor(current, fallback)\n\n if (current instanceof ConstantProperty) {\n return { base, property: current }\n }\n\n const property = new ConstantProperty(base)\n install(property)\n\n return { base, property }\n}\n\n// Targets the colour inside the material rather than the material itself, which would be the\n// rebuild colorSlot is avoiding.\nfunction materialSlot(graphic: Filled): KmlOpacitySlot {\n const material = graphic.material\n\n if (material instanceof ImageMaterialProperty || material instanceof ColorMaterialProperty) {\n return colorSlot(material.color, Color.WHITE, (property) => {\n material.color = property\n })\n }\n\n // An unstyled KML polygon or polyline has no material at all — the white it draws in comes from\n // the visualizer's default, so there is nothing to read and one has to be created.\n const created = new ColorMaterialProperty(Color.WHITE)\n graphic.material = created\n\n return colorSlot(created.color, Color.WHITE, (property) => {\n created.color = property\n })\n}\n\nfunction fillSlots(graphic: Filled | undefined): KmlOpacitySlot[] {\n return graphic ? [materialSlot(graphic)] : []\n}\n\n// Cesium's GeometryUpdater draws an absent outline colour black, so capturing white here would\n// repaint unstyled geometry the moment the slots were collected.\nfunction outlineSlots(graphic: Outlined | undefined): KmlOpacitySlot[] {\n if (!graphic) {\n return []\n }\n\n return [\n colorSlot(graphic.outlineColor, Color.BLACK, (property) => {\n graphic.outlineColor = property\n }),\n ]\n}\n\n// White as the fallback leaves the image or disc uncoloured, so only the alpha ever moves.\nfunction tintSlots(graphic: Tinted | undefined): KmlOpacitySlot[] {\n if (!graphic) {\n return []\n }\n\n return [\n colorSlot(graphic.color, Color.WHITE, (property) => {\n graphic.color = property\n }),\n ]\n}\n\nfunction entitySlots(entity: Entity): KmlOpacitySlot[] {\n const { polygon, polyline, wall, rectangle, path, billboard, point } = entity\n\n return [\n ...fillSlots(polygon),\n ...outlineSlots(polygon),\n ...fillSlots(polyline),\n ...fillSlots(wall),\n ...outlineSlots(wall),\n ...fillSlots(rectangle),\n ...fillSlots(path),\n ...tintSlots(billboard),\n ...tintSlots(point),\n ...outlineSlots(point),\n ]\n}\n\nexport function collectKmlOpacitySlots(entities: EntityCollection): KmlOpacitySlot[] {\n return entities.values.flatMap(entitySlots)\n}\n\n// ConstantProperty.setValue clones into the Color it already holds, so one scratch can carry every\n// write without ever being retained — and it skips its change event when the colour has not moved.\nconst scratchColor = new Color()\n\nexport function applyKmlOpacity(slots: readonly KmlOpacitySlot[], opacity: number): void {\n for (const slot of slots) {\n slot.property.setValue(Color.fromAlpha(slot.base, slot.base.alpha * opacity, scratchColor))\n }\n}\n","import type { IKmlParams } from '@xgis/xgis-common'\nimport {\n KML_DEFAULT_COLOR,\n KML_LABEL_FONT,\n KML_LABEL_FONT_SIZE_PX,\n KML_LABEL_OUTLINE_COLOR,\n KML_LABEL_OUTLINE_PX,\n KML_MARKER_SIZE_PX,\n kmlExtractStyles,\n} from '@xgis/xgis-common'\nimport type {\n Cartesian3,\n Entity,\n EntityCollection,\n LabelGraphics,\n MaterialProperty,\n PolygonGraphics,\n PolylineGraphics,\n Property,\n} from 'cesium'\nimport {\n ArcType,\n Color,\n ColorMaterialProperty,\n ConstantProperty,\n HeightReference,\n Iso8601,\n PointGraphics,\n PolygonHierarchy,\n Resource,\n} from 'cesium'\n\nconst DEFAULT_COLOR = Color.fromCssColorString(KML_DEFAULT_COLOR)\nconst LABEL_OUTLINE_COLOR = Color.fromCssColorString(KML_LABEL_OUTLINE_COLOR)\n\nconst SDF_FONT_SIZE_PX = 48\n\nconst LABEL_OUTLINE_WIDTH = (KML_LABEL_OUTLINE_PX * SDF_FONT_SIZE_PX) / KML_LABEL_FONT_SIZE_PX\n\n// Cesium draws a polygon outline with a WebGL line width, clamped to\n// ContextLimits.maximumAliasedLineWidth — 1 on Chrome/ANGLE and most desktop GPUs. Anything wider\n// has to be drawn as a polyline, which goes through a shader that honours width.\nconst MIN_DRAWN_OUTLINE_WIDTH = 1\n\nfunction constantValue(property: Property | undefined): unknown {\n return property?.getValue(Iso8601.MINIMUM_VALUE)\n}\n\nfunction markerHeightReference(clampToGround: boolean): HeightReference {\n return clampToGround ? HeightReference.CLAMP_TO_GROUND : HeightReference.NONE\n}\n\nfunction makeLabelReadable(label: LabelGraphics): void {\n label.font = new ConstantProperty(KML_LABEL_FONT)\n label.outlineColor = new ConstantProperty(LABEL_OUTLINE_COLOR)\n label.outlineWidth = new ConstantProperty(LABEL_OUTLINE_WIDTH)\n}\n\nexport function normaliseKmlEntities(entities: EntityCollection, clampToGround: boolean): void {\n for (const entity of entities.values) {\n if (entity.label) {\n makeLabelReadable(entity.label)\n }\n\n // Cesium only drapes a KML line carrying <tessellate>1</tessellate> and leaves every other one\n // at ArcType.NONE — a straight chord through the ellipsoid, buried under any terrain.\n if (entity.polyline && clampToGround) {\n entity.polyline.clampToGround = new ConstantProperty(true)\n entity.polyline.arcType = new ConstantProperty(ArcType.GEODESIC)\n }\n }\n}\n\nfunction ringPositions(polygon: PolygonGraphics): Cartesian3[][] {\n const hierarchy = constantValue(polygon.hierarchy)\n\n if (!(hierarchy instanceof PolygonHierarchy)) {\n return []\n }\n\n return [hierarchy.positions, ...hierarchy.holes.map((hole) => hole.positions)]\n}\n\n// Cesium gives every KML polygon a white outline whether the document asked for one or not, so an\n// untouched white cannot be told from a deliberate one. xgis2d defaults an unnamed stroke to black,\n// and matching that matters more here: a white border disappears on a light basemap.\nfunction boundaryColor(polygon: PolygonGraphics, stroke: Color | undefined): Color {\n if (stroke) {\n return stroke\n }\n\n const outlineColor = constantValue(polygon.outlineColor)\n\n if (outlineColor instanceof Color && !Color.equals(outlineColor, Color.WHITE)) {\n return outlineColor\n }\n\n return DEFAULT_COLOR\n}\n\nfunction boundaryEntities(\n entity: Entity,\n polygon: PolygonGraphics,\n stroke: Color | undefined,\n width: number,\n clampToGround: boolean,\n): Entity.ConstructorOptions[] {\n const rings = ringPositions(polygon)\n\n if (rings.length === 0) {\n return []\n }\n\n const color = boundaryColor(polygon, stroke)\n\n // The 1px outline would otherwise sit just under the polyline, showing through as a fringe.\n polygon.outline = new ConstantProperty(false)\n\n return rings.map((positions) => ({\n parent: entity,\n polyline: {\n positions,\n width,\n material: new ColorMaterialProperty(color),\n clampToGround,\n arcType: clampToGround ? ArcType.GEODESIC : ArcType.NONE,\n },\n }))\n}\n\ntype FilledGraphic = {\n material: MaterialProperty\n outline: Property | undefined\n outlineColor: Property | undefined\n}\n\nfunction styleFilled(\n graphic: FilledGraphic | undefined,\n fill: Color | undefined,\n stroke: Color | undefined,\n): void {\n if (!graphic) {\n return\n }\n\n if (fill) {\n graphic.material = new ColorMaterialProperty(fill)\n }\n\n if (stroke) {\n graphic.outline = new ConstantProperty(true)\n graphic.outlineColor = new ConstantProperty(stroke)\n }\n}\n\nfunction stylePolyline(\n polyline: PolylineGraphics | undefined,\n stroke: Color | undefined,\n width: number | undefined,\n): void {\n if (!polyline) {\n return\n }\n\n if (stroke) {\n polyline.material = new ColorMaterialProperty(stroke)\n }\n\n if (width !== undefined) {\n polyline.width = new ConstantProperty(width)\n }\n}\n\n// Cesium renders a KML point as a billboard, defaulting to a yellow pushpin PinBuilder draws onto a\n// canvas. An <IconStyle><Icon><href> arrives as a Resource — a deliberate choice by the KML author,\n// so only an explicit `symbol` overrides it. Testing for a string would miss every real KML icon.\nfunction hasAuthoredIcon(entity: Entity): boolean {\n const image = constantValue(entity.billboard?.image)\n\n return image instanceof Resource || typeof image === 'string'\n}\n\nfunction stylePoint(\n entity: Entity,\n params: IKmlParams,\n markerColor: Color | undefined,\n clampToGround: boolean,\n): void {\n const billboard = entity.billboard\n\n if (!billboard) {\n return\n }\n\n if (params.symbol) {\n billboard.image = new ConstantProperty(params.symbol)\n // Cesium sized and placed the billboard for whatever icon it is replacing — its own 32x32\n // default, or an <IconStyle> scale, hotSpot and sprite region. None of that describes the\n // configured image, and a leftover offset puts it metres off the placemark.\n billboard.width = undefined\n billboard.height = undefined\n billboard.scale = undefined\n billboard.pixelOffset = undefined\n billboard.imageSubRegion = undefined\n\n return\n }\n\n if (!markerColor || hasAuthoredIcon(entity)) {\n return\n }\n\n entity.billboard = undefined\n entity.point = new PointGraphics({\n pixelSize: KML_MARKER_SIZE_PX,\n color: markerColor,\n heightReference: markerHeightReference(clampToGround),\n })\n}\n\nexport function applyKmlStyle(\n entities: EntityCollection,\n params: IKmlParams,\n clampToGround: boolean,\n): void {\n const stroke = params.lineColor ? Color.fromCssColorString(params.lineColor) : undefined\n const fill = params.fillColor ? Color.fromCssColorString(params.fillColor) : undefined\n const width = params.lineThickness\n\n // xgis2d draws a marker whenever the config names any style field, falling back to black when it\n // names no colour. Resolving the same way keeps a point the same shape and colour in both engines.\n const markerColor = kmlExtractStyles(params) ? undefined : (fill ?? stroke ?? DEFAULT_COLOR)\n\n const boundaries: Entity.ConstructorOptions[] = []\n\n for (const entity of entities.values) {\n styleFilled(entity.polygon, fill, stroke)\n styleFilled(entity.wall, fill, stroke)\n stylePolyline(entity.polyline, stroke, width)\n stylePoint(entity, params, markerColor, clampToGround)\n\n const polygon = entity.polygon\n\n if (polygon && width !== undefined && width > MIN_DRAWN_OUTLINE_WIDTH) {\n boundaries.push(...boundaryEntities(entity, polygon, stroke, width, clampToGround))\n }\n }\n\n // Added after the walk, so the loop cannot reach the entities it is producing.\n for (const boundary of boundaries) {\n entities.add(boundary)\n }\n}\n","import type { IKmlParams } from '@xgis/xgis-common'\nimport type { Camera } from 'cesium'\nimport { KmlDataSource } from 'cesium'\n\nimport type { KmlOpacitySlot } from './kmlEntityOpacity'\nimport { collectKmlOpacitySlots } from './kmlEntityOpacity'\nimport { applyKmlStyle, normaliseKmlEntities } from './kmlEntityStyle'\n\nexport interface CreatedKml {\n dataSource: KmlDataSource\n opacitySlots: KmlOpacitySlot[]\n}\n\nconst CLAMPED_ALTITUDE_MODE = 'clampToGround'\n\n// Only these carry an altitudeMode that decides how geometry is drawn. KML puts the same element on\n// <LookAt>, <Camera> and <Region> too, where it describes a viewpoint — and Google Earth writes a\n// <LookAt> into almost everything it exports, so reading those would un-drape a whole document that\n// never asked for it.\nconst GEOMETRY_TAGS = ['Point', 'LineString', 'LinearRing', 'Polygon', 'Track', 'MultiTrack']\n\nfunction declaresOwnAltitude(geometry: Element): boolean {\n return Array.from(geometry.children).some((child) => {\n if (child.localName !== 'altitudeMode') {\n return false\n }\n\n const mode = (child.textContent ?? '').trim()\n\n // Cesium falls back to clampToGround for a mode it does not recognise, empty included.\n return mode !== '' && mode !== CLAMPED_ALTITUDE_MODE\n })\n}\n\n// Geometry that names an altitude keeps it — draping something its author placed at a height would\n// throw that height away. Everything else Cesium draws flat on the ellipsoid, which puts it under\n// the terrain. Cesium decides this per placemark, but nothing on the loaded entity records the\n// choice, so it has to be read off the document before the load.\nfunction shouldClampToGround(kmlDocument: Document): boolean {\n return !GEOMETRY_TAGS.some((tag) =>\n Array.from(kmlDocument.getElementsByTagNameNS('*', tag)).some(declaresOwnAltitude),\n )\n}\n\nexport async function createKML(\n params: IKmlParams,\n camera: Camera,\n canvas: HTMLCanvasElement,\n): Promise<CreatedKml> {\n const kmlDocument = new DOMParser().parseFromString(params.objects, 'application/xml')\n const clampToGround = shouldClampToGround(kmlDocument)\n\n const dataSource = await KmlDataSource.load(kmlDocument, { camera, canvas, clampToGround })\n\n normaliseKmlEntities(dataSource.entities, clampToGround)\n applyKmlStyle(dataSource.entities, params, clampToGround)\n\n return { dataSource, opacitySlots: collectKmlOpacitySlots(dataSource.entities) }\n}\n","import type {\n CesiumTilingScheme,\n CrsAxisOrder,\n LayerPresentation,\n OgcMapsSource,\n} from '@xgis/xgis-common'\nimport { ogcMapsCesiumCrs, ogcMapsMapUrl, ogcMapsQuery, withQuery } from '@xgis/xgis-common'\nimport type { ImageryProvider } from 'cesium'\nimport { GeographicTilingScheme, UrlTemplateImageryProvider, WebMercatorTilingScheme } from 'cesium'\n\nconst TILE_SIZE = 256\n\nconst BBOX_TEMPLATE: Record<CesiumTilingScheme, Record<CrsAxisOrder, string>> = {\n geographic: {\n eastingFirst: '{westDegrees},{southDegrees},{eastDegrees},{northDegrees}',\n northingFirst: '{southDegrees},{westDegrees},{northDegrees},{eastDegrees}',\n },\n webMercator: {\n eastingFirst: '{westProjected},{southProjected},{eastProjected},{northProjected}',\n northingFirst: '{southProjected},{westProjected},{northProjected},{eastProjected}',\n },\n}\n\nexport function createOGCMaps(\n source: OgcMapsSource,\n presentation: LayerPresentation,\n capabilities?: string,\n): ImageryProvider | null {\n if (!capabilities) {\n return null\n }\n\n const resolved = ogcMapsCesiumCrs(capabilities)\n\n if (!resolved) {\n return null\n }\n\n const { projection, crs, axisOrder } = resolved\n\n return new UrlTemplateImageryProvider({\n url: withQuery(ogcMapsMapUrl(source), {\n ...ogcMapsQuery(source),\n crs,\n 'bbox-crs': crs,\n bbox: BBOX_TEMPLATE[projection][axisOrder],\n width: '{width}',\n height: '{height}',\n }),\n tilingScheme:\n projection === 'webMercator' ? new WebMercatorTilingScheme() : new GeographicTilingScheme(),\n tileWidth: TILE_SIZE,\n tileHeight: TILE_SIZE,\n credit: presentation.copyright,\n })\n}\n","import type { LayerPresentation, OgcTilesSource, ResolvedOgcTileset } from '@xgis/xgis-common'\nimport { stringifyParams, withQuery } from '@xgis/xgis-common'\nimport type { ImageryProvider } from 'cesium'\nimport { GeographicTilingScheme, UrlTemplateImageryProvider, WebMercatorTilingScheme } from 'cesium'\n\nexport function createOGCTiles(\n source: OgcTilesSource,\n presentation: LayerPresentation,\n tileset: ResolvedOgcTileset,\n): ImageryProvider | null {\n const { cesium } = tileset\n\n if (!cesium) {\n return null\n }\n\n const labels = cesium.tileMatrixLabels\n\n return new UrlTemplateImageryProvider({\n url: withQuery(cesium.url, stringifyParams(source.params)),\n tilingScheme:\n cesium.tilingScheme === 'webMercator'\n ? new WebMercatorTilingScheme()\n : new GeographicTilingScheme(),\n tileWidth: cesium.tileWidth,\n tileHeight: cesium.tileHeight,\n minimumLevel: cesium.minimumLevel,\n maximumLevel: cesium.maximumLevel,\n customTags: labels\n ? {\n tileMatrix: (\n _provider: UrlTemplateImageryProvider,\n _x: number,\n _y: number,\n level: number,\n ) => labels[level] ?? '',\n }\n : undefined,\n credit: presentation.copyright,\n })\n}\n","import type { TilingScheme } from 'cesium'\nimport { Rectangle } from 'cesium'\n\n//copy of Cesium's TileMapServiceImageryProvider calculateSafeMinimumDetailLevel\nexport function safeMinimumLevel(\n scheme: TilingScheme,\n rectangle: Rectangle,\n minimumLevel: number,\n): number {\n const southwest = scheme.positionToTileXY(Rectangle.southwest(rectangle), minimumLevel)\n const northeast = scheme.positionToTileXY(Rectangle.northeast(rectangle), minimumLevel)\n\n if (!southwest || !northeast) {\n return 0\n }\n\n const tiles =\n (Math.abs(northeast.x - southwest.x) + 1) * (Math.abs(northeast.y - southwest.y) + 1)\n\n return tiles > 4 ? 0 : minimumLevel\n}\n","import type { LayerPresentation, ParsedTmsTileMap, TmsSource } from '@xgis/xgis-common'\nimport {\n parseTmsTileMap,\n tmsCesiumSchemeFor,\n tmsLevelRange,\n tmsTileBase,\n tmsTileSuffix,\n} from '@xgis/xgis-common'\nimport type { ImageryProvider, TilingScheme } from 'cesium'\nimport {\n Cartesian3,\n GeographicTilingScheme,\n Rectangle,\n UrlTemplateImageryProvider,\n WebMercatorProjection,\n WebMercatorTilingScheme,\n} from 'cesium'\n\nimport { safeMinimumLevel } from './safeMinimumLevel'\n\nfunction tilesetRectangle(tileMap: ParsedTmsTileMap, geographic: boolean): Rectangle {\n const [minX, minY, maxX, maxY] = tileMap.extent\n\n if (geographic) {\n return Rectangle.fromDegrees(minX, minY, maxX, maxY)\n }\n\n const projection = new WebMercatorProjection()\n const southwest = projection.unproject(new Cartesian3(minX, minY, 0))\n const northeast = projection.unproject(new Cartesian3(maxX, maxY, 0))\n\n return new Rectangle(\n southwest.longitude,\n southwest.latitude,\n northeast.longitude,\n northeast.latitude,\n )\n}\n\nfunction confineToScheme(rectangle: Rectangle, scheme: TilingScheme): Rectangle {\n return Rectangle.intersection(rectangle, scheme.rectangle) ?? scheme.rectangle\n}\n\nexport function createTMS(\n source: TmsSource,\n presentation: LayerPresentation,\n capabilitiesText: string,\n): ImageryProvider | null {\n const tileMap = parseTmsTileMap(capabilitiesText)\n const scheme = tileMap ? tmsCesiumSchemeFor(tileMap) : undefined\n\n if (!tileMap || !scheme) {\n return null\n }\n\n const geographic = scheme === 'geographic'\n const tilingScheme = geographic ? new GeographicTilingScheme() : new WebMercatorTilingScheme()\n const rectangle = confineToScheme(tilesetRectangle(tileMap, geographic), tilingScheme)\n const { minimum, maximum } = tmsLevelRange(tileMap)\n\n return new UrlTemplateImageryProvider({\n url: `${tmsTileBase(source.href)}{z}/{x}/{reverseY}${tmsTileSuffix(tileMap.extension)}`,\n tilingScheme,\n rectangle,\n tileWidth: tileMap.tileWidth,\n tileHeight: tileMap.tileHeight,\n minimumLevel: safeMinimumLevel(tilingScheme, rectangle, minimum),\n maximumLevel: maximum,\n credit: presentation.copyright,\n })\n}\n","import type { LayerPresentation, WmsSource } from '@xgis/xgis-common'\nimport { parseWmsCaps } from '@xgis/xgis-common'\nimport type { ImageryProvider, Rectangle } from 'cesium'\nimport {\n GeographicTilingScheme,\n WebMapServiceImageryProvider,\n WebMercatorTilingScheme,\n} from 'cesium'\n\nexport function createWMS(\n source: WmsSource,\n presentation: LayerPresentation,\n capabilities?: string,\n rectangle?: Rectangle,\n): ImageryProvider | null {\n if (!capabilities) {\n return null\n }\n\n const request = parseWmsCaps(capabilities, source.layers, source.version)\n\n if (!request) {\n return null\n }\n\n return new WebMapServiceImageryProvider({\n url: source.href,\n layers: source.layers.join(','),\n parameters: {\n ...source.params,\n format: source.format ?? 'image/png',\n styles: source.styles ?? '',\n version: request.version,\n },\n crs: request.crs,\n srs: request.crs,\n tilingScheme:\n request.projection === 'webMercator'\n ? new WebMercatorTilingScheme()\n : new GeographicTilingScheme(),\n rectangle,\n credit: presentation.copyright,\n })\n}\n","import type { LayerPresentation, WmtsSource } from '@xgis/xgis-common'\nimport {\n fallbackTileTemplate,\n parseWmtsCapabilities,\n stringifyParams,\n withQuery,\n} from '@xgis/xgis-common'\nimport type { ImageryProvider, TilingScheme } from 'cesium'\nimport {\n GeographicTilingScheme,\n Rectangle,\n WebMapTileServiceImageryProvider,\n WebMercatorTilingScheme,\n} from 'cesium'\n\nimport { safeMinimumLevel } from './safeMinimumLevel'\n\nfunction coarsestLevel(\n tilingScheme: TilingScheme,\n rectangle: Rectangle | undefined,\n minimumLevel: number | undefined,\n): number | undefined {\n if (minimumLevel === undefined) {\n return undefined\n }\n\n return safeMinimumLevel(tilingScheme, rectangle ?? tilingScheme.rectangle, minimumLevel)\n}\n\nfunction layerRectangle(\n bbox: [number, number, number, number] | undefined,\n topic: Rectangle | undefined,\n): Rectangle | undefined {\n if (!bbox) {\n return topic\n }\n\n return Rectangle.fromDegrees(...bbox)\n}\n\nexport function createWMTS(\n source: WmtsSource,\n presentation: LayerPresentation,\n capabilitiesText: string,\n rectangle?: Rectangle,\n): ImageryProvider | null {\n const parsed = parseWmtsCapabilities(capabilitiesText, source.layer, source.format)\n\n if (!parsed) {\n return null\n }\n\n const style = source.styles ?? 'default'\n const url = parsed.tileTemplate ?? fallbackTileTemplate(source.href, source.layer, style)\n\n const tilingScheme =\n parsed.tilingScheme === 'geographic'\n ? new GeographicTilingScheme()\n : new WebMercatorTilingScheme()\n\n const extent = layerRectangle(parsed.wgs84BoundingBox, rectangle)\n\n return new WebMapTileServiceImageryProvider({\n url: withQuery(url, stringifyParams(source.params)),\n layer: source.layer,\n style,\n tileMatrixSetID: parsed.tileMatrixSetID,\n dimensions: parsed.dimensions,\n tileMatrixLabels: parsed.tileMatrixLabels.length > 0 ? parsed.tileMatrixLabels : undefined,\n format: source.format,\n tilingScheme,\n maximumLevel: parsed.maximumLevel,\n minimumLevel: coarsestLevel(tilingScheme, extent, parsed.minimumLevel),\n credit: presentation.copyright,\n rectangle: extent,\n })\n}\n","import type { BasemapPlanEntry } from '@xgis/xgis-common'\nimport { ImageryProvider, Rectangle, Viewer as CesiumViewer } from 'cesium'\n\nimport type { Created3DTileset } from './create3DTilesetLayer'\nimport { create3DTileset } from './create3DTilesetLayer'\nimport type { CreatedKml } from './createKMLLayer'\nimport { createKML } from './createKMLLayer'\nimport { createOGCMaps } from './createOGCMapsLayer'\nimport { createOGCTiles } from './createOGCTilesLayer'\nimport { createTMS } from './createTMSLayer'\nimport { createWMS } from './createWMSLayer'\nimport { createWMTS } from './createWMTSLayer'\n\nexport type CesiumBaseLayer =\n | { kind: 'imagery'; provider: ImageryProvider }\n | { kind: 'kml'; kml: Promise<CreatedKml> }\n | { kind: 'tileset'; tileset: Promise<Created3DTileset | null> }\n\nexport function createCesiumBaseLayer(\n entry: BasemapPlanEntry,\n viewer: CesiumViewer,\n rectangle?: Rectangle,\n): CesiumBaseLayer | null {\n const { layer, capabilities, tileset } = entry\n const { source } = layer\n\n switch (source.kind) {\n case 'wms': {\n const provider = createWMS(source, layer, capabilities, rectangle)\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'wmts': {\n if (!capabilities) {\n return null\n }\n\n const provider = createWMTS(source, layer, capabilities, rectangle)\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'ogcMaps': {\n const provider = createOGCMaps(source, layer, capabilities)\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'ogcTiles': {\n const provider = tileset ? createOGCTiles(source, layer, tileset) : null\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'tms': {\n const provider = capabilities ? createTMS(source, layer, capabilities) : null\n return provider ? { kind: 'imagery', provider } : null\n }\n case 'tileset3d':\n return { kind: 'tileset', tileset: create3DTileset(source.tileset) }\n case 'kml':\n return {\n kind: 'kml',\n kml: createKML(source.params, viewer.scene.camera, viewer.scene.canvas),\n }\n default:\n return source satisfies never\n }\n}\n","import type { EpsgCode, MapExtent } from '@xgis/xgis-common'\nimport { Rectangle } from 'cesium'\n\nimport { mapToWgs84 } from '../projection'\n\nexport function topicRectangle(\n bbox: MapExtent | null,\n projection: EpsgCode,\n): Rectangle | undefined {\n if (!bbox) {\n return undefined\n }\n\n const [minX, minY, maxX, maxY] = bbox\n const [west, south] = mapToWgs84(projection, minX, minY)\n const [east, north] = mapToWgs84(projection, maxX, maxY)\n\n return Rectangle.fromDegrees(west, south, east, north)\n}\n","import { toAlpha } from '@xgis/xgis-common'\nimport type {\n ImageryLayer,\n ImageryProvider,\n TileProviderError,\n Viewer as CesiumViewer,\n} from 'cesium'\nimport { useMemo, useRef } from 'react'\n\nimport type { Created3DTileset } from '../utils/create3DTilesetLayer'\nimport { apply3DTilesetOpacity } from '../utils/create3DTilesetLayer'\nimport type { CreatedKml } from '../utils/createKMLLayer'\nimport { applyKmlOpacity } from '../utils/kmlEntityOpacity'\n\nexport interface CesiumBasemapAttachments {\n addImagery: (provider: ImageryProvider) => void\n addTileset: (tileset: Created3DTileset) => void\n addKml: (kml: CreatedKml) => void\n detachAll: () => void\n setOpacity: (opacity: number) => void\n}\n\nfunction errorStatus(error: TileProviderError): number | undefined {\n const cause: unknown = error.error\n\n if (typeof cause !== 'object' || cause === null || !('statusCode' in cause)) {\n return undefined\n }\n\n return typeof cause.statusCode === 'number' ? cause.statusCode : undefined\n}\n\nfunction logImageryErrors(provider: ImageryProvider): void {\n provider.errorEvent.addEventListener((error: TileProviderError) => {\n const status = errorStatus(error)\n\n console.warn(`Base map imagery request failed (${status ?? 'no status'}): ${error.message}`)\n })\n}\n\nexport function useCesiumBasemapAttachments(viewer: CesiumViewer): CesiumBasemapAttachments {\n const imageryRef = useRef<ImageryLayer[]>([])\n const kmlRef = useRef<CreatedKml[]>([])\n const tilesetRef = useRef<Created3DTileset[]>([])\n\n const opacityRef = useRef(100)\n\n return useMemo(\n () => ({\n addImagery(provider: ImageryProvider) {\n logImageryErrors(provider)\n\n const layer = viewer.imageryLayers.addImageryProvider(provider, 0)\n layer.alpha = toAlpha(opacityRef.current)\n imageryRef.current.push(layer)\n viewer.scene.requestRender()\n },\n\n addTileset(tileset: Created3DTileset) {\n tilesetRef.current.push(tileset)\n viewer.scene.primitives.add(tileset.primitive)\n apply3DTilesetOpacity(tileset, toAlpha(opacityRef.current))\n viewer.scene.requestRender()\n },\n\n addKml(kml: CreatedKml) {\n kmlRef.current.push(kml)\n viewer.dataSources.add(kml.dataSource)\n applyKmlOpacity(kml.opacitySlots, toAlpha(opacityRef.current))\n viewer.scene.requestRender()\n },\n\n detachAll() {\n for (const layer of imageryRef.current) {\n viewer.imageryLayers.remove(layer)\n }\n imageryRef.current = []\n\n for (const kml of kmlRef.current) {\n viewer.dataSources.remove(kml.dataSource, true)\n }\n kmlRef.current = []\n\n for (const tileset of tilesetRef.current) {\n viewer.scene.primitives.remove(tileset.primitive)\n }\n tilesetRef.current = []\n },\n\n setOpacity(opacity: number) {\n opacityRef.current = opacity\n\n for (const layer of imageryRef.current) {\n layer.alpha = toAlpha(opacity)\n }\n\n for (const tileset of tilesetRef.current) {\n apply3DTilesetOpacity(tileset, toAlpha(opacity))\n }\n\n // Cesium has no per-DataSource alpha, so a KML basemap fades entity by entity.\n for (const kml of kmlRef.current) {\n applyKmlOpacity(kml.opacitySlots, toAlpha(opacity))\n }\n\n viewer.scene.requestRender()\n },\n }),\n [viewer],\n )\n}\n","import {\n bus,\n translate,\n useActiveBasemapPlan,\n useBasemapStore,\n useMapViewStore,\n useProjectionStore,\n} from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { useEffect, useMemo } from 'react'\n\nimport { createCesiumBaseLayer } from '../utils/layerCreation'\nimport { topicRectangle } from '../utils/topicRectangle'\nimport { useCesiumBasemapAttachments } from './useCesiumBasemapAttachments'\n\nexport function useCesiumBasemapReconciler(viewer: CesiumViewer): void {\n const basemapOpacity = useBasemapStore((s) => s.opacity3d)\n const { entries, ready } = useActiveBasemapPlan('3d')\n const constraintBbox = useMapViewStore((s) => s.constraintBbox)\n const projection = useProjectionStore((s) => s.projection)\n\n const rectangle = useMemo(\n () => topicRectangle(constraintBbox, projection),\n [constraintBbox, projection],\n )\n\n const attachments = useCesiumBasemapAttachments(viewer)\n\n useEffect(() => {\n attachments.setOpacity(basemapOpacity)\n }, [attachments, basemapOpacity])\n\n useEffect(() => {\n if (!ready) {\n return\n }\n\n attachments.detachAll()\n\n let cancelled = false\n\n const attachAsync = <T>(\n load: Promise<T | null>,\n attach: (value: T) => void,\n failure: string,\n toastKey?: string,\n ) => {\n void (async () => {\n try {\n const value = await load\n\n if (!cancelled && value) {\n attach(value)\n }\n } catch (error) {\n console.warn(failure, error)\n\n if (!toastKey || cancelled) {\n return\n }\n\n bus.emit('showToast', { message: translate(toastKey), severity: 'error' })\n }\n })()\n }\n\n for (const entry of entries) {\n const created = createCesiumBaseLayer(entry, viewer, rectangle)\n\n if (!created) {\n continue\n }\n\n if (created.kind === 'imagery') {\n attachments.addImagery(created.provider)\n } else if (created.kind === 'tileset') {\n attachAsync(\n created.tileset,\n attachments.addTileset,\n 'Failed to load 3D tileset basemap',\n 'error.basemap.tileset3dFailed',\n )\n } else {\n attachAsync(created.kml, attachments.addKml, 'Failed to load KML basemap')\n }\n }\n\n return () => {\n cancelled = true\n }\n }, [viewer, attachments, entries, ready, rectangle])\n\n useEffect(() => attachments.detachAll, [attachments])\n}\n","import type { MapExtent } from '@xgis/xgis-common'\nimport { extentCenter, useMapViewStore, useProjectionStore } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { useEffect } from 'react'\n\nimport { sampleTerrainHeight } from '../capabilities/cesiumCamera'\nimport type { EntryView } from '../entryCamera'\nimport { entryTarget, raiseEntryCameraToTerrain } from '../entryCamera'\n\n// Canvas input that means the user has taken over.\nconst TAKEOVER_EVENTS = ['pointerdown', 'wheel'] as const\n\n// How far the shared view's centre may drift before the entry view counts as superseded.\nconst CENTRE_TOLERANCE_METRES = 1\n\n// Distance rather than equality on the store's fields: `fireChange` rounds zoom, wraps rotation and\n// rebuilds the bbox, so none of them compare reliably. Only the centre carries intent.\nfunction viewRecentred(entryBbox: MapExtent, currentBbox: MapExtent): boolean {\n const [entryX, entryY] = extentCenter(entryBbox)\n const [currentX, currentY] = extentCenter(currentBbox)\n\n return Math.hypot(currentX - entryX, currentY - entryY) >= CENTRE_TOLERANCE_METRES\n}\n\n/**\n * Re-places the entry camera against terrain once a provider arrives.\n *\n * `Map3D` has to place it synchronously, before any provider exists, so it stands off from the\n * ellipsoid instead — too close to the ground for the zoom it claims. See ADR 0020.\n */\nexport function useCesiumEntryCamera(viewer: CesiumViewer, view: EntryView): void {\n useEffect(() => {\n // Read once: the entry view is in the projection Map3D mounted with, and a later topic in\n // another projection fits itself.\n const projection = useProjectionStore.getState().projection\n const canvas = viewer.scene.canvas\n let done = false\n let userTookOver = false\n let stopListening = (): void => {}\n\n function noteTakeover(): void {\n userTookOver = true\n }\n\n function finish(): void {\n done = true\n stopListening()\n TAKEOVER_EVENTS.forEach((event) => canvas.removeEventListener(event, noteTakeover))\n }\n\n async function refine(): Promise<void> {\n if (done) {\n return\n }\n\n try {\n const height = await sampleTerrainHeight(\n viewer.terrainProvider,\n entryTarget(viewer, view, projection),\n )\n\n // No terrain yet — keep listening for the provider that brings some.\n if (done || height === undefined) {\n return\n }\n\n if (userTookOver || viewRecentred(view.bbox, useMapViewStore.getState().bbox)) {\n finish()\n return\n }\n\n raiseEntryCameraToTerrain(viewer, entryTarget(viewer, view, projection), height)\n finish()\n } catch (error) {\n // A failed tile request, not an answer. The subscription stays up so a later provider\n // change retries; until then the ellipsoid placement stands — too low, but usable.\n console.error('Failed to sample terrain for the entry camera', error)\n }\n }\n\n TAKEOVER_EVENTS.forEach((event) => canvas.addEventListener(event, noteTakeover))\n\n stopListening = viewer.scene.globe.terrainProviderChanged.addEventListener(() => {\n refine()\n })\n\n // Covers a provider already in place, which will fire no change event.\n refine()\n\n return finish\n }, [viewer, view])\n}\n","import { useTerrainStore } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { CesiumTerrainProvider, EllipsoidTerrainProvider } from 'cesium'\nimport { useEffect } from 'react'\n\nexport function useCesiumTerrainReconciler(viewer: CesiumViewer): void {\n const terrainUrl = useTerrainStore((s) => s.terrainUrl)\n\n useEffect(() => {\n if (!terrainUrl) {\n return\n }\n\n let cancelled = false\n\n async function loadTerrain(url: string) {\n try {\n const provider = await CesiumTerrainProvider.fromUrl(url)\n\n if (!cancelled) {\n viewer.terrainProvider = provider\n }\n } catch (err) {\n console.error('Failed to load terrain provider', err)\n }\n }\n\n loadTerrain(terrainUrl)\n\n return () => {\n cancelled = true\n viewer.terrainProvider = new EllipsoidTerrainProvider()\n }\n }, [viewer, terrainUrl])\n}\n","import type { Radians } from '@xgis/xgis-common'\nimport { Cartesian3, Matrix4, PolygonHierarchy, Transforms } from 'cesium'\n\nconst HALF_SPAN: Radians = (35 * Math.PI) / 180\nconst ARC_SEGMENTS = 16\n\nexport const CONE_SCREEN_RADIUS_PX = 40\n\nconst MIN_RADIUS_METERS = 1\n\nexport function coneRadiusForScreenSize(range: number, fov: number, spanPx: number): number {\n const metersPerPixel = (2 * range * Math.tan(fov / 2)) / spanPx\n return Math.max(MIN_RADIUS_METERS, metersPerPixel * CONE_SCREEN_RADIUS_PX)\n}\n\nexport function coneHierarchy(\n lon: number,\n lat: number,\n heading: Radians,\n radiusMeters: number,\n): PolygonHierarchy {\n const origin = Cartesian3.fromDegrees(lon, lat)\n const enuFrame = Transforms.eastNorthUpToFixedFrame(origin)\n const positions = [origin]\n\n for (let i = 0; i <= ARC_SEGMENTS; i++) {\n const angle = heading - HALF_SPAN + (2 * HALF_SPAN * i) / ARC_SEGMENTS\n const local = new Cartesian3(radiusMeters * Math.sin(angle), radiusMeters * Math.cos(angle), 0)\n positions.push(Matrix4.multiplyByPoint(enuFrame, local, new Cartesian3()))\n }\n\n return new PolygonHierarchy(positions)\n}\n","import { useUserMarkerStore } from '@xgis/xgis-common'\nimport type { Entity, Viewer as CesiumViewer } from 'cesium'\nimport {\n Cartesian3,\n Color,\n ConstantPositionProperty,\n ConstantProperty,\n HeightReference,\n} from 'cesium'\nimport { useEffect, useRef } from 'react'\n\nimport { fovSpanPx } from '../projection'\nimport { coneHierarchy, coneRadiusForScreenSize } from './userMarkerCone'\n\n// Matches cameraScale.ts's own fallback for a non-perspective frustum.\nconst DEFAULT_FOV = Math.PI / 3\n\nexport function useCesiumUserMarker(viewer: CesiumViewer): void {\n const marker = useUserMarkerStore((s) => s.marker)\n const heading = useUserMarkerStore((s) => s.heading)\n const entityRef = useRef<Entity | null>(null)\n const coneEntityRef = useRef<Entity | null>(null)\n const markerRef = useRef(marker)\n const headingRef = useRef(heading)\n markerRef.current = marker\n headingRef.current = heading\n const updateConeRef = useRef<(() => void) | null>(null)\n\n useEffect(() => {\n const entity = viewer.entities.add({\n point: {\n pixelSize: 12,\n color: Color.fromCssColorString('#2563EB'),\n outlineColor: Color.WHITE,\n outlineWidth: 2,\n heightReference: HeightReference.CLAMP_TO_GROUND,\n disableDepthTestDistance: Number.POSITIVE_INFINITY,\n },\n show: false,\n })\n entityRef.current = entity\n\n const coneEntity = viewer.entities.add({\n polygon: {\n material: Color.fromCssColorString('#2563EB').withAlpha(0.35),\n },\n show: false,\n })\n coneEntityRef.current = coneEntity\n\n function updateCone(): void {\n const currentMarker = markerRef.current\n const currentHeading = headingRef.current\n\n if (currentMarker === null || currentHeading === null || !coneEntity.polygon) {\n return\n }\n\n const camera = viewer.camera\n const markerPosition = Cartesian3.fromDegrees(currentMarker.lon, currentMarker.lat)\n const range = Cartesian3.distance(camera.position, markerPosition)\n const frustum = camera.frustum\n const fov = 'fov' in frustum && frustum.fov !== undefined ? frustum.fov : DEFAULT_FOV\n const canvas = viewer.scene.canvas\n const spanPx = fovSpanPx(canvas.clientWidth, canvas.clientHeight)\n\n const radius = coneRadiusForScreenSize(range, fov, spanPx)\n coneEntity.polygon.hierarchy = new ConstantProperty(\n coneHierarchy(currentMarker.lon, currentMarker.lat, currentHeading, radius),\n )\n }\n\n updateConeRef.current = updateCone\n const removeCameraListener = viewer.camera.changed.addEventListener(updateCone)\n\n return () => {\n removeCameraListener()\n viewer.entities.remove(entity)\n viewer.entities.remove(coneEntity)\n entityRef.current = null\n coneEntityRef.current = null\n updateConeRef.current = null\n }\n }, [viewer])\n\n useEffect(() => {\n const entity = entityRef.current\n const coneEntity = coneEntityRef.current\n if (!entity || !coneEntity) {\n return\n }\n\n if (marker === null) {\n entity.show = false\n coneEntity.show = false\n } else {\n entity.position = new ConstantPositionProperty(Cartesian3.fromDegrees(marker.lon, marker.lat))\n entity.show = true\n coneEntity.show = heading !== null\n updateConeRef.current?.()\n }\n\n viewer.scene.requestRender()\n }, [marker, heading, viewer])\n}\n","import { useMapViewStore, useProjectionStore } from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { useEffect } from 'react'\n\nimport { createCameraBoundsGuard } from '../cameraBoundsGuard'\n\n/**\n * Cesium has no extent constraint, so the topic bbox and zoom ceiling are enforced by a per-frame\n * camera guard.\n */\nexport function useCesiumViewBounds(viewer: CesiumViewer): void {\n const constraintBbox = useMapViewStore((s) => s.constraintBbox)\n const zoomCeiling = useMapViewStore((s) => s.zoomCeiling)\n const projection = useProjectionStore((s) => s.projection)\n\n useEffect(() => {\n if (!constraintBbox) {\n return\n }\n\n return createCameraBoundsGuard(viewer, constraintBbox, projection, zoomCeiling)\n }, [viewer, constraintBbox, projection, zoomCeiling])\n}\n","// MF remotes have no HTML of their own — CSS must be imported explicitly.\nimport 'cesium/Build/Cesium/Widgets/widgets.css'\n\nimport type { EpsgCode, IEngineRegistration, IMapEngine } from '@xgis/xgis-common'\nimport {\n MAX_ZOOM,\n MIN_ZOOM,\n RADIANS_TO_DEGREES,\n useMapViewStore,\n useProjectionStore,\n useTranslate,\n} from '@xgis/xgis-common'\nimport type { Viewer as CesiumViewer } from 'cesium'\nimport { Color } from 'cesium'\nimport { useCallback, useEffect, useState } from 'react'\nimport type { CesiumComponentRef } from 'resium'\nimport { Viewer } from 'resium'\n\nimport { rangeForZoom } from './cameraScale'\nimport { createCesiumCameraCapability } from './capabilities/cesiumCamera'\nimport { createCesiumEngineHealth } from './capabilities/cesiumEngineHealth'\nimport { createCesiumViewLimitsCapability } from './capabilities/cesiumViewLimits'\nimport { ensureCesiumBaseUrl } from './cesiumBaseUrl'\nimport type { EntryView } from './entryCamera'\nimport { ELLIPSOID_HEIGHT, entryTarget, placeEntryCamera } from './entryCamera'\nimport { createCanvasPressRelay } from './interactions/canvasPressRelay'\nimport { createCentroidTilt } from './interactions/centroidTilt'\nimport { createCesiumKeyboardHandler } from './interactions/cesiumKeyboardHandler'\nimport { createNadirLimit } from './interactions/nadirLimit'\nimport { metresPerMapUnit } from './projection'\nimport { useCesiumBasemapReconciler } from './reconcilers/useCesiumBasemapReconciler'\nimport { useCesiumEntryCamera } from './reconcilers/useCesiumEntryCamera'\nimport { useCesiumTerrainReconciler } from './reconcilers/useCesiumTerrainReconciler'\nimport { useCesiumUserMarker } from './reconcilers/useCesiumUserMarker'\nimport { useCesiumViewBounds } from './reconcilers/useCesiumViewBounds'\n\nconst currentProjection = (): EpsgCode => useProjectionStore.getState().projection\n\n// Keep camera input deterministic: gestures stop when input stops, without inertial movement.\nconst CAMERA_INERTIA = 0\n\n// Gesture guard only — mapViewStore.setZoom and the camera bounds guard enforce the zoom borders.\n// The topic's zoom ceiling must not go here: Cesium's wheel step shrinks with the distance left to\n// minimumZoomDistance, so a ceiling well above the ground makes zooming crawl towards it. Cesium\n// compares these against the camera's height above the ellipsoid while rangeForZoom yields a slant\n// range, so at a tilt the clamp is loose by 1/sin(-pitch); close enough for a backstop. The scale\n// is taken where the camera stands when the limits are applied, not as it moves.\nfunction applyZoomDistanceLimits(viewer: CesiumViewer, projection: EpsgCode): void {\n const { longitude, latitude } = viewer.camera.positionCartographic\n const metresPerUnit = metresPerMapUnit(\n projection,\n longitude * RADIANS_TO_DEGREES,\n latitude * RADIANS_TO_DEGREES,\n )\n const controller = viewer.scene.screenSpaceCameraController\n\n controller.maximumZoomDistance = rangeForZoom(viewer, MIN_ZOOM, metresPerUnit)\n controller.minimumZoomDistance = rangeForZoom(viewer, MAX_ZOOM, metresPerUnit)\n}\n\n// enableRotate is left alone — it also drives ordinary panning, not just rotation. enableTilt and\n// enableLook both fold a heading change into the same gesture that changes pitch, so a topic that\n// forbids rotating loses tilt along with it — Cesium has no input that changes only one.\nexport function applyRotationPermission(viewer: CesiumViewer, rotationAllowed: boolean): void {\n viewer.scene.screenSpaceCameraController.enableTilt = rotationAllowed\n viewer.scene.screenSpaceCameraController.enableLook = rotationAllowed\n}\n\n// Cesium's destroy() never releases the context itself.\nexport function releaseWebglContext(canvas: HTMLCanvasElement): void {\n const gl = canvas.getContext('webgl2') ?? canvas.getContext('webgl')\n\n gl?.getExtension('WEBGL_lose_context')?.loseContext()\n}\n\nconst MSAA = 1\n\nfunction applyGlobeSettings(viewer: CesiumViewer): void {\n const globe = viewer.scene.globe\n\n globe.baseColor = Color.WHITE\n globe.showGroundAtmosphere = false\n globe.maximumScreenSpaceError = 2.2\n globe.depthTestAgainstTerrain = true\n}\n\ninterface CesiumLayerSyncProps {\n viewer: CesiumViewer\n entry: EntryView\n}\n\n// useCesiumEntryCamera must follow useCesiumTerrainReconciler so the fetch is in flight before it\n// subscribes.\nfunction CesiumLayerSync({ viewer, entry }: CesiumLayerSyncProps) {\n useCesiumBasemapReconciler(viewer)\n useCesiumTerrainReconciler(viewer)\n useCesiumEntryCamera(viewer, entry)\n useCesiumUserMarker(viewer)\n useCesiumViewBounds(viewer)\n return null\n}\n\ninterface Map3DProps {\n onEngineReady: (engine: IMapEngine) => IEngineRegistration\n}\n\nexport function Map3D({ onEngineReady }: Map3DProps) {\n // Cesium builds worker and asset URLs lazily, first doing so when the Viewer below is\n // constructed. Setting the base URL here as well as at module scope keeps that guarantee\n // independent of how a bundler orders this package's own imports, which flattening can change.\n ensureCesiumBaseUrl()\n\n const [cesiumViewer, setCesiumViewer] = useState<CesiumViewer | null>(null)\n const [entry, setEntry] = useState<EntryView | null>(null)\n const rotationAllowed = useMapViewStore((s) => s.rotationAllowed)\n const projection = useProjectionStore((s) => s.projection)\n const t = useTranslate()\n const canvasLabel = t('map.3d.aria')\n\n const onViewerInit = useCallback((ref: CesiumComponentRef<CesiumViewer> | null) => {\n if (!ref?.cesiumElement) {\n return\n }\n\n const viewer = ref.cesiumElement\n const view = useMapViewStore.getState()\n\n // Against the ellipsoid: no terrain provider exists yet. useCesiumEntryCamera re-places it.\n placeEntryCamera(viewer, entryTarget(viewer, view, currentProjection()), ELLIPSOID_HEIGHT)\n\n applyGlobeSettings(viewer)\n applyRotationPermission(viewer, view.rotationAllowed)\n viewer.scene.screenSpaceCameraController.inertiaSpin = CAMERA_INERTIA\n viewer.scene.screenSpaceCameraController.inertiaZoom = CAMERA_INERTIA\n viewer.scene.screenSpaceCameraController.minimumCollisionTerrainHeight =\n Number.POSITIVE_INFINITY\n\n setEntry(view)\n setCesiumViewer(viewer)\n }, [])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n const health = createCesiumEngineHealth(cesiumViewer)\n\n const engine: IMapEngine = {\n type: '3d',\n capabilities: {\n camera: createCesiumCameraCapability(cesiumViewer, currentProjection),\n viewLimits: createCesiumViewLimitsCapability(cesiumViewer),\n },\n destroy() {},\n reportError: health.reportError,\n onError: health.onError,\n }\n\n const { unregister } = onEngineReady(engine)\n\n return () => {\n health.dispose()\n unregister()\n }\n }, [cesiumViewer, onEngineReady])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n const canvas = cesiumViewer.canvas\n\n return () => {\n releaseWebglContext(canvas)\n }\n }, [cesiumViewer])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n return createCesiumKeyboardHandler(cesiumViewer, canvasLabel)\n }, [cesiumViewer, canvasLabel])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n return createCanvasPressRelay(cesiumViewer)\n }, [cesiumViewer])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n return createNadirLimit(cesiumViewer)\n }, [cesiumViewer])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n return createCentroidTilt(cesiumViewer)\n }, [cesiumViewer])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n // The zoom<->range mapping depends on the viewport and, as zoom is in map units, on the topic\n // projection. A window resize or a parallel-view divider drag does not remount this component.\n applyZoomDistanceLimits(cesiumViewer, projection)\n\n const observer = new ResizeObserver(() => applyZoomDistanceLimits(cesiumViewer, projection))\n observer.observe(cesiumViewer.scene.canvas)\n\n return () => {\n observer.disconnect()\n }\n }, [cesiumViewer, projection])\n\n useEffect(() => {\n if (!cesiumViewer) {\n return\n }\n\n applyRotationPermission(cesiumViewer, rotationAllowed)\n }, [cesiumViewer, rotationAllowed])\n\n return (\n <Viewer\n ref={onViewerInit}\n full\n animation={false}\n baseLayerPicker={false}\n fullscreenButton={false}\n geocoder={false}\n homeButton={false}\n infoBox={false}\n sceneModePicker={false}\n selectionIndicator={false}\n timeline={false}\n navigationHelpButton={false}\n baseLayer={false}\n requestRenderMode\n maximumRenderTimeChange={Infinity}\n scene3DOnly\n useBrowserRecommendedResolution={false}\n msaaSamples={MSAA}\n showRenderLoopErrors={false}\n >\n {cesiumViewer && entry && <CesiumLayerSync viewer={cesiumViewer} entry={entry} />}\n </Viewer>\n )\n}\n"],"names":["DEFAULT_FOV","CesiumMath","canvas"],"mappings":";;;;;;;AAWA,MAAM,SAAA,GAAY,sBAAA;AAElB,IAAI,QAAA;AAIJ,SAAS,QAAA,GAAmB;AAC1B,EAAA,OAAO,QAAA,CAAS,cAA+B,CAAA,WAAA,EAAc,SAAS,IAAI,CAAA,EAAG,OAAA,CAAQ,MAAK,IAAK,EAAA;AACjG;AAOO,SAAS,mBAAA,GAA4B;AAG1C,EAAA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,IAAA;AAAA,EACF;AAGA,EAAA,IAAI,aAAa,MAAA,EAAW;AAC1B,IAAA,QAAA,GAAW,QAAA,EAAS,IAAK,CAAA,QAAA,EAAW,SAAkB,CAAA,CAAA;AAAA,EACxD;AAEA,EA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,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,CAAC,YAAA,EAAc;AACjB,MAAA;AAAA,IACF;AAEA,IAAA,uBAAA,CAAwB,cAAc,eAAe,CAAA;AAAA,EACvD,CAAA,EAAG,CAAC,YAAA,EAAc,eAAe,CAAC,CAAA;AAElC,EAAA,uBACE,GAAA;AAAA,IAAC,MAAA;AAAA,IAAA;AAAA,MACC,GAAA,EAAK,YAAA;AAAA,MACL,IAAA,EAAI,IAAA;AAAA,MACJ,SAAA,EAAW,KAAA;AAAA,MACX,eAAA,EAAiB,KAAA;AAAA,MACjB,gBAAA,EAAkB,KAAA;AAAA,MAClB,QAAA,EAAU,KAAA;AAAA,MACV,UAAA,EAAY,KAAA;AAAA,MACZ,OAAA,EAAS,KAAA;AAAA,MACT,eAAA,EAAiB,KAAA;AAAA,MACjB,kBAAA,EAAoB,KAAA;AAAA,MACpB,QAAA,EAAU,KAAA;AAAA,MACV,oBAAA,EAAsB,KAAA;AAAA,MACtB,SAAA,EAAW,KAAA;AAAA,MACX,iBAAA,EAAiB,IAAA;AAAA,MACjB,uBAAA,EAAyB,QAAA;AAAA,MACzB,WAAA,EAAW,IAAA;AAAA,MACX,+BAAA,EAAiC,KAAA;AAAA,MACjC,WAAA,EAAa,IAAA;AAAA,MACb,oBAAA,EAAsB,KAAA;AAAA,MAErB,0BAAgB,KAAA,oBAAS,GAAA,CAAC,eAAA,EAAA,EAAgB,MAAA,EAAQ,cAAc,KAAA,EAAc;AAAA;AAAA,GACjF;AAEJ;;"}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
1
|
import type { Viewer as CesiumViewer } from 'cesium';
|
|
2
|
-
/**
|
|
2
|
+
/**
|
|
3
|
+
* Cesium has no extent constraint, so the topic bbox and zoom ceiling are enforced by a per-frame
|
|
4
|
+
* camera guard.
|
|
5
|
+
*/
|
|
3
6
|
export declare function useCesiumViewBounds(viewer: CesiumViewer): void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { IKmlParams } from '@xgis/xgis-common';
|
|
2
2
|
import type { Camera } from 'cesium';
|
|
3
3
|
import { KmlDataSource } from 'cesium';
|
|
4
4
|
import type { KmlOpacitySlot } from './kmlEntityOpacity';
|
|
@@ -6,4 +6,4 @@ export interface CreatedKml {
|
|
|
6
6
|
dataSource: KmlDataSource;
|
|
7
7
|
opacitySlots: KmlOpacitySlot[];
|
|
8
8
|
}
|
|
9
|
-
export declare function createKML(params:
|
|
9
|
+
export declare function createKML(params: IKmlParams, camera: Camera, canvas: HTMLCanvasElement): Promise<CreatedKml>;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { LayerPresentation, WmsSource } from '@xgis/xgis-common';
|
|
2
|
-
import type { ImageryProvider } from 'cesium';
|
|
3
|
-
export declare function createWMS(source: WmsSource, presentation: LayerPresentation, capabilities?: string): ImageryProvider | null;
|
|
2
|
+
import type { ImageryProvider, Rectangle } from 'cesium';
|
|
3
|
+
export declare function createWMS(source: WmsSource, presentation: LayerPresentation, capabilities?: string, rectangle?: Rectangle): ImageryProvider | null;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { LayerPresentation, WmtsSource } from '@xgis/xgis-common';
|
|
2
2
|
import type { ImageryProvider } from 'cesium';
|
|
3
|
-
|
|
3
|
+
import { Rectangle } from 'cesium';
|
|
4
|
+
export declare function createWMTS(source: WmtsSource, presentation: LayerPresentation, capabilitiesText: string, rectangle?: Rectangle): ImageryProvider | null;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { IKmlParams } from '@xgis/xgis-common';
|
|
2
2
|
import type { EntityCollection } from 'cesium';
|
|
3
3
|
export declare function normaliseKmlEntities(entities: EntityCollection, clampToGround: boolean): void;
|
|
4
|
-
export declare function applyKmlStyle(entities: EntityCollection, params:
|
|
4
|
+
export declare function applyKmlStyle(entities: EntityCollection, params: IKmlParams, clampToGround: boolean): void;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { BasemapPlanEntry } from '@xgis/xgis-common';
|
|
2
|
-
import { ImageryProvider, Viewer as CesiumViewer } from 'cesium';
|
|
2
|
+
import { ImageryProvider, Rectangle, Viewer as CesiumViewer } from 'cesium';
|
|
3
3
|
import type { Created3DTileset } from './create3DTilesetLayer';
|
|
4
4
|
import type { CreatedKml } from './createKMLLayer';
|
|
5
5
|
export type CesiumBaseLayer = {
|
|
@@ -12,4 +12,4 @@ export type CesiumBaseLayer = {
|
|
|
12
12
|
kind: 'tileset';
|
|
13
13
|
tileset: Promise<Created3DTileset | null>;
|
|
14
14
|
};
|
|
15
|
-
export declare function createCesiumBaseLayer(entry: BasemapPlanEntry, viewer: CesiumViewer): CesiumBaseLayer | null;
|
|
15
|
+
export declare function createCesiumBaseLayer(entry: BasemapPlanEntry, viewer: CesiumViewer, rectangle?: Rectangle): CesiumBaseLayer | null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xgis/xgis3d",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "XGIS 3D map engine, built on CesiumJS.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|
|
21
21
|
"react": "^18.3.1 || ^19.0.0",
|
|
22
|
-
"@xgis/xgis-common": "^0.
|
|
22
|
+
"@xgis/xgis-common": "^0.4.1"
|
|
23
23
|
},
|
|
24
24
|
"peerDependenciesMeta": {},
|
|
25
25
|
"dependencies": {
|
|
@@ -35,7 +35,6 @@
|
|
|
35
35
|
"@types/node": "^22.20.1",
|
|
36
36
|
"@types/react": "^19.2.15",
|
|
37
37
|
"@vitejs/plugin-react": "^4.7.0",
|
|
38
|
-
"@vitest/coverage-v8": "^4.1.12",
|
|
39
38
|
"react": "^19.2.6",
|
|
40
39
|
"react-dom": "^19.2.6",
|
|
41
40
|
"typescript": "^6.0.3",
|
|
@@ -44,8 +43,8 @@
|
|
|
44
43
|
"@xgis/eslint-config": "0.0.0",
|
|
45
44
|
"@xgis/tsconfig": "0.0.0",
|
|
46
45
|
"@xgis/vitest-config": "0.0.0",
|
|
47
|
-
"@xgis/
|
|
48
|
-
"@xgis/
|
|
46
|
+
"@xgis/xgis-common": "0.4.1",
|
|
47
|
+
"@xgis/xgis3d-build": "0.4.1"
|
|
49
48
|
},
|
|
50
49
|
"scripts": {
|
|
51
50
|
"dev": "vite --port 4202",
|
|
@@ -54,7 +53,6 @@
|
|
|
54
53
|
"lint": "eslint src",
|
|
55
54
|
"typecheck": "tsc --noEmit",
|
|
56
55
|
"test": "vitest run",
|
|
57
|
-
"test:coverage": "vitest run --coverage",
|
|
58
56
|
"build:lib": "vite build --config vite.lib.config.ts && tsc -p tsconfig.build.json"
|
|
59
57
|
},
|
|
60
58
|
"main": "./dist/index.js",
|