bruce-cesium 7.7.7 → 7.7.9

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.
Files changed (51) hide show
  1. package/dist/bruce-cesium.es5.js +2649 -69
  2. package/dist/bruce-cesium.es5.js.map +1 -1
  3. package/dist/bruce-cesium.umd.js +2628 -66
  4. package/dist/bruce-cesium.umd.js.map +1 -1
  5. package/dist/lib/bruce-cesium.js +6 -1
  6. package/dist/lib/bruce-cesium.js.map +1 -1
  7. package/dist/lib/rendering/entity-render-engine-model3d.js +2 -2
  8. package/dist/lib/rendering/entity-render-engine-model3d.js.map +1 -1
  9. package/dist/lib/rendering/entity-render-engine-polygon.js +5 -4
  10. package/dist/lib/rendering/entity-render-engine-polygon.js.map +1 -1
  11. package/dist/lib/rendering/entity-render-engine-polyline.js +2 -1
  12. package/dist/lib/rendering/entity-render-engine-polyline.js.map +1 -1
  13. package/dist/lib/rendering/render-managers/common/entity-simulation.js +1 -1
  14. package/dist/lib/rendering/render-managers/common/entity-simulation.js.map +1 -1
  15. package/dist/lib/rendering/render-managers/tilesets/tileset-google-photos-render-manager.js +3 -0
  16. package/dist/lib/rendering/render-managers/tilesets/tileset-google-photos-render-manager.js.map +1 -1
  17. package/dist/lib/rendering/tileset-render-engine.js +47 -14
  18. package/dist/lib/rendering/tileset-render-engine.js.map +1 -1
  19. package/dist/lib/rendering/view-render-engine.js +30 -24
  20. package/dist/lib/rendering/view-render-engine.js.map +1 -1
  21. package/dist/lib/rendering/visuals-register.js +93 -8
  22. package/dist/lib/rendering/visuals-register.js.map +1 -1
  23. package/dist/lib/rendering/xgrids-render-engine.js +20 -3
  24. package/dist/lib/rendering/xgrids-render-engine.js.map +1 -1
  25. package/dist/lib/utils/cesium-map-grid.js +807 -0
  26. package/dist/lib/utils/cesium-map-grid.js.map +1 -0
  27. package/dist/lib/utils/device-profile.js +302 -0
  28. package/dist/lib/utils/device-profile.js.map +1 -0
  29. package/dist/lib/utils/gltf-generator.js +307 -0
  30. package/dist/lib/utils/gltf-generator.js.map +1 -0
  31. package/dist/lib/utils/gltf-gizmo.js +136 -0
  32. package/dist/lib/utils/gltf-gizmo.js.map +1 -0
  33. package/dist/lib/utils/view-utils.js +9 -0
  34. package/dist/lib/utils/view-utils.js.map +1 -1
  35. package/dist/lib/viewer/camera-controls.js +899 -0
  36. package/dist/lib/viewer/camera-controls.js.map +1 -0
  37. package/dist/lib/viewer/viewer-utils.js +9 -1
  38. package/dist/lib/viewer/viewer-utils.js.map +1 -1
  39. package/dist/types/bruce-cesium.d.ts +6 -1
  40. package/dist/types/rendering/tileset-render-engine.d.ts +10 -2
  41. package/dist/types/rendering/view-render-engine.d.ts +4 -0
  42. package/dist/types/rendering/visuals-register.d.ts +4 -0
  43. package/dist/types/rendering/xgrids-render-engine.d.ts +2 -0
  44. package/dist/types/utils/cesium-map-grid.d.ts +23 -0
  45. package/dist/types/utils/device-profile.d.ts +84 -0
  46. package/dist/types/utils/gltf-generator.d.ts +104 -0
  47. package/dist/types/utils/gltf-gizmo.d.ts +18 -0
  48. package/dist/types/utils/view-utils.d.ts +4 -0
  49. package/dist/types/viewer/camera-controls.d.ts +27 -0
  50. package/dist/types/viewer/viewer-utils.d.ts +1 -0
  51. package/package.json +3 -2
@@ -907,6 +907,897 @@
907
907
  return true;
908
908
  }
909
909
 
