bruce-cesium 7.9.4 → 7.9.6

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.
@@ -1,6 +1,6 @@
1
1
  import * as Cesium from 'cesium';
2
- import { Cartographic, ColorMaterialProperty, Entity, Color, ConstantProperty, CallbackProperty, Primitive, Cesium3DTileFeature, ConstantPositionProperty, HeightReference, DistanceDisplayCondition, Math as Math$1, Cartesian3, JulianDate, Quaternion, Transforms, HeadingPitchRoll, Matrix4, ClassificationType, ArcType, CornerType, ShaderSource, Ellipsoid, Geometry, GeometryAttribute, ComponentDatatype, PrimitiveType, BoundingSphere, GeometryPipeline, Cartesian2, Cartesian4, sampleTerrain, Texture, PixelFormat, Sampler, TextureWrap, TextureMinificationFilter, TextureMagnificationFilter, PixelDatatype, VertexArray, BufferUsage, ShaderProgram, RenderState, BlendingState, DrawCommand, Pass, HorizontalOrigin, VerticalOrigin, SceneMode, IntersectionTests, Ray, SceneTransforms, ColorBlendMode, Model, ImageMaterialProperty, PolygonHierarchy, PolylineGraphics, Rectangle, NearFarScalar, Matrix3, KmlDataSource, GeoJsonDataSource, Cesium3DTileStyle, Cesium3DTileColorBlendMode, HeadingPitchRange, Ion, IonResource, OrthographicFrustum, EasingFunction, EllipsoidTerrainProvider, IonImageryProvider, createWorldImagery, createWorldImageryAsync, BingMapsImageryProvider, BingMapsStyle, MapboxImageryProvider, MapboxStyleImageryProvider, ArcGisMapServerImageryProvider, OpenStreetMapImageryProvider, UrlTemplateImageryProvider, GridImageryProvider, GeographicTilingScheme, ImageryLayer, TileMapServiceImageryProvider, CesiumTerrainProvider, Intersect, FeatureDetection, Cesium3DTileset, WebGLConstants, EllipsoidGeodesic, sampleTerrainMostDetailed, PolygonPipeline, ModelGraphics, PolygonGraphics, CorridorGraphics, PointGraphics, BillboardGraphics, EllipseGraphics, PolylineDashMaterialProperty, PrimitiveCollection, ShadowMode, PolylineCollection, LabelCollection, LabelStyle, Material, CustomDataSource, Event, CesiumInspector, defined, ClockRange, DynamicEnvironmentMapManager, ScreenSpaceEventHandler, ScreenSpaceEventType, CameraEventType, Plane, OrientedBoundingBox, GeometryInstance, Fullscreen, CzmlDataSource } from 'cesium';
3
- import { Cartes, LRUCache, Carto, ProjectViewTile, EntityHistoricData, BruceEvent, DelayQueue, Entity as Entity$1, EntityTag, PathUtils, ClientFile, ENVIRONMENT, EntityAttachmentType, EntityRelationType, EntityType, Tileset, Calculator, DataLab, Style, ObjectUtils, MenuItem, ZoomControl, AccountConcept, RecordChangeFeed, Geometry as Geometry$1, Api, ProjectView, ProjectViewBookmark, EntityLod, UrlUtils, Bounds, ClientFileValueMap, Color as Color$1, Assembly, EntityCoords, BruceApi, EntityRelation, EntitySource, Camera, ProgramKey, ProjectViewLegacyTile, Account, AccountLimits, Session, ProjectViewBookmarkGroup, EntityAttachment, EntityAttribute, MathUtils } from 'bruce-models';
2
+ import { Cartographic, ColorMaterialProperty, Entity, Color, ConstantProperty, CallbackProperty, Primitive, Cesium3DTileFeature, ConstantPositionProperty, HeightReference, DistanceDisplayCondition, Math as Math$1, Cartesian3, JulianDate, Quaternion, Transforms, HeadingPitchRoll, Matrix4, ColorBlendMode, Model, ClassificationType, ArcType, CornerType, HorizontalOrigin, VerticalOrigin, ShaderSource, Ellipsoid, Geometry, GeometryAttribute, ComponentDatatype, PrimitiveType, BoundingSphere, GeometryPipeline, sampleTerrain, Cartesian4, Cartesian2, SceneMode, Intersect, Texture, PixelFormat, Sampler, TextureWrap, TextureMinificationFilter, TextureMagnificationFilter, PixelDatatype, VertexArray, BufferUsage, ShaderProgram, RenderState, BlendingState, DrawCommand, Pass, ImageMaterialProperty, IntersectionTests, Ray, SceneTransforms, PolygonHierarchy, PolylineGraphics, Rectangle, NearFarScalar, Matrix3, GeoJsonDataSource, KmlDataSource, Cesium3DTileStyle, HeadingPitchRange, Ion, IonResource, FeatureDetection, Cesium3DTileColorBlendMode, EllipsoidTerrainProvider, IonImageryProvider, createWorldImagery, createWorldImageryAsync, BingMapsImageryProvider, BingMapsStyle, MapboxImageryProvider, MapboxStyleImageryProvider, ArcGisMapServerImageryProvider, OpenStreetMapImageryProvider, UrlTemplateImageryProvider, GridImageryProvider, GeographicTilingScheme, ImageryLayer, TileMapServiceImageryProvider, CesiumTerrainProvider, Cesium3DTileset, WebGLConstants, ShadowMode, CustomDataSource, OrthographicFrustum, EasingFunction, EllipsoidGeodesic, sampleTerrainMostDetailed, PolygonPipeline, ModelGraphics, PolygonGraphics, CorridorGraphics, PointGraphics, BillboardGraphics, EllipseGraphics, PolylineDashMaterialProperty, GeometryInstance, CesiumInspector, defined, ClockRange, DynamicEnvironmentMapManager, PrimitiveCollection, PolylineCollection, LabelCollection, LabelStyle, Material, Event, ScreenSpaceEventHandler, ScreenSpaceEventType, CameraEventType, KeyboardEventModifier, Plane, OrientedBoundingBox, Fullscreen, CzmlDataSource } from 'cesium';
3
+ import { Cartes, LRUCache, Carto, ProjectViewTile, EntityHistoricData, BruceEvent, DelayQueue, Entity as Entity$1, EntityTag, PathUtils, ClientFile, ENVIRONMENT, EntityAttachmentType, EntityRelationType, EntityType, Tileset, Calculator, DataLab, Style, ObjectUtils, MenuItem, ZoomControl, AccountConcept, RecordChangeFeed, EntityLod, UrlUtils, Geometry as Geometry$1, Api, ClientFileValueMap, Color as Color$1, Assembly, EntityCoords, Bounds, ProjectView, ProjectViewBookmark, EntityRelation, BruceApi, EntitySource, ProgramKey, ProjectViewLegacyTile, Camera, Account, AccountLimits, Session, ProjectViewBookmarkGroup, EntityAttachment, EntityAttribute, MathUtils } from 'bruce-models';
4
4
 
5
5
  /**
6
6
  * Ensures a number is returned from a given value.
@@ -1385,6 +1385,24 @@ const ZOOM_LOADING_SHARE = 0.7;
1385
1385
  const HIDDEN_GLOBE_MAX_HEIGHT = 10000000;
1386
1386
  // Marks a tileset that stands in for the globe, such as Google's photorealistic tiles.
1387
1387
  const GROUND_TILESET_KEY = "_nextspace_camera_ground";
1388
+ // A viewer's own mouse scheme and wheel direction, kept on the viewer so a host may set them before Attach.
1389
+ const MOUSE_KEY = "_nextspace_camera_mouse";
1390
+ // Marks a wheel event these controls turned round, so it is not turned back again.
1391
+ const MIRRORED_WHEEL_KEY = "_nextspace_mirrored";
1392
+ /**
1393
+ * Which mouse buttons pan, orbit and zoom: CesiumJS's own, or a familiar desktop 3D app's.
1394
+ */
1395
+ var ECameraMouseScheme;
1396
+ (function (ECameraMouseScheme) {
1397
+ // CesiumJS's own: left drag pans, middle or ctrl drag orbits, right drag zooms.
1398
+ ECameraMouseScheme["Default"] = "default";
1399
+ // Autodesk Fusion, Revit, Navisworks and AutoCAD: middle drag pans, shift+middle orbits, ctrl+shift+middle zooms.
1400
+ ECameraMouseScheme["Autodesk"] = "autodesk";
1401
+ // SketchUp: middle drag orbits, shift+middle pans.
1402
+ ECameraMouseScheme["SketchUp"] = "sketchup";
1403
+ })(ECameraMouseScheme || (ECameraMouseScheme = {}));
1404
+ // What a viewer without its own setting uses: the app user's preference, set once for every viewer the app makes.
1405
+ const _mouseDefault = { scheme: ECameraMouseScheme.Default, wheelReversed: false };
1388
1406
  var EDrag;