910
+ const CESIUM_CAMERA_CONTROLS_KEY = "_nextspace_camera_controls";
911
+ // How far a wheel notch or its drag equivalent moves the camera, as a share of the distance to what it points at.
912
+ const ZOOM_SHARE = 0.18;
913
+ // The distance a zoom step treats anything closer as, so the camera keeps moving through a surface instead of stalling.
914
+ const MIN_ZOOM_DISTANCE = 4;
915
+ // How far from the origin zooming out may take a model-space camera, beyond which the scene is a dot on a planet.
916
+ const MODEL_SPACE_MAX_RANGE = 250000;
917
+ // Above this height a geospatial scene is a planet, which CesiumJS's own controller navigates better.
918
+ const GEO_HANDOFF_HEIGHT = 15000;
919
+ // The furthest a depth pick is trusted from a camera close to the ground; further up the limit grows with height.
920
+ const PLAUSIBLE_PICK_FLOOR = 1000;
921
+ // Pixels of right drag that make one wheel notch.
922
+ const DRAG_PIXELS_PER_NOTCH = 40;
923
+ // Share of the outstanding wheel movement applied each animation frame.
924
+ const ZOOM_EASE = 0.35;
925
+ // A pan plane seen closer to edge on than this (sine of the angle) is swapped for one facing the camera.
926
+ const GRAZING_SINE = 0.12;
927
+ // Closest the view may get to straight up or down while orbiting, in radians, so the camera never flips over.
928
+ const ORBIT_POLE_MARGIN = Cesium.Math.toRadians(1);
929
+ // How far above the ground a camera coming down from above stops, until pushed on through.
930
+ const GROUND_STANDOFF = 2;
931
+ // Height above the ground within which a descent slows, so the ground is approached rather than hit.
932
+ const GROUND_APPROACH = 10;
933
+ // The slowest a descent gets near the ground, as a share of its usual speed.
934
+ const GROUND_APPROACH_FLOOR = 0.5;
935
+ // How far below the ground a push through it lands, so the camera is clearly under it.
936
+ const GROUND_BREAK_DEPTH = 1.5;
937
+ // Wheel notches of pushing at the ground that take the camera through it, with and without data found below it.
938
+ const PUSH_NOTCHES_DATA_BELOW = 3;
939
+ const PUSH_NOTCHES_NOTHING_BELOW = 10;
940
+ // Pushes further apart than this start counting again.
941
+ const PUSH_WINDOW_MS = 1200;
942
+ // How far below the ground something must reach to count as data underground, in metres.
943
+ const UNDERGROUND_MARGIN = 3;
944
+ // How long a scan of the scene for underground data and stand-in ground is trusted, in milliseconds.
945
+ const SCENE_SCAN_MS = 2000;
946
+ // The most entities one scan looks at, so a large scene is sampled rather than walked each time.
947
+ const SCENE_SCAN_ENTITIES = 3000;
948
+ // Zoom speed, as a share of the usual, toward a point that is a guess (nothing drawn there) or while terrain loads.
949
+ const ZOOM_GUESS_SHARE = 0.5;
950
+ const ZOOM_LOADING_SHARE = 0.7;
951
+ // The highest a camera zooms out to with the globe hidden, which CesiumJS's controller cannot navigate.
952
+ const HIDDEN_GLOBE_MAX_HEIGHT = 10000000;
953
+ // Marks a tileset that stands in for the globe, such as Google's photorealistic tiles.
954
+ const GROUND_TILESET_KEY = "_nextspace_camera_ground";
955
+ var EDrag;
956
+ (function (EDrag) {
957
+ EDrag["Pan"] = "pan";
958
+ EDrag["Orbit"] = "orbit";
959
+ EDrag["Zoom"] = "zoom";
960
+ })(EDrag || (EDrag = {}));
961
+ (function (CameraControls) {
962
+ /**
963
+ * Takes over mouse drag and wheel navigation close to the ground; CesiumJS keeps planet scale, pinch and look.
964
+ */
965
+ function Attach(viewer) {
966
+ var _a, _b, _c;
967
+ if (!viewer || viewer.isDestroyed() || viewer[CESIUM_CAMERA_CONTROLS_KEY]) {
968
+ return;
969
+ }
970
+ const scene = viewer.scene;
971
+ const controller = scene === null || scene === void 0 ? void 0 : scene.screenSpaceCameraController;
972
+ if (!controller || !scene.canvas || !scene.preUpdate) {
973
+ return;
974
+ }
975
+ const state = {
976
+ viewer,
977
+ getModelSpaceFrame: null,
978
+ drag: null,
979
+ touches: new Set(),
980
+ pendingZoom: new Cesium.Cartesian3(),
981
+ zoomFrame: null,
982
+ zoomPosition: null,
983
+ lastDistance: 100,
984
+ push: { notches: 0, at: 0 },
985
+ scan: null,
986
+ undergroundOverride: null,
987
+ saved: {
988
+ rotateEventTypes: controller.rotateEventTypes,
989
+ zoomEventTypes: controller.zoomEventTypes,
990
+ tiltEventTypes: controller.tiltEventTypes,
991
+ enableCollisionDetection: controller.enableCollisionDetection,
992
+ backFaceAlpha: (_b = (_a = scene.globe) === null || _a === void 0 ? void 0 : _a.translucency) === null || _b === void 0 ? void 0 : _b.backFaceAlpha,
993
+ showSkirts: (_c = scene.globe) === null || _c === void 0 ? void 0 : _c.showSkirts
994
+ },
995
+ ours: false,
996
+ removals: []
997
+ };
998
+ viewer[CESIUM_CAMERA_CONTROLS_KEY] = state;
999
+ // The camera may go below the ground; zooming slows near a surface, so it takes a deliberate push.
1000
+ controller.enableCollisionDetection = false;
1001
+ const canvas = scene.canvas;
1002
+ const listen = (target, type, handler, options) => {
1003
+ target.addEventListener(type, handler, options);
1004
+ state.removals.push(() => target.removeEventListener(type, handler, options));
1005
+ };
1006
+ listen(canvas, "pointerdown", (e) => onPointerDown(state, e));
1007
+ listen(window, "pointermove", (e) => onPointerMove(state, e));
1008
+ listen(window, "pointerup", (e) => onPointerUp(state, e));
1009
+ listen(window, "pointercancel", (e) => onPointerUp(state, e));
1010
+ listen(canvas, "wheel", (e) => onWheel(state, e), { passive: true });
1011
+ state.removals.push(scene.preUpdate.addEventListener(() => syncController(state)));
1012
+ syncController(state);
1013
+ scene.requestRender();
1014
+ }
1015
+ CameraControls.Attach = Attach;
1016
+ /**
1017
+ * Hands navigation back to CesiumJS's own camera controller, as it was before Attach.
1018
+ */
1019
+ function Detach(viewer) {
1020
+ const state = viewer === null || viewer === void 0 ? void 0 : viewer[CESIUM_CAMERA_CONTROLS_KEY];
1021
+ if (!state) {
1022
+ return;
1023
+ }
1024
+ SetModelSpace(viewer, null);
1025
+ viewer[CESIUM_CAMERA_CONTROLS_KEY] = null;
1026
+ state.removals.forEach((removal) => removal());
1027
+ state.removals = [];
1028
+ if (state.zoomFrame != null) {
1029
+ cancelAnimationFrame(state.zoomFrame);
1030
+ }
1031
+ if (viewer.isDestroyed()) {
1032
+ return;
1033
+ }
1034
+ restoreCesiumGestures(state);
1035
+ viewer.scene.screenSpaceCameraController.enableCollisionDetection = state.saved.enableCollisionDetection;
1036
+ viewer.scene.requestRender();
1037
+ }
1038
+ CameraControls.Detach = Detach;
1039
+ function IsAttached(viewer) {
1040
+ return Boolean(viewer === null || viewer === void 0 ? void 0 : viewer[CESIUM_CAMERA_CONTROLS_KEY]);
1041
+ }
1042
+ CameraControls.IsAttached = IsAttached;
1043
+ /**
1044
+ * Marks a tileset as standing in for the globe (Google's photorealistic tiles), so the camera treats it as ground.
1045
+ */
1046
+ function SetGroundTileset(tileset, isGround) {
1047
+ if (tileset) {
1048
+ tileset[GROUND_TILESET_KEY] = isGround;
1049
+ }
1050
+ }
1051
+ CameraControls.SetGroundTileset = SetGroundTileset;
1052
+ /**
1053
+ * Says whether the scene has data underground, which makes the ground easier to push through; null scans for it.
1054
+ */
1055
+ function SetUndergroundData(viewer, present) {
1056
+ const state = viewer === null || viewer === void 0 ? void 0 : viewer[CESIUM_CAMERA_CONTROLS_KEY];
1057
+ if (state) {
1058
+ state.undergroundOverride = present;
1059
+ }
1060
+ }
1061
+ CameraControls.SetUndergroundData = SetUndergroundData;
1062
+ /**
1063
+ * Switches to navigating model-space measured from the frame getFrame returns, or back to geospatial with null.
1064
+ */
1065
+ function SetModelSpace(viewer, getFrame) {
1066
+ const state = viewer === null || viewer === void 0 ? void 0 : viewer[CESIUM_CAMERA_CONTROLS_KEY];
1067
+ if (!state || viewer.isDestroyed()) {
1068
+ return;
1069
+ }
1070
+ const wasModelSpace = Boolean(state.getModelSpaceFrame);
1071
+ state.getModelSpaceFrame = getFrame !== null && getFrame !== void 0 ? getFrame : null;
1072
+ syncController(state);
1073
+ if (wasModelSpace === Boolean(getFrame)) {
1074
+ return;
1075
+ }
1076
+ const globe = viewer.scene.globe;
1077
+ const translucency = globe === null || globe === void 0 ? void 0 : globe.translucency;
1078
+ if (getFrame) {
1079
+ // The ground is see-through from below, so what stands on it stays in view underground.
1080
+ if (translucency && typeof translucency.backFaceAlpha === "number") {
1081
+ translucency.backFaceAlpha = 0.5;
1082
+ }
1083
+ // Skirts hide seams flat model-space ground never has, and below it they are walls.
1084
+ if (typeof state.saved.showSkirts === "boolean") {
1085
+ globe.showSkirts = false;
1086
+ }
1087
+ }
1088
+ else {
1089
+ if (translucency && typeof state.saved.backFaceAlpha === "number") {
1090
+ translucency.backFaceAlpha = state.saved.backFaceAlpha;
1091
+ }
1092
+ if (typeof state.saved.showSkirts === "boolean") {
1093
+ globe.showSkirts = state.saved.showSkirts;
1094
+ }
1095
+ }
1096
+ viewer.scene.requestRender();
1097
+ }
1098
+ CameraControls.SetModelSpace = SetModelSpace;
1099
+ })(exports.CameraControls || (exports.CameraControls = {}));
1100
+ function restoreCesiumGestures(state) {
1101
+ const controller = state.viewer.scene.screenSpaceCameraController;
1102
+ controller.rotateEventTypes = state.saved.rotateEventTypes;
1103
+ controller.zoomEventTypes = state.saved.zoomEventTypes;
1104
+ controller.tiltEventTypes = state.saved.tiltEventTypes;
1105
+ }
1106
+ /*
1107
+ * Decides each frame who has the mouse: these controls near the ground, CesiumJS for planets, orthographic and tracking.
1108
+ */
1109
+ function syncController(state) {
1110
+ const viewer = state.viewer;
1111
+ if (viewer.isDestroyed() || state.drag) {
1112
+ return;
1113
+ }
1114
+ const ours = shouldControl(state);
1115
+ if (ours === state.ours) {
1116
+ return;
1117
+ }
1118
+ state.ours = ours;
1119
+ if (ours) {
1120
+ const controller = viewer.scene.screenSpaceCameraController;
1121
+ controller.rotateEventTypes = [];
1122
+ controller.zoomEventTypes = [Cesium.CameraEventType.PINCH];
1123
+ controller.tiltEventTypes = [Cesium.CameraEventType.PINCH];
1124
+ }
1125
+ else {
1126
+ restoreCesiumGestures(state);
1127
+ }
1128
+ }
1129
+ function shouldControl(state) {
1130
+ const viewer = state.viewer;
1131
+ const camera = viewer.camera;
1132
+ if (viewer.scene.mode !== Cesium.SceneMode.SCENE3D || camera.frustum instanceof Cesium.OrthographicFrustum) {
1133
+ return false;
1134
+ }
1135
+ // A camera following something is CesiumJS's to move.
1136
+ if (!Cesium.Matrix4.equals(camera.transform, Cesium.Matrix4.IDENTITY)) {
1137
+ return false;
1138
+ }
1139
+ if (state.getModelSpaceFrame) {
1140
+ return true;
1141
+ }
1142
+ // CesiumJS's controller measures against the globe, so with it hidden these controls keep the camera at any height.
1143
+ if (!globeShown(state)) {
1144
+ return true;
1145
+ }
1146
+ return heightOf(state, camera.positionWC) < GEO_HANDOFF_HEIGHT;
1147
+ }
1148
+ function globeShown(state) {
1149
+ const globe = state.viewer.scene.globe;
1150
+ return Boolean(globe) && globe.show !== false;
1151
+ }
1152
+ /*
1153
+ * The terrain's height at a place from the tiles loaded, undefined with the globe hidden or nothing loaded there.
1154
+ */
1155
+ function terrainHeightAt(state, carto) {
1156
+ const globe = state.viewer.scene.globe;
1157
+ if (!carto || !globeShown(state) || typeof globe.getHeight !== "function") {
1158
+ return undefined;
1159
+ }
1160
+ const height = globe.getHeight(carto);
1161
+ return Number.isFinite(height) ? height : undefined;
1162
+ }
1163
+ function ellipsoidOf(state) {
1164
+ var _a, _b;
1165
+ return (_b = (_a = state.viewer.scene.globe) === null || _a === void 0 ? void 0 : _a.ellipsoid) !== null && _b !== void 0 ? _b : Cesium.Ellipsoid.WGS84;
1166
+ }
1167
+ function heightOf(state, position) {
1168
+ const carto = ellipsoidOf(state).cartesianToCartographic(position);
1169
+ return carto ? carto.height : Number.POSITIVE_INFINITY;
1170
+ }
1171
+ function canvasPosition(viewer, e) {
1172
+ const rect = viewer.scene.canvas.getBoundingClientRect();
1173
+ return new Cesium.Cartesian2(e.clientX - rect.left, e.clientY - rect.top);
1174
+ }
1175
+ /*
1176
+ * Up at a point: the model-space frame's up in model-space, else the ellipsoid's surface normal there.
1177
+ */
1178
+ function upAt(state, position) {
1179
+ if (state.getModelSpaceFrame) {
1180
+ const up = Cesium.Matrix4.multiplyByPointAsVector(state.getModelSpaceFrame(), Cesium.Cartesian3.UNIT_Z, new Cesium.Cartesian3());
1181
+ return Cesium.Cartesian3.normalize(up, up);
1182
+ }
1183
+ return ellipsoidOf(state).geodeticSurfaceNormal(position, new Cesium.Cartesian3());
1184
+ }
1185
+ /*
1186
+ * The level plane standing in for the ground when nothing is drawn under the cursor.
1187
+ */
1188
+ function groundPlane(state) {
1189
+ var _a;
1190
+ if (state.getModelSpaceFrame) {
1191
+ const frame = state.getModelSpaceFrame();
1192
+ return Cesium.Plane.fromPointNormal(Cesium.Matrix4.getTranslation(frame, new Cesium.Cartesian3()), upAt(state, null));
1193
+ }
1194
+ const camera = state.viewer.camera;
1195
+ const ellipsoid = ellipsoidOf(state);
1196
+ const carto = ellipsoid.cartesianToCartographic(camera.positionWC);
1197
+ if (!carto) {
1198
+ return null;
1199
+ }
1200
+ // Level with the terrain under the camera, not sea level, so a guess over high ground is not far too deep.
1201
+ const surface = Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, (_a = terrainHeightAt(state, carto)) !== null && _a !== void 0 ? _a : 0, ellipsoid);
1202
+ return Cesium.Plane.fromPointNormal(surface, ellipsoid.geodeticSurfaceNormal(surface, new Cesium.Cartesian3()));
1203
+ }
1204
+ /*
1205
+ * How far away a depth pick is believable, since below ground the depth buffer can hold the globe's inside.
1206
+ */
1207
+ function plausibleDistance(state) {
1208
+ const camera = state.viewer.camera;
1209
+ if (state.getModelSpaceFrame) {
1210
+ const origin = Cesium.Matrix4.getTranslation(state.getModelSpaceFrame(), new Cesium.Cartesian3());
1211
+ return Math.max(PLAUSIBLE_PICK_FLOOR, Cesium.Cartesian3.distance(camera.positionWC, origin) * 10);
1212
+ }
1213
+ const height = Math.abs(heightOf(state, camera.positionWC) - (Number(state.viewer.scene.globeHeight) || 0));
1214
+ const horizon = Math.sqrt(2 * ellipsoidOf(state).maximumRadius * Math.max(height, 0));
1215
+ return Math.max(PLAUSIBLE_PICK_FLOOR, height * 10, horizon * 1.5);
1216
+ }
1217
+ /*
1218
+ * The point under a screen position: what is drawn there, else the ground plane, else a point at the last distance.
1219
+ */
1220
+ function pickTarget(state, position) {
1221
+ const viewer = state.viewer;
1222
+ const scene = viewer.scene;
1223
+ const camera = viewer.camera;
1224
+ const ray = camera.getPickRay(position);
1225
+ if (!ray) {
1226
+ return null;
1227
+ }
1228
+ let picked;
1229
+ if (scene.pickPositionSupported) {
1230
+ try {
1231
+ picked = scene.pickPosition(position);
1232
+ }
1233
+ catch (e) {
1234
+ picked = null;
1235
+ }
1236
+ }
1237
+ const plausible = plausibleDistance(state);
1238
+ if (isAhead(camera, picked) && Cesium.Cartesian3.distance(picked, camera.positionWC) < plausible) {
1239
+ return { point: picked, source: "pick", ground: isGroundPick(state, position) };
1240
+ }
1241
+ const ground = groundPlane(state);
1242
+ const onGround = ground ? Cesium.IntersectionTests.rayPlane(ray, ground) : null;
1243
+ if (isAhead(camera, onGround) && Cesium.Cartesian3.distance(onGround, camera.positionWC) < plausible) {
1244
+ // The plane stands in for the ground only where there is ground to stand in for.
1245
+ return { point: onGround, source: "plane", ground: !state.getModelSpaceFrame && hasGround(state) };
1246
+ }
1247
+ return { point: Cesium.Ray.getPoint(ray, state.lastDistance), source: "last", ground: false };
1248
+ }
1249
+ /*
1250
+ * Whether what is drawn under a screen position is the ground: the globe, or a tileset standing in for it.
1251
+ */
1252
+ function isGroundPick(state, position) {
1253
+ var _a, _b, _c;
1254
+ if (state.getModelSpaceFrame) {
1255
+ return false;
1256
+ }
1257
+ const scene = state.viewer.scene;
1258
+ let picked;
1259
+ try {
1260
+ picked = typeof scene.pick === "function" ? scene.pick(position) : undefined;
1261
+ }
1262
+ catch (e) {
1263
+ picked = undefined;
1264
+ }
1265
+ if (!picked) {
1266
+ // Nothing pickable means the globe, when it is drawn.
1267
+ return globeShown(state);
1268
+ }
1269
+ const tileset = (_b = (_a = picked.tileset) !== null && _a !== void 0 ? _a : picked.primitive) !== null && _b !== void 0 ? _b : (_c = picked.content) === null || _c === void 0 ? void 0 : _c.tileset;
1270
+ return Boolean(tileset === null || tileset === void 0 ? void 0 : tileset[GROUND_TILESET_KEY]);
1271
+ }
1272
+ /*
1273
+ * Whether there is ground to come down onto: the globe drawn, or a tileset standing in for it.
1274
+ */
1275
+ function hasGround(state) {
1276
+ return globeShown(state) || scanScene(state).groundTileset;
1277
+ }
1278
+ function isAhead(camera, point) {
1279
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y) || !Number.isFinite(point.z)) {
1280
+ return false;
1281
+ }
1282
+ const toPoint = Cesium.Cartesian3.subtract(point, camera.positionWC, new Cesium.Cartesian3());
1283
+ return Cesium.Cartesian3.dot(toPoint, camera.directionWC) > 0;
1284
+ }
1285
+ /*
1286
+ * Picks which gesture a button and its modifiers start, matching CesiumJS's own mapping.
1287
+ */
1288
+ function dragKind(e) {
1289
+ if (e.shiftKey) {
1290
+ // Shift drag looks around, which CesiumJS still handles.
1291
+ return null;
1292
+ }
1293
+ if (e.button === 1 || (e.ctrlKey && (e.button === 0 || e.button === 2))) {
1294
+ return EDrag.Orbit;
1295
+ }
1296
+ if (e.button === 0) {
1297
+ return EDrag.Pan;
1298
+ }
1299
+ if (e.button === 2) {
1300
+ return EDrag.Zoom;
1301
+ }
1302
+ return null;
1303
+ }
1304
+ function allows(state, kind) {
1305
+ const controller = state.viewer.scene.screenSpaceCameraController;
1306
+ if (!controller.enableInputs) {
1307
+ return false;
1308
+ }
1309
+ switch (kind) {
1310
+ case EDrag.Pan:
1311
+ return controller.enableRotate;
1312
+ case EDrag.Orbit:
1313
+ return controller.enableTilt;
1314
+ case EDrag.Zoom:
1315
+ return controller.enableZoom;
1316
+ }
1317
+ return false;
1318
+ }
1319
+ function onPointerDown(state, e) {
1320
+ const viewer = state.viewer;
1321
+ if (viewer.isDestroyed() || !state.ours) {
1322
+ return;
1323
+ }
1324
+ if (e.pointerType === "touch") {
1325
+ state.touches.add(e.pointerId);
1326
+ // A second finger makes it a pinch, which CesiumJS handles.
1327
+ if (state.touches.size > 1) {
1328
+ endDrag(state);
1329
+ return;
1330
+ }
1331
+ }
1332
+ const kind = dragKind(e);
1333
+ if (!kind || !allows(state, kind)) {
1334
+ return;
1335
+ }
1336
+ const position = canvasPosition(viewer, e);
1337
+ const picked = pickTarget(state, position);
1338
+ if (!picked) {
1339
+ return;
1340
+ }
1341
+ const target = picked.point;
1342
+ const camera = viewer.camera;
1343
+ const distance = Cesium.Cartesian3.distance(camera.positionWC, target);
1344
+ state.lastDistance = Math.max(distance, MIN_ZOOM_DISTANCE);
1345
+ const drag = { kind, pointerId: e.pointerId, last: position, target, up: upAt(state, target), distance, picked };
1346
+ if (kind === EDrag.Pan) {
1347
+ drag.plane = panPlane(camera, target, drag.up);
1348
+ }
1349
+ else if (kind === EDrag.Zoom) {
1350
+ drag.direction = Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(target, camera.positionWC, new Cesium.Cartesian3()), new Cesium.Cartesian3());
1351
+ }
1352
+ state.drag = drag;
1353
+ }
1354
+ /*
1355
+ * A level plane through the grabbed point, or one facing the camera when the level one is seen edge on.
1356
+ */
1357
+ function panPlane(camera, target, up) {
1358
+ if (Math.abs(Cesium.Cartesian3.dot(camera.directionWC, up)) > GRAZING_SINE) {
1359
+ return Cesium.Plane.fromPointNormal(target, up);
1360
+ }
1361
+ return Cesium.Plane.fromPointNormal(target, Cesium.Cartesian3.negate(camera.directionWC, new Cesium.Cartesian3()));
1362
+ }
1363
+ function onPointerMove(state, e) {
1364
+ const drag = state.drag;
1365
+ const viewer = state.viewer;
1366
+ if (!drag || drag.pointerId !== e.pointerId || viewer.isDestroyed()) {
1367
+ return;
1368
+ }
1369
+ if (!allows(state, drag.kind)) {
1370
+ endDrag(state);
1371
+ return;
1372
+ }
1373
+ const position = canvasPosition(viewer, e);
1374
+ const dx = position.x - drag.last.x;
1375
+ const dy = position.y - drag.last.y;
1376
+ if (dx === 0 && dy === 0) {
1377
+ return;
1378
+ }
1379
+ switch (drag.kind) {
1380
+ case EDrag.Pan:
1381
+ pan(state, drag, position);
1382
+ break;
1383
+ case EDrag.Orbit:
1384
+ orbit(state, drag, dx, dy);
1385
+ break;
1386
+ case EDrag.Zoom:
1387
+ // Dragging down zooms in, as it does in CesiumJS.
1388
+ moveAlong(state, drag.direction, drag.picked, dy / DRAG_PIXELS_PER_NOTCH);
1389
+ break;
1390
+ }
1391
+ drag.last = position;
1392
+ viewer.scene.requestRender();
1393
+ }
1394
+ function onPointerUp(state, e) {
1395
+ var _a;
1396
+ state.touches.delete(e.pointerId);
1397
+ if (((_a = state.drag) === null || _a === void 0 ? void 0 : _a.pointerId) === e.pointerId) {
1398
+ endDrag(state);
1399
+ }
1400
+ }
1401
+ function endDrag(state) {
1402
+ state.drag = null;
1403
+ }
1404
+ /*
1405
+ * Slides the camera so the grabbed point stays under the cursor.
1406
+ */
1407
+ function pan(state, drag, position) {
1408
+ const camera = state.viewer.camera;
1409
+ const ray = camera.getPickRay(position);
1410
+ const hit = ray ? Cesium.IntersectionTests.rayPlane(ray, drag.plane) : null;
1411
+ if (!isAhead(camera, hit)) {
1412
+ return;
1413
+ }
1414
+ const delta = Cesium.Cartesian3.subtract(drag.target, hit, new Cesium.Cartesian3());
1415
+ // Near the horizon a pixel covers kilometres, so one move is capped at a few times the grab distance.
1416
+ const limit = Math.max(drag.distance, MIN_ZOOM_DISTANCE) * 3;
1417
+ const length = Cesium.Cartesian3.magnitude(delta);
1418
+ if (length > limit) {
1419
+ Cesium.Cartesian3.multiplyByScalar(delta, limit / length, delta);
1420
+ }
1421
+ // A pan never takes a camera above the ground down through it; it keeps the sideways part of the move.
1422
+ if (wouldSinkBelowGround(state, camera.position, delta)) {
1423
+ const up = upAt(state, camera.position);
1424
+ const down = Cesium.Cartesian3.dot(delta, up);
1425
+ if (down < 0) {
1426
+ Cesium.Cartesian3.subtract(delta, Cesium.Cartesian3.multiplyByScalar(up, down, new Cesium.Cartesian3()), delta);
1427
+ }
1428
+ }
1429
+ Cesium.Cartesian3.add(camera.position, delta, camera.position);
1430
+ }
1431
+ /*
1432
+ * Turns the camera around the grabbed point: sideways about up there, and up or down about the camera's right.
1433
+ */
1434
+ function orbit(state, drag, dx, dy) {
1435
+ const viewer = state.viewer;
1436
+ const camera = viewer.camera;
1437
+ const canvas = viewer.scene.canvas;
1438
+ const up = drag.up;
1439
+ const heading = -dx / Math.max(canvas.clientWidth, 1) * Math.PI * 2;
1440
+ // Dragging down looks further down, as CesiumJS's own tilt does.
1441
+ let pitch = -dy / Math.max(canvas.clientHeight, 1) * Math.PI;
1442
+ // Keeps the view from tipping past straight up or down, where it would flip over.
1443
+ const elevation = Math.asin(Cesium.Math.clamp(Cesium.Cartesian3.dot(camera.direction, up), -1, 1));
1444
+ const limit = Math.PI / 2 - ORBIT_POLE_MARGIN;
1445
+ pitch = Cesium.Math.clamp(elevation + pitch, -limit, limit) - elevation;
1446
+ rotateAbout(camera, drag.target, up, heading);
1447
+ const right = Cesium.Cartesian3.cross(camera.direction, up, new Cesium.Cartesian3());
1448
+ if (Cesium.Cartesian3.magnitude(right) > Cesium.Math.EPSILON6) {
1449
+ Cesium.Cartesian3.normalize(right, right);
1450
+ const before = Cesium.Cartesian3.clone(camera.position);
1451
+ rotateAbout(camera, drag.target, right, pitch);
1452
+ // Orbiting does not swing a camera above the ground down through it; the tilt that would is undone.
1453
+ const moved = Cesium.Cartesian3.subtract(camera.position, before, new Cesium.Cartesian3());
1454
+ if (wouldSinkBelowGround(state, before, moved)) {
1455
+ rotateAbout(camera, drag.target, right, -pitch);
1456
+ }
1457
+ }
1458
+ levelCamera(camera, upAt(state, camera.position));
1459
+ }
1460
+ function rotateAbout(camera, pivot, axis, angle) {
1461
+ if (!angle) {
1462
+ return;
1463
+ }
1464
+ const rotation = Cesium.Matrix3.fromQuaternion(Cesium.Quaternion.fromAxisAngle(axis, angle));
1465
+ const offset = Cesium.Cartesian3.subtract(camera.position, pivot, new Cesium.Cartesian3());
1466
+ Cesium.Matrix3.multiplyByVector(rotation, offset, offset);
1467
+ Cesium.Cartesian3.add(pivot, offset, camera.position);
1468
+ Cesium.Matrix3.multiplyByVector(rotation, camera.direction, camera.direction);
1469
+ Cesium.Matrix3.multiplyByVector(rotation, camera.up, camera.up);
1470
+ Cesium.Matrix3.multiplyByVector(rotation, camera.right, camera.right);
1471
+ }
1472
+ /*
1473
+ * Takes any roll out, so the horizon stays level however the camera has turned.
1474
+ */
1475
+ function levelCamera(camera, up) {
1476
+ const direction = Cesium.Cartesian3.normalize(camera.direction, camera.direction);
1477
+ const right = Cesium.Cartesian3.cross(direction, up, new Cesium.Cartesian3());
1478
+ if (Cesium.Cartesian3.magnitude(right) < Cesium.Math.EPSILON6) {
1479
+ return;
1480
+ }
1481
+ Cesium.Cartesian3.normalize(right, camera.right);
1482
+ Cesium.Cartesian3.cross(camera.right, direction, camera.up);
1483
+ Cesium.Cartesian3.normalize(camera.up, camera.up);
1484
+ }
1485
+ function onWheel(state, e) {
1486
+ const viewer = state.viewer;
1487
+ if (viewer.isDestroyed() || !state.ours || !allows(state, EDrag.Zoom)) {
1488
+ return;
1489
+ }
1490
+ let notches = e.deltaMode === 1 ? e.deltaY / 3 : e.deltaMode === 2 ? e.deltaY : e.deltaY / 100;
1491
+ notches = Cesium.Math.clamp(-notches, -3, 3);
1492
+ if (!notches) {
1493
+ return;
1494
+ }
1495
+ const position = canvasPosition(viewer, e);
1496
+ const camera = viewer.camera;
1497
+ const target = pickTarget(state, position);
1498
+ const ray = camera.getPickRay(position);
1499
+ if (!target || !ray) {
1500
+ return;
1501
+ }
1502
+ const step = zoomStep(state, ray.direction, target, notches);
1503
+ Cesium.Cartesian3.add(state.pendingZoom, step, state.pendingZoom);
1504
+ state.zoomPosition = Cesium.Cartesian3.clone(camera.position);
1505
+ if (state.zoomFrame == null) {
1506
+ state.zoomFrame = requestAnimationFrame(() => easeZoom(state));
1507
+ }
1508
+ }
1509
+ /*
1510
+ * Applies part of the outstanding wheel movement each frame, so a notch glides rather than jumps.
1511
+ */
1512
+ function easeZoom(state) {
1513
+ state.zoomFrame = null;
1514
+ const viewer = state.viewer;
1515
+ if (viewer.isDestroyed() || !viewer[CESIUM_CAMERA_CONTROLS_KEY]) {
1516
+ return;
1517
+ }
1518
+ // A tool locking the camera mid glide (walkthrough, a camera lock) owns it from then on.
1519
+ if (!allows(state, EDrag.Zoom) ||
1520
+ !state.zoomPosition ||
1521
+ !Cesium.Cartesian3.equalsEpsilon(viewer.camera.position, state.zoomPosition, 0, 1e-3)) {
1522
+ state.pendingZoom = new Cesium.Cartesian3();
1523
+ return;
1524
+ }
1525
+ const remaining = Cesium.Cartesian3.magnitude(state.pendingZoom);
1526
+ const share = remaining < 0.01 ? 1 : ZOOM_EASE;
1527
+ const step = Cesium.Cartesian3.multiplyByScalar(state.pendingZoom, share, new Cesium.Cartesian3());
1528
+ Cesium.Cartesian3.subtract(state.pendingZoom, step, state.pendingZoom);
1529
+ Cesium.Cartesian3.add(viewer.camera.position, step, viewer.camera.position);
1530
+ state.zoomPosition = Cesium.Cartesian3.clone(viewer.camera.position);
1531
+ viewer.scene.requestRender();
1532
+ if (share < 1) {
1533
+ state.zoomFrame = requestAnimationFrame(() => easeZoom(state));
1534
+ }
1535
+ }
1536
+ function moveAlong(state, direction, target, notches) {
1537
+ const step = zoomStep(state, direction, target, notches);
1538
+ Cesium.Cartesian3.add(state.viewer.camera.position, step, state.viewer.camera.position);
1539
+ }
1540
+ /*
1541
+ * The move for some notches toward a target along a direction, a share of the distance with a floor so it never stalls.
1542
+ */
1543
+ function zoomStep(state, direction, picked, notches) {
1544
+ const camera = state.viewer.camera;
1545
+ const target = picked.point;
1546
+ // Where the camera will be once the glide already under way ends, which this step continues from.
1547
+ const from = Cesium.Cartesian3.add(camera.positionWC, state.pendingZoom, new Cesium.Cartesian3());
1548
+ const distance = Math.max(Cesium.Cartesian3.distance(from, target), MIN_ZOOM_DISTANCE);
1549
+ state.lastDistance = distance;
1550
+ let length = distance * ZOOM_SHARE * notches * zoomSpeedShare(state, picked);
1551
+ // A geospatial camera zooming out hands over to CesiumJS once it is high enough, so only model-space is capped.
1552
+ if (length < 0 && state.getModelSpaceFrame) {
1553
+ const origin = Cesium.Matrix4.getTranslation(state.getModelSpaceFrame(), new Cesium.Cartesian3());
1554
+ const range = Cesium.Cartesian3.distance(from, origin);
1555
+ length = Math.max(length, range - MODEL_SPACE_MAX_RANGE);
1556
+ if (length >= 0) {
1557
+ return new Cesium.Cartesian3();
1558
+ }
1559
+ }
1560
+ const unit = Cesium.Cartesian3.normalize(direction, new Cesium.Cartesian3());
1561
+ // With the globe hidden there is no hand-over, so zooming out stops where the Earth is a dot.
1562
+ if (length < 0 && !state.getModelSpaceFrame && !globeShown(state)) {
1563
+ const rise = -Cesium.Cartesian3.dot(unit, upAt(state, from));
1564
+ const headroom = HIDDEN_GLOBE_MAX_HEIGHT - heightOf(state, from);
1565
+ if (rise > 0) {
1566
+ length = Math.max(length, -Math.max(headroom, 0) / rise);
1567
+ }
1568
+ if (length >= 0) {
1569
+ return new Cesium.Cartesian3();
1570
+ }
1571
+ }
1572
+ const step = Cesium.Cartesian3.multiplyByScalar(unit, length, new Cesium.Cartesian3());
1573
+ return length > 0 ? resistDescent(state, from, step, picked, notches) : step;
1574
+ }
1575
+ /*
1576
+ * How fast to zoom toward a target: slower toward a guess, or while the terrain that would give a real one loads.
1577
+ */
1578
+ function zoomSpeedShare(state, picked) {
1579
+ let share = 1;
1580
+ if (picked.source !== "pick") {
1581
+ share *= ZOOM_GUESS_SHARE;
1582
+ }
1583
+ const globe = state.viewer.scene.globe;
1584
+ if (!state.getModelSpaceFrame && globeShown(state) && globe.tilesLoaded === false) {
1585
+ share *= ZOOM_LOADING_SHARE;
1586
+ }
1587
+ return share;
1588
+ }
1589
+ /*
1590
+ * The ground a move comes down onto: the ground picked, else the terrain under where the move ends; null for none.
1591
+ */
1592
+ function groundUnderMove(state, from, step, picked) {
1593
+ var _a, _b;
1594
+ if (state.getModelSpaceFrame || !hasGround(state)) {
1595
+ return null;
1596
+ }
1597
+ if (picked === null || picked === void 0 ? void 0 : picked.ground) {
1598
+ return { point: picked.point, up: upAt(state, picked.point) };
1599
+ }
1600
+ if (!globeShown(state)) {
1601
+ return null;
1602
+ }
1603
+ const ellipsoid = ellipsoidOf(state);
1604
+ const end = Cesium.Cartesian3.add(from, step, new Cesium.Cartesian3());
1605
+ const carto = ellipsoid.cartesianToCartographic(end);
1606
+ if (!carto) {
1607
+ return null;
1608
+ }
1609
+ const height = (_b = (_a = terrainHeightAt(state, carto)) !== null && _a !== void 0 ? _a : terrainHeightAt(state, ellipsoid.cartesianToCartographic(from))) !== null && _b !== void 0 ? _b : 0;
1610
+ const point = Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude, height, ellipsoid);
1611
+ return { point, up: ellipsoid.geodeticSurfaceNormal(point, new Cesium.Cartesian3()) };
1612
+ }
1613
+ /*
1614
+ * Whether a move takes a camera that is above the ground to within the stand-off of it or below.
1615
+ */
1616
+ function wouldSinkBelowGround(state, from, step) {
1617
+ const ground = groundUnderMove(state, from, step, null);
1618
+ if (!ground) {
1619
+ return false;
1620
+ }
1621
+ const before = Cesium.Cartesian3.dot(Cesium.Cartesian3.subtract(from, ground.point, new Cesium.Cartesian3()), ground.up);
1622
+ const after = before + Cesium.Cartesian3.dot(step, ground.up);
1623
+ return before > 0 && after < Math.min(GROUND_STANDOFF, before);
1624
+ }
1625
+ /*
1626
+ * Slows a camera coming down from above as it nears the ground and stops it just above, until pushed on enough to
1627
+ * pass through; harder when nothing is known to be underground. A camera already below the ground moves freely.
1628
+ */
1629
+ function resistDescent(state, from, step, picked, notches) {
1630
+ const ground = groundUnderMove(state, from, step, picked);
1631
+ const length = Cesium.Cartesian3.magnitude(step);
1632
+ if (!ground || length === 0) {
1633
+ return step;
1634
+ }
1635
+ const above = Cesium.Cartesian3.dot(Cesium.Cartesian3.subtract(from, ground.point, new Cesium.Cartesian3()), ground.up);
1636
+ const unit = Cesium.Cartesian3.divideByScalar(step, length, new Cesium.Cartesian3());
1637
+ const sink = -Cesium.Cartesian3.dot(unit, ground.up);
1638
+ if (above <= 0 || sink <= 0) {
1639
+ return step;
1640
+ }
1641
+ let allowed = length;
1642
+ if (above < GROUND_APPROACH) {
1643
+ allowed *= Math.max(above / GROUND_APPROACH, GROUND_APPROACH_FLOOR);
1644
+ }
1645
+ const toStandOff = Math.max(above - GROUND_STANDOFF, 0) / sink;
1646
+ if (allowed <= toStandOff) {
1647
+ return Cesium.Cartesian3.multiplyByScalar(unit, allowed, new Cesium.Cartesian3());
1648
+ }
1649
+ // Held at the stand-off: each push counts, and enough close together go through.
1650
+ const now = Date.now();
1651
+ if (now - state.push.at > PUSH_WINDOW_MS) {
1652
+ state.push.notches = 0;
1653
+ }
1654
+ state.push.at = now;
1655
+ state.push.notches += Math.abs(notches);
1656
+ const needed = scanScene(state).undergroundData ? PUSH_NOTCHES_DATA_BELOW : PUSH_NOTCHES_NOTHING_BELOW;
1657
+ if (state.push.notches >= needed) {
1658
+ state.push.notches = 0;
1659
+ // A shallow push would land far along the ground to get under it, so it goes no further than a usual step.
1660
+ const through = Math.min((above + GROUND_BREAK_DEPTH) / sink, Math.max(length, (above + GROUND_BREAK_DEPTH) * 4));
1661
+ return Cesium.Cartesian3.multiplyByScalar(unit, through, new Cesium.Cartesian3());
1662
+ }
1663
+ return Cesium.Cartesian3.multiplyByScalar(unit, toStandOff, new Cesium.Cartesian3());
1664
+ }
1665
+ /*
1666
+ * What the scene holds that the camera cares about, rescanned at most every couple of seconds.
1667
+ */
1668
+ function scanScene(state) {
1669
+ var _a, _b;
1670
+ const now = Date.now();
1671
+ if (state.scan && now - state.scan.at < SCENE_SCAN_MS) {
1672
+ return applyOverride(state, state.scan);
1673
+ }
1674
+ const scene = state.viewer.scene;
1675
+ const found = { at: now, undergroundData: false, groundTileset: false };
1676
+ // Seeing through the ground is turned on to look at what is under it.
1677
+ if ((_b = (_a = scene.globe) === null || _a === void 0 ? void 0 : _a.translucency) === null || _b === void 0 ? void 0 : _b.enabled) {
1678
+ found.undergroundData = true;
1679
+ }
1680
+ const visit = (primitive) => {
1681
+ if (!primitive || primitive.show === false || (primitive.isDestroyed && primitive.isDestroyed())) {
1682
+ return;
1683
+ }
1684
+ if (typeof primitive.length === "number" && typeof primitive.get === "function") {
1685
+ for (let i = 0; i < primitive.length; i++) {
1686
+ visit(primitive.get(i));
1687
+ }
1688
+ return;
1689
+ }
1690
+ if (primitive[GROUND_TILESET_KEY]) {
1691
+ found.groundTileset = true;
1692
+ return;
1693
+ }
1694
+ if (!found.undergroundData && reachesBelowGround(state, lowestPointOf(primitive))) {
1695
+ found.undergroundData = true;
1696
+ }
1697
+ };
1698
+ visit(scene.primitives);
1699
+ if (!found.undergroundData) {
1700
+ found.undergroundData = entitiesBelowGround(state);
1701
+ }
1702
+ state.scan = found;
1703
+ return applyOverride(state, found);
1704
+ }
1705
+ function applyOverride(state, found) {
1706
+ return state.undergroundOverride == null ? found : { ...found, undergroundData: state.undergroundOverride };
1707
+ }
1708
+ /*
1709
+ * The lowest point of a tileset or model: its root box's lowest corner, or its bounding sphere's centre.
1710
+ */
1711
+ function lowestPointOf(primitive) {
1712
+ var _a, _b, _c;
1713
+ const volume = (_a = primitive === null || primitive === void 0 ? void 0 : primitive.root) === null || _a === void 0 ? void 0 : _a.boundingVolume;
1714
+ if (volume) {
1715
+ const region = Number.isFinite(volume.minimumHeight) && volume.rectangle;
1716
+ if (region) {
1717
+ return Cesium.Cartesian3.fromRadians(Cesium.Rectangle.center(volume.rectangle).longitude, Cesium.Rectangle.center(volume.rectangle).latitude, volume.minimumHeight);
1718
+ }
1719
+ const box = volume.boundingVolume;
1720
+ const corners = box instanceof Cesium.OrientedBoundingBox && typeof Cesium.OrientedBoundingBox.computeCorners === "function" ? Cesium.OrientedBoundingBox.computeCorners(box) : null;
1721
+ if (corners === null || corners === void 0 ? void 0 : corners.length) {
1722
+ return lowestOf(corners);
1723
+ }
1724
+ }
1725
+ // A sphere's centre, as its radius reaches below the ground for anything standing on it.
1726
+ return (_c = (_b = primitive === null || primitive === void 0 ? void 0 : primitive.boundingSphere) === null || _b === void 0 ? void 0 : _b.center) !== null && _c !== void 0 ? _c : null;
1727
+ }
1728
+ function lowestOf(points) {
1729
+ var _a, _b;
1730
+ let lowest = null;
1731
+ let lowestHeight = Number.POSITIVE_INFINITY;
1732
+ for (const point of points) {
1733
+ const height = (_b = (_a = Cesium.Cartographic.fromCartesian(point)) === null || _a === void 0 ? void 0 : _a.height) !== null && _b !== void 0 ? _b : Number.POSITIVE_INFINITY;
1734
+ if (height < lowestHeight) {
1735
+ lowestHeight = height;
1736
+ lowest = point;
1737
+ }
1738
+ }
1739
+ return lowest;
1740
+ }
1741
+ /*
1742
+ * Whether a point is clearly below the ground at its place: the terrain there, else sea level.
1743
+ */
1744
+ function reachesBelowGround(state, point) {
1745
+ var _a;
1746
+ if (!point) {
1747
+ return false;
1748
+ }
1749
+ const carto = ellipsoidOf(state).cartesianToCartographic(point);
1750
+ if (!carto) {
1751
+ return false;
1752
+ }
1753
+ return carto.height < ((_a = terrainHeightAt(state, carto)) !== null && _a !== void 0 ? _a : 0) - UNDERGROUND_MARGIN;
1754
+ }
1755
+ /*
1756
+ * Whether any of the first entities sits clearly below the ground: a point, or a line's first or last vertex.
1757
+ */
1758
+ function entitiesBelowGround(state) {
1759
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
1760
+ const viewer = state.viewer;
1761
+ const collections = [viewer.entities];
1762
+ const sources = viewer.dataSources;
1763
+ for (let i = 0; i < ((_a = sources === null || sources === void 0 ? void 0 : sources.length) !== null && _a !== void 0 ? _a : 0); i++) {
1764
+ collections.push((_b = sources.get(i)) === null || _b === void 0 ? void 0 : _b.entities);
1765
+ }
1766
+ const time = (_d = (_c = viewer.clock) === null || _c === void 0 ? void 0 : _c.currentTime) !== null && _d !== void 0 ? _d : Cesium.JulianDate.now();
1767
+ let seen = 0;
1768
+ for (const collection of collections) {
1769
+ for (const entity of (_e = collection === null || collection === void 0 ? void 0 : collection.values) !== null && _e !== void 0 ? _e : []) {
1770
+ if (seen++ >= SCENE_SCAN_ENTITIES) {
1771
+ return false;
1772
+ }
1773
+ if (!entity || entity.show === false) {
1774
+ continue;
1775
+ }
1776
+ const graphic = (_j = (_h = (_g = (_f = entity.model) !== null && _f !== void 0 ? _f : entity.point) !== null && _g !== void 0 ? _g : entity.billboard) !== null && _h !== void 0 ? _h : entity.box) !== null && _j !== void 0 ? _j : entity.cylinder;
1777
+ const reference = (_l = (_k = graphic === null || graphic === void 0 ? void 0 : graphic.heightReference) === null || _k === void 0 ? void 0 : _k.getValue) === null || _l === void 0 ? void 0 : _l.call(_k, time);
1778
+ if (reference === Cesium.HeightReference.CLAMP_TO_GROUND) {
1779
+ continue;
1780
+ }
1781
+ const position = (_o = (_m = entity.position) === null || _m === void 0 ? void 0 : _m.getValue) === null || _o === void 0 ? void 0 : _o.call(_m, time);
1782
+ if (position) {
1783
+ const relative = reference === Cesium.HeightReference.RELATIVE_TO_GROUND;
1784
+ const height = relative ? (_p = ellipsoidOf(state).cartesianToCartographic(position)) === null || _p === void 0 ? void 0 : _p.height : null;
1785
+ if (relative ? height < -UNDERGROUND_MARGIN : reachesBelowGround(state, position)) {
1786
+ return true;
1787
+ }
1788
+ }
1789
+ const line = entity.polyline;
1790
+ if (line && !((_r = (_q = line.clampToGround) === null || _q === void 0 ? void 0 : _q.getValue) === null || _r === void 0 ? void 0 : _r.call(_q, time))) {
1791
+ const positions = (_u = (_t = (_s = line.positions) === null || _s === void 0 ? void 0 : _s.getValue) === null || _t === void 0 ? void 0 : _t.call(_s, time)) !== null && _u !== void 0 ? _u : [];
1792
+ if (positions.length && (reachesBelowGround(state, positions[0]) || reachesBelowGround(state, positions[positions.length - 1]))) {
1793
+ return true;
1794
+ }
1795
+ }
1796
+ }
1797
+ }
1798
+ return false;
1799
+ }
1800
+
910
1801
  const CESIUM_INSPECTOR_KEY = "_nextspace_inspector";
911
1802
  const CESIUM_TIMELINE_KEY = "_nextspace_timeline";
912
1803
  const CESIUM_TIMELINE_LIVE_KEY = "_nextspace_timeline_live";
@@ -1383,6 +2274,13 @@
1383
2274
  return overriddenImageBasedLighting || null;
1384
2275
  }
1385
2276
  ViewUtils.GetDefaultImageBasedLighting = GetDefaultImageBasedLighting;
2277
+ /**
2278
+ * Shadow mode for the Entity graphics this library draws, following the scene's shadow switch.
2279
+ */
2280
+ function GetEntityShadowMode(viewer) {
2281
+ return (viewer === null || viewer === void 0 ? void 0 : viewer.shadows) ? Cesium.ShadowMode.ENABLED : Cesium.ShadowMode.DISABLED;
2282
+ }
2283
+ ViewUtils.GetEntityShadowMode = GetEntityShadowMode;
1386
2284
  function EngineShadesModelsDarker() {
1387
2285
  return typeof Cesium.DynamicEnvironmentMapManager !== "undefined";
1388
2286
  }
@@ -1454,6 +2352,7 @@
1454
2352
  viewer[CESIUM_MODEL_SPACE_KEY] = modelSpace;
1455
2353
  // Reload globe since we display it differently between the two modes.
1456
2354
  SetGlobeDetails({ viewer });
2355
+ exports.CameraControls.SetModelSpace(viewer, modelSpace ? () => GetModelSpaceFrame(viewer) : null);
1457
2356
  }
1458
2357
  ViewUtils.SetModelSpace = SetModelSpace;