1389
1407
  (function (EDrag) {
1390
1408
  EDrag["Pan"] = "pan";
@@ -1400,7 +1418,7 @@ var CameraControls;
1400
1418
  * Takes over mouse drag and wheel navigation close to the ground; CesiumJS keeps planet scale, pinch and look.
1401
1419
  */
1402
1420
  function Attach(viewer) {
1403
- var _a, _b, _c;
1421
+ var _a, _b, _c, _d;
1404
1422
  if (!viewer || viewer.isDestroyed() || viewer[CESIUM_CAMERA_CONTROLS_KEY]) {
1405
1423
  return;
1406
1424
  }
@@ -1426,11 +1444,13 @@ var CameraControls;
1426
1444
  rotateEventTypes: controller.rotateEventTypes,
1427
1445
  zoomEventTypes: controller.zoomEventTypes,
1428
1446
  tiltEventTypes: controller.tiltEventTypes,
1447
+ translateEventTypes: controller.translateEventTypes,
1429
1448
  enableCollisionDetection: controller.enableCollisionDetection,
1430
1449
  backFaceAlpha: (_b = (_a = scene.globe) === null || _a === void 0 ? void 0 : _a.translucency) === null || _b === void 0 ? void 0 : _b.backFaceAlpha,
1431
1450
  showSkirts: (_c = scene.globe) === null || _c === void 0 ? void 0 : _c.showSkirts
1432
1451
  },
1433
1452
  ours: false,
1453
+ cesiumScheme: null,
1434
1454
  removals: []
1435
1455
  };
1436
1456
  viewer[CESIUM_CAMERA_CONTROLS_KEY] = state;
@@ -1446,6 +1466,9 @@ var CameraControls;
1446
1466
  listen(window, "pointerup", (e) => onPointerUp(state, e));
1447
1467
  listen(window, "pointercancel", (e) => onPointerUp(state, e));
1448
1468
  listen(canvas, "wheel", (e) => onWheel(state, e), { passive: true });
1469
+ // Caught before the canvas sees it, so CesiumJS's controller and these controls both get the turned wheel.
1470
+ const wheelHost = (_d = canvas.parentElement) !== null && _d !== void 0 ? _d : window;
1471
+ listen(wheelHost, "wheel", (e) => mirrorWheel(state, e), { capture: true, passive: false });
1449
1472
  state.removals.push(scene.preUpdate.addEventListener(() => {
1450
1473
  syncController(state);
1451
1474
  keepAboveGround(state);
@@ -1481,6 +1504,52 @@ var CameraControls;
1481
1504
  return Boolean(viewer === null || viewer === void 0 ? void 0 : viewer[CESIUM_CAMERA_CONTROLS_KEY]);
1482
1505
  }
1483
1506
  CameraControls.IsAttached = IsAttached;
1507
+ /**
1508
+ * Picks which mouse buttons pan, orbit and zoom, here and for CesiumJS's controller above the hand-over height.
1509
+ */
1510
+ function SetMouseScheme(viewer, scheme) {
1511
+ if (!viewer || viewer.isDestroyed()) {
1512
+ return;
1513
+ }
1514
+ viewer[MOUSE_KEY] = { ...viewer[MOUSE_KEY], scheme: knownScheme(scheme) };
1515
+ const state = viewer[CESIUM_CAMERA_CONTROLS_KEY];
1516
+ if (state && !state.ours) {
1517
+ applyCesiumGestures(state);
1518
+ }
1519
+ }
1520
+ CameraControls.SetMouseScheme = SetMouseScheme;
1521
+ /**
1522
+ * Sets the scheme for every viewer without its own, such as the app user's preference; viewers follow next frame.
1523
+ */
1524
+ function SetMouseSchemeDefault(scheme) {
1525
+ _mouseDefault.scheme = knownScheme(scheme);
1526
+ }
1527
+ CameraControls.SetMouseSchemeDefault = SetMouseSchemeDefault;
1528
+ function GetMouseScheme(viewer) {
1529
+ return mouseOf(viewer).scheme;
1530
+ }
1531
+ CameraControls.GetMouseScheme = GetMouseScheme;
1532
+ /**
1533
+ * Makes wheel forward zoom out instead of in, for these controls and CesiumJS's controller alike.
1534
+ */
1535
+ function SetMouseWheelReversed(viewer, reversed) {
1536
+ if (!viewer || viewer.isDestroyed()) {
1537
+ return;
1538
+ }
1539
+ viewer[MOUSE_KEY] = { ...viewer[MOUSE_KEY], wheelReversed: Boolean(reversed) };
1540
+ }
1541
+ CameraControls.SetMouseWheelReversed = SetMouseWheelReversed;
1542
+ /**
1543
+ * Sets the wheel direction for every viewer without its own, such as the app user's preference.
1544
+ */
1545
+ function SetMouseWheelReversedDefault(reversed) {
1546
+ _mouseDefault.wheelReversed = Boolean(reversed);
1547
+ }
1548
+ CameraControls.SetMouseWheelReversedDefault = SetMouseWheelReversedDefault;
1549
+ function GetMouseWheelReversed(viewer) {
1550
+ return mouseOf(viewer).wheelReversed;
1551
+ }
1552
+ CameraControls.GetMouseWheelReversed = GetMouseWheelReversed;
1484
1553
  /**
1485
1554
  * Marks a tileset as standing in for the globe (Google's photorealistic tiles), so the camera treats it as ground.
1486
1555
  */
@@ -1490,6 +1559,13 @@ var CameraControls;
1490
1559
  }
1491
1560
  }
1492
1561
  CameraControls.SetGroundTileset = SetGroundTileset;
1562
+ /**
1563
+ * Whether a tileset was marked as standing in for the globe.
1564
+ */
1565
+ function IsGroundTileset(tileset) {
1566
+ return Boolean(tileset === null || tileset === void 0 ? void 0 : tileset[GROUND_TILESET_KEY]);
1567
+ }
1568
+ CameraControls.IsGroundTileset = IsGroundTileset;
1493
1569
  /**
1494
1570
  * Says whether the scene has data underground, which makes the ground easier to push through; null scans for it.
1495
1571
  */
@@ -1538,11 +1614,67 @@ var CameraControls;
1538
1614
  }
1539
1615
  CameraControls.SetModelSpace = SetModelSpace;
1540
1616
  })(CameraControls || (CameraControls = {}));
1617
+ /*
1618
+ * The scheme and wheel direction a viewer uses: its own where set, else the app default.
1619
+ */
1620
+ function mouseOf(viewer) {
1621
+ var _a, _b;
1622
+ const own = viewer === null || viewer === void 0 ? void 0 : viewer[MOUSE_KEY];
1623
+ return {
1624
+ scheme: (_a = own === null || own === void 0 ? void 0 : own.scheme) !== null && _a !== void 0 ? _a : _mouseDefault.scheme,
1625
+ wheelReversed: (_b = own === null || own === void 0 ? void 0 : own.wheelReversed) !== null && _b !== void 0 ? _b : _mouseDefault.wheelReversed
1626
+ };
1627
+ }
1628
+ /*
1629
+ * A scheme this version knows, or Default for one saved by a newer app or mistyped.
1630
+ */
1631
+ function knownScheme(scheme) {
1632
+ return Object.values(ECameraMouseScheme).includes(scheme) ? scheme : ECameraMouseScheme.Default;
1633
+ }
1541
1634
  function restoreCesiumGestures(state) {
1542
1635
  const controller = state.viewer.scene.screenSpaceCameraController;
1543
1636
  controller.rotateEventTypes = state.saved.rotateEventTypes;
1544
1637
  controller.zoomEventTypes = state.saved.zoomEventTypes;
1545
1638
  controller.tiltEventTypes = state.saved.tiltEventTypes;
1639
+ if (state.saved.translateEventTypes !== undefined) {
1640
+ controller.translateEventTypes = state.saved.translateEventTypes;
1641
+ }
1642
+ }
1643
+ /*
1644
+ * Gives CesiumJS's controller its own gestures under the mouse scheme, so the buttons do not swap at the hand-over.
1645
+ */
1646
+ function applyCesiumGestures(state) {
1647
+ restoreCesiumGestures(state);
1648
+ const scheme = mouseOf(state.viewer).scheme;
1649
+ state.cesiumScheme = scheme;
1650
+ if (scheme === ECameraMouseScheme.Default) {
1651
+ return;
1652
+ }
1653
+ const middle = CameraEventType.MIDDLE_DRAG;
1654
+ const shiftMiddle = { eventType: middle, modifier: KeyboardEventModifier.SHIFT };
1655
+ const tilt = asEventTypes(state.saved.tiltEventTypes);
1656
+ // A host that moved CesiumJS's middle drag elsewhere has its own mapping, which is left alone.
1657
+ if (!tilt.includes(middle)) {
1658
+ return;
1659
+ }
1660
+ // CesiumJS orbits with tilt and pans with rotate in 3D, or translate in 2D and Columbus view.
1661
+ const orbit = scheme === ECameraMouseScheme.Autodesk ? shiftMiddle : middle;
1662
+ const pan = scheme === ECameraMouseScheme.Autodesk ? middle : shiftMiddle;
1663
+ const controller = state.viewer.scene.screenSpaceCameraController;
1664
+ controller.tiltEventTypes = tilt.map((type) => (type === middle ? orbit : type));
1665
+ controller.rotateEventTypes = [...asEventTypes(state.saved.rotateEventTypes), pan];
1666
+ if (state.saved.translateEventTypes !== undefined) {
1667
+ controller.translateEventTypes = [...asEventTypes(state.saved.translateEventTypes), pan];
1668
+ }
1669
+ }
1670
+ /*
1671
+ * CesiumJS takes one event type or a list of them; this always gives a list.
1672
+ */
1673
+ function asEventTypes(types) {
1674
+ if (types == null) {
1675
+ return [];
1676
+ }
1677
+ return Array.isArray(types) ? types : [types];
1546
1678
  }
1547
1679
  /*
1548
1680
  * Decides each frame who has the mouse: these controls near the ground, CesiumJS for planets, orthographic and tracking.
@@ -1554,6 +1686,9 @@ function syncController(state) {
1554
1686
  }
1555
1687
  const ours = shouldControl(state);
1556
1688
  if (ours === state.ours) {
1689
+ if (!ours && state.cesiumScheme !== mouseOf(viewer).scheme) {
1690
+ applyCesiumGestures(state);
1691
+ }
1557
1692
  return;
1558
1693
  }
1559
1694
  state.ours = ours;
@@ -1564,7 +1699,7 @@ function syncController(state) {
1564
1699
  controller.tiltEventTypes = [CameraEventType.PINCH];
1565
1700
  }
1566
1701
  else {
1567
- restoreCesiumGestures(state);
1702
+ applyCesiumGestures(state);
1568
1703
  }
1569
1704
  }
1570
1705
  function shouldControl(state) {
@@ -1978,9 +2113,18 @@ function isAhead(camera, point) {
1978
2113
  return Cartesian3.dot(toPoint, camera.directionWC) > 0;
1979
2114
  }
1980
2115
  /*
1981
- * Picks which gesture a button and its modifiers start, matching CesiumJS's own mapping.
2116
+ * Picks which gesture a button and its modifiers start under the mouse scheme; Default matches CesiumJS's own mapping.
1982
2117
  */
1983
- function dragKind(e) {
2118
+ function dragKind(e, scheme) {
2119
+ if (scheme === ECameraMouseScheme.Autodesk && e.button === 1) {
2120
+ if (e.shiftKey && e.ctrlKey) {
2121
+ return EDrag.Zoom;
2122
+ }
2123
+ return e.shiftKey ? EDrag.Orbit : EDrag.Pan;
2124
+ }
2125
+ if (scheme === ECameraMouseScheme.SketchUp && e.button === 1) {
2126
+ return e.shiftKey ? EDrag.Pan : EDrag.Orbit;
2127
+ }
1984
2128
  if (e.shiftKey) {
1985
2129
  // Shift drag looks around, which CesiumJS still handles.
1986
2130
  return null;
@@ -2024,7 +2168,7 @@ function onPointerDown(state, e) {
2024
2168
  return;
2025
2169
  }
2026
2170
  }
2027
- const kind = dragKind(e);
2171
+ const kind = dragKind(e, mouseOf(viewer).scheme);
2028
2172
  if (!kind || !allows(state, kind)) {
2029
2173
  return;
2030
2174
  }
@@ -2220,6 +2364,37 @@ function onWheel(state, e) {
2220
2364
  state.zoomFrame = requestAnimationFrame(() => easeZoom(state));
2221
2365
  }
2222
2366
  }
2367
+ /*
2368
+ * Swaps a wheel event over the scene for one turned round, so wheel forward zooms out when the user asked for that.
2369
+ */
2370
+ function mirrorWheel(state, e) {
2371
+ const viewer = state.viewer;
2372
+ const canvas = viewer.isDestroyed() ? null : viewer.scene.canvas;
2373
+ if (!canvas || e.target !== canvas || e[MIRRORED_WHEEL_KEY] || !mouseOf(viewer).wheelReversed) {
2374
+ return;
2375
+ }
2376
+ e.stopImmediatePropagation();
2377
+ e.preventDefault();
2378
+ const mirrored = new WheelEvent("wheel", {
2379
+ bubbles: true,
2380
+ cancelable: true,
2381
+ clientX: e.clientX,
2382
+ clientY: e.clientY,
2383
+ screenX: e.screenX,
2384
+ screenY: e.screenY,
2385
+ ctrlKey: e.ctrlKey,
2386
+ shiftKey: e.shiftKey,
2387
+ altKey: e.altKey,
2388
+ metaKey: e.metaKey,
2389
+ buttons: e.buttons,
2390
+ deltaMode: e.deltaMode,
2391
+ deltaX: e.deltaX,
2392
+ deltaY: -e.deltaY,
2393
+ deltaZ: e.deltaZ
2394
+ });
2395
+ mirrored[MIRRORED_WHEEL_KEY] = true;
2396
+ canvas.dispatchEvent(mirrored);
2397
+ }
2223
2398
  /*
2224
2399
  * Applies part of the outstanding wheel movement each frame, so a notch glides rather than jumps.
2225
2400
  */
@@ -57712,12 +57887,6 @@ var DisplacedSurfacePrimitive;
57712
57887
  const SKIRT_FRACTION = 0.015;
57713
57888
  // Alpha below which a texel counts as no-data and is not drawn at all.
57714
57889
  const COVERAGE_CUTOFF = 0.35;
57715
- // Terrain is sampled on this grid and interpolated between samples.
57716
- // Per-texel sampling would be hundreds of thousands of lookups for a surface whose own data is far coarser than that.
57717
- const GROUND_SAMPLES_PER_SIDE = 64;
57718
- // Terrain detail level the samples are taken at.
57719
- // Most-detailed would fetch every tile under a parcel that can be a hundred kilometres across.
57720
- const GROUND_SAMPLE_LEVEL = 11;
57721
57890
  // Height window the packed ground texture covers, wide enough for any terrain on Earth.
57722
57891
  // Ground samples across the clearance regions rather than the whole extent.
57723
57892
  const MASK_GROUND_SAMPLES_PER_SIDE = 128;
@@ -57725,9 +57894,23 @@ var DisplacedSurfacePrimitive;
57725
57894
  const MASK_GROUND_LEVEL_MAX = 13;
57726
57895
  const MASK_GROUND_LEVEL_MIN = 8;
57727
57896
  const MASK_GROUND_TILE_BUDGET = 64;
57897
+ // Finest terrain level a ground block is read at, and how many terrain tiles one block may pull.
57898
+ const FINE_GROUND_LEVEL_MAX = 18;
57899
+ const FINE_GROUND_TILE_BUDGET = 16;
57728
57900
  // Longest side of the rasterised region mask. The mask decides whether a texel is held up, so it
57729
57901
  // wants to be finer than the value raster it is compared against.
57730
57902
  const MASK_TEXTURE_MAX_SIDE = 1024;
57903
+ const DEFAULT_DRAPE_LIFT_METRES = 4;
57904
+ const DEFAULT_DRAPE_BAND_METRES = 3;
57905
+ // A ground tileset is measured against the ground raster at this many points around the camera, this far apart.
57906
+ const OFFSET_PROBES_PER_SIDE = 3;
57907
+ const OFFSET_PROBE_SPACING_METRES = 250;
57908
+ // The camera has to move this far before a ground tileset is measured again.
57909
+ const OFFSET_REPROBE_METRES = 1500;
57910
+ // Low percentile of tileset minus ground, so roofs and canopy over a probe do not lift the water.
57911
+ const OFFSET_PERCENTILE = 0.25;
57912
+ const WGS84_A = 6378137.0;
57913
+ const WGS84_E2 = 0.00669437999014;
57731
57914
  // Stands in for "no floor" and "no clearance", far below anything the sheet can reach.
57732
57915
  const NO_LIMIT_METRES = -1e6;
57733
57916
  // Ripple layers to cycle across the field's own repeat.
@@ -57772,6 +57955,32 @@ var DisplacedSurfacePrimitive;
57772
57955
  const GROUND_MAX_METRES = 9000;
57773
57956
  const DEFAULT_LOW_COLOR = { red: 255, green: 255, blue: 255, alpha: 0.12 };
57774
57957
  const DEFAULT_HIGH_COLOR = { red: 21, green: 96, blue: 196, alpha: 0.92 };
57958
+ // Decodes the packed ground raster, shared by both shaders.
57959
+ const GROUND_GLSL = `
57960
+ float decodeGround(vec2 uv) {
57961
+ // Channels arrive normalised to 0..1, so they go back to bytes before being reassembled.
57962
+ vec3 bytes = texture(u_groundTexture, uv).rgb * 255.0;
57963
+ float normalised = dot(bytes, vec3(65536.0, 256.0, 1.0)) / 16777215.0;
57964
+ return u_groundRange.x + normalised * (u_groundRange.y - u_groundRange.x);
57965
+ }
57966
+
57967
+ /*
57968
+ * Bilinear by hand, because the height is packed across three channels and hardware filtering would
57969
+ * blend the packing rather than the heights, turning a smooth slope into noise at every texel edge.
57970
+ */
57971
+ float sampleGround(vec2 uv) {
57972
+ vec2 texel = 1.0 / u_groundSize;
57973
+ vec2 coord = uv * u_groundSize - 0.5;
57974
+ vec2 base = floor(coord);
57975
+ vec2 f = coord - base;
57976
+ vec2 origin = (base + 0.5) * texel;
57977
+ float h00 = decodeGround(origin);
57978
+ float h10 = decodeGround(origin + vec2(texel.x, 0.0));
57979
+ float h01 = decodeGround(origin + vec2(0.0, texel.y));
57980
+ float h11 = decodeGround(origin + texel);
57981
+ return mix(mix(h00, h10, f.x), mix(h01, h11, f.x), f.y);
57982
+ }
57983
+ `;
57775
57984
  const VERTEX_SHADER_GLSL300 = `
57776
57985
  in vec3 position3DHigh;
57777
57986
  in vec3 position3DLow;
@@ -57806,6 +58015,9 @@ uniform vec2 u_maskGroundSize;
57806
58015
  uniform vec4 u_extentDegrees;
57807
58016
  uniform vec4 u_maskGroundDegrees;
57808
58017
  uniform float u_coverageCutoffVertex;
58018
+ uniform float u_drape;
58019
+ uniform float u_drapeLift;
58020
+ uniform float u_groundOffset;
57809
58021
  //#water
57810
58022
  uniform vec2 u_extentMetres;
57811
58023
  uniform vec2 u_waveOrigin;
@@ -57814,6 +58026,7 @@ uniform vec2 u_waveOrigin;
57814
58026
  out vec2 v_st;
57815
58027
  out float v_value;
57816
58028
  out float v_coverage;
58029
+ out vec3 v_eyeEC;
57817
58030
  //#water
57818
58031
  out vec3 v_positionEC;
57819
58032
  out vec3 v_eastEC;
@@ -57822,30 +58035,7 @@ out vec3 v_upEC;
57822
58035
  out vec2 v_waveMetres;
57823
58036
  //#endwater
57824
58037
 
57825
- float decodeGround(vec2 uv) {
57826
- // Channels arrive normalised to 0..1, so they go back to bytes before being reassembled.
57827
- vec3 packed = texture(u_groundTexture, uv).rgb * 255.0;
57828
- float normalised = dot(packed, vec3(65536.0, 256.0, 1.0)) / 16777215.0;
57829
- return u_groundRange.x + normalised * (u_groundRange.y - u_groundRange.x);
57830
- }
57831
-
57832
- /*
57833
- * Bilinear by hand, because the height is packed across three channels and hardware filtering would
57834
- * blend the packing rather than the heights, turning a smooth slope into noise at every texel edge.
57835
- */
57836
- float sampleGround(vec2 uv) {
57837
- vec2 texel = 1.0 / u_groundSize;
57838
- vec2 coord = uv * u_groundSize - 0.5;
57839
- vec2 base = floor(coord);
57840
- vec2 f = coord - base;
57841
- vec2 origin = (base + 0.5) * texel;
57842
- float h00 = decodeGround(origin);
57843
- float h10 = decodeGround(origin + vec2(texel.x, 0.0));
57844
- float h01 = decodeGround(origin + vec2(0.0, texel.y));
57845
- float h11 = decodeGround(origin + texel);
57846
- return mix(mix(h00, h10, f.x), mix(h01, h11, f.x), f.y);
57847
- }
57848
-
58038
+ ${GROUND_GLSL}
57849
58039
  /*
57850
58040
  * Height of the terrain under a point of the surface, read from the region's own ground raster.
57851
58041
  *
@@ -57927,12 +58117,13 @@ void main() {
57927
58117
 
57928
58118
  // Value zero sits at the polygon's own altitude, plus the terrain underneath when the polygon
57929
58119
  // is following the ground rather than absolutely positioned.
57930
- float ground = sampleGround(st) * u_groundWeight;
58120
+ float ground = (sampleGround(st) + u_groundOffset) * u_groundWeight;
57931
58121
 
57932
58122
  // Coverage scales the displacement only where it is measured from the terrain, because there a
57933
58123
  // zero means the surface sits on the ground.
57934
58124
  float coverageScale = mix(1.0, v_coverage, u_groundWeight);
57935
- float placed = u_baseHeight + ground + metres * coverageScale;
58125
+ // Draped, the sheet only has to stand above what is drawn; the fragment paints the drawn surface behind it.
58126
+ float placed = u_baseHeight + ground + metres * coverageScale + u_drapeLift * u_drape;
57936
58127
 
57937
58128
  // Held above whichever is higher, the region's own floor or the terrain under it plus a margin.
57938
58129
  // Only inside the region: lifting the whole sheet would raise it over dry land as well.
@@ -57956,6 +58147,7 @@ void main() {
57956
58147
  v_waveMetres = st * u_extentMetres - u_waveOrigin;
57957
58148
  //#endwater
57958
58149
 
58150
+ v_eyeEC = (czm_modelViewRelativeToEye * p).xyz;
57959
58151
  gl_Position = czm_modelViewProjectionRelativeToEye * p;
57960
58152
  }
57961
58153
  `;
@@ -57970,7 +58162,32 @@ uniform float u_valuePacked;
57970
58162
  uniform float u_valueRange;
57971
58163
  uniform float u_exaggeration;
57972
58164
  uniform float u_metresPerTexel;
58165
+ uniform float u_valueMin;
58166
+ uniform sampler2D u_groundTexture;
58167
+ uniform vec2 u_groundRange;
58168
+ uniform vec2 u_groundSize;
58169
+ uniform float u_groundWeight;
58170
+ uniform float u_groundOffset;
58171
+ uniform float u_drape;
58172
+ // Metres a drawn surface may stand above the water level and still be painted, below zero to paint whatever is drawn.
58173
+ uniform float u_drapeBand;
58174
+ // The extent centre on the ellipsoid in eye coordinates, with its east, north and up axes.
58175
+ uniform vec3 u_drapeCentreEC;
58176
+ uniform vec3 u_drapeEastEC;
58177
+ uniform vec3 u_drapeNorthEC;
58178
+ uniform vec3 u_drapeUpEC;
58179
+ // Centre longitude and latitude in radians, then the meridian and prime vertical radii of curvature there.
58180
+ uniform vec4 u_drapeGeo;
58181
+ // West, East, North, South in radians.
58182
+ uniform vec4 u_extentRadians;
58183
+ uniform sampler2D u_maskTexture;
58184
+ uniform float u_maskWeight;
58185
+ uniform float u_maskFill;
58186
+ uniform float u_maskFillValue;
58187
+ uniform float u_maskFloor;
57973
58188
  //#water
58189
+ uniform vec2 u_extentMetres;
58190
+ uniform vec2 u_waveOrigin;
57974
58191
  uniform float u_waterWavelength;
57975
58192
  uniform float u_waterAmplitude;
57976
58193
  uniform float u_waterReflectivity;
@@ -57987,6 +58204,7 @@ uniform float u_wavePeriod;
57987
58204
  in vec2 v_st;
57988
58205
  in float v_value;
57989
58206
  in float v_coverage;
58207
+ in vec3 v_eyeEC;
57990
58208
  //#water
57991
58209
  in vec3 v_positionEC;
57992
58210
  in vec3 v_eastEC;
@@ -58008,6 +58226,72 @@ float valueAt(vec2 uv) {
58008
58226
  return mix(decodeValue(texture(u_valueTextureFrom, uv)), decodeValue(texture(u_valueTexture, uv)), u_valueFade);
58009
58227
  }
58010
58228
 
58229
+ ${GROUND_GLSL}
58230
+
58231
+ /*
58232
+ * The opaque surface drawn behind this pixel, or false when none, outside the extent, or above the band.
58233
+ */
58234
+ bool drawnBehind(out vec2 uv, out float value, out float coverage, out vec3 positionEC) {
58235
+ float depth = czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw));
58236
+ if (depth <= 0.0 || depth >= 1.0) {
58237
+ return false;
58238
+ }
58239
+ vec4 eye = czm_windowToEyeCoordinates(gl_FragCoord.xy, depth);
58240
+ positionEC = eye.xyz / eye.w;
58241
+
58242
+ // East, north and up metres from the extent centre, small numbers that keep their precision.
58243
+ vec3 offset = positionEC - u_drapeCentreEC;
58244
+ float east = dot(offset, u_drapeEastEC);
58245
+ float north = dot(offset, u_drapeNorthEC);
58246
+ float up = dot(offset, u_drapeUpEC);
58247
+ float latitude = u_drapeGeo.y + north / u_drapeGeo.z;
58248
+ float longitude = u_drapeGeo.x + east / (u_drapeGeo.w * cos(latitude));
58249
+ uv = vec2((longitude - u_extentRadians.x) / (u_extentRadians.y - u_extentRadians.x),
58250
+ (u_extentRadians.z - latitude) / (u_extentRadians.z - u_extentRadians.w));
58251
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
58252
+ return false;
58253
+ }
58254
+
58255
+ // Bilinear by hand between texel centres, so cell edges on the ground read as a shoreline, not squares.
58256
+ vec2 coord = uv / u_texelSize - 0.5;
58257
+ vec2 base = floor(coord);
58258
+ vec2 f = coord - base;
58259
+ vec2 origin = (base + 0.5) * u_texelSize;
58260
+ vec2 values = vec2(0.0);
58261
+ vec2 weights = vec2(0.0);
58262
+ for (int i = 0; i < 4; i++) {
58263
+ vec2 step01 = vec2(float(i - (i / 2) * 2), float(i / 2));
58264
+ vec2 at = origin + step01 * u_texelSize;
58265
+ float w = mix(1.0 - f.x, f.x, step01.x) * mix(1.0 - f.y, f.y, step01.y);
58266
+ vec4 texelTo = texture(u_valueTexture, at);
58267
+ vec4 texelFrom = texture(u_valueTextureFrom, at);
58268
+ float a = mix(texelFrom.a, texelTo.a, u_valueFade);
58269
+ // Weighted by coverage too, so a no-data neighbour fades the edge instead of dragging the value to zero.
58270
+ values += vec2(mix(decodeValue(texelFrom), decodeValue(texelTo), u_valueFade) * a, a) * w;
58271
+ weights += vec2(a, 1.0) * w;
58272
+ }
58273
+ value = values.x / max(values.y, 1e-6);
58274
+ coverage = values.y;
58275
+
58276
+ // A region known to be water paints its gaps here too, the same way the vertex shader fills them.
58277
+ float inMask = u_maskWeight * texture(u_maskTexture, uv).a;
58278
+ float hasData = step(u_coverageCutoff, coverage);
58279
+ value = mix(value, mix(u_maskFillValue, max(value, u_maskFillValue), hasData), inMask * u_maskFill);
58280
+ coverage = max(coverage, inMask * u_maskFill);
58281
+
58282
+ if (u_drapeBand >= 0.0) {
58283
+ // The tangent plane falls away from the ellipsoid by distance squared over twice the radius.
58284
+ float height = up + (east * east + north * north) / (2.0 * u_drapeGeo.w);
58285
+ float level = (sampleGround(uv) + u_groundOffset) * u_groundWeight + u_valueMin + value * u_valueRange * u_exaggeration;
58286
+ // Inside a region the water is never below its known floor, so a deck or bank under that floor is still wet.
58287
+ level = mix(level, max(level, u_maskFloor), step(0.5, inMask));
58288
+ if (height - level > u_drapeBand) {
58289
+ return false;
58290
+ }
58291
+ }
58292
+ return true;
58293
+ }
58294
+
58011
58295
  //#water