1459
2358
  function GetModelSpace(viewer) {
@@ -6166,7 +7065,7 @@
6166
7065
  const byTime = new Map();
6167
7066
  for (const set of this.sets.values()) {
6168
7067
  for (const [ms, record] of set.records.get(entityId) || []) {
6169
- if (attrKey && record.attrKey && record.attrKey !== attrKey) {
7068
+ if (attrKey && record.attrKey && !BModels.PathUtils.Equals(record.attrKey, attrKey)) {
6170
7069
  continue;
6171
7070
  }
6172
7071
  const held = byTime.get(ms);
@@ -11965,6 +12864,28 @@
11965
12864
  return highest;
11966
12865
  }
11967
12866
  const MAX_SHOW_DEPTH = 10;
12867
+ // Entity graphics whose shadows follow the scene's shadow switch.
12868
+ const SHADOWED_GRAPHICS = ["model", "polygon", "polyline", "corridor"];
12869
+ /*
12870
+ * Points a registered Entity graphic, and the graphics drawn beside it, at the given shadow mode.
12871
+ */
12872
+ function updateCEntityShadows(viewer, visual, mode, depth = 0) {
12873
+ if (!visual || depth > MAX_SHOW_DEPTH) {
12874
+ return;
12875
+ }
12876
+ for (const key of SHADOWED_GRAPHICS) {
12877
+ const graphic = visual[key];
12878
+ // Only graphics drawn with a mode; one left at Cesium's default was never meant to shadow.
12879
+ if ((graphic === null || graphic === void 0 ? void 0 : graphic.shadows) != null) {
12880
+ SetCPropIfChanged({ viewer, graphic, property: "shadows", value: mode });
12881
+ }
12882
+ }
12883
+ if (visual._siblingGraphics) {
12884
+ for (let i = 0; i < visual._siblingGraphics.length; i++) {
12885
+ updateCEntityShadows(viewer, visual._siblingGraphics[i], mode, depth + 1);
12886
+ }
12887
+ }
12888
+ }
11968
12889
  function updateCEntityShow(viewer, visual, rego, show, ignoreParent, depth = 0) {
11969
12890
  if (depth > MAX_SHOW_DEPTH) {
11970
12891
  console.warn("updateCEntityShow(): Max show depth reached. EntityId = " + rego.entityId);
@@ -12297,7 +13218,7 @@
12297
13218
  }
12298
13219
  get OnLabelGroupsChanged() { return this.labelGroupsChanged; }
12299
13220
  constructor(params) {
12300
- var _a, _b;
13221
+ var _a, _b, _c, _d, _e, _f, _g;
12301
13222
  this.id = BModels.ObjectUtils.UId();
12302
13223
  this.disposed = false;
12303
13224
  this.rego = {};
@@ -12347,6 +13268,7 @@
12347
13268
  this.sourceOrderDirty = false;
12348
13269
  // Stops following what is simulated, so labels can read it again when it changes.
12349
13270
  this.simulationRemoval = null;
13271
+ this.shadowsRemoval = null;
12350
13272
  this.labelGroupsChanged = new BModels.BruceEvent();
12351
13273
  this.hoverRingState = {};
12352
13274
  this.retiringHoverLabels = new Map();
@@ -12382,6 +13304,27 @@
12382
13304
  register: this
12383
13305
  });
12384
13306
  this.simulationRemoval = (_b = (_a = exports.EntitySimulation.Get(this.viewer)) === null || _a === void 0 ? void 0 : _a.OnChanged.Subscribe((change) => this.reloadLabels(change.entityIds))) !== null && _b !== void 0 ? _b : null;
13307
+ this.entityShadows = Boolean((_c = this.viewer) === null || _c === void 0 ? void 0 : _c.shadows);
13308
+ this.shadowsRemoval = (_g = (_f = (_e = (_d = this.viewer) === null || _d === void 0 ? void 0 : _d.scene) === null || _e === void 0 ? void 0 : _e.preUpdate) === null || _f === void 0 ? void 0 : _f.addEventListener(() => this.syncEntityShadows())) !== null && _g !== void 0 ? _g : null;
13309
+ }
13310
+ /*
13311
+ * Follows the scene's shadow switch on every registered Entity, whichever app or bookmark flipped it.
13312
+ */
13313
+ syncEntityShadows() {
13314
+ const viewer = this.viewer;
13315
+ const enabled = Boolean(viewer === null || viewer === void 0 ? void 0 : viewer.shadows);
13316
+ if (enabled === this.entityShadows || this.disposed || !viewer || viewer.isDestroyed()) {
13317
+ return;
13318
+ }
13319
+ this.entityShadows = enabled;
13320
+ const mode = enabled ? Cesium.ShadowMode.ENABLED : Cesium.ShadowMode.DISABLED;
13321
+ for (const regos of Object.values(this.rego)) {
13322
+ for (const rego of regos) {
13323
+ if (rego.visual instanceof Cesium.Entity) {
13324
+ updateCEntityShadows(viewer, rego.visual, mode);
13325
+ }
13326
+ }
13327
+ }
12385
13328
  }
12386
13329
  /*
12387
13330
  * Tells labels to read their Entity again, since they keep what they read when drawn.
@@ -13310,9 +14253,11 @@
13310
14253
  (_b = this.viewer.scene) === null || _b === void 0 ? void 0 : _b.requestRender();
13311
14254
  }
13312
14255
  Dispose() {
13313
- var _a, _b, _c, _d, _e, _f;
14256
+ var _a, _b, _c, _d, _e, _f, _g;
13314
14257
  (_a = this.simulationRemoval) === null || _a === void 0 ? void 0 : _a.call(this);
13315
14258
  this.simulationRemoval = null;
14259
+ (_b = this.shadowsRemoval) === null || _b === void 0 ? void 0 : _b.call(this);
14260
+ this.shadowsRemoval = null;
13316
14261
  exports.CesiumEntityStyler.SetDimming(this.viewer, this.id, false);
13317
14262
  this.ClearLabelHover();
13318
14263
  clearTimeout(this.hoverRingReset);
@@ -13322,14 +14267,14 @@
13322
14267
  exports.EntityLabel.Detatch({ label });
13323
14268
  }
13324
14269
  this.retiringHoverLabels.clear();
13325
- (_b = this.labelGroups) === null || _b === void 0 ? void 0 : _b.Dispose();
14270
+ (_c = this.labelGroups) === null || _c === void 0 ? void 0 : _c.Dispose();
13326
14271
  this.labelGroupsChanged.Clear();
13327
14272
  for (const regos of Object.values(this.rego)) {
13328
14273
  for (const rego of regos)
13329
14274
  exports.EntityLabel.Detatch({ rego, force: true });
13330
14275
  }
13331
14276
  exports.EntityLabel.SetContainer(this.viewer);
13332
- (_c = this.cameraCullerDispose) === null || _c === void 0 ? void 0 : _c.call(this, {
14277
+ (_d = this.cameraCullerDispose) === null || _d === void 0 ? void 0 : _d.call(this, {
13333
14278
  uncull: false
13334
14279
  });
13335
14280
  this.cameraCullerDispose = null;
@@ -13346,7 +14291,7 @@
13346
14291
  this.disposed = true;
13347
14292
  for (const record of Array.from(this.menuItemSources.values())) {
13348
14293
  try {
13349
- (_e = (_d = this.viewer) === null || _d === void 0 ? void 0 : _d.dataSources) === null || _e === void 0 ? void 0 : _e.remove(record.source, true);
14294
+ (_f = (_e = this.viewer) === null || _e === void 0 ? void 0 : _e.dataSources) === null || _f === void 0 ? void 0 : _f.remove(record.source, true);
13350
14295
  }
13351
14296
  catch (e) {
13352
14297
  console.error(e);
@@ -13355,7 +14300,7 @@
13355
14300
  this.menuItemSources.clear();
13356
14301
  // Hand every tileset's show flag back to its owner, holding whatever the owner last asked for.
13357
14302
  for (const rego of Array.from(this.tilesets.values())) {
13358
- (_f = rego.gate) === null || _f === void 0 ? void 0 : _f.Release();
14303
+ (_g = rego.gate) === null || _g === void 0 ? void 0 : _g.Release();
13359
14304
  }
13360
14305
  this.tilesets.clear();
13361
14306
  }
@@ -14079,8 +15024,11 @@
14079
15024
  }
14080
15025
  }
14081
15026
  // Add the new visual to the register.
15027
+ // Tileset managers add the same rego again for each tile holding more of the Entity.
14082
15028
  const entityRegos = (_a = this.rego[entityId]) !== null && _a !== void 0 ? _a : [];
14083
- entityRegos.push(rego);
15029
+ if (!entityRegos.includes(rego)) {
15030
+ entityRegos.push(rego);
15031
+ }
14084
15032
  this.rego[entityId] = entityRegos;
14085
15033
  this.indexMenuItemEntity(rego.menuItemId, entityId);
14086
15034
  // Mark the visual as part of this register so selection works.
@@ -14514,6 +15462,28 @@
14514
15462
  }
14515
15463
  }
14516
15464
  }
15465
+ /*
15466
+ * Hands a tile feature rego to a sibling feature from another tile when its own tile unloads.
15467
+ * An Entity split across tiles keeps drawing from those, so it must stay registered for them.
15468
+ */
15469
+ promoteTileSibling(rego, removing) {
15470
+ var _a;
15471
+ const departing = rego.visual;
15472
+ if (!(departing instanceof Cesium.Cesium3DTileFeature) || !((_a = departing._siblingGraphics) === null || _a === void 0 ? void 0 : _a.length)) {
15473
+ return false;
15474
+ }
15475
+ const remaining = departing._siblingGraphics.filter(s => !removing.has(s));
15476
+ if (!remaining.length) {
15477
+ return false;
15478
+ }
15479
+ departing._siblingGraphics = undefined;
15480
+ unmarkEntity(departing, true);
15481
+ const promoted = remaining[0];
15482
+ promoted._siblingGraphics = remaining.slice(1);
15483
+ rego.visual = promoted;
15484
+ markEntity(this, rego, promoted, false);
15485
+ return true;
15486
+ }
14517
15487
  /**
14518
15488
  * Removes regos matching given visuals.
14519
15489
  * This is used when we cannot unpack properties from the visual any longer to determine its ID.
@@ -14524,6 +15494,7 @@
14524
15494
  var _a, _b, _c;
14525
15495
  const { doRemove = true, requestRender = true, source, doUpdate, menuItemId } = params;
14526
15496
  const removedEntityIds = new Set();
15497
+ const removing = new Set(params.visuals);
14527
15498
  for (const visual of params.visuals) {
14528
15499
  const visExt = visual;
14529
15500
  const rego = (visExt === null || visExt === void 0 ? void 0 : visExt._register) === this ? visExt._rego : null;
@@ -14535,7 +15506,20 @@
14535
15506
  if (!entityRegos) {
14536
15507
  continue;
14537
15508
  }
14538
- if (rego.visual === visual) {
15509
+ if (rego.visual === visual && this.promoteTileSibling(rego, removing)) {
15510
+ if (doRemove != false) {
15511
+ removeEntity(this.viewer, visual);
15512
+ }
15513
+ // The label was placed against the departing feature, the refresh attaches it again.
15514
+ exports.EntityLabel.Detatch({
15515
+ rego, force: true
15516
+ });
15517
+ this.queueUpdate({
15518
+ entityId: entityId,
15519
+ refresh: true
15520
+ });
15521
+ }
15522
+ else if (rego.visual === visual) {
14539
15523
  exports.EntityLabel.Detatch({
14540
15524
  rego, force: true
14541
15525
  });
@@ -16187,6 +17171,300 @@
16187
17171
  }
16188
17172
  }
16189
17173
 
17174
+ // viewer[VIEWER_WATCH_KEY] is true once the viewer's canvas reports context loss to DeviceProfile.
17175
+ const VIEWER_WATCH_KEY = "_bruceDeviceProfileWatch";
17176
+ // localStorage[DEMOTION_KEY] holds an IDemotion written after this browser lost a WebGL context.
17177
+ const DEMOTION_KEY = "bruce-cesium-device-demotion";
17178
+ // A lost context demotes for this long, so one driver reset does not cap a strong device forever.
17179
+ // Measured on the wall clock, not the viewer's: it spans sessions, and a scene clock can be historic.
17180
+ const DEMOTION_MS = 14 * 24 * 60 * 60 * 1000;
17181
+ // Each loss demotes one more tier, up to this many.
17182
+ const DEMOTION_MAX = 2;
17183
+ /*
17184
+ * Reads the demotion left by earlier context losses, ignoring an expired or unreadable one.
17185
+ */
17186
+ function readDemotion(now) {
17187
+ try {
17188
+ const value = JSON.parse(window.localStorage.getItem(DEMOTION_KEY));
17189
+ if (value &&
17190
+ Number.isFinite(value.count) &&
17191
+ Number.isFinite(value.at) &&
17192
+ now - value.at < DEMOTION_MS) {
17193
+ return value;
17194
+ }
17195
+ }
17196
+ catch (e) {
17197
+ // Storage is blocked (private mode, sandboxed frame) or holds junk; treat as no demotion.
17198
+ }
17199
+ return null;
17200
+ }
17201
+ /*
17202
+ * Stores or clears the demotion, carrying on without it where storage is blocked.
17203
+ */
17204
+ function writeDemotion(value) {
17205
+ try {
17206
+ if (value) {
17207
+ window.localStorage.setItem(DEMOTION_KEY, JSON.stringify(value));
17208
+ }
17209
+ else {
17210
+ window.localStorage.removeItem(DEMOTION_KEY);
17211
+ }
17212
+ }
17213
+ catch (e) {
17214
+ // Without storage the demotion lasts only for this page.
17215
+ }
17216
+ }
17217
+ /*
17218
+ * Reads the GPU name, preferring the unmasked one, which browsers that hide it simply do not offer.
17219
+ */
17220
+ function readRenderer(gl) {
17221
+ try {
17222
+ const ext = gl.getExtension("WEBGL_debug_renderer_info");
17223
+ const name = ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
17224
+ return typeof name === "string" && name ? name : undefined;
17225
+ }
17226
+ catch (e) {
17227
+ return undefined;
17228
+ }
17229
+ }
17230
+ (function (DeviceProfile) {
17231
+ let ETier;
17232
+ (function (ETier) {
17233
+ ETier["Low"] = "LOW";
17234
+ ETier["Mid"] = "MID";
17235
+ ETier["High"] = "HIGH";
17236
+ })(ETier = DeviceProfile.ETier || (DeviceProfile.ETier = {}));
17237
+ DeviceProfile.BUDGETS = {
17238
+ [ETier.Low]: { tilesetMb: 384, splats: 1000000 },
17239
+ [ETier.Mid]: { tilesetMb: 1024, splats: 3000000 },
17240
+ [ETier.High]: { tilesetMb: 2048, splats: 6000000 }
17241
+ };
17242
+ const ORDER = [ETier.Low, ETier.Mid, ETier.High];
17243
+ /**
17244
+ * Raised after the override or a demotion changes the tier, so live budgets can be redistributed.
17245
+ */
17246
+ DeviceProfile.Changed = new Cesium.Event();
17247
+ let override = null;
17248
+ let detected = null;
17249
+ let logged = false;
17250
+ /*
17251
+ * Sorts a GPU name into a class. Order matters: Intel Arc is discrete, SwiftShader names any vendor.
17252
+ */
17253
+ function ClassifyGpu(renderer) {
17254
+ const name = (renderer || "").toLowerCase();
17255
+ if (!name) {
17256
+ return "unknown";
17257
+ }
17258
+ if (/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/.test(name)) {
17259
+ return "software";
17260
+ }
17261
+ if (/mali|adreno|powervr|apple gpu|videocore|immortalis|xclipse|tegra/.test(name)) {
17262
+ return "mobile";
17263
+ }
17264
+ if (/apple m\d+ (pro|max|ultra)/.test(name)) {
17265
+ return "discrete";
17266
+ }
17267
+ if (/nvidia|geforce|quadro|rtx|radeon (rx|pro|r9|vii)|firepro|arc(\(tm\))? a\d/.test(name)) {
17268
+ return "discrete";
17269
+ }
17270
+ if (/intel|apple m\d|radeon(\(tm\))? graphics|vega \d/.test(name)) {
17271
+ return "integrated";
17272
+ }
17273
+ return "unknown";
17274
+ }
17275
+ DeviceProfile.ClassifyGpu = ClassifyGpu;
17276
+ /**
17277
+ * Guesses a tier from the hardware alone. Unknown hardware stays mid; only clear evidence moves it.
17278
+ */
17279
+ function Classify(env) {
17280
+ const ua = (env.userAgent || "").toLowerCase();
17281
+ const mobile = /android|iphone|ipad|ipod|mobile/.test(ua) || (/macintosh/.test(ua) && env.maxTouchPoints > 1);
17282
+ const gpuClass = ClassifyGpu(env.gpuRenderer);
17283
+ const memory = env.deviceMemory;
17284
+ const reasons = [];
17285
+ let tier = ETier.Mid;
17286
+ if (gpuClass === "software") {
17287
+ reasons.push("software renderer");
17288
+ tier = ETier.Low;
17289
+ }
17290
+ if (mobile) {
17291
+ reasons.push("mobile device");
17292
+ tier = ETier.Low;
17293
+ }
17294
+ if (Number.isFinite(memory) && memory < 4) {
17295
+ reasons.push(`${memory} GB device memory`);
17296
+ tier = ETier.Low;
17297
+ }
17298
+ if (Number.isFinite(env.maxTextureSize) && env.maxTextureSize < 8192) {
17299
+ reasons.push(`max texture ${env.maxTextureSize}`);
17300
+ tier = ETier.Low;
17301
+ }
17302
+ if (tier === ETier.Mid && gpuClass === "discrete") {
17303
+ if (!Number.isFinite(memory) || memory >= 8) {
17304
+ reasons.push("discrete GPU");
17305
+ tier = ETier.High;
17306
+ }
17307
+ else {
17308
+ reasons.push(`discrete GPU held to mid by ${memory} GB device memory`);
17309
+ }
17310
+ }
17311
+ if (!reasons.length) {
17312
+ reasons.push(`${gpuClass} GPU`);
17313
+ }
17314
+ return { tier, gpuClass, mobile, reasons };
17315
+ }
17316
+ DeviceProfile.Classify = Classify;
17317
+ /*
17318
+ * Reads the browser environment, from the viewer's GL context when given rather than a spare one.
17319
+ */
17320
+ function readEnvironment(viewer) {
17321
+ var _a, _b, _c;
17322
+ const nav = typeof navigator !== "undefined" ? navigator : {};
17323
+ const env = {
17324
+ userAgent: nav.userAgent,
17325
+ maxTouchPoints: nav.maxTouchPoints,
17326
+ deviceMemory: nav.deviceMemory,
17327
+ hardwareConcurrency: nav.hardwareConcurrency
17328
+ };
17329
+ let gl = (_b = (_a = viewer === null || viewer === void 0 ? void 0 : viewer.scene) === null || _a === void 0 ? void 0 : _a.context) === null || _b === void 0 ? void 0 : _b._gl;
17330
+ let spare = false;
17331
+ if (!gl && typeof document !== "undefined") {
17332
+ try {
17333
+ gl = document.createElement("canvas").getContext("webgl");
17334
+ spare = Boolean(gl);
17335
+ }
17336
+ catch (e) {
17337
+ gl = null;
17338
+ }
17339
+ }
17340
+ // Detection must never stop a scene loading, so anything odd leaves the GPU unknown.
17341
+ if (gl &&
17342
+ typeof gl.getParameter === "function" &&
17343
+ typeof gl.getExtension === "function") {
17344
+ env.gpuRenderer = readRenderer(gl);
17345
+ try {
17346
+ env.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) || undefined;
17347
+ if (spare) {
17348
+ // Browsers cap live contexts per page; give this one back now rather than at GC.
17349
+ (_c = gl.getExtension("WEBGL_lose_context")) === null || _c === void 0 ? void 0 : _c.loseContext();
17350
+ }
17351
+ }
17352
+ catch (e) {
17353
+ // Leave it unknown.
17354
+ }
17355
+ }
17356
+ return env;
17357
+ }
17358
+ /**
17359
+ * Returns this device's profile, detecting it once per page. Pass the viewer to read its GL context.
17360
+ */
17361
+ function Get(viewer) {
17362
+ var _a, _b;
17363
+ if (!detected) {
17364
+ const environment = readEnvironment(viewer);
17365
+ detected = { ...Classify(environment), environment };
17366
+ }
17367
+ const demotion = readDemotion(Date.now());
17368
+ const demoted = Math.min((_a = demotion === null || demotion === void 0 ? void 0 : demotion.count) !== null && _a !== void 0 ? _a : 0, DEMOTION_MAX);
17369
+ let tier = ORDER[Math.max(0, ORDER.indexOf(detected.tier) - demoted)];
17370
+ if (override) {
17371
+ tier = override;
17372
+ }
17373
+ const profile = {
17374
+ tier,
17375
+ detectedTier: detected.tier,
17376
+ gpuClass: detected.gpuClass,
17377
+ mobile: detected.mobile,
17378
+ demoted,
17379
+ overridden: Boolean(override),
17380
+ reasons: [...detected.reasons],
17381
+ environment: { ...detected.environment }
17382
+ };
17383
+ if (!logged) {
17384
+ logged = true;
17385
+ console.info(`[DeviceProfile] tier ${profile.tier} (${profile.reasons.join(", ")}` +
17386
+ `${demoted ? `, demoted ${demoted} after lost WebGL context` : ""}` +
17387
+ `${override ? ", overridden" : ""}). GPU: ${(_b = profile.environment.gpuRenderer) !== null && _b !== void 0 ? _b : "unknown"}.`);
17388
+ }
17389
+ return profile;
17390
+ }
17391
+ DeviceProfile.Get = Get;
17392
+ /**
17393
+ * Returns the memory budgets for this device's tier, or for a given tier.
17394
+ */
17395
+ function GetBudget(tier) {
17396
+ return DeviceProfile.BUDGETS[tier !== null && tier !== void 0 ? tier : Get().tier];
17397
+ }
17398
+ DeviceProfile.GetBudget = GetBudget;
17399
+ /**
17400
+ * Forces a tier, for a user who knows better than the guess. Null returns to detection.
17401
+ */
17402
+ function SetOverride(tier) {
17403
+ const next = tier && ORDER.includes(tier) ? tier : null;
17404
+ if (next === override) {
17405
+ return;
17406
+ }
17407
+ override = next;
17408
+ DeviceProfile.Changed.raiseEvent();
17409
+ }
17410
+ DeviceProfile.SetOverride = SetOverride;
17411
+ /**
17412
+ * Returns the forced tier, or null while detection decides.
17413
+ */
17414
+ function GetOverride() {
17415
+ return override;
17416
+ }
17417
+ DeviceProfile.GetOverride = GetOverride;
17418
+ /**
17419
+ * Records that a WebGL context was lost, so this and later sessions start a tier lower.
17420
+ */
17421
+ function RecordContextLost() {
17422
+ var _a, _b;
17423
+ const now = Date.now();
17424
+ const count = Math.min(((_b = (_a = readDemotion(now)) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0) + 1, DEMOTION_MAX);
17425
+ writeDemotion({ count, at: now });
17426
+ console.warn(`[DeviceProfile] WebGL context lost; demoting the memory tier by ${count}.`);
17427
+ DeviceProfile.Changed.raiseEvent();
17428
+ }
17429
+ DeviceProfile.RecordContextLost = RecordContextLost;
17430
+ /**
17431
+ * Forgets earlier context losses, for a host that offers a reset.
17432
+ */
17433
+ function ClearDemotion() {
17434
+ writeDemotion(null);
17435
+ DeviceProfile.Changed.raiseEvent();
17436
+ }
17437
+ DeviceProfile.ClearDemotion = ClearDemotion;
17438
+ /**
17439
+ * Reports the viewer's context losses. Safe to call repeatedly.
17440
+ */
17441
+ function WatchViewer(viewer) {
17442
+ const canvas = viewer === null || viewer === void 0 ? void 0 : viewer.canvas;
17443
+ if (!canvas ||
17444
+ viewer[VIEWER_WATCH_KEY] ||
17445
+ typeof canvas.addEventListener !== "function") {
17446
+ return;
17447
+ }
17448
+ viewer[VIEWER_WATCH_KEY] = true;
17449
+ canvas.addEventListener("webglcontextlost", () => {
17450
+ // Ignore a loss caused by tearing the viewer down.
17451
+ if (!viewer.isDestroyed()) {
17452
+ RecordContextLost();
17453
+ }
17454
+ });
17455
+ }
17456
+ DeviceProfile.WatchViewer = WatchViewer;
17457
+ /**
17458
+ * Forgets the detected hardware and override, for tests.
17459
+ */
17460
+ function Reset() {
17461
+ detected = null;
17462
+ override = null;
17463
+ logged = false;
17464
+ }
17465
+ DeviceProfile.Reset = Reset;
17466
+ })(exports.DeviceProfile || (exports.DeviceProfile = {}));
17467
+
16190
17468
  /**
16191
17469
  * Returns if a given tileset is alive and in the scene.
16192
17470
  * @param viewer
@@ -16205,7 +17483,7 @@
16205
17483
  }
16206
17484
  return viewer.scene.primitives.contains(cTileset);
16207
17485
  }
16208
- const VIEWER_WATCH_KEY = "bruce-viewer-watch";
17486
+ const VIEWER_WATCH_KEY$1 = "bruce-viewer-watch";
16209
17487
  const WATCH_KEY = "bruce-tileset-watch";
16210
17488
  const VIEWER_DATE_RANGE_WATCH_KEY = "bruce-viewer-date-range-watch";
16211
17489
  const DATE_RANGE_WATCH_KEY = "bruce-tileset-date-range-watch";
@@ -16267,6 +17545,22 @@
16267
17545
  }
16268
17546
  renderObject._bruceDateRangeVisible = visible;
16269
17547
  }
17548
+ // A tileset may pass its cache share by this fraction before Cesium coarsens it to fit.
17549
+ const TILESET_OVERFLOW_RATIO = 0.25;
17550
+ /*
17551
+ * Returns the options capping a tileset's tile cache at the given MB, in the form the running Cesium reads.
17552
+ */
17553
+ function getTilesetMemoryProps(mb) {
17554
+ const prototype = Cesium.Cesium3DTileset.prototype;
17555
+ if ("cacheBytes" in prototype) {
17556
+ const props = { cacheBytes: Math.round(mb * 1024 * 1024) };
17557
+ if ("maximumCacheOverflowBytes" in prototype) {
17558
+ props.maximumCacheOverflowBytes = Math.round(mb * TILESET_OVERFLOW_RATIO * 1024 * 1024);
17559
+ }
17560
+ return props;
17561
+ }
17562
+ return { maximumMemoryUsage: mb };
17563
+ }
16270
17564
  /**
16271
17565
  * Creates and returns a tileset instance from a given url.
16272
17566
  * This is made to handle the difference between old and new cesium versions.
@@ -16283,8 +17577,8 @@
16283
17577
  };
16284
17578
  Object.assign(defaultProps, exports.ViewUtils.DefaultLightingProps());
16285
17579
  if (noMemoryLimit != true) {
16286
- // "The maximum amount of memory in MB that can be used by the tileset.".
16287
- defaultProps.maximumMemoryUsage = 512;
17580
+ // The memory watcher narrows this to a share once the tileset joins it.
17581
+ Object.assign(defaultProps, getTilesetMemoryProps(exports.TilesetRenderEngine.GetTilesetMemoryBudget()));
16288
17582
  }
16289
17583
  const C3DT = Cesium.Cesium3DTileset;
16290
17584
  if (C3DT.fromUrl) {
@@ -16835,10 +18129,23 @@
16835
18129
  }
16836
18130
  TilesetRenderEngine.UnwatchDateRange = UnwatchDateRange;
16837
18131
  /**
16838
- * The maximum memory in MB that can be used by all tilesets.
16839
- * This is distributed evenly between all loaded tilesets.
18132
+ * Total MB all tilesets may use, split evenly; null leaves it to the DeviceProfile tier.
18133
+ */
18134
+ TilesetRenderEngine.MAX_TILESET_MEMORY = null;
18135
+ /**
18136
+ * Smallest MB share a tileset gets; small, since Cesium coarsens one that needs more.
16840
18137
  */
16841
- TilesetRenderEngine.MAX_TILESET_MEMORY = 1024;
18138
+ TilesetRenderEngine.MIN_TILESET_MEMORY = 32;
18139
+ /**
18140
+ * Returns the total MB all tilesets may use, from MAX_TILESET_MEMORY or else the device tier.
18141
+ */
18142
+ function GetTilesetMemoryBudget() {
18143
+ if (Number.isFinite(TilesetRenderEngine.MAX_TILESET_MEMORY) && TilesetRenderEngine.MAX_TILESET_MEMORY > 0) {
18144
+ return TilesetRenderEngine.MAX_TILESET_MEMORY;
18145
+ }
18146
+ return exports.DeviceProfile.GetBudget().tilesetMb;
18147
+ }
18148
+ TilesetRenderEngine.GetTilesetMemoryBudget = GetTilesetMemoryBudget;
16842
18149
  /**
16843
18150
  * Watches tileset date cutoffs and toggles their primitive visibility based on the viewer clock.
16844
18151
  */
@@ -16929,23 +18236,26 @@
16929
18236
  constructor(viewer) {
16930
18237
  this.watched = [];
16931
18238
  this.viewer = viewer;
18239
+ exports.DeviceProfile.Get(viewer);
18240
+ exports.DeviceProfile.WatchViewer(viewer);
18241
+ this.removeChanged = exports.DeviceProfile.Changed.addEventListener(() => this.distributeMemory());
16932
18242
  }
16933
18243
  distributeMemory() {
16934
18244
  this.clean();
16935
- // Total 1gb as default.
16936
- // We'll need to allow user to change this somehow.
16937
- const maxMemory = TilesetRenderEngine.MAX_TILESET_MEMORY;
16938
- // Minimum memory in MB per tileset.
16939
- const minMemory = 80;
16940
- const totalPerTileset = Math.max(this.watched.length ? maxMemory / this.watched.length : maxMemory, minMemory);
18245
+ if (!this.watched.length) {
18246
+ return;
18247
+ }
18248
+ const share = Math.max(GetTilesetMemoryBudget() / this.watched.length, TilesetRenderEngine.MIN_TILESET_MEMORY);
18249
+ const props = getTilesetMemoryProps(share);
16941
18250
  this.watched.forEach(x => {
16942
- // Newer Cesium killed this property.
16943
- // TODO: Check if it's needed then.
16944
- x["maximumMemoryUsage"] = totalPerTileset;
18251
+ Object.assign(x, props);
16945
18252
  });
16946
18253
  }
16947
18254
  destroy() {
18255
+ var _a;
16948
18256
  this.watched = [];
18257
+ (_a = this.removeChanged) === null || _a === void 0 ? void 0 : _a.call(this);
18258
+ this.removeChanged = null;
16949
18259
  }
16950
18260
  /**
16951
18261
  * Remove all dead tilesets.
@@ -16994,10 +18304,10 @@
16994
18304
  if (!viewer || viewer.isDestroyed()) {
16995
18305
  return null;
16996
18306
  }
16997
- if (!viewer[VIEWER_WATCH_KEY]) {
16998
- viewer[VIEWER_WATCH_KEY] = new MemoryWatcher(viewer);
18307
+ if (!viewer[VIEWER_WATCH_KEY$1]) {
18308
+ viewer[VIEWER_WATCH_KEY$1] = new MemoryWatcher(viewer);
16999
18309
  }
17000
- return viewer[VIEWER_WATCH_KEY];
18310
+ return viewer[VIEWER_WATCH_KEY$1];
17001
18311
  }
17002
18312
  TilesetRenderEngine.GetMemoryWatcher = GetMemoryWatcher;
17003
18313
  function GetDateRangeWatcher(viewer) {
@@ -28159,7 +29469,9 @@
28159
29469
  if (loadUrl.indexOf("?") !== -1) {
28160
29470
  loadUrl = loadUrl.split("?")[0];
28161
29471
  }
28162
- let maxSplats = 6000000;
29472
+ const profile = exports.DeviceProfile.Get(viewer);
29473
+ exports.DeviceProfile.WatchViewer(viewer);
29474
+ let maxSplats = exports.DeviceProfile.GetBudget(profile.tier).splats;
28163
29475
  /*
28164
29476
  * Configures optional LOD capabilities once metadata or initial geometry is ready.
28165
29477
  */
@@ -28244,8 +29556,7 @@
28244
29556
  }
28245
29557
  try {
28246
29558
  const sdkBudget = typeof obj.getCurrentConfig === "function" ? (_d = obj.getCurrentConfig()) === null || _d === void 0 ? void 0 : _d.maxLoadSplatCount : undefined;
28247
- // Preserve the SDK's mobile and weak-GPU limits before applying any temporary startup cap.
28248
- maxSplats = Number.isFinite(sdkBudget) && sdkBudget > 0 && sdkBudget <= 2000000 ? sdkBudget : 6000000;
29559
+ maxSplats = GetSplatBudget(sdkBudget, profile);
28249
29560
  if (LCCRender.nextspaceMetadataReady === 1 &&
28250
29561
  typeof obj.setNextspaceMetadataCallback === "function" &&
28251
29562
  typeof obj.setMaxSplats === "function") {
@@ -28286,6 +29597,21 @@
28286
29597
  return obj;
28287
29598
  }
28288
29599
  XGridsRenderEngine.Render = Render;
29600
+ /*
29601
+ * The most splats a scan may load: the tier's, lowered by the SDK's GPU limit unless overridden.
29602
+ */
29603
+ function GetSplatBudget(sdkBudget, profile) {
29604
+ const budget = exports.DeviceProfile.GetBudget(profile.tier).splats;
29605
+ // Above 2M the SDK is reporting its flat default, not a limit it chose for this GPU.
29606
+ if (!profile.overridden &&
29607
+ Number.isFinite(sdkBudget) &&
29608
+ sdkBudget > 0 &&
29609
+ sdkBudget <= 2000000) {
29610
+ return Math.min(sdkBudget, budget);
29611
+ }
29612
+ return budget;
29613
+ }
29614
+ XGridsRenderEngine.GetSplatBudget = GetSplatBudget;
28289
29615
  /*
28290
29616
  * Detaches optional tuning before unloading the scan.
28291
29617
  */
@@ -29867,6 +31193,8 @@
29867
31193
  this.doDispose();
29868
31194
  return;
29869
31195
  }
31196
+ // Photorealistic tiles cover the Earth, so the camera treats them as the ground when the globe is hidden.
31197
+ exports.CameraControls.SetGroundTileset(this.cTileset, true);
29870
31198
  this.viewer.scene.primitives.add(this.cTileset);
29871
31199
  this.applyColorMask();
29872
31200
  this.viewer.scene.requestRender();
@@ -38712,6 +40040,1228 @@
38712
40040
  })(Terrain = TileRenderEngine.Terrain || (TileRenderEngine.Terrain = {}));