58012
58296
  /*
58013
58297
  * Slope of the ripple field at a point, in metres of rise per metre travelled.
@@ -58039,17 +58323,17 @@ ${WATER_WAVES.map((wave, index) => {
58039
58323
  * The sheet shaded as a water surface: a flat body colour seen through a sun glint and a grazing
58040
58324
  * sky reflection, with the ripple field standing in for a geometry it is far too fine to carry.
58041
58325
  */
58042
- vec4 water(vec3 relief, vec4 color) {
58043
- float metresPerPixel = czm_metersPerPixel(vec4(v_positionEC, 1.0));
58326
+ vec4 water(vec3 relief, vec4 color, vec3 positionEC, vec2 waveMetres, float coverage) {
58327
+ float metresPerPixel = czm_metersPerPixel(vec4(positionEC, 1.0));
58044
58328
  float detail;
58045
- vec2 slope = rippleSlope(v_waveMetres, metresPerPixel, detail);
58329
+ vec2 slope = rippleSlope(waveMetres, metresPerPixel, detail);
58046
58330
 
58047
58331
  // relief arrives normalised, so its horizontal part over its vertical part is the slope it means.
58048
58332
  vec2 reliefSlope = relief.xy / max(relief.z, 1e-3);
58049
58333
  vec3 local = normalize(vec3(-(slope + reliefSlope), 1.0));
58050
58334
  vec3 normalEC = normalize(local.x * v_eastEC + local.y * v_northEC + local.z * v_upEC);
58051
58335
 
58052
- vec3 view = normalize(-v_positionEC);
58336
+ vec3 view = normalize(-positionEC);
58053
58337
  // Drawn with culling off, so the underside of the sheet arrives with its normal pointing away.
58054
58338
  normalEC = dot(normalEC, view) < 0.0 ? -normalEC : normalEC;
58055
58339
  vec3 sun = normalize(czm_sunDirectionEC);
@@ -58076,46 +58360,54 @@ vec4 water(vec3 relief, vec4 color) {
58076
58360
  /*
58077
58361
  * The same fog the globe under it is already drawing with.
58078
58362
  */
58079
- lit = czm_fog(length(v_positionEC), lit, u_waterSky);
58363
+ lit = czm_fog(length(positionEC), lit, u_waterSky);
58080
58364
 
58081
58365
  // A reflection seen through a half-transparent sheet is not a reflection, so the surface is
58082
58366
  // allowed to close up exactly where it is being reflective.
58083
- float alpha = color.a * v_coverage;
58367
+ float alpha = color.a * coverage;
58084
58368
  alpha = clamp(alpha + (1.0 - alpha) * (fresnel * 0.55 + glint), 0.0, 1.0);
58085
58369
  return vec4(lit, alpha);
58086
58370
  }
58087
58371
  //#endwater
58088
58372
 
58089
58373
  void main() {
58090
- if (v_coverage < u_coverageCutoff) {
58374
+ vec2 uv = v_st;
58375
+ float value = v_value;
58376
+ float coverage = v_coverage;
58377
+ vec3 positionEC = v_eyeEC;
58378
+ // Clamped: paint what is drawn behind this pixel, so the water sits on it however far off the sheet is.
58379
+ if (u_drape > 0.5 && !drawnBehind(uv, value, coverage, positionEC)) {
58380
+ discard;
58381
+ }
58382
+ if (coverage < u_coverageCutoff) {
58091
58383
  discard;
58092
58384
  }
58093
58385
  // The ramp is baked to a lookup rather than lerped between two colours, so a banded style with a
58094
58386
  // hidden floor reads the same here as it does on the flat drape.
58095
58387
  // Without it this surface painted water the style hides, and the cell grid then correctly refused to outline any of it.
58096
- vec4 color = texture(u_rampTexture, vec2(clamp(v_value, 0.0, 1.0), 0.5));
58388
+ vec4 color = texture(u_rampTexture, vec2(clamp(value, 0.0, 1.0), 0.5));
58097
58389
  if (color.a <= 0.0) {
58098
58390
  discard;
58099
58391
  }
58100
58392
 
58101
58393
  // Relief shading from the value gradient, so the displacement reads at a distance without
58102
58394
  // recomputing vertex normals every time the texture changes.
58103
- float left = valueAt(v_st - vec2(u_texelSize.x, 0.0));
58104
- float right = valueAt(v_st + vec2(u_texelSize.x, 0.0));
58105
- float down = valueAt(v_st - vec2(0.0, u_texelSize.y));
58106
- float up = valueAt(v_st + vec2(0.0, u_texelSize.y));
58395
+ float left = valueAt(uv - vec2(u_texelSize.x, 0.0));
58396
+ float right = valueAt(uv + vec2(u_texelSize.x, 0.0));
58397
+ float down = valueAt(uv - vec2(0.0, u_texelSize.y));
58398
+ float up = valueAt(uv + vec2(0.0, u_texelSize.y));
58107
58399
  float scale = u_valueRange * u_exaggeration;
58108
58400
  vec3 n = normalize(vec3((left - right) * scale, (down - up) * scale, 2.0 * u_metresPerTexel));
58109
58401
 
58110
58402
  //#water
58111
- out_FragColor = water(n, color);
58403
+ out_FragColor = water(n, color, positionEC, mix(v_waveMetres, uv * u_extentMetres - u_waveOrigin, u_drape), coverage);
58112
58404
  return;
58113
58405
  //#endwater
58114
58406
 
58115
58407
  float lambert = clamp(dot(n, normalize(vec3(-0.5, -0.6, 0.62))), 0.0, 1.0);
58116
58408
  color.rgb *= 0.45 + 0.9 * lambert;
58117
58409
 
58118
- out_FragColor = vec4(color.rgb, color.a * v_coverage);
58410
+ out_FragColor = vec4(color.rgb, color.a * coverage);
58119
58411
  }
58120
58412
  `;
58121
58413
  /*
@@ -58161,9 +58453,25 @@ void main() {
58161
58453
  // No probe means no evidence the host rewrites anything, so trust the context alone.
58162
58454
  modernizes = false;
58163
58455
  }
58164
- _glsl300Support = Boolean(context.webgl2) && !modernizes;
58456
+ _glsl300Support = context.webgl2 ? !modernizes : demotes(context);
58165
58457
  return _glsl300Support;
58166
58458
  }
58459
+ /*
58460
+ * True when the host takes GLSL 300 and rewrites it down itself on a WebGL1 context, as Cesium 1.102 onwards does.
58461
+ */
58462
+ function demotes(context) {
58463
+ try {
58464
+ const probe = new ShaderSource({
58465
+ sources: ["in float a_probe;\nout float v_probe;\nvoid main() { v_probe = a_probe; gl_Position = vec4(0.0); }"],
58466
+ includeBuiltIns: false
58467
+ });
58468
+ const combined = probe.createCombinedVertexShader(context);
58469
+ return combined.indexOf("attribute") >= 0;
58470
+ }
58471
+ catch (e) {
58472
+ return false;
58473
+ }
58474
+ }
58167
58475
  /*
58168
58476
  * Places grid node (fx, fy) on the ellipsoid, stepping the way the raster was sampled.
58169
58477
  * A raster sampled at lon/lat has to be walked in degrees; one sampled linearly across a projected CRS has to be walked in tangent-plane metres.
@@ -58445,9 +58753,334 @@ void main() {
58445
58753
  }
58446
58754
  return MASK_GROUND_LEVEL_MIN;
58447
58755
  }
58756
+ // Ground under a clamped value surface: coarse everywhere first, then refined block by block nearest the camera.
58757
+ let GroundRaster;
58758
+ (function (GroundRaster) {
58759
+ // Height window the packed raster covers, wide enough for any terrain on Earth.
58760
+ GroundRaster.MIN_METRES = -1000;
58761
+ GroundRaster.MAX_METRES = 9000;
58762
+ const PACKED_MAX = 16777215;
58763
+ // Samples per side of the first pass over the whole extent.
58764
+ const COARSE_SAMPLES = 64;
58765
+ // Samples per side of one refined block.
58766
+ GroundRaster.BLOCK_SAMPLES = 64;
58767
+ const MAX_SIDE = 2048;
58768
+ // Blocks being sampled at once, so a fast camera does not queue the whole model.
58769
+ const MAX_IN_FLIGHT = 2;
58770
+ // A block is refined once the camera is within this many block widths of it.
58771
+ const REFINE_BLOCK_WIDTHS = 12;
58772
+ /**
58773
+ * Raster side for a value source of the given size: a whole number of blocks, at least one, at most the cap.
58774
+ */
58775
+ function SideFor(width, height) {
58776
+ const wanted = Math.max(1, Math.round(Math.max(width || 0, height || 0)));
58777
+ const blocks = Math.ceil(wanted / GroundRaster.BLOCK_SAMPLES);
58778
+ return Math.min(MAX_SIDE, Math.max(1, blocks) * GroundRaster.BLOCK_SAMPLES);
58779
+ }
58780
+ GroundRaster.SideFor = SideFor;
58781
+ /**
58782
+ * Packs a height into three bytes the way the vertex shader unpacks it.
58783
+ */
58784
+ function Pack(height, into, at) {
58785
+ const known = typeof height === "number" && isFinite(height);
58786
+ const clamped = Math.min(GroundRaster.MAX_METRES, Math.max(GroundRaster.MIN_METRES, known ? height : 0));
58787
+ const packed = Math.round(((clamped - GroundRaster.MIN_METRES) / (GroundRaster.MAX_METRES - GroundRaster.MIN_METRES)) * PACKED_MAX);
58788
+ into[at] = (packed >> 16) & 255;
58789
+ into[at + 1] = (packed >> 8) & 255;
58790
+ into[at + 2] = packed & 255;
58791
+ into[at + 3] = known ? 255 : 0;
58792
+ }
58793
+ GroundRaster.Pack = Pack;
58794
+ /**
58795
+ * Bilinear between texel centres, the way the shader reads it.
58796
+ */
58797
+ function Bilinear(heights, side, u, v) {
58798
+ const read = (x, y) => heights[Math.min(side - 1, Math.max(0, y)) * side + Math.min(side - 1, Math.max(0, x))];
58799
+ const x = u * side - 0.5;
58800
+ const y = v * side - 0.5;
58801
+ const x0 = Math.floor(x);
58802
+ const y0 = Math.floor(y);
58803
+ const fx = x - x0;
58804
+ const fy = y - y0;
58805
+ const top = read(x0, y0) + (read(x0 + 1, y0) - read(x0, y0)) * fx;
58806
+ const bottom = read(x0, y0 + 1) + (read(x0 + 1, y0 + 1) - read(x0, y0 + 1)) * fx;
58807
+ return top + (bottom - top) * fy;
58808
+ }
58809
+ GroundRaster.Bilinear = Bilinear;
58810
+ class Raster {
58811
+ constructor(extent, side, sampler) {
58812
+ this.extent = extent;
58813
+ this.sampler = sampler;
58814
+ this.inFlight = new Set();
58815
+ this.dirty = [];
58816
+ this.coarseDone = false;
58817
+ this.coarseStarted = false;
58818
+ this.disposed = false;
58819
+ this.version = 0;
58820
+ this.side = Math.max(GroundRaster.BLOCK_SAMPLES, Math.round(side / GroundRaster.BLOCK_SAMPLES) * GroundRaster.BLOCK_SAMPLES);
58821
+ this.blocksPerSide = this.side / GroundRaster.BLOCK_SAMPLES;
58822
+ this.pixels = new Uint8Array(this.side * this.side * 4);
58823
+ this.heights = new Float32Array(this.side * this.side);
58824
+ this.refined = new Uint8Array(this.blocksPerSide * this.blocksPerSide);
58825
+ }
58826
+ Dispose() {
58827
+ this.disposed = true;
58828
+ }
58829
+ HasCoarse() {
58830
+ return this.coarseDone;
58831
+ }
58832
+ /**
58833
+ * Changes whenever any height changes.
58834
+ */
58835
+ GetVersion() {
58836
+ return this.version;
58837
+ }
58838
+ RefinedCount() {
58839
+ return this.refined.reduce((sum, value) => sum + value, 0);
58840
+ }
58841
+ InFlightCount() {
58842
+ return this.inFlight.size;
58843
+ }
58844
+ /**
58845
+ * Metres above the ellipsoid at a normalised point, north at v zero.
58846
+ */
58847
+ HeightAt(u, v) {
58848
+ return Bilinear(this.heights, this.side, u, v);
58849
+ }
58850
+ /**
58851
+ * The regions changed since the last call.
58852
+ */
58853
+ TakeDirty() {
58854
+ const dirty = this.dirty;
58855
+ this.dirty = [];
58856
+ return dirty;
58857
+ }
58858
+ /**
58859
+ * Samples the whole extent once, at the cheap level.
58860
+ */
58861
+ StartCoarse() {
58862
+ if (this.coarseStarted) {
58863
+ return Promise.resolve();
58864
+ }
58865
+ this.coarseStarted = true;
58866
+ const positions = this.grid(0, 0, 1, 1, COARSE_SAMPLES);
58867
+ return this.sampler.coarse(positions)
58868
+ .then((heights) => {
58869
+ if (this.disposed) {
58870
+ return;
58871
+ }
58872
+ const coarse = new Float32Array(COARSE_SAMPLES * COARSE_SAMPLES);
58873
+ for (let i = 0; i < coarse.length; i++) {
58874
+ const h = heights[i];
58875
+ coarse[i] = typeof h === "number" && isFinite(h) ? h : 0;
58876
+ }
58877
+ for (let y = 0; y < this.side; y++) {
58878
+ for (let x = 0; x < this.side; x++) {
58879
+ this.write(x, y, Bilinear(coarse, COARSE_SAMPLES, (x + 0.5) / this.side, (y + 0.5) / this.side));
58880
+ }
58881
+ }
58882
+ this.coarseDone = true;
58883
+ this.markDirty(0, 0, this.side, this.side);
58884
+ })
58885
+ .catch(() => {
58886
+ // Terrain that cannot be sampled leaves the sheet at its base height.
58887
+ });
58888
+ }
58889
+ /*
58890
+ * Starts sampling the unrefined visible blocks nearest the eye (world coordinates), up to the cap.
58891
+ */
58892
+ Refine(eye, isVisible) {
58893
+ if (!this.coarseDone || this.disposed || this.inFlight.size >= MAX_IN_FLIGHT) {
58894
+ return 0;
58895
+ }
58896
+ const candidates = [];
58897
+ const blockMetres = this.blockMetres();
58898
+ for (let by = 0; by < this.blocksPerSide; by++) {
58899
+ for (let bx = 0; bx < this.blocksPerSide; bx++) {
58900
+ const index = by * this.blocksPerSide + bx;
58901
+ if (this.refined[index] || this.inFlight.has(index)) {
58902
+ continue;
58903
+ }
58904
+ const sphere = this.blockSphere(bx, by, blockMetres);
58905
+ const distance = Math.max(0, Cartesian3.distance(eye, sphere.center) - sphere.radius);
58906
+ if (distance > blockMetres * REFINE_BLOCK_WIDTHS) {
58907
+ continue;
58908
+ }
58909
+ if (isVisible && !isVisible(sphere)) {
58910
+ continue;
58911
+ }
58912
+ candidates.push({ index, distance });
58913
+ }
58914
+ }
58915
+ candidates.sort((a, b) => a.distance - b.distance);
58916
+ let started = 0;
58917
+ for (const candidate of candidates) {
58918
+ if (this.inFlight.size >= MAX_IN_FLIGHT) {
58919
+ break;
58920
+ }
58921
+ this.refineBlock(candidate.index);
58922
+ started++;
58923
+ }
58924
+ return started;
58925
+ }
58926
+ refineBlock(index) {
58927
+ this.inFlight.add(index);
58928
+ const bx = index % this.blocksPerSide;
58929
+ const by = Math.floor(index / this.blocksPerSide);
58930
+ const u0 = bx / this.blocksPerSide;
58931
+ const v0 = by / this.blocksPerSide;
58932
+ const span = 1 / this.blocksPerSide;
58933
+ const positions = this.grid(u0, v0, span, span, GroundRaster.BLOCK_SAMPLES);
58934
+ const e = this.extent;
58935
+ const box = {
58936
+ West: Math$1.lerp(e.West, e.East, u0),
58937
+ East: Math$1.lerp(e.West, e.East, u0 + span),
58938
+ North: Math$1.lerp(e.North, e.South, v0),
58939
+ South: Math$1.lerp(e.North, e.South, v0 + span)
58940
+ };
58941
+ this.sampler.fine(positions, box)
58942
+ .then((heights) => {
58943
+ if (this.disposed) {
58944
+ return;
58945
+ }
58946
+ for (let row = 0; row < GroundRaster.BLOCK_SAMPLES; row++) {
58947
+ for (let col = 0; col < GroundRaster.BLOCK_SAMPLES; col++) {
58948
+ const h = heights[row * GroundRaster.BLOCK_SAMPLES + col];
58949
+ // Keeping the coarse height where the source has nothing finer.
58950
+ if (typeof h === "number" && isFinite(h)) {
58951
+ this.write(bx * GroundRaster.BLOCK_SAMPLES + col, by * GroundRaster.BLOCK_SAMPLES + row, h);
58952
+ }
58953
+ }
58954
+ }
58955
+ this.markDirty(bx * GroundRaster.BLOCK_SAMPLES, by * GroundRaster.BLOCK_SAMPLES, GroundRaster.BLOCK_SAMPLES, GroundRaster.BLOCK_SAMPLES);
58956
+ })
58957
+ .catch(() => {
58958
+ // A block that cannot be sampled keeps its coarse heights.
58959
+ })
58960
+ .then(() => {
58961
+ this.refined[index] = 1;
58962
+ this.inFlight.delete(index);
58963
+ });
58964
+ }
58965
+ /*
58966
+ * Positions at texel centres of a sub-box, given in normalised extent coordinates, north at v zero.
58967
+ */
58968
+ grid(u0, v0, uSpan, vSpan, samples) {
58969
+ const positions = [];
58970
+ const e = this.extent;
58971
+ for (let row = 0; row < samples; row++) {
58972
+ const v = v0 + vSpan * (row + 0.5) / samples;
58973
+ const latitude = Math$1.lerp(e.North, e.South, v);
58974
+ for (let col = 0; col < samples; col++) {
58975
+ const u = u0 + uSpan * (col + 0.5) / samples;
58976
+ positions.push(Cartographic.fromDegrees(Math$1.lerp(e.West, e.East, u), latitude));
58977
+ }
58978
+ }
58979
+ return positions;
58980
+ }
58981
+ write(x, y, height) {
58982
+ const at = y * this.side + x;
58983
+ this.heights[at] = height;
58984
+ Pack(height, this.pixels, at * 4);
58985
+ }
58986
+ markDirty(x, y, width, height) {
58987
+ this.dirty.push({ x, y, width, height });
58988
+ this.version++;
58989
+ }
58990
+ blockMetres() {
58991
+ const e = this.extent;
58992
+ const midLat = (e.North + e.South) / 2;
58993
+ const west = Cartesian3.fromDegrees(e.West, midLat);
58994
+ const east = Cartesian3.fromDegrees(e.East, midLat);
58995
+ const south = Cartesian3.fromDegrees(e.West, e.South);
58996
+ const north = Cartesian3.fromDegrees(e.West, e.North);
58997
+ const across = Math.max(Cartesian3.distance(west, east), Cartesian3.distance(south, north));
58998
+ return across / this.blocksPerSide;
58999
+ }
59000
+ blockSphere(bx, by, blockMetres) {
59001
+ const e = this.extent;
59002
+ const u = (bx + 0.5) / this.blocksPerSide;
59003
+ const v = (by + 0.5) / this.blocksPerSide;
59004
+ const centre = Cartesian3.fromDegrees(Math$1.lerp(e.West, e.East, u), Math$1.lerp(e.North, e.South, v), this.HeightAt(u, v));
59005
+ return new BoundingSphere(centre, blockMetres * Math.SQRT1_2);
59006
+ }
59007
+ }
59008
+ GroundRaster.Raster = Raster;
59009
+ })(GroundRaster = DisplacedSurfacePrimitive.GroundRaster || (DisplacedSurfacePrimitive.GroundRaster = {}));
59010
+ /**
59011
+ * Drawn ground minus sampled ground: a low percentile, so roofs and canopy over a probe are ignored.
59012
+ */
59013
+ function GroundOffsetFrom(differences) {
59014
+ const known = differences.filter((d) => typeof d === "number" && isFinite(d)).sort((a, b) => a - b);
59015
+ if (!known.length) {
59016
+ return null;
59017
+ }
59018
+ return known[Math.floor(OFFSET_PERCENTILE * (known.length - 1))];
59019
+ }
59020
+ DisplacedSurfacePrimitive.GroundOffsetFrom = GroundOffsetFrom;
59021
+ /*
59022
+ * The first shown tileset standing in for the globe, such as Google's photorealistic tiles.
59023
+ */
59024
+ function findGroundTileset(collection) {
59025
+ if (!collection) {
59026
+ return null;
59027
+ }
59028
+ for (let i = 0; i < collection.length; i++) {
59029
+ const primitive = collection.get(i);
59030
+ if (!primitive || primitive.show === false) {
59031
+ continue;
59032
+ }
59033
+ if (typeof primitive.length === "number" && typeof primitive.get === "function") {
59034
+ const nested = findGroundTileset(primitive);
59035
+ if (nested) {
59036
+ return nested;
59037
+ }
59038
+ }
59039
+ else if (CameraControls.IsGroundTileset(primitive)) {
59040
+ return primitive;
59041
+ }
59042
+ }
59043
+ return null;
59044
+ }
59045
+ /*
59046
+ * The finest level a ground block can be sampled at within a few tiles, and no finer than the terrain has there.
59047
+ */
59048
+ function fineLevelFor(box, provider) {
59049
+ const scheme = provider && provider.tilingScheme;
59050
+ let available = FINE_GROUND_LEVEL_MAX;
59051
+ const availability = provider && provider.availability;
59052
+ if (availability && typeof availability.computeMaximumLevelAtPosition === "function") {
59053
+ const centre = Cartographic.fromDegrees((box.West + box.East) / 2, (box.North + box.South) / 2);
59054
+ available = Math.min(available, availability.computeMaximumLevelAtPosition(centre));
59055
+ }
59056
+ for (let level = available; level > MASK_GROUND_LEVEL_MIN; level--) {
59057
+ const across = scheme && typeof scheme.getNumberOfXTilesAtLevel === "function"
59058
+ ? scheme.getNumberOfXTilesAtLevel(level)
59059
+ : Math.pow(2, level + 1);
59060
+ const down = scheme && typeof scheme.getNumberOfYTilesAtLevel === "function"
59061
+ ? scheme.getNumberOfYTilesAtLevel(level)
59062
+ : Math.pow(2, level);
59063
+ const tiles = Math.ceil((box.East - box.West) / (360 / across) + 1)
59064
+ * Math.ceil((box.North - box.South) / (180 / down) + 1);
59065
+ if (tiles <= FINE_GROUND_TILE_BUDGET) {
59066
+ return level;
59067
+ }
59068
+ }
59069
+ return MASK_GROUND_LEVEL_MIN;
59070
+ }
59071
+ /*
59072
+ * Heights for a ground raster from a terrain provider: a cheap level first, then the finest in budget per block.
59073
+ */
59074
+ function terrainSampler(provider, extent) {
59075
+ const heightsOf = (sampled) => (sampled || []).map((c) => (c && isFinite(c.height) ? c.height : undefined));
59076
+ return {
59077
+ coarse: (positions) => Promise.resolve(sampleTerrain(provider, groundLevelFor(extent, provider), positions)).then(heightsOf),
59078
+ fine: (positions, box) => Promise.resolve(sampleTerrain(provider, fineLevelFor(box, provider), positions)).then(heightsOf)
59079
+ };
59080
+ }
58448
59081
  class Surface {
58449
59082
  constructor(options, hasCoverage) {
58450
- var _a, _b, _c, _d;
59083
+ var _a, _b, _c, _d, _e, _f;
58451
59084
  this.show = true;
58452
59085
  this.valueSource = null;
58453
59086
  this.lastPresentVersion = -1;
@@ -58468,9 +59101,22 @@ void main() {
58468
59101
  this.lastEyePosition = null;
58469
59102
  this.lastSelectionMs = -Infinity;
58470
59103
  this.selectionDirty = true;
59104
+ this.groundRaster = null;
59105
+ this.groundTextureSide = 0;
59106
+ // Draping reads globe coordinates back from depth, true only in 3D; 2D and Columbus keep the raised sheet.
59107
+ this.drapeActive = false;
59108
+ // Drawn ground minus the ground raster, measured where a ground tileset such as Google's is shown.
59109
+ this.groundOffset = 0;
59110
+ this.offsetProbe = { at: null, busy: false };
59111
+ this.drapeFrame = {
59112
+ centreEC: new Cartesian3(),
59113
+ eastEC: new Cartesian3(),
59114
+ northEC: new Cartesian3(),
59115
+ upEC: new Cartesian3(),
59116
+ geo: new Cartesian4(),
59117
+ extent: new Cartesian4()
59118
+ };
58471
59119
  this.groundTexture = null;
58472
- this.groundPixels = null;
58473
- this.groundRequested = false;
58474
59120
  this.groundClearance = null;
58475
59121
  this.maskTexture = null;
58476
59122
  this.maskPixels = null;
@@ -58487,13 +59133,18 @@ void main() {
58487
59133
  this.wavePhaseScratch = [new Cartesian4(), new Cartesian4()];
58488
59134
  this.waterSkyScratch = new Cartesian3();
58489
59135
  this.followGround = Boolean(options.followGround);
59136
+ this.groundRasterSide = options.groundRasterSide;
59137
+ this.scene = options.scene || null;
59138
+ this.drape = Boolean(options.followGround) && options.drape !== false;
59139
+ this.drapeLift = (_a = options.drapeLift) !== null && _a !== void 0 ? _a : DEFAULT_DRAPE_LIFT_METRES;
59140
+ this.drapeBand = (_b = options.drapeBand) !== null && _b !== void 0 ? _b : DEFAULT_DRAPE_BAND_METRES;
58490
59141
  this.terrainProvider = options.terrainProvider || null;
58491
59142
  this.extent = options.extent;
58492
59143
  this.source = options.source || null;
58493
- this.valueMin = (_a = options.valueMin) !== null && _a !== void 0 ? _a : 0;
58494
- this.valueMax = (_b = options.valueMax) !== null && _b !== void 0 ? _b : 1;
58495
- this.exaggeration = (_c = options.exaggeration) !== null && _c !== void 0 ? _c : 1;
58496
- this.baseHeight = (_d = options.baseHeight) !== null && _d !== void 0 ? _d : 0;
59144
+ this.valueMin = (_c = options.valueMin) !== null && _c !== void 0 ? _c : 0;
59145
+ this.valueMax = (_d = options.valueMax) !== null && _d !== void 0 ? _d : 1;
59146
+ this.exaggeration = (_e = options.exaggeration) !== null && _e !== void 0 ? _e : 1;
59147
+ this.baseHeight = (_f = options.baseHeight) !== null && _f !== void 0 ? _f : 0;
58497
59148
  this.packedValue = Boolean(options.packedValue);
58498
59149
  this.pixelPlacement = options.pixelPlacement;
58499
59150
  this.tileSkirts = Boolean(options.tileSkirts);
@@ -58598,8 +59249,9 @@ void main() {
58598
59249
  return;
58599
59250
  }
58600
59251
  this.terrainProvider = provider;
58601
- this.groundPixels = null;
58602
- this.groundRequested = false;
59252
+ this.dropGroundRaster();
59253
+ this.groundOffset = 0;
59254
+ this.offsetProbe = { at: null, busy: false };
58603
59255
  this.maskGroundPixels = null;
58604
59256
  this.maskGroundRequested = false;
58605
59257
  this.maskGroundLevel = 0;
@@ -58653,15 +59305,15 @@ void main() {
58653
59305
  ? (pixels[at] * 256 + pixels[at + 1]) / 65535
58654
59306
  : pixels[at] / 255;
58655
59307
  const metres = this.valueMin + normalised * (this.valueMax - this.valueMin) * this.exaggeration;
58656
- const following = this.followGround && Boolean(this.groundPixels);
58657
- const ground = following ? this.groundAt(fx, fy) : 0;
59308
+ const following = this.hasGround();
59309
+ const ground = following ? this.groundRaster.HeightAt(fx, fy) + this.groundOffset : 0;
58658
59310
  return this.baseHeight + ground + metres * (following ? coverage : 1);
58659
59311
  }
58660
59312
  /**
58661
59313
  * Changes whenever HeightAt would answer differently for the same frame.
58662
59314
  */
58663
59315
  GetPlacementKey() {
58664
- return [this.groundPixels ? 1 : 0, this.baseHeight, this.exaggeration, this.followGround ? 1 : 0].join("|");
59316
+ return [this.groundRaster ? this.groundRaster.GetVersion() : 0, this.baseHeight, this.exaggeration, this.followGround ? 1 : 0].join("|");
58665
59317
  }
58666
59318
  /**
58667
59319
  * Repaints the sheet with new colours, keeping its geometry and the frames it is reading.
@@ -58687,25 +59339,19 @@ void main() {
58687
59339
  return this.rampPixels;
58688
59340
  }
58689
59341
  /*
58690
- * The packed ground raster read the way sampleGround reads it, bilinear between texel centres.
58691
- */
58692
- groundAt(u, v) {
58693
- const size = GROUND_SAMPLES_PER_SIDE;
58694
- const pixels = this.groundPixels;
58695
- const read = (x, y) => {
58696
- const i = (Math.min(size - 1, Math.max(0, y)) * size + Math.min(size - 1, Math.max(0, x))) * 4;
58697
- const packed = (pixels[i] << 16) + (pixels[i + 1] << 8) + pixels[i + 2];
58698
- return GROUND_MIN_METRES + (packed / 16777215) * (GROUND_MAX_METRES - GROUND_MIN_METRES);
58699
- };
58700
- const x = u * size - 0.5;
58701
- const y = v * size - 0.5;
58702
- const x0 = Math.floor(x);
58703
- const y0 = Math.floor(y);
58704
- const fx = x - x0;
58705
- const fy = y - y0;
58706
- const top = read(x0, y0) + (read(x0 + 1, y0) - read(x0, y0)) * fx;
58707
- const bottom = read(x0, y0 + 1) + (read(x0 + 1, y0 + 1) - read(x0, y0 + 1)) * fx;
58708
- return top + (bottom - top) * fy;
59342
+ * Whether a clamped sheet has ground to stand on yet.
59343
+ */
59344
+ hasGround() {
59345
+ return this.followGround && Boolean(this.groundRaster) && this.groundRaster.HasCoarse();
59346
+ }
59347
+ /*
59348
+ * Lets go of the ground raster, so samples still in flight land nowhere.
59349
+ */
59350
+ dropGroundRaster() {
59351
+ if (this.groundRaster) {
59352
+ this.groundRaster.Dispose();
59353
+ this.groundRaster = null;
59354
+ }
58709
59355
  }
58710
59356
  /**
58711
59357
  * Feeds the surface from an animated frame series.
@@ -58759,8 +59405,13 @@ void main() {
58759
59405
  this.syncTexture(context);
58760
59406
  }
58761
59407
  this.syncRampTexture(context);
58762
- this.requestGround();
59408
+ this.requestGround(frameState);
58763
59409
  this.syncGroundTexture(context);
59410
+ this.drapeActive = this.drape && frameState.mode === SceneMode.SCENE3D;
59411
+ if (this.drapeActive) {
59412
+ this.probeGroundOffset(frameState);
59413
+ this.updateDrapeFrame(frameState);
59414
+ }
58764
59415
  this.requestMaskGround();
58765
59416
  this.syncMaskTextures(context);
58766
59417
  // A tile needs one mesh before it has a bounding sphere to measure against.
@@ -58817,6 +59468,7 @@ void main() {
58817
59468
  this.groundTexture.destroy();
58818
59469
  this.groundTexture = null;
58819
59470
  }
59471
+ this.dropGroundRaster();
58820
59472
  if (this.maskTexture) {
58821
59473
  this.maskTexture.destroy();
58822
59474
  this.maskTexture = null;
@@ -58828,42 +59480,108 @@ void main() {
58828
59480
  return undefined;
58829
59481
  }
58830
59482
  /*
58831
- * Samples terrain across the extent once and packs it into a texture the vertex shader reads.
58832
- *
58833
- * A texture rather than heights baked into the meshes, because the samples arrive
58834
- * asynchronously and every cached tile mesh would otherwise have to be rebuilt when they land.
59483
+ * The extent centre's frame in eye coordinates, in double precision each frame, for the draped fragment shader.
59484
+ */
59485
+ updateDrapeFrame(frameState) {
59486
+ const e = this.extent;
59487
+ const lon = Math$1.toRadians((e.West + e.East) / 2);
59488
+ const lat = Math$1.toRadians((e.North + e.South) / 2);
59489
+ const centre = Cartesian3.fromRadians(lon, lat, 0);
59490
+ const enu = Transforms.eastNorthUpToFixedFrame(centre);
59491
+ const view = frameState.camera.viewMatrix;
59492
+ const f = this.drapeFrame;
59493
+ Matrix4.multiplyByPoint(view, centre, f.centreEC);
59494
+ const axis = new Cartesian3();
59495
+ const columns = [f.eastEC, f.northEC, f.upEC];
59496
+ for (let i = 0; i < 3; i++) {
59497
+ Matrix4.getColumn(enu, i, axis);
59498
+ Matrix4.multiplyByPointAsVector(view, axis, columns[i]);
59499
+ Cartesian3.normalize(columns[i], columns[i]);
59500
+ }
59501
+ const sin = Math.sin(lat);
59502
+ const w = 1 - WGS84_E2 * sin * sin;
59503
+ f.geo = new Cartesian4(lon, lat, WGS84_A * (1 - WGS84_E2) / Math.pow(w, 1.5), WGS84_A / Math.sqrt(w));
59504
+ f.extent = new Cartesian4(Math$1.toRadians(e.West), Math$1.toRadians(e.East), Math$1.toRadians(e.North), Math$1.toRadians(e.South));
59505
+ }
59506
+ /*
59507
+ * Measures a shown ground tileset such as Google's against the ground raster near the camera.
58835
59508
  */
58836
- requestGround() {
58837
- if (this.groundRequested || !this.followGround) {
59509
+ probeGroundOffset(frameState) {
59510
+ const raster = this.groundRaster;
59511
+ const scene = this.scene;
59512
+ if (!raster || !raster.HasCoarse() || !scene || this.offsetProbe.busy || typeof scene.sampleHeightMostDetailed !== "function") {
58838
59513
  return;
58839
59514
  }
58840
- this.groundRequested = true;
58841
- const sampler = sampleTerrain;
58842
- if (!this.terrainProvider || typeof sampler !== "function") {
59515
+ const eye = frameState.camera.positionWC;
59516
+ if (this.offsetProbe.at && Cartesian3.distance(this.offsetProbe.at, eye) < OFFSET_REPROBE_METRES) {
58843
59517
  return;
58844
59518
  }
58845
- const positions = [];
58846
- for (let row = 0; row < GROUND_SAMPLES_PER_SIDE; row++) {
58847
- const fy = row / (GROUND_SAMPLES_PER_SIDE - 1);
58848
- const latitude = Math$1.lerp(this.extent.North, this.extent.South, fy);
58849
- for (let col = 0; col < GROUND_SAMPLES_PER_SIDE; col++) {
58850
- const fx = col / (GROUND_SAMPLES_PER_SIDE - 1);
58851
- const longitude = Math$1.lerp(this.extent.West, this.extent.East, fx);
58852
- positions.push(Cartographic.fromDegrees(longitude, latitude));
59519
+ this.offsetProbe.at = Cartesian3.clone(eye);
59520
+ const tileset = findGroundTileset(scene.primitives);
59521
+ if (!tileset || !scene.sampleHeightSupported) {
59522
+ this.groundOffset = 0;
59523
+ return;
59524
+ }
59525
+ const e = this.extent;
59526
+ const camera = Cartographic.fromCartesian(eye);
59527
+ if (!camera) {
59528
+ return;
59529
+ }
59530
+ const toDegrees = 180 / (Math.PI * WGS84_A);
59531
+ const latStep = OFFSET_PROBE_SPACING_METRES * toDegrees;
59532
+ const lonStep = latStep / Math.max(0.1, Math.cos(camera.latitude));
59533
+ const lon0 = Math.min(e.East, Math.max(e.West, Math$1.toDegrees(camera.longitude)));
59534
+ const lat0 = Math.min(e.North, Math.max(e.South, Math$1.toDegrees(camera.latitude)));
59535
+ const probes = [];
59536
+ const half = (OFFSET_PROBES_PER_SIDE - 1) / 2;
59537
+ for (let row = 0; row < OFFSET_PROBES_PER_SIDE; row++) {
59538
+ for (let col = 0; col < OFFSET_PROBES_PER_SIDE; col++) {
59539
+ const lon = Math.min(e.East, Math.max(e.West, lon0 + (col - half) * lonStep));
59540
+ const lat = Math.min(e.North, Math.max(e.South, lat0 + (row - half) * latStep));
59541
+ probes.push(Cartographic.fromDegrees(lon, lat));
58853
59542
  }
58854
59543
  }
58855
- Promise.resolve(sampler(this.terrainProvider, GROUND_SAMPLE_LEVEL, positions))
58856
- .then((sampled) => {
58857
- if (this.destroyed || !sampled) {
59544
+ this.offsetProbe.busy = true;
59545
+ Promise.resolve(scene.sampleHeightMostDetailed(probes, [this]))
59546
+ .then((drawn) => {
59547
+ if (this.destroyed || this.groundRaster !== raster) {
58858
59548
  return;
58859
59549
  }
58860
- this.groundPixels = packHeights(sampled);
59550
+ const differences = (drawn || []).map((c) => {
59551
+ const u = (Math$1.toDegrees(c.longitude) - e.West) / (e.East - e.West);
59552
+ const v = (e.North - Math$1.toDegrees(c.latitude)) / (e.North - e.South);
59553
+ return c && isFinite(c.height) ? c.height - raster.HeightAt(u, v) : NaN;
59554
+ });
59555
+ const offset = GroundOffsetFrom(differences);
59556
+ if (offset !== null) {
59557
+ this.groundOffset = offset;
59558
+ }
58861
59559
  })
58862
59560
  .catch(() => {
58863
- // Terrain that cannot be sampled leaves the surface on the ellipsoid, which is
58864
- // where a clamped polygon sat before this existed.
59561
+ // Unmeasured, the sheet keeps its last offset.
59562
+ })
59563
+ .then(() => {
59564
+ this.offsetProbe.busy = false;
58865
59565
  });
58866
59566
  }
59567
+ /*
59568
+ * Starts the ground raster a clamped sheet stands on, and refines it near the camera each frame.
59569
+ */
59570
+ requestGround(frameState) {
59571
+ if (!this.followGround || !this.terrainProvider || !this.sourceDims) {
59572
+ return;
59573
+ }
59574
+ if (!this.groundRaster) {
59575
+ const side = this.groundRasterSide || GroundRaster.SideFor(this.sourceDims.width, this.sourceDims.height);
59576
+ this.groundRaster = new GroundRaster.Raster(this.extent, side, terrainSampler(this.terrainProvider, this.extent));
59577
+ this.groundRaster.StartCoarse();
59578
+ return;
59579
+ }
59580
+ const culling = frameState.cullingVolume;
59581
+ this.groundRaster.Refine(frameState.camera.positionWC, culling
59582
+ ? (sphere) => culling.computeVisibility(sphere) !== Intersect.OUTSIDE
59583
+ : undefined);
59584
+ }
58867
59585
  /*
58868
59586
  * Samples the terrain under the clearance regions.
58869
59587
  *
@@ -58892,10 +59610,10 @@ void main() {
58892
59610
  // does not cover are never asked for at all.
58893
59611
  const slots = [];
58894
59612
  for (let row = 0; row < MASK_GROUND_SAMPLES_PER_SIDE; row++) {
58895
- const fy = row / (MASK_GROUND_SAMPLES_PER_SIDE - 1);
59613
+ const fy = (row + 0.5) / MASK_GROUND_SAMPLES_PER_SIDE;
58896
59614
  const latitude = Math$1.lerp(box.North, box.South, fy);
58897
59615
  for (let col = 0; col < MASK_GROUND_SAMPLES_PER_SIDE; col++) {
58898
- const fx = col / (MASK_GROUND_SAMPLES_PER_SIDE - 1);
59616
+ const fx = (col + 0.5) / MASK_GROUND_SAMPLES_PER_SIDE;
58899
59617
  const at = Cartographic.fromDegrees(Math$1.lerp(box.West, box.East, fx), latitude);
58900
59618
  // An imported terrain covers a survey area, so asking outside it answers 404 and
58901
59619
  // fills the console with failures for points that were never going to have a height.
@@ -58979,27 +59697,48 @@ void main() {
58979
59697
  * shader always has a texture bound whether or not this surface follows the ground.
58980
59698
  */
58981
59699
  syncGroundTexture(context) {
58982
- if (this.groundTexture && (!this.groundPixels || this.groundTexture.width === GROUND_SAMPLES_PER_SIDE)) {
59700
+ const raster = this.hasGround() ? this.groundRaster : null;
59701
+ const side = raster ? raster.side : 1;
59702
+ if (!this.groundTexture || this.groundTextureSide !== side) {
59703
+ if (this.groundTexture) {
59704
+ this.groundTexture.destroy();
59705
+ }
59706
+ const stand = new Uint8Array(4);
59707
+ GroundRaster.Pack(0, stand, 0);
59708
+ this.groundTexture = new Texture({
59709
+ context,
59710
+ pixelFormat: PixelFormat.RGBA,
59711
+ source: { width: side, height: side, arrayBufferView: raster ? raster.pixels : stand },
59712
+ flipY: false,
59713
+ sampler: new Sampler({
59714
+ wrapS: TextureWrap.CLAMP_TO_EDGE,
59715
+ wrapT: TextureWrap.CLAMP_TO_EDGE,
59716
+ // Nearest, because the shader interpolates decoded heights itself.
59717
+ minificationFilter: TextureMinificationFilter.NEAREST,
59718
+ magnificationFilter: TextureMagnificationFilter.NEAREST
59719
+ })
59720
+ });
59721
+ this.groundTextureSide = side;
59722
+ if (raster) {
59723
+ raster.TakeDirty();
59724
+ }
58983
59725
  return;
58984
59726
  }
58985
- if (this.groundTexture) {
58986
- this.groundTexture.destroy();
59727
+ if (!raster) {
59728
+ return;
59729
+ }
59730
+ for (const region of raster.TakeDirty()) {
59731
+ const block = new Uint8Array(region.width * region.height * 4);
59732
+ for (let row = 0; row < region.height; row++) {
59733
+ const from = ((region.y + row) * side + region.x) * 4;
59734
+ block.set(raster.pixels.subarray(from, from + region.width * 4), row * region.width * 4);
59735
+ }
59736
+ this.groundTexture.copyFrom({
59737
+ source: { width: region.width, height: region.height, arrayBufferView: block },
59738
+ xOffset: region.x,
59739
+ yOffset: region.y
59740
+ });
58987
59741
  }
58988
- const size = this.groundPixels ? GROUND_SAMPLES_PER_SIDE : 1;
58989
- const arrayBufferView = this.groundPixels || packHeights([{ height: 0 }]);
58990
- this.groundTexture = new Texture({
58991
- context,
58992
- pixelFormat: PixelFormat.RGBA,
58993
- source: { width: size, height: size, arrayBufferView },
58994
- flipY: false,
58995
- sampler: new Sampler({
58996
- wrapS: TextureWrap.CLAMP_TO_EDGE,
58997
- wrapT: TextureWrap.CLAMP_TO_EDGE,
58998
- // Nearest, because the shader interpolates decoded heights itself.
58999
- minificationFilter: TextureMinificationFilter.NEAREST,
59000
- magnificationFilter: TextureMagnificationFilter.NEAREST
59001
- })
59002
- });
59003
59742
  }
59004
59743
  /*
59005
59744
  * Metres the extent spans west to east and north to south, which is what turns the shader's
@@ -59320,9 +60059,9 @@ void main() {
59320
60059
  u_valueFade: () => (self.fade && self.fade.from ? self.fade.mix : 1),
59321
60060
  u_groundTexture: () => self.groundTexture,
59322
60061
  u_valuePacked: () => (self.packedValue ? 1 : 0),
59323
- u_groundWeight: () => (self.followGround && self.groundPixels ? 1 : 0),
60062
+ u_groundWeight: () => (self.hasGround() ? 1 : 0),
59324
60063
  u_groundRange: () => new Cartesian2(GROUND_MIN_METRES, GROUND_MAX_METRES),
59325
- u_groundSize: () => new Cartesian2(self.groundPixels ? GROUND_SAMPLES_PER_SIDE : 1, self.groundPixels ? GROUND_SAMPLES_PER_SIDE : 1),
60064
+ u_groundSize: () => new Cartesian2(self.groundTextureSide || 1, self.groundTextureSide || 1),
59326
60065
  u_maskTexture: () => self.maskTexture,
59327
60066
  u_maskGroundTexture: () => self.maskGroundTexture,
59328
60067
  u_maskWeight: () => (self.groundClearance && self.maskPixels ? 1 : 0),
@@ -59381,7 +60120,17 @@ void main() {
59381
60120
  u_wavePhaseB: () => self.wavePhase(4),
59382
60121
  u_wavePeriod: () => self.wavePeriod(),
59383
60122
  u_waveOrigin: () => self.waveOrigin,
59384
- u_extentMetres: () => self.extentMetres()
60123
+ u_extentMetres: () => self.extentMetres(),
60124
+ u_drape: () => (self.drapeActive ? 1 : 0),
60125
+ u_drapeLift: () => self.drapeLift,
60126
+ u_drapeBand: () => self.drapeBand,
60127
+ u_groundOffset: () => self.groundOffset,
60128
+ u_drapeCentreEC: () => self.drapeFrame.centreEC,
60129
+ u_drapeEastEC: () => self.drapeFrame.eastEC,
60130
+ u_drapeNorthEC: () => self.drapeFrame.northEC,
60131
+ u_drapeUpEC: () => self.drapeFrame.upEC,
60132
+ u_drapeGeo: () => self.drapeFrame.geo,
60133
+ u_extentRadians: () => self.drapeFrame.extent
59385
60134
  }
59386
60135
  });
59387
60136
  }
@@ -60311,6 +61060,7 @@ function syncDisplacedSurface(params) {
60311
61060
  baseHeight: placement.baseHeight,
60312
61061
  followGround: placement.followGround,
60313
61062
  terrainProvider: viewer && viewer.terrainProvider,
61063
+ scene: viewer && viewer.scene,
60314
61064
  valueMin: extrusionArchive.metadata.ValueMin,
60315
61065
  valueMax: extrusionArchive.metadata.ValueMax,
60316
61066
  packedValue: TextureFrameSeriesAnimator.IsPackedValue(extrusionArchive.metadata),
@@ -62320,7 +63070,7 @@ var StyleUtils;
62320
63070
  StyleUtils.ApplyTypeStyle = ApplyTypeStyle;
62321
63071
  })(StyleUtils || (StyleUtils = {}));
62322
63072
 
62323
- const VERSION = "7.9.4";
63073
+ const VERSION = "7.9.6";
62324
63074
  /**
62325
63075
  * Updates the environment instance used by bruce-cesium to one specified.
62326
63076
  * This can be used to ensure that the instance a parent is referencing is shared between bruce-cesium, bruce-models, and the parent app.
@@ -62337,5 +63087,5 @@ const getENVIRONMENT = () => {
62337
63087
  return ENVIRONMENT;
62338
63088
  };
62339
63089
 
62340
- export { VERSION, setENVIRONMENT, getENVIRONMENT, ClusterItems, PointClustering, PointClusterSize, CesiumAnimatedInOut, DisplacedSurfacePrimitive, CesiumAnimatedProperty, isStyleChanged, isOutlineChanged$1 as isOutlineChanged, StyleEffective, EntityRenderEngine, EntityRenderEngineModel3d, EntityRenderEnginePoint, extractMetadataFromFileUrl, EntityRenderEnginePolygon, EntityRenderEnginePolyline, TextureFrameSeriesAnimator, TextureValueLabels, MenuItemCreator, MenuItemManager, MenuItemStyles, MenuItemStyleOverlay, CesiumParabola, EntityLabel, EntityLabelGroup, LiveCursor, SharedGetters, EntitySimulation, DataSourceStaticKmlManager, DataLabRenderManager, EntitiesIdsRenderManager, EntitiesLoadedRenderManager, EntitiesRenderManager, EntityRenderManager, AssemblyRenderManager, GoogleSearchRenderManager, RelationsRenderManager, RenderManager, TilesetArbRenderManager, TilesetCadRenderManager, TilesetEntitiesRenderManager, TilesetGooglePhotosRenderManager, TilesetOsmRenderManager, TilesetPointcloudRenderManager, TileRenderEngine, createTileset, TilesetRenderEngine, ViewRenderEngine, VisualRegisterCuller, VisualsRegister, XGridsRenderEngine, CesiumEntityStyler, DrawingUtils, EntityUtils, MeasureUtils, StyleUtils, CESIUM_INSPECTOR_KEY, CESIUM_TIMELINE_KEY, CESIUM_TIMELINE_LIVE_KEY, CESIUM_TIMELINE_LIVE_PADDING_KEY, CESIUM_TIMELINE_INTERVAL_KEY, CESIUM_MODEL_SPACE_KEY, CESIUM_MODEL_SPACE_POSITIONING_KEY, DEFAULT_LIVE_PADDING_SECONDS, DEFAULT_BRIGHTNESS_SHIFT, DEFAULT_LIGHT_INTENSITY, LIGHTING_SETTINGS_VERSION, LIGHT_INTENSITY_COMPENSATION, MAX_COMPENSATED_LIGHT_INTENSITY, ViewUtils, CesiumMapGrid, GltfGenerator, GltfGizmo, DeviceProfile, CesiumViewMonitor, CameraControls, FindGapSurfaces, NearClearance, GrabPoint, ViewGroundArea, ViewerEventTracker, ViewerUtils, Draw3dPolygon, Draw3dPolyline, MeasureCreator, Walkthrough, WidgetControlViewBar, WidgetControlViewBarSearch, WidgetLeftPanelTab, WidgetLeftPanelTabBookmarks, WidgetLeftPanelTabDashboard, EMenuItemState, WidgetLeftPanelTabMenuItems, Widget, VIEWER_BOOKMARKS_WIDGET_KEY, WidgetBookmarks, WidgetBranding, ECursor, WidgetCursorBar, WidgetEmbeddedInfoView, WidgetInfoView, VIEWER_LEFT_PANEL_WIDGET_KEY, VIEWER_LEFT_PANEL_CSS_VAR_LEFT, CreateTabIconSvg, WidgetLeftPanel, WidgetNavCompass$$1 as WidgetNavCompass, VIEWER_VIEW_BAR_WIDGET_KEY, WidgetViewBar };
63090
+ export { VERSION, setENVIRONMENT, getENVIRONMENT, ClusterItems, PointClustering, PointClusterSize, CesiumAnimatedInOut, DisplacedSurfacePrimitive, CesiumAnimatedProperty, isStyleChanged, isOutlineChanged$1 as isOutlineChanged, StyleEffective, EntityRenderEngine, EntityRenderEngineModel3d, EntityRenderEnginePoint, extractMetadataFromFileUrl, EntityRenderEnginePolygon, EntityRenderEnginePolyline, TextureFrameSeriesAnimator, TextureValueLabels, MenuItemCreator, MenuItemManager, MenuItemStyles, MenuItemStyleOverlay, CesiumParabola, EntityLabel, EntityLabelGroup, LiveCursor, SharedGetters, EntitySimulation, DataSourceStaticKmlManager, DataLabRenderManager, EntitiesIdsRenderManager, EntitiesLoadedRenderManager, EntitiesRenderManager, EntityRenderManager, AssemblyRenderManager, GoogleSearchRenderManager, RelationsRenderManager, RenderManager, TilesetArbRenderManager, TilesetCadRenderManager, TilesetEntitiesRenderManager, TilesetGooglePhotosRenderManager, TilesetOsmRenderManager, TilesetPointcloudRenderManager, TileRenderEngine, createTileset, TilesetRenderEngine, ViewRenderEngine, VisualRegisterCuller, VisualsRegister, XGridsRenderEngine, CesiumEntityStyler, DrawingUtils, EntityUtils, MeasureUtils, StyleUtils, CESIUM_INSPECTOR_KEY, CESIUM_TIMELINE_KEY, CESIUM_TIMELINE_LIVE_KEY, CESIUM_TIMELINE_LIVE_PADDING_KEY, CESIUM_TIMELINE_INTERVAL_KEY, CESIUM_MODEL_SPACE_KEY, CESIUM_MODEL_SPACE_POSITIONING_KEY, DEFAULT_LIVE_PADDING_SECONDS, DEFAULT_BRIGHTNESS_SHIFT, DEFAULT_LIGHT_INTENSITY, LIGHTING_SETTINGS_VERSION, LIGHT_INTENSITY_COMPENSATION, MAX_COMPENSATED_LIGHT_INTENSITY, ViewUtils, CesiumMapGrid, GltfGenerator, GltfGizmo, DeviceProfile, CesiumViewMonitor, ECameraMouseScheme, CameraControls, FindGapSurfaces, NearClearance, GrabPoint, ViewGroundArea, ViewerEventTracker, ViewerUtils, Draw3dPolygon, Draw3dPolyline, MeasureCreator, Walkthrough, WidgetControlViewBar, WidgetControlViewBarSearch, WidgetLeftPanelTab, WidgetLeftPanelTabBookmarks, WidgetLeftPanelTabDashboard, EMenuItemState, WidgetLeftPanelTabMenuItems, Widget, VIEWER_BOOKMARKS_WIDGET_KEY, WidgetBookmarks, WidgetBranding, ECursor, WidgetCursorBar, WidgetEmbeddedInfoView, WidgetInfoView, VIEWER_LEFT_PANEL_WIDGET_KEY, VIEWER_LEFT_PANEL_CSS_VAR_LEFT, CreateTabIconSvg, WidgetLeftPanel, WidgetNavCompass$$1 as WidgetNavCompass, VIEWER_VIEW_BAR_WIDGET_KEY, WidgetViewBar };
62341
63091
  //# sourceMappingURL=bruce-cesium.es5.js.map