38713
40041
  })(exports.TileRenderEngine || (exports.TileRenderEngine = {}));
38714
40042
 
40043
+ // Builds simple meshes into binary glTF in code. Nothing here imports Cesium, so it can move to bruce-models as is.
40044
+ const GLB_MAGIC = 0x46546C67;
40045
+ const GLB_CHUNK_JSON = 0x4E4F534A;
40046
+ const GLB_CHUNK_BIN = 0x004E4942;
40047
+ const GL_ARRAY_BUFFER = 34962;
40048
+ const GL_ELEMENT_ARRAY_BUFFER = 34963;
40049
+ const GL_UNSIGNED_SHORT = 5123;
40050
+ const GL_UNSIGNED_INT = 5125;
40051
+ const GL_FLOAT = 5126;
40052
+ const GL_TRIANGLES = 4;
40053
+ (function (GltfGenerator) {
40054
+ /**
40055
+ * Vertices and triangles collected by the shape functions, one material's worth.
40056
+ */
40057
+ class Mesh {
40058
+ constructor() {
40059
+ this.positions = [];
40060
+ this.normals = [];
40061
+ this.indices = [];
40062
+ }
40063
+ AddVertex(position, normal) {
40064
+ this.positions.push(position[0], position[1], position[2]);
40065
+ this.normals.push(normal[0], normal[1], normal[2]);
40066
+ return this.positions.length / 3 - 1;
40067
+ }
40068
+ /**
40069
+ * Adds a triangle wound so its front faces along normal, whichever order the corners come in.
40070
+ * Per corner normals smooth it; without them every corner takes the face normal.
40071
+ */
40072
+ AddTriangle(a, b, c, normal, corners) {
40073
+ var _a, _b, _c;
40074
+ const ia = this.AddVertex(a, (_a = corners === null || corners === void 0 ? void 0 : corners[0]) !== null && _a !== void 0 ? _a : normal);
40075
+ const ib = this.AddVertex(b, (_b = corners === null || corners === void 0 ? void 0 : corners[1]) !== null && _b !== void 0 ? _b : normal);
40076
+ const ic = this.AddVertex(c, (_c = corners === null || corners === void 0 ? void 0 : corners[2]) !== null && _c !== void 0 ? _c : normal);
40077
+ if (Dot(Cross(Sub(b, a), Sub(c, a)), normal) >= 0) {
40078
+ this.indices.push(ia, ib, ic);
40079
+ }
40080
+ else {
40081
+ this.indices.push(ia, ic, ib);
40082
+ }
40083
+ }
40084
+ /**
40085
+ * Joins three added vertices into a triangle facing along normal, so shapes can share corners.
40086
+ */
40087
+ AddIndexedTriangle(ia, ib, ic, normal) {
40088
+ const at = (i) => [this.positions[i * 3], this.positions[i * 3 + 1], this.positions[i * 3 + 2]];
40089
+ const a = at(ia);
40090
+ if (Dot(Cross(Sub(at(ib), a), Sub(at(ic), a)), normal) >= 0) {
40091
+ this.indices.push(ia, ib, ic);
40092
+ }
40093
+ else {
40094
+ this.indices.push(ia, ic, ib);
40095
+ }
40096
+ }
40097
+ get VertexCount() {
40098
+ return this.positions.length / 3;
40099
+ }
40100
+ }
40101
+ GltfGenerator.Mesh = Mesh;
40102
+ function Add(a, b) {
40103
+ return [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
40104
+ }
40105
+ GltfGenerator.Add = Add;
40106
+ function Sub(a, b) {
40107
+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
40108
+ }
40109
+ GltfGenerator.Sub = Sub;
40110
+ function Scale(a, s) {
40111
+ return [a[0] * s, a[1] * s, a[2] * s];
40112
+ }
40113
+ GltfGenerator.Scale = Scale;
40114
+ function Dot(a, b) {
40115
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
40116
+ }
40117
+ GltfGenerator.Dot = Dot;
40118
+ function Cross(a, b) {
40119
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
40120
+ }
40121
+ GltfGenerator.Cross = Cross;
40122
+ function Normalize(a) {
40123
+ const length = Math.hypot(a[0], a[1], a[2]);
40124
+ return length ? Scale(a, 1 / length) : [0, 0, 0];
40125
+ }
40126
+ GltfGenerator.Normalize = Normalize;
40127
+ /*
40128
+ * Two unit vectors at right angles to an axis and each other, the first along start where one is given.
40129
+ */
40130
+ function perpendiculars(axis, start) {
40131
+ const n = Normalize(axis);
40132
+ let u = start ? Sub(start, Scale(n, Dot(start, n))) : null;
40133
+ if (!u || Math.hypot(u[0], u[1], u[2]) < 1e-9) {
40134
+ u = Math.abs(n[0]) < 0.9 ? Cross(n, [1, 0, 0]) : Cross(n, [0, 1, 0]);
40135
+ }
40136
+ u = Normalize(u);
40137
+ return [u, Cross(n, u)];
40138
+ }
40139
+ /*
40140
+ * The point on a circle around centre at a given turn, in the plane the two perpendiculars span.
40141
+ */
40142
+ function onCircle(centre, u, v, radius, angle) {
40143
+ return Add(centre, Add(Scale(u, Math.cos(angle) * radius), Scale(v, Math.sin(angle) * radius)));
40144
+ }
40145
+ /**
40146
+ * Adds a flat disc facing along normal.
40147
+ */
40148
+ function AddDisc(mesh, params) {
40149
+ const { centre, radius, sides } = params;
40150
+ const normal = Normalize(params.normal);
40151
+ const [u, v] = perpendiculars(normal, params.start);
40152
+ for (let i = 0; i < sides; i++) {
40153
+ const a = onCircle(centre, u, v, radius, i / sides * Math.PI * 2);
40154
+ const b = onCircle(centre, u, v, radius, (i + 1) / sides * Math.PI * 2);
40155
+ mesh.AddTriangle(centre, a, b, normal);
40156
+ }
40157
+ }
40158
+ GltfGenerator.AddDisc = AddDisc;
40159
+ /**
40160
+ * Adds a smooth sided cylinder between two points, closed at the start by default.
40161
+ */
40162
+ function AddCylinder(mesh, params) {
40163
+ const { start, end, radius, sides } = params;
40164
+ const axis = Normalize(Sub(end, start));
40165
+ const [u, v] = perpendiculars(axis);
40166
+ for (let i = 0; i < sides; i++) {
40167
+ const angleA = i / sides * Math.PI * 2;
40168
+ const angleB = (i + 1) / sides * Math.PI * 2;
40169
+ const outA = onCircle([0, 0, 0], u, v, 1, angleA);
40170
+ const outB = onCircle([0, 0, 0], u, v, 1, angleB);
40171
+ const a0 = onCircle(start, u, v, radius, angleA);
40172
+ const b0 = onCircle(start, u, v, radius, angleB);
40173
+ const a1 = onCircle(end, u, v, radius, angleA);
40174
+ const b1 = onCircle(end, u, v, radius, angleB);
40175
+ const face = Normalize(Add(outA, outB));
40176
+ mesh.AddTriangle(a0, b0, b1, face, [outA, outB, outB]);
40177
+ mesh.AddTriangle(a0, b1, a1, face, [outA, outB, outA]);
40178
+ }
40179
+ if (params.capStart != false) {
40180
+ AddDisc(mesh, { centre: start, normal: Scale(axis, -1), radius, sides });
40181
+ }
40182
+ if (params.capEnd) {
40183
+ AddDisc(mesh, { centre: end, normal: axis, radius, sides });
40184
+ }
40185
+ }
40186
+ GltfGenerator.AddCylinder = AddCylinder;
40187
+ /**
40188
+ * Adds a cone from a base circle to a tip, closed at the base by default.
40189
+ */
40190
+ function AddCone(mesh, params) {
40191
+ const { base, tip, radius, sides } = params;
40192
+ const toTip = Sub(tip, base);
40193
+ const height = Math.hypot(toTip[0], toTip[1], toTip[2]);
40194
+ const axis = Normalize(toTip);
40195
+ const [u, v] = perpendiculars(axis, params.start);
40196
+ // A side normal leans toward the tip by the slope of the side.
40197
+ const sideNormal = (angle) => Normalize(Add(Scale(onCircle([0, 0, 0], u, v, 1, angle), height), Scale(axis, radius)));
40198
+ for (let i = 0; i < sides; i++) {
40199
+ const angleA = i / sides * Math.PI * 2;
40200
+ const angleB = (i + 1) / sides * Math.PI * 2;
40201
+ const a = onCircle(base, u, v, radius, angleA);
40202
+ const b = onCircle(base, u, v, radius, angleB);
40203
+ const face = sideNormal((angleA + angleB) / 2);
40204
+ mesh.AddTriangle(a, b, tip, face, params.faceted ? undefined : [sideNormal(angleA), sideNormal(angleB), face]);
40205
+ }
40206
+ if (params.cap != false) {
40207
+ AddDisc(mesh, { centre: base, normal: Scale(axis, -1), radius, sides, start: params.start });
40208
+ }
40209
+ }
40210
+ GltfGenerator.AddCone = AddCone;
40211
+ /**
40212
+ * Adds a smooth ring of tube around an axis through centre.
40213
+ */
40214
+ function AddTorus(mesh, params) {
40215
+ const { centre, radius, tube, segments, sides } = params;
40216
+ const axis = Normalize(params.axis);
40217
+ const [u, v] = perpendiculars(axis);
40218
+ // A grid of shared corners, wrapping round both ways.
40219
+ const first = mesh.VertexCount;
40220
+ for (let i = 0; i < segments; i++) {
40221
+ const out = onCircle([0, 0, 0], u, v, 1, i / segments * Math.PI * 2);
40222
+ for (let j = 0; j < sides; j++) {
40223
+ const turn = j / sides * Math.PI * 2;
40224
+ const normal = Add(Scale(out, Math.cos(turn)), Scale(axis, Math.sin(turn)));
40225
+ mesh.AddVertex(Add(Add(centre, Scale(out, radius)), Scale(normal, tube)), normal);
40226
+ }
40227
+ }
40228
+ const at = (i, j) => first + (i % segments) * sides + (j % sides);
40229
+ const normalAt = (i) => [mesh.normals[i * 3], mesh.normals[i * 3 + 1], mesh.normals[i * 3 + 2]];
40230
+ for (let i = 0; i < segments; i++) {
40231
+ for (let j = 0; j < sides; j++) {
40232
+ const quad = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)];
40233
+ const normal = Normalize(Add(normalAt(quad[0]), normalAt(quad[2])));
40234
+ mesh.AddIndexedTriangle(quad[0], quad[1], quad[2], normal);
40235
+ mesh.AddIndexedTriangle(quad[0], quad[2], quad[3], normal);
40236
+ }
40237
+ }
40238
+ }
40239
+ GltfGenerator.AddTorus = AddTorus;
40240
+ /**
40241
+ * Adds a flat convex outline, given in a plane's own across and up coordinates, facing along normal.
40242
+ */
40243
+ function AddConvexOutline(mesh, params) {
40244
+ const { points, origin, across, up } = params;
40245
+ const normal = Normalize(params.normal);
40246
+ const at = ([x, y]) => Add(origin, Add(Scale(across, x), Scale(up, y)));
40247
+ for (let i = 1; i < points.length - 1; i++) {
40248
+ mesh.AddTriangle(at(points[0]), at(points[i]), at(points[i + 1]), normal);
40249
+ }
40250
+ }
40251
+ GltfGenerator.AddConvexOutline = AddConvexOutline;
40252
+ function align4(length) {
40253
+ return Math.ceil(length / 4) * 4;
40254
+ }
40255
+ function bounds(positions) {
40256
+ const min = [Infinity, Infinity, Infinity];
40257
+ const max = [-Infinity, -Infinity, -Infinity];
40258
+ for (let i = 0; i < positions.length; i++) {
40259
+ const k = i % 3;
40260
+ min[k] = Math.min(min[k], positions[i]);
40261
+ max[k] = Math.max(max[k], positions[i]);
40262
+ }
40263
+ return { min, max };
40264
+ }
40265
+ /**
40266
+ * Packs a mesh into GLB bytes, under a chain of node matrices (outermost first) when given.
40267
+ */
40268
+ function ToGlb(params) {
40269
+ var _a, _b, _c;
40270
+ const { mesh, material } = params;
40271
+ const count = mesh.VertexCount;
40272
+ const wide = count > 0xFFFF;
40273
+ const IndexArray = wide ? Uint32Array : Uint16Array;
40274
+ const indexLength = mesh.indices.length * IndexArray.BYTES_PER_ELEMENT;
40275
+ const indexBytes = align4(indexLength);
40276
+ const vertexBytes = count * 12;
40277
+ const bin = new ArrayBuffer(indexBytes + vertexBytes * 2);
40278
+ new IndexArray(bin, 0, mesh.indices.length).set(mesh.indices);
40279
+ new Float32Array(bin, indexBytes, count * 3).set(mesh.positions);
40280
+ new Float32Array(bin, indexBytes + vertexBytes, count * 3).set(mesh.normals);
40281
+ // The mesh node is last, each matrix node holding the next.
40282
+ const matrices = (_a = params.matrices) !== null && _a !== void 0 ? _a : [];
40283
+ const nodes = matrices.map((matrix, i) => ({ matrix, children: [i + 1] }));
40284
+ nodes.push({ mesh: 0 });
40285
+ const json = {
40286
+ asset: { version: "2.0", generator: "bruce-cesium GltfGenerator" },
40287
+ scene: 0,
40288
+ scenes: [{ nodes: [0] }],
40289
+ nodes,
40290
+ meshes: [{ primitives: [{ attributes: { POSITION: 1, NORMAL: 2 }, indices: 0, material: 0, mode: GL_TRIANGLES }] }],
40291
+ materials: [{
40292
+ pbrMetallicRoughness: {
40293
+ baseColorFactor: material.color,
40294
+ metallicFactor: (_b = material.metallic) !== null && _b !== void 0 ? _b : 0,
40295
+ roughnessFactor: (_c = material.roughness) !== null && _c !== void 0 ? _c : 1
40296
+ },
40297
+ doubleSided: Boolean(material.doubleSided)
40298
+ }],
40299
+ buffers: [{ byteLength: bin.byteLength }],
40300
+ bufferViews: [
40301
+ { buffer: 0, byteOffset: 0, byteLength: indexLength, target: GL_ELEMENT_ARRAY_BUFFER },
40302
+ { buffer: 0, byteOffset: indexBytes, byteLength: vertexBytes, target: GL_ARRAY_BUFFER },
40303
+ { buffer: 0, byteOffset: indexBytes + vertexBytes, byteLength: vertexBytes, target: GL_ARRAY_BUFFER }
40304
+ ],
40305
+ accessors: [
40306
+ { bufferView: 0, componentType: wide ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, count: mesh.indices.length, type: "SCALAR" },
40307
+ { bufferView: 1, componentType: GL_FLOAT, count, type: "VEC3", ...bounds(mesh.positions) },
40308
+ { bufferView: 2, componentType: GL_FLOAT, count, type: "VEC3" }
40309
+ ]
40310
+ };
40311
+ let text = JSON.stringify(json);
40312
+ text += " ".repeat(align4(text.length) - text.length);
40313
+ const jsonBytes = new TextEncoder().encode(text);
40314
+ const glb = new Uint8Array(20 + jsonBytes.length + 8 + bin.byteLength);
40315
+ const view = new DataView(glb.buffer);
40316
+ view.setUint32(0, GLB_MAGIC, true);
40317
+ view.setUint32(4, 2, true);
40318
+ view.setUint32(8, glb.length, true);
40319
+ view.setUint32(12, jsonBytes.length, true);
40320
+ view.setUint32(16, GLB_CHUNK_JSON, true);
40321
+ glb.set(jsonBytes, 20);
40322
+ const binStart = 20 + jsonBytes.length;
40323
+ view.setUint32(binStart, bin.byteLength, true);
40324
+ view.setUint32(binStart + 4, GLB_CHUNK_BIN, true);
40325
+ glb.set(new Uint8Array(bin), binStart + 8);
40326
+ return glb;
40327
+ }
40328
+ GltfGenerator.ToGlb = ToGlb;
40329
+ /**
40330
+ * Packs a mesh into a GLB data URI, which loads as a model url with nothing to fetch.
40331
+ */
40332
+ function ToDataUri(params) {
40333
+ const glb = ToGlb(params);
40334
+ let binary = "";
40335
+ for (let i = 0; i < glb.length; i += 0x8000) {
40336
+ binary += String.fromCharCode.apply(null, glb.subarray(i, i + 0x8000));
40337
+ }
40338
+ return "data:model/gltf-binary;base64," + btoa(binary);
40339
+ }
40340
+ GltfGenerator.ToDataUri = ToDataUri;
40341
+ })(exports.GltfGenerator || (exports.GltfGenerator = {}));
40342
+
40343
+ // Sides on an arrow's shaft and cone.
40344
+ const ARROW_SIDES = 16;
40345
+ const SHAFT_RADIUS = 2.4;
40346
+ const SHAFT_LENGTH = 265;
40347
+ const CONE_RADIUS = 10;
40348
+ const CONE_BASE = 264.6;
40349
+ const CONE_TIP = 306.3;
40350
+ const RING_RADIUS = 210;
40351
+ const RING_TUBE = 1;
40352
+ const RING_SEGMENTS = 60;
40353
+ const RING_SIDES = 10;
40354
+ // The ring's two arrowheads sit either side of its 45 degree mark, each pointing back toward it.
40355
+ const RING_MARK_ANGLES = [137.64, -47.64];
40356
+ const RING_MARK_LENGTH = 5.82;
40357
+ const RING_MARK_CENTRE = 209.8;
40358
+ const RING_MARK_RADIUS = 8.5;
40359
+ const RING_MARK_SIDES = 8;
40360
+ // Turns the original models' Y up node into the Z up frame the pieces were drawn in.
40361
+ const ROOT_MATRIX = [1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1];
40362
+ // Points a piece drawn along +Z down another axis, as the original models' mesh nodes did.
40363
+ const TO_X_MATRIX = [0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1];
40364
+ const TO_Y_ARROW_MATRIX = [0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1];
40365
+ const TO_Y_RING_MATRIX = [1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1];
40366
+ const RED = { color: [1, 0, 0, 1] };
40367
+ const GREEN = { color: [0.2196, 0.5216, 0.1647, 1] };
40368
+ const BLUE = { color: [0.1608, 0.3843, 0.698, 1] };
40369
+ const LETTER_X = {
40370
+ across: [0, 1, 0],
40371
+ facing: [-1, 0, 0],
40372
+ strokes: [
40373
+ [[16.4, 318.6], [16.4, 324.2], [-19.4, 349.8], [-19.4, 343.9]],
40374
+ [[-19.4, 316.9], [-19.4, 322.6], [16.4, 348.8], [16.4, 343.6]]
40375
+ ]
40376
+ };
40377
+ const LETTER_Y = {
40378
+ across: [0, 1, 0],
40379
+ facing: [-1, 0, 0],
40380
+ strokes: [
40381
+ [[-1.9, 320.1], [2.8, 320.1], [2.8, 337.7], [-1.9, 337.7]],
40382
+ [[-1.9, 335.3], [2.8, 335.3], [-10.7, 355.9], [-16.2, 355.9]],
40383
+ [[-1.9, 335.3], [2.8, 335.3], [16.6, 355.9], [10.9, 355.9]]
40384
+ ]
40385
+ };
40386
+ const LETTER_Z = {
40387
+ across: [1, 0, 0],
40388
+ facing: [0, -1, 0],
40389
+ strokes: [
40390
+ [[-14.6, 319], [13.7, 319], [13.7, 323.3], [-14.6, 323.3]],
40391
+ [[-14.6, 323.3], [-9.1, 323.3], [13.1, 350.6], [7.5, 350.6]],
40392
+ [[-12.5, 350.6], [13.1, 350.6], [13.1, 354.8], [-12.5, 354.8]]
40393
+ ]
40394
+ };
40395
+ /*
40396
+ * An axis arrow along +Z: shaft, cone and the axis letter past the tip.
40397
+ */
40398
+ function arrowMesh(letter) {
40399
+ const mesh = new exports.GltfGenerator.Mesh();
40400
+ exports.GltfGenerator.AddCylinder(mesh, { start: [0, 0, 0], end: [0, 0, SHAFT_LENGTH], radius: SHAFT_RADIUS, sides: ARROW_SIDES });
40401
+ exports.GltfGenerator.AddCone(mesh, { base: [0, 0, CONE_BASE], tip: [0, 0, CONE_TIP], radius: CONE_RADIUS, sides: ARROW_SIDES });
40402
+ for (const stroke of letter.strokes) {
40403
+ exports.GltfGenerator.AddConvexOutline(mesh, { points: stroke, origin: [0, 0, 0], across: letter.across, up: [0, 0, 1], normal: letter.facing });
40404
+ }
40405
+ return mesh;
40406
+ }
40407
+ function onRing(degrees, radius) {
40408
+ const angle = degrees * Math.PI / 180;
40409
+ return [Math.cos(angle) * radius, Math.sin(angle) * radius, 0];
40410
+ }
40411
+ /*
40412
+ * A rotation ring about +Z with its two arrowheads.
40413
+ */
40414
+ function ringMesh() {
40415
+ const mesh = new exports.GltfGenerator.Mesh();
40416
+ exports.GltfGenerator.AddTorus(mesh, {
40417
+ centre: [0, 0, 0],
40418
+ axis: [0, 0, 1],
40419
+ radius: RING_RADIUS,
40420
+ tube: RING_TUBE,
40421
+ segments: RING_SEGMENTS,
40422
+ sides: RING_SIDES
40423
+ });
40424
+ for (const degrees of RING_MARK_ANGLES) {
40425
+ const toward = degrees > 45 ? -RING_MARK_LENGTH : RING_MARK_LENGTH;
40426
+ exports.GltfGenerator.AddCone(mesh, {
40427
+ base: onRing(degrees, RING_MARK_CENTRE),
40428
+ tip: onRing(degrees + toward, RING_MARK_CENTRE),
40429
+ radius: RING_MARK_RADIUS,
40430
+ sides: RING_MARK_SIDES,
40431
+ faceted: true,
40432
+ // A rim corner points at the ring's centre, as the original arrowheads' did.
40433
+ start: onRing(degrees, 1)
40434
+ });
40435
+ }
40436
+ return mesh;
40437
+ }
40438
+ (function (GltfGizmo) {
40439
+ let EPiece;
40440
+ (function (EPiece) {
40441
+ EPiece["X"] = "x";
40442
+ EPiece["Y"] = "y";
40443
+ EPiece["Z"] = "z";
40444
+ EPiece["XRotation"] = "x-rot";
40445
+ EPiece["YRotation"] = "y-rot";
40446
+ EPiece["ZRotation"] = "z-rot";
40447
+ })(EPiece = GltfGizmo.EPiece || (GltfGizmo.EPiece = {}));
40448
+ const BUILDERS = {
40449
+ [EPiece.X]: () => exports.GltfGenerator.ToDataUri({ mesh: arrowMesh(LETTER_X), material: RED, matrices: [ROOT_MATRIX, TO_X_MATRIX] }),
40450
+ [EPiece.Y]: () => exports.GltfGenerator.ToDataUri({ mesh: arrowMesh(LETTER_Y), material: GREEN, matrices: [ROOT_MATRIX, TO_Y_ARROW_MATRIX] }),
40451
+ [EPiece.Z]: () => exports.GltfGenerator.ToDataUri({ mesh: arrowMesh(LETTER_Z), material: BLUE, matrices: [ROOT_MATRIX] }),
40452
+ [EPiece.XRotation]: () => exports.GltfGenerator.ToDataUri({ mesh: ringMesh(), material: RED, matrices: [ROOT_MATRIX, TO_X_MATRIX] }),
40453
+ [EPiece.YRotation]: () => exports.GltfGenerator.ToDataUri({ mesh: ringMesh(), material: GREEN, matrices: [ROOT_MATRIX, TO_Y_RING_MATRIX] }),
40454
+ [EPiece.ZRotation]: () => exports.GltfGenerator.ToDataUri({ mesh: ringMesh(), material: BLUE, matrices: [ROOT_MATRIX] })
40455
+ };
40456
+ // Built pieces, so every gizmo shares one string per piece and CesiumJS's model cache sees the same url.
40457
+ const built = {};
40458
+ /**
40459
+ * Returns a piece's model as a data URI, to pass wherever a model url is taken.
40460
+ */
40461
+ function GetUri(piece) {
40462
+ if (!built[piece]) {
40463
+ built[piece] = BUILDERS[piece]();
40464
+ }
40465
+ return built[piece];
40466
+ }
40467
+ GltfGizmo.GetUri = GetUri;
40468
+ })(exports.GltfGizmo || (exports.GltfGizmo = {}));
40469
+
40470
+ // viewer[CLASS_INSTANCE_KEY] will point at an instance of MapGridHandler.
40471
+ const CLASS_INSTANCE_KEY = "nextspace-navigator-grid-handler";
40472
+ // viewer[UPDATE_MARKER_KEY] will point at a number that is incremented every time the grid is updated.
40473
+ // This is used to determine if the grid is still valid or if it needs to be redrawn.
40474
+ const UPDATE_MARKER_KEY = "nextspace-marker-grid";
40475
+ // viewer[LAST_SETTINGS_KEY] will point at the last settings used for the grid.
40476
+ const LAST_SETTINGS_KEY = "nextspace-navigator-last-settings-grid";
40477
+ /*
40478
+ * The point a distance in metres along a heading in degrees from another, over a spherical earth.
40479
+ */
40480
+ function offsetPoint$1(point, distance, heading) {
40481
+ // Radius of earth.
40482
+ const radius = 6371e3;
40483
+ const δ = distance / radius;
40484
+ const θ = Cesium.Math.toRadians(heading);
40485
+ const φ1 = Cesium.Math.toRadians(point.latitude);
40486
+ const λ1 = Cesium.Math.toRadians(point.longitude);
40487
+ const sinφ2 = Math.sin(φ1) * Math.cos(δ) + Math.cos(φ1) * Math.sin(δ) * Math.cos(θ);
40488
+ const φ2 = Math.asin(sinφ2);
40489
+ const y = Math.sin(θ) * Math.sin(δ) * Math.cos(φ1);
40490
+ const x = Math.cos(δ) - Math.sin(φ1) * sinφ2;
40491
+ const λ2 = λ1 + Math.atan2(y, x);
40492
+ return {
40493
+ altitude: point.altitude,
40494
+ latitude: Cesium.Math.toDegrees(φ2),
40495
+ longitude: Cesium.Math.toDegrees(λ2)
40496
+ };
40497
+ }
40498
+ /**
40499
+ * Handler for drawing a grid of lines on the map with a specified spacing.
40500
+ * Initially this grid is for model-space viewing which means we start at 0,0 lat/lon and have it expand from there.
40501
+ * However, it should be a general-use tool for drawing a grid anywhere.
40502
+ *
40503
+ * It reacts to camera changes and draws the grid within view with padding.
40504
+ * This helps avoid performance issues around drawing too many lines.
40505
+ */
40506
+ class MapGridHandler {
40507
+ constructor(viewer, spacingInMeters = 100, modelSpace = false) {
40508
+ this.gridCenterGizmoPieces = [];
40509
+ this.maxCacheSize = 1000;
40510
+ // === Thresholds for grid stability.
40511
+ // As a fraction of current grid extent.
40512
+ this.CAMERA_MOVE_THRESHOLD = 0.5;
40513
+ // 40% change in camera height triggers redraw.
40514
+ this.HEIGHT_CHANGE_THRESHOLD = 0.4;
40515
+ // 40% change in grid extent triggers redraw.
40516
+ this.GRID_EXTENT_CHANGE_THRESHOLD = 0.4;
40517
+ // 5km - distance that triggers origin reset.
40518
+ this.EXTREME_DISTANCE_THRESHOLD = 5000;
40519
+ // Grid limits to prevent drawing too many lines.
40520
+ this.MAX_LINES = 500;
40521
+ // 50% padding around visible area.
40522
+ this.VIEW_PADDING_FACTOR = 0.5;
40523
+ // Minimum pixels between grid lines to show them.
40524
+ this.MIN_GRID_PIXEL_SIZE = 20;
40525
+ // Base ratio - will be adjusted dynamically based on spacing size and camera height.
40526
+ this.BASE_MAX_VISIBILITY_RATIO = 30;
40527
+ // Height to spacing ratio.
40528
+ this.HEIGHT_TO_SPACING_RATIO = 100;
40529
+ // === Label settings
40530
+ // Label every nth intersection.
40531
+ this.LABEL_INTERVAL = 2;
40532
+ // Maximum number of labels to show.
40533
+ this.MAX_LABELS = 100;
40534
+ // Spacing levels to use for adaptive spacing.
40535
+ this.SPACING_LEVELS = [
40536
+ 1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 300, 400, 500, 1000, 2000, 2500, 5000, 10000, 20000, 25000, 50000, 100000
40537
+ ];
40538
+ // Minimum zoom distance to prevent precision issues.
40539
+ this.MINIMUM_ZOOM_DISTANCE = 40;
40540
+ // Base spacing to use for adaptive spacing.
40541
+ this.BASE_SPACING = 1;
40542
+ // Maximum number of attempts to find a suitable spacing.
40543
+ this.MAX_ADAPTIVE_ATTEMPTS = 5;
40544
+ this.viewer = viewer;
40545
+ this.spacingInMeters = spacingInMeters;
40546
+ this.isUpdating = false;
40547
+ this.modelSpace = modelSpace;
40548
+ this.lastCameraPosition = null;
40549
+ this.fixedGridOrigin = null;
40550
+ this.lastGridExtent = 0;
40551
+ this.offsetCache = new Map();
40552
+ this.gridPrimitives = new Cesium.PrimitiveCollection();
40553
+ this.viewer.scene.primitives.add(this.gridPrimitives);
40554
+ this.currentMarker = viewer[UPDATE_MARKER_KEY] || 1;
40555
+ const isMac = typeof navigator !== "undefined" && (navigator.platform.toUpperCase().indexOf("MAC") !== -1 ||
40556
+ navigator.userAgent.toUpperCase().indexOf("MAC") !== -1);
40557
+ if (modelSpace && isMac) {
40558
+ console.log("[MAC-FIX] Applying camera distance limits for Mac");
40559
+ viewer.scene.screenSpaceCameraController.minimumZoomDistance = this.MINIMUM_ZOOM_DISTANCE;
40560
+ }
40561
+ const manager = exports.ViewerUtils.GetManager({
40562
+ viewer: this.viewer,
40563
+ createIfMissing: false
40564
+ });
40565
+ if (manager) {
40566
+ this.cameraChangeRemoval = manager.Monitor.Updated().Subscribe(() => {
40567
+ this.onCameraChanged();
40568
+ });
40569
+ }
40570
+ // Initial grid draw.
40571
+ this.onCameraChanged();
40572
+ }
40573
+ Update(spacingInMeters, modelSpace) {
40574
+ this.currentMarker = this.viewer[UPDATE_MARKER_KEY] || 1;
40575
+ let needsUpdate = false;
40576
+ if (this.spacingInMeters !== spacingInMeters) {
40577
+ this.spacingInMeters = spacingInMeters;
40578
+ needsUpdate = true;
40579
+ }
40580
+ if (modelSpace !== undefined && this.modelSpace !== modelSpace) {
40581
+ this.modelSpace = modelSpace;
40582
+ needsUpdate = true;
40583
+ }
40584
+ if (needsUpdate) {
40585
+ this.clearGrid();
40586
+ // When spacing or model space changes, clear the cached origin to force recalculation
40587
+ // This ensures grid alignment at the new spacing.
40588
+ this.fixedGridOrigin = null;
40589
+ this.offsetCache.clear();
40590
+ this.onCameraChanged();
40591
+ }
40592
+ }
40593
+ Dispose() {
40594
+ this.clearGrid();
40595
+ this.clearGizmoPieces();
40596
+ if (this.cameraChangeRemoval) {
40597
+ this.cameraChangeRemoval();
40598
+ this.cameraChangeRemoval = null;
40599
+ }
40600
+ if (this.gridPrimitives) {
40601
+ this.viewer.scene.primitives.remove(this.gridPrimitives);
40602
+ this.gridPrimitives = null;
40603
+ }
40604
+ if (this.viewer) {
40605
+ this.viewer = null;
40606
+ }
40607
+ this.offsetCache.clear();
40608
+ this.fixedGridOrigin = null;
40609
+ }
40610
+ clearGrid() {
40611
+ if (this.gridPrimitives) {
40612
+ this.gridPrimitives.removeAll();
40613
+ this.gridLines = null;
40614
+ this.gridLabels = null;
40615
+ }
40616
+ }
40617
+ calculateAdaptiveSpacing(cameraHeight, baseSpacing) {
40618
+ // Define spacing levels that look good (powers of 2, 5, and 10)
40619
+ const spacingLevels = this.SPACING_LEVELS;
40620
+ // Ensure base spacing is at least 1m
40621
+ const adjustedBaseSpacing = Math.max(this.BASE_SPACING, baseSpacing);
40622
+ // For very close cameras, use much smaller spacing regardless of base
40623
+ if (cameraHeight < 10) {
40624
+ // Find the smallest reasonable spacing for this height
40625
+ // Rule: spacing should be roughly 1/20th to 1/50th of camera height, but at least 1m
40626
+ const targetSpacing = Math.max(this.BASE_SPACING, cameraHeight / 30);
40627
+ // Find the closest spacing level to our target
40628
+ let bestSpacing = this.BASE_SPACING; // Start with minimum
40629
+ let bestDifference = Math.abs(1 - targetSpacing);
40630
+ for (const spacing of spacingLevels) {
40631
+ if (spacing >= this.BASE_SPACING) { // Only consider valid spacings
40632
+ const difference = Math.abs(spacing - targetSpacing);
40633
+ if (difference < bestDifference) {
40634
+ bestSpacing = spacing;
40635
+ bestDifference = difference;
40636
+ }
40637
+ }
40638
+ }
40639
+ return bestSpacing;
40640
+ }
40641
+ // For medium distances (10m - 200m), scale more gradually
40642
+ if (cameraHeight < 200) {
40643
+ const targetSpacing = cameraHeight / 10; // More conservative scaling// Find closest spacing level, but prefer going up from base spacing
40644
+ let bestSpacing = adjustedBaseSpacing;
40645
+ let bestDifference = Math.abs(adjustedBaseSpacing - targetSpacing);
40646
+ for (const spacing of spacingLevels) {
40647
+ if (spacing >= Math.min(adjustedBaseSpacing, targetSpacing)) {
40648
+ const difference = Math.abs(spacing - targetSpacing);
40649
+ if (difference < bestDifference) {
40650
+ bestSpacing = spacing;
40651
+ bestDifference = difference;
40652
+ }
40653
+ }
40654
+ }
40655
+ return bestSpacing;
40656
+ }
40657
+ // For far distances (100m+), scale up aggressively
40658
+ const targetSpacing = cameraHeight / 20;
40659
+ // Find the spacing level that's closest to target but not smaller than base
40660
+ let bestSpacing = adjustedBaseSpacing;
40661
+ let bestDifference = Math.abs(adjustedBaseSpacing - targetSpacing);
40662
+ for (const spacing of spacingLevels) {
40663
+ if (spacing >= adjustedBaseSpacing) {
40664
+ const difference = Math.abs(spacing - targetSpacing);
40665
+ if (difference < bestDifference) {
40666
+ bestSpacing = spacing;
40667
+ bestDifference = difference;
40668
+ }
40669
+ }
40670
+ }
40671
+ return bestSpacing;
40672
+ }
40673
+ /*
40674
+ * The point model-space treats as 0,0,0: the UCS in UCS placement, otherwise 0,0 lat/lon at sea level.
40675
+ */
40676
+ modelSpaceOrigin() {
40677
+ const origin = exports.ViewUtils.IsModelSpaceUcs(this.viewer) ? exports.ViewUtils.GetModelSpaceOrigin(this.viewer) : null;
40678
+ return origin !== null && origin !== void 0 ? origin : { latitude: 0, longitude: 0, altitude: 0 };
40679
+ }
40680
+ /*
40681
+ * The origin as a scene position, where the axis gizmo sits.
40682
+ */
40683
+ modelSpaceOriginPos3d() {
40684
+ const origin = this.modelSpaceOrigin();
40685
+ return Cesium.Cartesian3.fromDegrees(origin.longitude, origin.latitude, origin.altitude);
40686
+ }
40687
+ drawGizmoPieces() {
40688
+ if (this.gridCenterGizmoPieces.length) {
40689
+ return;
40690
+ }
40691
+ // X.
40692
+ {
40693
+ const pos3d = this.modelSpaceOriginPos3d();
40694
+ const scale = new Cesium.CallbackProperty(() => Cesium.Cartesian3.distance(this.viewer.camera.position, pos3d) * 0.0002, false);
40695
+ const orientation = Cesium.Transforms.headingPitchRollQuaternion(pos3d, new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(90), 0, 0));
40696
+ const entity = this.viewer.entities.add(new Cesium.Entity({
40697
+ model: {
40698
+ uri: exports.GltfGizmo.GetUri(exports.GltfGizmo.EPiece.X),
40699
+ heightReference: Cesium.HeightReference.NONE,
40700
+ shadows: Cesium.ShadowMode.DISABLED,
40701
+ distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, Number.MAX_VALUE),
40702
+ scale
40703
+ },
40704
+ position: pos3d,
40705
+ orientation: new Cesium.ConstantProperty(orientation)
40706
+ }));
40707
+ this.gridCenterGizmoPieces.push(entity);
40708
+ }
40709
+ // Y.
40710
+ {
40711
+ const pos3d = this.modelSpaceOriginPos3d();
40712
+ const scale = new Cesium.CallbackProperty(() => Cesium.Cartesian3.distance(this.viewer.camera.position, pos3d) * 0.0002, false);
40713
+ const orientation = Cesium.Transforms.headingPitchRollQuaternion(pos3d, new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(90), 0, 0));
40714
+ const entity = this.viewer.entities.add(new Cesium.Entity({
40715
+ model: {
40716
+ uri: exports.GltfGizmo.GetUri(exports.GltfGizmo.EPiece.Y),
40717
+ heightReference: Cesium.HeightReference.NONE,
40718
+ shadows: Cesium.ShadowMode.DISABLED,
40719
+ distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, Number.MAX_VALUE),
40720
+ scale
40721
+ },
40722
+ position: pos3d,
40723
+ orientation: new Cesium.ConstantProperty(orientation)
40724
+ }));
40725
+ this.gridCenterGizmoPieces.push(entity);
40726
+ }
40727
+ // Z.
40728
+ {
40729
+ const pos3d = this.modelSpaceOriginPos3d();
40730
+ const scale = new Cesium.CallbackProperty(() => Cesium.Cartesian3.distance(this.viewer.camera.position, pos3d) * 0.0002, false);
40731
+ const orientation = Cesium.Transforms.headingPitchRollQuaternion(pos3d, new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(90), 0, 0));
40732
+ const entity = this.viewer.entities.add(new Cesium.Entity({
40733
+ model: {
40734
+ uri: exports.GltfGizmo.GetUri(exports.GltfGizmo.EPiece.Z),
40735
+ heightReference: Cesium.HeightReference.NONE,
40736
+ shadows: Cesium.ShadowMode.DISABLED,
40737
+ distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, Number.MAX_VALUE),
40738
+ scale
40739
+ },
40740
+ position: pos3d,
40741
+ orientation: new Cesium.ConstantProperty(orientation)
40742
+ }));
40743
+ this.gridCenterGizmoPieces.push(entity);
40744
+ }
40745
+ }
40746
+ clearGizmoPieces() {
40747
+ for (const piece of this.gridCenterGizmoPieces) {
40748
+ if (piece && this.viewer.entities.contains(piece)) {
40749
+ this.viewer.entities.remove(piece);
40750
+ }
40751
+ }
40752
+ this.gridCenterGizmoPieces = [];
40753
+ }
40754
+ onCameraChanged() {
40755
+ if (this.isUpdating) {
40756
+ return;
40757
+ }
40758
+ else if (this.currentMarker !== this.viewer[UPDATE_MARKER_KEY]) {
40759
+ return;
40760
+ }
40761
+ this.isUpdating = true;
40762
+ // Small delay to avoid excessive updates during camera movement.
40763
+ setTimeout(() => {
40764
+ if (this.currentMarker !== this.viewer[UPDATE_MARKER_KEY]) {
40765
+ this.isUpdating = false;
40766
+ return;
40767
+ }
40768
+ try {
40769
+ // The grid goes first, since it notices when the origin has moved and the gizmo has to follow.
40770
+ this.updateGrid();
40771
+ if (this.modelSpace) {
40772
+ this.drawGizmoPieces();
40773
+ }
40774
+ else {
40775
+ this.clearGizmoPieces();
40776
+ }
40777
+ }
40778
+ catch (e) {
40779
+ console.error(e);
40780
+ }
40781
+ finally {
40782
+ this.isUpdating = false;
40783
+ }
40784
+ }, 100);
40785
+ }
40786
+ cachedOffsetPoint(point, distance, heading) {
40787
+ const key = `${point.latitude.toFixed(8)},${point.longitude.toFixed(8)},${distance.toFixed(1)},${heading}`;
40788
+ if (this.offsetCache.has(key)) {
40789
+ return this.offsetCache.get(key);
40790
+ }
40791
+ const result = offsetPoint$1(point, distance, heading);
40792
+ this.offsetCache.set(key, result);
40793
+ if (this.offsetCache.size > this.maxCacheSize) {
40794
+ const keys = Array.from(this.offsetCache.keys());
40795
+ for (let i = 0; i < 100; i++) {
40796
+ this.offsetCache.delete(keys[i]);
40797
+ }
40798
+ }
40799
+ return result;
40800
+ }
40801
+ /**
40802
+ * Calculates a dynamic visibility ratio based on spacing size.
40803
+ * For small grid spacings, we can show the grid from farther away.
40804
+ * For large grid spacings, we need to hide it sooner to prevent performance issues.
40805
+ */
40806
+ getMaxVisibilityRatio() {
40807
+ if (this.spacingInMeters <= 10) {
40808
+ return this.BASE_MAX_VISIBILITY_RATIO;
40809
+ }
40810
+ if (this.spacingInMeters <= 100) {
40811
+ const factor = 1 - ((this.spacingInMeters - 10) / 90);
40812
+ return this.BASE_MAX_VISIBILITY_RATIO * (0.5 + (factor * 0.5));
40813
+ }
40814
+ const largeGridFactor = Math.min(1, 100 / this.spacingInMeters);
40815
+ return this.BASE_MAX_VISIBILITY_RATIO * 0.5 * largeGridFactor;
40816
+ }
40817
+ updateGrid() {
40818
+ const cameraPosition = this.viewer.camera.position;
40819
+ const cameraCartographic = Cesium.Cartographic.fromCartesian(cameraPosition);
40820
+ const cameraHeight = cameraCartographic.height;
40821
+ let adaptiveSpacing = this.calculateAdaptiveSpacing(cameraHeight, this.spacingInMeters);
40822
+ // Calculate visible area.
40823
+ const visibleArea = this.calculateVisibleArea();
40824
+ if (!visibleArea) {
40825
+ return;
40826
+ }
40827
+ let densityCheckPassed = false;
40828
+ let attempts = 0;
40829
+ while (!densityCheckPassed && attempts < this.MAX_ADAPTIVE_ATTEMPTS) {
40830
+ if (this.isGridDensityAcceptable(visibleArea, cameraHeight, adaptiveSpacing)) {
40831
+ densityCheckPassed = true;
40832
+ }
40833
+ else {
40834
+ adaptiveSpacing *= 2;
40835
+ attempts++;
40836
+ }
40837
+ }
40838
+ // The origin follows the UCS of what is shown, so the grid moves with it when that changes.
40839
+ if (this.modelSpace && this.fixedGridOrigin && !BModels.Carto.IsEqual(this.fixedGridOrigin, this.modelSpaceOrigin())) {
40840
+ this.fixedGridOrigin = null;
40841
+ this.lastCameraPosition = null;
40842
+ this.clearGizmoPieces();
40843
+ }
40844
+ // Calculate grid origin if we don't have one yet.
40845
+ if (!this.fixedGridOrigin) {
40846
+ if (this.modelSpace) {
40847
+ this.fixedGridOrigin = this.modelSpaceOrigin();
40848
+ }
40849
+ else {
40850
+ const centerCartographic = Cesium.Cartographic.fromCartesian(visibleArea.centerCartesian);
40851
+ const centerPoint = {
40852
+ latitude: Cesium.Math.toDegrees(centerCartographic.latitude),
40853
+ longitude: Cesium.Math.toDegrees(centerCartographic.longitude),
40854
+ altitude: 0
40855
+ };
40856
+ // Simple attempt at snapping to the grid, should do something smarter.
40857
+ this.fixedGridOrigin = {
40858
+ latitude: Math.round(centerPoint.latitude * 100000) / 100000,
40859
+ longitude: Math.round(centerPoint.longitude * 100000) / 100000,
40860
+ altitude: 0
40861
+ };
40862
+ }
40863
+ }
40864
+ // Calculate appropriate grid extent based on camera height.
40865
+ // For larger grid spacings, we use a tighter extent to prevent performance issues.
40866
+ const scaledExtentFactor = Math.max(0.5, Math.min(3, 3 - Math.log10(Math.max(1, adaptiveSpacing)) * 0.5));
40867
+ const visibilityRadius = Math.min(cameraHeight * scaledExtentFactor, Infinity);
40868
+ // Check if we should redraw the grid.
40869
+ const shouldRedraw = this.shouldRedrawGrid(cameraPosition, cameraHeight, visibilityRadius, adaptiveSpacing);
40870
+ if (!shouldRedraw) {
40871
+ return;
40872
+ }
40873
+ // Remember current settings for next comparison.
40874
+ this.lastCameraHeight = cameraHeight;
40875
+ this.lastCameraPosition = cameraPosition.clone();
40876
+ this.lastGridExtent = visibilityRadius;
40877
+ // Clear existing grid and create a new one.
40878
+ this.clearGrid();
40879
+ this.gridLines = new Cesium.PolylineCollection();
40880
+ this.gridLabels = new Cesium.LabelCollection({
40881
+ scene: this.viewer.scene
40882
+ });
40883
+ this.gridPrimitives.add(this.gridLines);
40884
+ this.gridPrimitives.add(this.gridLabels);
40885
+ // Generate grid lines and labels using our fixed origin.
40886
+ this.generateGridLines(this.fixedGridOrigin, visibilityRadius, adaptiveSpacing);
40887
+ }
40888
+ shouldRedrawGrid(cameraPosition, cameraHeight, gridExtent, currentSpacing) {
40889
+ // check if the spacing has changed
40890
+ if (this.lastUsedSpacing && this.lastUsedSpacing !== currentSpacing) {
40891
+ return true;
40892
+ }
40893
+ // Always draw if we don't have a grid yet.
40894
+ if (!this.gridLines || !this.lastCameraPosition || !this.fixedGridOrigin) {
40895
+ return true;
40896
+ }
40897
+ // Check for significant height change.
40898
+ const heightRatio = cameraHeight / this.lastCameraHeight;
40899
+ if (heightRatio > (1 + this.HEIGHT_CHANGE_THRESHOLD) ||
40900
+ heightRatio < (1 - this.HEIGHT_CHANGE_THRESHOLD)) {
40901
+ return true;
40902
+ }
40903
+ // Check for significant position change relative to current grid extent.
40904
+ const distance = Cesium.Cartesian3.distance(cameraPosition, this.lastCameraPosition);
40905
+ const moveThreshold = gridExtent * this.CAMERA_MOVE_THRESHOLD;
40906
+ if (distance > moveThreshold) {
40907
+ return true;
40908
+ }
40909
+ // Check for significant grid extent change.
40910
+ const extentRatio = gridExtent / this.lastGridExtent;
40911
+ if (extentRatio > (1 + this.GRID_EXTENT_CHANGE_THRESHOLD) ||
40912
+ extentRatio < (1 - this.GRID_EXTENT_CHANGE_THRESHOLD)) {
40913
+ return true;
40914
+ }
40915
+ // No significant changes, keep current grid.
40916
+ return false;
40917
+ }
40918
+ isGridDensityAcceptable(visibleArea, cameraHeight, spacingToCheck = this.spacingInMeters) {
40919
+ const lonRange = visibleArea.eastLon - visibleArea.westLon;
40920
+ const latRange = visibleArea.northLat - visibleArea.southLat;
40921
+ // Convert to approximate meters at center
40922
+ const centerCartographic = Cesium.Cartographic.fromCartesian(visibleArea.centerCartesian);
40923
+ const metersPerDegreeLon = 111319.9 * Math.cos(centerCartographic.latitude);
40924
+ const canvas = this.viewer.scene.canvas;
40925
+ const spacingInDegrees = spacingToCheck / metersPerDegreeLon;
40926
+ const canvasWidth = canvas.clientWidth;
40927
+ const pixelsPerDegree = canvasWidth / lonRange;
40928
+ const pixelsBetweenGridLines = pixelsPerDegree * spacingInDegrees;
40929
+ const minPixelSize = 1;
40930
+ return pixelsBetweenGridLines >= minPixelSize;
40931
+ }
40932
+ calculateVisibleArea() {
40933
+ const scene = this.viewer.scene;
40934
+ const camera = scene.camera;
40935
+ const globe = scene.globe;
40936
+ // Get the corners of the view frustum
40937
+ const canvas = scene.canvas;
40938
+ const corners = [
40939
+ new Cesium.Cartesian2(0, 0),
40940
+ new Cesium.Cartesian2(canvas.clientWidth, 0),
40941
+ new Cesium.Cartesian2(0, canvas.clientHeight),
40942
+ new Cesium.Cartesian2(canvas.clientWidth, canvas.clientHeight),
40943
+ new Cesium.Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2) // Center
40944
+ ];
40945
+ // Project corners to the globe
40946
+ const cartographicCorners = [];
40947
+ for (const corner of corners) {
40948
+ const ray = camera.getPickRay(corner);
40949
+ if (!ray) {
40950
+ continue;
40951
+ }
40952
+ const position = globe.pick(ray, scene);
40953
+ if (!position) {
40954
+ continue;
40955
+ }
40956
+ cartographicCorners.push(Cesium.Cartographic.fromCartesian(position));
40957
+ }
40958
+ if (cartographicCorners.length === 0) {
40959
+ return null;
40960
+ }
40961
+ // Find the bounding rectangle
40962
+ let westLon = Number.POSITIVE_INFINITY;
40963
+ let eastLon = Number.NEGATIVE_INFINITY;
40964
+ let southLat = Number.POSITIVE_INFINITY;
40965
+ let northLat = Number.NEGATIVE_INFINITY;
40966
+ for (const corner of cartographicCorners) {
40967
+ westLon = Math.min(westLon, corner.longitude);
40968
+ eastLon = Math.max(eastLon, corner.longitude);
40969
+ southLat = Math.min(southLat, corner.latitude);
40970
+ northLat = Math.max(northLat, corner.latitude);
40971
+ }
40972
+ // Add some padding around the visible area
40973
+ const lonPadding = (eastLon - westLon) * this.VIEW_PADDING_FACTOR;
40974
+ const latPadding = (northLat - southLat) * this.VIEW_PADDING_FACTOR;
40975
+ westLon -= lonPadding;
40976
+ eastLon += lonPadding;
40977
+ southLat -= latPadding;
40978
+ northLat += latPadding;
40979
+ // Get center position for reference
40980
+ const centerCartographic = new Cesium.Cartographic((westLon + eastLon) / 2, (southLat + northLat) / 2);
40981
+ const centerCartesian = Cesium.Cartesian3.fromRadians(centerCartographic.longitude, centerCartographic.latitude, 0);
40982
+ return {
40983
+ westLon: Cesium.Math.toDegrees(westLon),
40984
+ eastLon: Cesium.Math.toDegrees(eastLon),
40985
+ southLat: Cesium.Math.toDegrees(southLat),
40986
+ northLat: Cesium.Math.toDegrees(northLat),
40987
+ centerCartesian: centerCartesian
40988
+ };
40989
+ }
40990
+ generateGridLines(originPoint, visibilityRadius, actualSpacing = this.spacingInMeters) {
40991
+ // Number of grid cells in each direction (add 1 for edge lines).
40992
+ const gridCellCount = Math.ceil(visibilityRadius / actualSpacing) + 1;
40993
+ const maxCells = Math.min(gridCellCount, Math.floor(this.MAX_LINES / 2));
40994
+ // Calculate interval to skip lines for density control.
40995
+ const spacingFactor = actualSpacing / 100;
40996
+ const heightFactor = this.lastCameraHeight / 500;
40997
+ let lineSkipInterval = Math.floor(spacingFactor * heightFactor);
40998
+ lineSkipInterval = Math.min(Math.max(lineSkipInterval, 1), 10); // Clamp between 1 and 10
40999
+ const intersections = [];
41000
+ // Generate north-south grid lines (longitude lines)
41001
+ for (let i = -maxCells; i <= maxCells; i++) {
41002
+ if (i % lineSkipInterval !== 0) {
41003
+ continue;
41004
+ }
41005
+ const positions = [];
41006
+ // Create a vertical line at this longitude offset.
41007
+ // East heading for longitude.
41008
+ const startPoint = this.cachedOffsetPoint(originPoint, i * actualSpacing, 90);
41009
+ // Draw the line from south to north
41010
+ for (let j = -maxCells; j <= maxCells; j++) {
41011
+ if (j % lineSkipInterval !== 0) {
41012
+ continue;
41013
+ }
41014
+ // North heading for latitude.
41015
+ const linePoint = this.cachedOffsetPoint(startPoint, j * actualSpacing, 0);
41016
+ const position = Cesium.Cartesian3.fromDegrees(linePoint.longitude, linePoint.latitude, linePoint.altitude);
41017
+ positions.push(position);
41018
+ intersections.push({
41019
+ position: position,
41020
+ i: i,
41021
+ j: j
41022
+ });
41023
+ }
41024
+ if (positions.length >= 2) {
41025
+ // Check if this is the primary Y axis (i=0) in model space
41026
+ const isPrimaryYAxis = this.modelSpace && i === 0;
41027
+ this.addGridLine(positions, isPrimaryYAxis ? "y" : null);
41028
+ }
41029
+ }
41030
+ // Generate east-west grid lines (latitude lines).
41031
+ for (let j = -maxCells; j <= maxCells; j++) {
41032
+ if (j % lineSkipInterval !== 0) {
41033
+ continue;
41034
+ }
41035
+ const positions = [];
41036
+ // Create a horizontal line at this latitude offset
41037
+ // North heading for latitude.
41038
+ const startPoint = this.cachedOffsetPoint(originPoint, j * actualSpacing, 0);
41039
+ // Draw the line from west to east.
41040
+ for (let i = -maxCells; i <= maxCells; i++) {
41041
+ if (i % lineSkipInterval !== 0) {
41042
+ continue;
41043
+ }
41044
+ // East heading for longitude.
41045
+ const linePoint = this.cachedOffsetPoint(startPoint, i * actualSpacing, 90);
41046
+ const position = Cesium.Cartesian3.fromDegrees(linePoint.longitude, linePoint.latitude, linePoint.altitude);
41047
+ positions.push(position);
41048
+ }
41049
+ if (positions.length >= 2) {
41050
+ // Check if this is the primary X axis (j=0) in model space
41051
+ const isPrimaryXAxis = this.modelSpace && j === 0;
41052
+ this.addGridLine(positions, isPrimaryXAxis ? "x" : null);
41053
+ }
41054
+ }
41055
+ this.addGridLabels(intersections, actualSpacing);
41056
+ }
41057
+ addGridLabels(intersections, actualSpacing) {
41058
+ if (!this.gridLabels) {
41059
+ return;
41060
+ }
41061
+ // Determine label interval based on number of intersections.
41062
+ // Use higher interval for more intersections to prevent crowding.
41063
+ const totalIntersections = intersections.length;
41064
+ let labelInterval = this.LABEL_INTERVAL;
41065
+ if (totalIntersections > 1000) {
41066
+ labelInterval = 5;
41067
+ }
41068
+ else if (totalIntersections > 500) {
41069
+ labelInterval = 3;
41070
+ }
41071
+ let labelCount = 0;
41072
+ // Filter intersections to only those at the labelInterval.
41073
+ const labelPoints = intersections.filter(point => {
41074
+ // Always label the origin (0,0).
41075
+ if (point.i === 0 && point.j === 0) {
41076
+ return true;
41077
+ }
41078
+ return (point.i % labelInterval === 0 && point.j % labelInterval === 0);
41079
+ });
41080
+ // Sort points by distance from origin.
41081
+ labelPoints.sort((a, b) => {
41082
+ const distA = Math.abs(a.i) + Math.abs(a.j);
41083
+ const distB = Math.abs(b.i) + Math.abs(b.j);
41084
+ return distA - distB;
41085
+ });
41086
+ // Add labels, prioritizing those closest to the origin.
41087
+ for (const point of labelPoints) {
41088
+ if (labelCount >= this.MAX_LABELS) {
41089
+ // Limit reached.
41090
+ break;
41091
+ }
41092
+ let labelText;
41093
+ // Model space coordinates (meters from origin).
41094
+ if (this.modelSpace) {
41095
+ const xMeters = point.i * actualSpacing;
41096
+ const yMeters = point.j * actualSpacing;
41097
+ if (point.i === 0 && point.j === 0) {
41098
+ labelText = "0,0,0";
41099
+ }
41100
+ else {
41101
+ labelText = `${xMeters},${yMeters}`;
41102
+ }
41103
+ }
41104
+ // Geographic coordinates (degrees).
41105
+ else {
41106
+ const cartographic = Cesium.Cartographic.fromCartesian(point.position);
41107
+ const latitude = Cesium.Math.toDegrees(cartographic.latitude);
41108
+ const longitude = Cesium.Math.toDegrees(cartographic.longitude);
41109
+ const latFormatted = latitude.toFixed(5);
41110
+ const lonFormatted = longitude.toFixed(5);
41111
+ labelText = `${latFormatted}, ${lonFormatted}`;
41112
+ }
41113
+ this.gridLabels.add({
41114
+ position: point.position,
41115
+ text: labelText,
41116
+ font: this.modelSpace && point.i === 0 && point.j === 0 ? "20px sans-serif" : "14px sans-serif",
41117
+ fillColor: this.modelSpace && point.i === 0 && point.j === 0 ? Cesium.Color.WHITE : Cesium.Color.WHITE.withAlpha(0.5),
41118
+ style: Cesium.LabelStyle.FILL,
41119
+ horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
41120
+ verticalOrigin: Cesium.VerticalOrigin.TOP,
41121
+ pixelOffset: new Cesium.Cartesian2(0, 10),
41122
+ // Fade out with distance.
41123
+ translucencyByDistance: new Cesium.NearFarScalar(1000, 1.0, 15000, 0.4)
41124
+ });
41125
+ labelCount++;
41126
+ }
41127
+ }
41128
+ addGridLine(positions, primaryAxis = null) {
41129
+ if (!this.gridLines || positions.length < 2) {
41130
+ return;
41131
+ }
41132
+ let lineColor;
41133
+ let lineWidth = 1.0;
41134
+ let lineAlpha = 0.2;
41135
+ // Red for X axis.
41136
+ if (primaryAxis === "x") {
41137
+ lineColor = Cesium.Color.RED;
41138
+ lineAlpha = 0.5;
41139
+ lineWidth = 1.5;
41140
+ }
41141
+ // Green for Y axis.
41142
+ else if (primaryAxis === "y") {
41143
+ lineColor = Cesium.Color.GREEN;
41144
+ lineAlpha = 0.5;
41145
+ lineWidth = 1.5;
41146
+ }
41147
+ // Default gray for regular grid lines.
41148
+ else {
41149
+ lineColor = Cesium.Color.LIGHTGRAY;
41150
+ }
41151
+ this.gridLines.add({
41152
+ positions: positions,
41153
+ width: lineWidth,
41154
+ material: Cesium.Material.fromType("Color", {
41155
+ color: lineColor.withAlpha(lineAlpha)
41156
+ })
41157
+ });
41158
+ }
41159
+ }
41160
+ // Grid square size used when settings name none, in metres.
41161
+ const DEFAULT_SPACING = 50;
41162
+ (function (CesiumMapGrid) {
41163
+ function GetCurrentSpacing(viewer) {
41164
+ if (!viewer || viewer.isDestroyed()) {
41165
+ return 0;
41166
+ }
41167
+ const handler = viewer[CLASS_INSTANCE_KEY];
41168
+ return handler ? handler.getCurrentSpacing() : 0;
41169
+ }
41170
+ CesiumMapGrid.GetCurrentSpacing = GetCurrentSpacing;
41171
+ function Remove(viewer) {
41172
+ if (!viewer || viewer.isDestroyed()) {
41173
+ return;
41174
+ }
41175
+ else if (!viewer[LAST_SETTINGS_KEY]) {
41176
+ return;
41177
+ }
41178
+ if (!viewer[UPDATE_MARKER_KEY]) {
41179
+ viewer[UPDATE_MARKER_KEY] = 1;
41180
+ }
41181
+ else {
41182
+ viewer[UPDATE_MARKER_KEY]++;
41183
+ }
41184
+ // Dispose of the handler.
41185
+ if (viewer[CLASS_INSTANCE_KEY]) {
41186
+ viewer[CLASS_INSTANCE_KEY].Dispose();
41187
+ viewer[CLASS_INSTANCE_KEY] = null;
41188
+ }
41189
+ viewer[LAST_SETTINGS_KEY] = {
41190
+ ...viewer[LAST_SETTINGS_KEY],
41191
+ enabled: false
41192
+ };
41193
+ }
41194
+ CesiumMapGrid.Remove = Remove;
41195
+ function Draw(viewer, spacingInMeters, modelSpace = true) {
41196
+ if (!viewer || viewer.isDestroyed()) {
41197
+ return;
41198
+ }
41199
+ let settings = viewer[LAST_SETTINGS_KEY];
41200
+ if (settings) {
41201
+ // See if the settings are the same as the last time.
41202
+ if (settings.spacing === spacingInMeters &&
41203
+ settings.modelSpace === modelSpace &&
41204
+ settings.enabled) {
41205
+ return;
41206
+ }
41207
+ }
41208
+ if (!viewer[UPDATE_MARKER_KEY]) {
41209
+ viewer[UPDATE_MARKER_KEY] = 1;
41210
+ }
41211
+ else {
41212
+ viewer[UPDATE_MARKER_KEY]++;
41213
+ }
41214
+ settings = {
41215
+ ...settings,
41216
+ enabled: true,
41217
+ spacing: spacingInMeters,
41218
+ modelSpace: modelSpace
41219
+ };
41220
+ viewer[LAST_SETTINGS_KEY] = settings;
41221
+ // Create or update the handler.
41222
+ if (viewer[CLASS_INSTANCE_KEY]) {
41223
+ viewer[CLASS_INSTANCE_KEY].Update(spacingInMeters, modelSpace);
41224
+ }
41225
+ else {
41226
+ viewer[CLASS_INSTANCE_KEY] = new MapGridHandler(viewer, spacingInMeters, modelSpace);
41227
+ }
41228
+ }
41229
+ CesiumMapGrid.Draw = Draw;
41230
+ /**
41231
+ * Draws a bookmark's grid, or removes the grid when it has none; only model-space draws one.
41232
+ */
41233
+ function Apply(viewer, grid, modelSpace) {
41234
+ if ((grid === null || grid === void 0 ? void 0 : grid.enabled) && modelSpace) {
41235
+ Draw(viewer, Number(grid.spacing) || DEFAULT_SPACING, modelSpace);
41236
+ }
41237
+ else {
41238
+ Remove(viewer);
41239
+ }
41240
+ }
41241
+ CesiumMapGrid.Apply = Apply;
41242
+ function GetIsEnabled(viewer) {
41243
+ if (!viewer || viewer.isDestroyed()) {
41244
+ return false;
41245
+ }
41246
+ const settings = viewer[LAST_SETTINGS_KEY];
41247
+ if (settings) {
41248
+ return Boolean(settings.enabled);
41249
+ }
41250
+ return false;
41251
+ }
41252
+ CesiumMapGrid.GetIsEnabled = GetIsEnabled;
41253
+ /**
41254
+ * Returns the last applied grid settings.
41255
+ */
41256
+ function GetSettings(viewer) {
41257
+ if (!viewer || viewer.isDestroyed()) {
41258
+ return null;
41259
+ }
41260
+ return viewer[LAST_SETTINGS_KEY];
41261
+ }
41262
+ CesiumMapGrid.GetSettings = GetSettings;
41263
+ })(exports.CesiumMapGrid || (exports.CesiumMapGrid = {}));
41264
+
38715
41265
  // TODO: Move these to the data model.
38716
41266
  const MIN_SHADOW_SIZE = 2048;
38717
41267
  const MAX_SHADOW_SIZE = 32768;
@@ -38903,7 +41453,7 @@
38903
41453
  * @param view
38904
41454
  */
38905
41455
  async function renderNavigator(iteration, params, bookmark, view, getters) {
38906
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8;
41456
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9;
38907
41457
  const viewer = params.manager.Viewer;
38908
41458
  const scene = viewer.scene;
38909
41459
  // Ion requests go through the server-side proxy (set up during viewer init or here as fallback).
@@ -39128,15 +41678,7 @@
39128
41678
  scene.globe.translucency.frontFaceAlphaByDistance.farValue = 1;
39129
41679
  }
39130
41680
  scene.globe.translucency.frontFaceAlphaByDistance.nearValue = EnsureNumber(globeAlpha, 1);
39131
- let shadows = bSettings === null || bSettings === void 0 ? void 0 : bSettings.shadows;
39132
- if (shadows == null) {
39133
- shadows = (_u = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _u === void 0 ? void 0 : _u.shadows;
39134
- }
39135
- if (shadows == null) {
39136
- shadows = {
39137
- enabled: false
39138
- };
39139
- }
41681
+ const shadows = exports.ViewRenderEngine.ResolveShadows(bSettings, defaults === null || defaults === void 0 ? void 0 : defaults.settings, contentType);
39140
41682
  viewer.shadows = Boolean(shadows.enabled);
39141
41683
  viewer.shadowMap.enabled = Boolean(shadows.enabled);
39142
41684
  let size = EnsureNumber(shadows.pixelSize);
@@ -39149,9 +41691,11 @@
39149
41691
  viewer.shadowMap.size = size;
39150
41692
  viewer.shadowMap.softShadows = Boolean(shadows.soften);
39151
41693
  viewer.shadowMap.darkness = EnsureNumber(shadows.darkness, 0.3);
41694
+ // Drawn after the model-space origin is resolved above, since the grid starts from it.
41695
+ exports.CesiumMapGrid.Apply(viewer, (_u = bSettings.grid) !== null && _u !== void 0 ? _u : (_v = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _v === void 0 ? void 0 : _v.grid, contentType == BModels.ProjectViewBookmark.EContentType.WEB_3D_MODEL_SPACE);
39152
41696
  let ambientOcclusion = bSettings === null || bSettings === void 0 ? void 0 : bSettings.ambientOcclusion;
39153
41697
  if (ambientOcclusion == null) {
39154
- ambientOcclusion = (_v = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _v === void 0 ? void 0 : _v.ambientOcclusion;
41698
+ ambientOcclusion = (_w = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _w === void 0 ? void 0 : _w.ambientOcclusion;
39155
41699
  }
39156
41700
  if (ambientOcclusion == null) {
39157
41701
  ambientOcclusion = {
@@ -39174,7 +41718,7 @@
39174
41718
  }
39175
41719
  let lighting = bSettings === null || bSettings === void 0 ? void 0 : bSettings.lighting;
39176
41720
  if (lighting == null) {
39177
- lighting = (_w = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _w === void 0 ? void 0 : _w.lighting;
41721
+ lighting = (_x = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _x === void 0 ? void 0 : _x.lighting;
39178
41722
  }
39179
41723
  if (lighting == null) {
39180
41724
  lighting = {
@@ -39192,7 +41736,7 @@
39192
41736
  exports.ViewUtils.ApplyDefaultBrightness(viewer, EnsureNumber(lighting.brightnessShift, DEFAULT_BRIGHTNESS_SHIFT));
39193
41737
  let quality = bSettings === null || bSettings === void 0 ? void 0 : bSettings.quality;
39194
41738
  if (quality == null) {
39195
- quality = (_x = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _x === void 0 ? void 0 : _x.quality;
41739
+ quality = (_y = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _y === void 0 ? void 0 : _y.quality;
39196
41740
  }
39197
41741
  if (quality == null) {
39198
41742
  quality = {
@@ -39203,11 +41747,11 @@
39203
41747
  fxaa.enabled = Boolean(quality.fxaa);
39204
41748
  let dateTime = bSettings === null || bSettings === void 0 ? void 0 : bSettings.dateTime;
39205
41749
  if (dateTime == null) {
39206
- dateTime = (_y = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _y === void 0 ? void 0 : _y.dateTime;
41750
+ dateTime = (_z = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _z === void 0 ? void 0 : _z.dateTime;
39207
41751
  }
39208
41752
  let timeline = bSettings === null || bSettings === void 0 ? void 0 : bSettings.timeline;
39209
41753
  if (timeline == null) {
39210
- timeline = (_z = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _z === void 0 ? void 0 : _z.timeline;
41754
+ timeline = (_0 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _0 === void 0 ? void 0 : _0.timeline;
39211
41755
  }
39212
41756
  if (timeline == null) {
39213
41757
  timeline = {
@@ -39231,7 +41775,7 @@
39231
41775
  // Newer version that has states per Entity ID + Menu Item ID.
39232
41776
  let states = bSettings === null || bSettings === void 0 ? void 0 : bSettings.states;
39233
41777
  if (states == null) {
39234
- states = (_0 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _0 === void 0 ? void 0 : _0.states;
41778
+ states = (_1 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _1 === void 0 ? void 0 : _1.states;
39235
41779
  }
39236
41780
  if (states != null) {
39237
41781
  params.manager.VisualsRegister.OverrideStates(states);
@@ -39240,7 +41784,7 @@
39240
41784
  else {
39241
41785
  let selectedIds = bSettings === null || bSettings === void 0 ? void 0 : bSettings.selectedEntityIds;
39242
41786
  if (selectedIds == null) {
39243
- selectedIds = (_1 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _1 === void 0 ? void 0 : _1.selectedEntityIds;
41787
+ selectedIds = (_2 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _2 === void 0 ? void 0 : _2.selectedEntityIds;
39244
41788
  }
39245
41789
  if (selectedIds != null) {
39246
41790
  params.manager.VisualsRegister.ClearSelected();
@@ -39254,7 +41798,7 @@
39254
41798
  params.manager.VisualsRegister.ClearHidden();
39255
41799
  let hiddenIds = bSettings === null || bSettings === void 0 ? void 0 : bSettings.hiddenEntityIds;
39256
41800
  if (hiddenIds == null) {
39257
- hiddenIds = (_2 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _2 === void 0 ? void 0 : _2.hiddenEntityIds;
41801
+ hiddenIds = (_3 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _3 === void 0 ? void 0 : _3.hiddenEntityIds;
39258
41802
  }
39259
41803
  if (hiddenIds != null) {
39260
41804
  params.manager.VisualsRegister.SetHidden({
@@ -39266,7 +41810,7 @@
39266
41810
  params.manager.VisualsRegister.ClearIsolated();
39267
41811
  let isolatedIds = bSettings === null || bSettings === void 0 ? void 0 : bSettings.isolatedEntityIds;
39268
41812
  if (isolatedIds == null) {
39269
- isolatedIds = (_3 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _3 === void 0 ? void 0 : _3.isolatedEntityIds;
41813
+ isolatedIds = (_4 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _4 === void 0 ? void 0 : _4.isolatedEntityIds;
39270
41814
  }
39271
41815
  if (isolatedIds != null) {
39272
41816
  params.manager.VisualsRegister.SetIsolated({
@@ -39277,7 +41821,7 @@
39277
41821
  }
39278
41822
  let labelledIds = bSettings === null || bSettings === void 0 ? void 0 : bSettings.labelledEntityIds;
39279
41823
  if (labelledIds == null) {
39280
- labelledIds = (_4 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _4 === void 0 ? void 0 : _4.labelledEntityIds;
41824
+ labelledIds = (_5 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _5 === void 0 ? void 0 : _5.labelledEntityIds;
39281
41825
  }
39282
41826
  if (!(labelledIds === null || labelledIds === void 0 ? void 0 : labelledIds.length)) {
39283
41827
  params.manager.VisualsRegister.ClearLabelled({
@@ -39301,7 +41845,7 @@
39301
41845
  params.manager.VisualsRegister.ClearOpacity();
39302
41846
  let entityOpacityMap = bSettings === null || bSettings === void 0 ? void 0 : bSettings.entityOpacityMap;
39303
41847
  if (entityOpacityMap == null) {
39304
- entityOpacityMap = (_5 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _5 === void 0 ? void 0 : _5.entityOpacityMap;
41848
+ entityOpacityMap = (_6 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _6 === void 0 ? void 0 : _6.entityOpacityMap;
39305
41849
  }
39306
41850
  if (entityOpacityMap != null) {
39307
41851
  for (const entityId in entityOpacityMap) {
@@ -39316,7 +41860,7 @@
39316
41860
  }
39317
41861
  }
39318
41862
  }
39319
- let imagery = (bSettings === null || bSettings === void 0 ? void 0 : bSettings.imagery) != null ? bSettings.imagery : (_6 = defaults.settings) === null || _6 === void 0 ? void 0 : _6.imagery;
41863
+ let imagery = (bSettings === null || bSettings === void 0 ? void 0 : bSettings.imagery) != null ? bSettings.imagery : (_7 = defaults.settings) === null || _7 === void 0 ? void 0 : _7.imagery;
39320
41864
  if (imagery == null) {
39321
41865
  // TODO: Need global default.
39322
41866
  imagery = [
@@ -39386,7 +41930,7 @@
39386
41930
  // Otherwise we cause a flicker of rendered graphics.
39387
41931
  // Maybe TODO to such a function for menu item manager.
39388
41932
  const curEnabled = params.manager.GetEnabledItemIds();
39389
- const newItemIds = (_7 = bSettings === null || bSettings === void 0 ? void 0 : bSettings.menuItemIds) !== null && _7 !== void 0 ? _7 : [];
41933
+ const newItemIds = (_8 = bSettings === null || bSettings === void 0 ? void 0 : bSettings.menuItemIds) !== null && _8 !== void 0 ? _8 : [];
39390
41934
  for (const id of curEnabled) {
39391
41935
  let shouldRemove;
39392
41936
  if (id == RELATION_MENU_ITEM_ID) {
@@ -39460,7 +42004,7 @@
39460
42004
  }
39461
42005
  let gOcclusion = bSettings === null || bSettings === void 0 ? void 0 : bSettings.groundOcclusion;
39462
42006
  if (gOcclusion == null) {
39463
- gOcclusion = (_8 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _8 === void 0 ? void 0 : _8.groundOcclusion;
42007
+ gOcclusion = (_9 = defaults === null || defaults === void 0 ? void 0 : defaults.settings) === null || _9 === void 0 ? void 0 : _9.groundOcclusion;
39464
42008
  }
39465
42009
  if (gOcclusion == null) {
39466
42010
  // TODO: Need global default.
@@ -39477,6 +42021,17 @@
39477
42021
  BModels.ProjectViewBookmark.EContentType.WEB_3D_MODEL_SPACE,
39478
42022
  BModels.ProjectViewBookmark.EContentType.WEB_3D_SPLIT_PLUGIN
39479
42023
  ];
42024
+ /**
42025
+ * A bookmark's own shadows, else the view's defaults unless it is model-space, which reads brighter without.
42026
+ */
42027
+ function ResolveShadows(bSettings, defaults, contentType) {
42028
+ let shadows = bSettings === null || bSettings === void 0 ? void 0 : bSettings.shadows;
42029
+ if (shadows == null && contentType != BModels.ProjectViewBookmark.EContentType.WEB_3D_MODEL_SPACE) {
42030
+ shadows = defaults === null || defaults === void 0 ? void 0 : defaults.shadows;
42031
+ }
42032
+ return shadows !== null && shadows !== void 0 ? shadows : { enabled: false };
42033
+ }
42034
+ ViewRenderEngine.ResolveShadows = ResolveShadows;
39480
42035
  /**
39481
42036
  * Returns where a model-space bookmark's camera goes, measured from the origin in effect.
39482
42037
  * @param viewer
@@ -44201,7 +46756,7 @@
44201
46756
  const HOLD_LOADER_DELAY_MS = 150;
44202
46757
  const CONTINUOUS_ANIMATION_SPEED = 0.02 / 3;
44203
46758
  const ZOOM_DISTANCE = 0.85;
44204
- const MIN_ZOOM_DISTANCE = 0.3;
46759
+ const MIN_ZOOM_DISTANCE$1 = 0.3;
44205
46760
  const NEAR_NADIR_PITCH = -Math.PI / 2 + 0.05;
44206
46761
  const MIN_ORBIT_OFFSET_METERS = 5;
44207
46762
  // Caps how far a pivot may be from the camera relative to the camera's own altitude.
@@ -44407,7 +46962,7 @@
44407
46962
  const mag = (ZOOM_DISTANCE * 0.5) / Math.max(1, 4 - Math.log10(height));
44408
46963
  const zoom = zoomIn ? 1 - mag : 1 + mag;
44409
46964
  const offset = Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.subtract(p, ground, new Cesium.Cartesian3()), zoom, new Cesium.Cartesian3());
44410
- if (zoomIn && Cesium.Cartesian3.magnitude(offset) <= MIN_ZOOM_DISTANCE) {
46965
+ if (zoomIn && Cesium.Cartesian3.magnitude(offset) <= MIN_ZOOM_DISTANCE$1) {
44411
46966
  return Promise.resolve(null);
44412
46967
  }
44413
46968
  const to = Cesium.Cartesian3.add(ground, offset, new Cesium.Cartesian3());
@@ -44631,7 +47186,7 @@
44631
47186
  const mag = (ZOOM_DISTANCE * 0.5) / Math.max(1, 4 - Math.log10(height));
44632
47187
  const zoom = zoomIn ? 1 - mag * 0.03 : 1 + mag * 0.03;
44633
47188
  const offset = Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.subtract(p, ground, new Cesium.Cartesian3()), zoom, new Cesium.Cartesian3());
44634
- if (zoomIn && Cesium.Cartesian3.magnitude(offset) <= MIN_ZOOM_DISTANCE) {
47189
+ if (zoomIn && Cesium.Cartesian3.magnitude(offset) <= MIN_ZOOM_DISTANCE$1) {
44635
47190
  active = false;
44636
47191
  return;
44637
47192
  }
@@ -45440,7 +47995,7 @@
45440
47995
  * @param viewer
45441
47996
  */
45442
47997
  function InitViewer(params) {
45443
- const { viewer, destroyWidgets, styleContainer, nextspaceWidgets, widgetParams } = params;
47998
+ const { viewer, destroyWidgets, styleContainer, nextspaceWidgets, widgetParams, cameraControls } = params;
45444
47999
  const data = { widgets: {} };
45445
48000
  if (destroyWidgets != false) {
45446
48001
  try {
@@ -45467,6 +48022,12 @@
45467
48022
  // Newer cesium is much dimmer by default so we shift brightness a bit.
45468
48023
  exports.ViewUtils.ApplyDefaultBrightness(viewer);
45469
48024
  backgroundRendering(viewer);
48025
+ if (cameraControls != false) {
48026
+ exports.CameraControls.Attach(viewer);
48027
+ if (exports.ViewUtils.GetModelSpace(viewer)) {
48028
+ exports.CameraControls.SetModelSpace(viewer, () => exports.ViewUtils.GetModelSpaceFrame(viewer));
48029
+ }
48030
+ }
45470
48031
  // Capturing the destroy call to destroy all widgets.
45471
48032
  const olDestroy = viewer.destroy;
45472
48033
  viewer.destroy = () => {
@@ -45475,6 +48036,7 @@
45475
48036
  }
45476
48037
  try {
45477
48038
  ViewerUtils.DisposeNextspaceWidgets(viewer);
48039
+ exports.CameraControls.Detach(viewer);
45478
48040
  }
45479
48041
  // We don't want the actual destroy to fail.
45480
48042
  catch (e) {
@@ -49609,7 +52171,7 @@
49609
52171
  ...exports.ViewUtils.DefaultLightingProps(),
49610
52172
  heightReference: heightRef,
49611
52173
  scale: new Cesium.CallbackProperty(() => scale * styleScale, true),
49612
- shadows: Cesium.ShadowMode.ENABLED,
52174
+ shadows: exports.ViewUtils.GetEntityShadowMode(params.viewer),
49613
52175
  colorBlendAmount: blendAmount,
49614
52176
  colorBlendMode: blendMode,
49615
52177
  color: new Cesium.CallbackProperty(() => {
@@ -49644,7 +52206,7 @@
49644
52206
  cEntity.model.uri = new Cesium.ConstantProperty(params.lodUrl);
49645
52207
  }
49646
52208
  cEntity.model.heightReference = new Cesium.ConstantProperty(heightRef);
49647
- cEntity.model.shadows = new Cesium.ConstantProperty(Cesium.ShadowMode.ENABLED);
52209
+ cEntity.model.shadows = new Cesium.ConstantProperty(exports.ViewUtils.GetEntityShadowMode(params.viewer));
49648
52210
  cEntity.model.colorBlendAmount = new Cesium.ConstantProperty(blendAmount);
49649
52211
  cEntity.model.colorBlendMode = new Cesium.ConstantProperty(blendMode);
49650
52212
  cEntity.model.distanceDisplayCondition = new Cesium.ConstantProperty(exports.EntityRenderEngine.GetDisplayCondition(params.minDistance, params.maxDistance));
@@ -50482,7 +53044,7 @@
50482
53044
  zIndex: getZIndex(style, entity, params.tags),
50483
53045
  distanceDisplayCondition: exports.EntityRenderEngine.GetDisplayCondition(params.minDistance, params.maxDistance, width),
50484
53046
  cornerType: Cesium.CornerType.MITERED,
50485
- shadows: Cesium.ShadowMode.ENABLED,
53047
+ shadows: exports.ViewUtils.GetEntityShadowMode(params.viewer),
50486
53048
  fill: true
50487
53049
  } : null,
50488
53050
  position: exports.EntityUtils.GetPos({
@@ -54937,7 +57499,7 @@ void main() {
54937
57499
  fill: !drawsDisplacedSurface,
54938
57500
  extrudedHeight: extrusion.value,
54939
57501
  extrudedHeightReference: extrusion.exHeightRef,
54940
- shadows: Cesium.ShadowMode.ENABLED,
57502
+ shadows: exports.ViewUtils.GetEntityShadowMode(params.viewer),
54941
57503
  heightReference: heightRef,
54942
57504
  classificationType: classification,
54943
57505
  perPositionHeight: heightRef == Cesium.HeightReference.CLAMP_TO_GROUND ? false : true,
@@ -55017,7 +57579,7 @@ void main() {
55017
57579
  viewer: params.viewer,
55018
57580
  graphic: cEntity.polygon,
55019
57581
  property: "shadows",
55020
- value: Cesium.ShadowMode.ENABLED
57582
+ value: exports.ViewUtils.GetEntityShadowMode(params.viewer)
55021
57583
  });
55022
57584
  SetCPropIfChanged({
55023
57585
  viewer: params.viewer,
@@ -55152,7 +57714,7 @@ void main() {
55152
57714
  cornerType: Cesium.CornerType.MITERED,
55153
57715
  classificationType: classification,
55154
57716
  distanceDisplayCondition: exports.EntityRenderEngine.GetDisplayCondition(params.minDistance, params.maxDistance, width, false, size),
55155
- shadows: Cesium.ShadowMode.ENABLED
57717
+ shadows: exports.ViewUtils.GetEntityShadowMode(params.viewer)
55156
57718
  } : null,
55157
57719
  show: true
55158
57720
  });
@@ -55275,7 +57837,7 @@ void main() {
55275
57837
  cornerType: Cesium.CornerType.MITERED,
55276
57838
  classificationType: classification,
55277
57839
  distanceDisplayCondition: exports.EntityRenderEngine.GetDisplayCondition(params.minDistance, params.maxDistance, width, false, size),
55278
- shadows: Cesium.ShadowMode.ENABLED,
57840
+ shadows: exports.ViewUtils.GetEntityShadowMode(params.viewer),
55279
57841
  } : null,
55280
57842
  show: true
55281
57843
  });
@@ -57596,7 +60158,7 @@ void main() {
57596
60158
  StyleUtils.ApplyTypeStyle = ApplyTypeStyle;
57597
60159
  })(exports.StyleUtils || (exports.StyleUtils = {}));
57598
60160
 
57599
- const VERSION = "7.7.7";
60161
+ const VERSION = "7.7.9";
57600
60162
  /**
57601
60163
  * Updates the environment instance used by bruce-cesium to one specified.
57602
60164
  * This can be used to ensure that the instance a parent is referencing is shared between bruce-cesium, bruce-models, and the parent app.