bruce-cesium 7.9.5 → 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.
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DisplacedSurfacePrimitive = void 0;
4
4
  const Cesium = require("cesium");
5
5
  const image_utils_1 = require("../internal/image-utils");
6
+ const camera_controls_1 = require("../viewer/camera-controls");
6
7
  /**
7
8
  * Renders a value texture as a displaced, coloured surface.
8
9
  * The source canvas is expected as RGBA: value in R, coverage in A.
@@ -23,12 +24,6 @@ var DisplacedSurfacePrimitive;
23
24
  const SKIRT_FRACTION = 0.015;
24
25
  // Alpha below which a texel counts as no-data and is not drawn at all.
25
26
  const COVERAGE_CUTOFF = 0.35;
26
- // Terrain is sampled on this grid and interpolated between samples.
27
- // Per-texel sampling would be hundreds of thousands of lookups for a surface whose own data is far coarser than that.
28
- const GROUND_SAMPLES_PER_SIDE = 64;
29
- // Terrain detail level the samples are taken at.
30
- // Most-detailed would fetch every tile under a parcel that can be a hundred kilometres across.
31
- const GROUND_SAMPLE_LEVEL = 11;
32
27
  // Height window the packed ground texture covers, wide enough for any terrain on Earth.
33
28
  // Ground samples across the clearance regions rather than the whole extent.
34
29
  const MASK_GROUND_SAMPLES_PER_SIDE = 128;
@@ -36,9 +31,23 @@ var DisplacedSurfacePrimitive;
36
31
  const MASK_GROUND_LEVEL_MAX = 13;
37
32
  const MASK_GROUND_LEVEL_MIN = 8;
38
33
  const MASK_GROUND_TILE_BUDGET = 64;
34
+ // Finest terrain level a ground block is read at, and how many terrain tiles one block may pull.
35
+ const FINE_GROUND_LEVEL_MAX = 18;
36
+ const FINE_GROUND_TILE_BUDGET = 16;
39
37
  // Longest side of the rasterised region mask. The mask decides whether a texel is held up, so it
40
38
  // wants to be finer than the value raster it is compared against.
41
39
  const MASK_TEXTURE_MAX_SIDE = 1024;
40
+ const DEFAULT_DRAPE_LIFT_METRES = 4;
41
+ const DEFAULT_DRAPE_BAND_METRES = 3;
42
+ // A ground tileset is measured against the ground raster at this many points around the camera, this far apart.
43
+ const OFFSET_PROBES_PER_SIDE = 3;
44
+ const OFFSET_PROBE_SPACING_METRES = 250;
45
+ // The camera has to move this far before a ground tileset is measured again.
46
+ const OFFSET_REPROBE_METRES = 1500;
47
+ // Low percentile of tileset minus ground, so roofs and canopy over a probe do not lift the water.
48
+ const OFFSET_PERCENTILE = 0.25;
49
+ const WGS84_A = 6378137.0;
50
+ const WGS84_E2 = 0.00669437999014;
42
51
  // Stands in for "no floor" and "no clearance", far below anything the sheet can reach.
43
52
  const NO_LIMIT_METRES = -1e6;
44
53
  // Ripple layers to cycle across the field's own repeat.
@@ -83,6 +92,32 @@ var DisplacedSurfacePrimitive;
83
92
  const GROUND_MAX_METRES = 9000;
84
93
  const DEFAULT_LOW_COLOR = { red: 255, green: 255, blue: 255, alpha: 0.12 };
85
94
  const DEFAULT_HIGH_COLOR = { red: 21, green: 96, blue: 196, alpha: 0.92 };
95
+ // Decodes the packed ground raster, shared by both shaders.
96
+ const GROUND_GLSL = `
97
+ float decodeGround(vec2 uv) {
98
+ // Channels arrive normalised to 0..1, so they go back to bytes before being reassembled.
99
+ vec3 bytes = texture(u_groundTexture, uv).rgb * 255.0;
100
+ float normalised = dot(bytes, vec3(65536.0, 256.0, 1.0)) / 16777215.0;
101
+ return u_groundRange.x + normalised * (u_groundRange.y - u_groundRange.x);
102
+ }
103
+
104
+ /*
105
+ * Bilinear by hand, because the height is packed across three channels and hardware filtering would
106
+ * blend the packing rather than the heights, turning a smooth slope into noise at every texel edge.
107
+ */
108
+ float sampleGround(vec2 uv) {
109
+ vec2 texel = 1.0 / u_groundSize;
110
+ vec2 coord = uv * u_groundSize - 0.5;
111
+ vec2 base = floor(coord);
112
+ vec2 f = coord - base;
113
+ vec2 origin = (base + 0.5) * texel;
114
+ float h00 = decodeGround(origin);
115
+ float h10 = decodeGround(origin + vec2(texel.x, 0.0));
116
+ float h01 = decodeGround(origin + vec2(0.0, texel.y));
117
+ float h11 = decodeGround(origin + texel);
118
+ return mix(mix(h00, h10, f.x), mix(h01, h11, f.x), f.y);
119
+ }
120
+ `;
86
121
  const VERTEX_SHADER_GLSL300 = `
87
122
  in vec3 position3DHigh;
88
123
  in vec3 position3DLow;
@@ -117,6 +152,9 @@ uniform vec2 u_maskGroundSize;
117
152
  uniform vec4 u_extentDegrees;
118
153
  uniform vec4 u_maskGroundDegrees;
119
154
  uniform float u_coverageCutoffVertex;
155
+ uniform float u_drape;
156
+ uniform float u_drapeLift;
157
+ uniform float u_groundOffset;
120
158
  //#water
121
159
  uniform vec2 u_extentMetres;
122
160
  uniform vec2 u_waveOrigin;
@@ -125,6 +163,7 @@ uniform vec2 u_waveOrigin;
125
163
  out vec2 v_st;
126
164
  out float v_value;
127
165
  out float v_coverage;
166
+ out vec3 v_eyeEC;
128
167
  //#water
129
168
  out vec3 v_positionEC;
130
169
  out vec3 v_eastEC;
@@ -133,30 +172,7 @@ out vec3 v_upEC;
133
172
  out vec2 v_waveMetres;
134
173
  //#endwater
135
174
 
136
- float decodeGround(vec2 uv) {
137
- // Channels arrive normalised to 0..1, so they go back to bytes before being reassembled.
138
- vec3 packed = texture(u_groundTexture, uv).rgb * 255.0;
139
- float normalised = dot(packed, vec3(65536.0, 256.0, 1.0)) / 16777215.0;
140
- return u_groundRange.x + normalised * (u_groundRange.y - u_groundRange.x);
141
- }
142
-
143
- /*
144
- * Bilinear by hand, because the height is packed across three channels and hardware filtering would
145
- * blend the packing rather than the heights, turning a smooth slope into noise at every texel edge.
146
- */
147
- float sampleGround(vec2 uv) {
148
- vec2 texel = 1.0 / u_groundSize;
149
- vec2 coord = uv * u_groundSize - 0.5;
150
- vec2 base = floor(coord);
151
- vec2 f = coord - base;
152
- vec2 origin = (base + 0.5) * texel;
153
- float h00 = decodeGround(origin);
154
- float h10 = decodeGround(origin + vec2(texel.x, 0.0));
155
- float h01 = decodeGround(origin + vec2(0.0, texel.y));
156
- float h11 = decodeGround(origin + texel);
157
- return mix(mix(h00, h10, f.x), mix(h01, h11, f.x), f.y);
158
- }
159
-
175
+ ${GROUND_GLSL}
160
176
  /*
161
177
  * Height of the terrain under a point of the surface, read from the region's own ground raster.
162
178
  *
@@ -238,12 +254,13 @@ void main() {
238
254
 
239
255
  // Value zero sits at the polygon's own altitude, plus the terrain underneath when the polygon
240
256
  // is following the ground rather than absolutely positioned.
241
- float ground = sampleGround(st) * u_groundWeight;
257
+ float ground = (sampleGround(st) + u_groundOffset) * u_groundWeight;
242
258
 
243
259
  // Coverage scales the displacement only where it is measured from the terrain, because there a
244
260
  // zero means the surface sits on the ground.
245
261
  float coverageScale = mix(1.0, v_coverage, u_groundWeight);
246
- float placed = u_baseHeight + ground + metres * coverageScale;
262
+ // Draped, the sheet only has to stand above what is drawn; the fragment paints the drawn surface behind it.
263
+ float placed = u_baseHeight + ground + metres * coverageScale + u_drapeLift * u_drape;
247
264
 
248
265
  // Held above whichever is higher, the region's own floor or the terrain under it plus a margin.
249
266
  // Only inside the region: lifting the whole sheet would raise it over dry land as well.
@@ -267,6 +284,7 @@ void main() {
267
284
  v_waveMetres = st * u_extentMetres - u_waveOrigin;
268
285
  //#endwater
269
286
 
287
+ v_eyeEC = (czm_modelViewRelativeToEye * p).xyz;
270
288
  gl_Position = czm_modelViewProjectionRelativeToEye * p;
271
289
  }
272
290
  `;
@@ -281,7 +299,32 @@ uniform float u_valuePacked;
281
299
  uniform float u_valueRange;
282
300
  uniform float u_exaggeration;
283
301
  uniform float u_metresPerTexel;
302
+ uniform float u_valueMin;
303
+ uniform sampler2D u_groundTexture;
304
+ uniform vec2 u_groundRange;
305
+ uniform vec2 u_groundSize;
306
+ uniform float u_groundWeight;
307
+ uniform float u_groundOffset;
308
+ uniform float u_drape;
309
+ // Metres a drawn surface may stand above the water level and still be painted, below zero to paint whatever is drawn.
310
+ uniform float u_drapeBand;
311
+ // The extent centre on the ellipsoid in eye coordinates, with its east, north and up axes.
312
+ uniform vec3 u_drapeCentreEC;
313
+ uniform vec3 u_drapeEastEC;
314
+ uniform vec3 u_drapeNorthEC;
315
+ uniform vec3 u_drapeUpEC;
316
+ // Centre longitude and latitude in radians, then the meridian and prime vertical radii of curvature there.
317
+ uniform vec4 u_drapeGeo;
318
+ // West, East, North, South in radians.
319
+ uniform vec4 u_extentRadians;
320
+ uniform sampler2D u_maskTexture;
321
+ uniform float u_maskWeight;
322
+ uniform float u_maskFill;
323
+ uniform float u_maskFillValue;
324
+ uniform float u_maskFloor;
284
325
  //#water
326
+ uniform vec2 u_extentMetres;
327
+ uniform vec2 u_waveOrigin;
285
328
  uniform float u_waterWavelength;
286
329
  uniform float u_waterAmplitude;
287
330
  uniform float u_waterReflectivity;
@@ -298,6 +341,7 @@ uniform float u_wavePeriod;
298
341
  in vec2 v_st;
299
342
  in float v_value;
300
343
  in float v_coverage;
344
+ in vec3 v_eyeEC;
301
345
  //#water
302
346
  in vec3 v_positionEC;
303
347
  in vec3 v_eastEC;
@@ -319,6 +363,72 @@ float valueAt(vec2 uv) {
319
363
  return mix(decodeValue(texture(u_valueTextureFrom, uv)), decodeValue(texture(u_valueTexture, uv)), u_valueFade);
320
364
  }
321
365
 
366
+ ${GROUND_GLSL}
367
+
368
+ /*
369
+ * The opaque surface drawn behind this pixel, or false when none, outside the extent, or above the band.
370
+ */
371
+ bool drawnBehind(out vec2 uv, out float value, out float coverage, out vec3 positionEC) {
372
+ float depth = czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw));
373
+ if (depth <= 0.0 || depth >= 1.0) {
374
+ return false;
375
+ }
376
+ vec4 eye = czm_windowToEyeCoordinates(gl_FragCoord.xy, depth);
377
+ positionEC = eye.xyz / eye.w;
378
+
379
+ // East, north and up metres from the extent centre, small numbers that keep their precision.
380
+ vec3 offset = positionEC - u_drapeCentreEC;
381
+ float east = dot(offset, u_drapeEastEC);
382
+ float north = dot(offset, u_drapeNorthEC);
383
+ float up = dot(offset, u_drapeUpEC);
384
+ float latitude = u_drapeGeo.y + north / u_drapeGeo.z;
385
+ float longitude = u_drapeGeo.x + east / (u_drapeGeo.w * cos(latitude));
386
+ uv = vec2((longitude - u_extentRadians.x) / (u_extentRadians.y - u_extentRadians.x),
387
+ (u_extentRadians.z - latitude) / (u_extentRadians.z - u_extentRadians.w));
388
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {
389
+ return false;
390
+ }
391
+
392
+ // Bilinear by hand between texel centres, so cell edges on the ground read as a shoreline, not squares.
393
+ vec2 coord = uv / u_texelSize - 0.5;
394
+ vec2 base = floor(coord);
395
+ vec2 f = coord - base;
396
+ vec2 origin = (base + 0.5) * u_texelSize;
397
+ vec2 values = vec2(0.0);
398
+ vec2 weights = vec2(0.0);
399
+ for (int i = 0; i < 4; i++) {
400
+ vec2 step01 = vec2(float(i - (i / 2) * 2), float(i / 2));
401
+ vec2 at = origin + step01 * u_texelSize;
402
+ float w = mix(1.0 - f.x, f.x, step01.x) * mix(1.0 - f.y, f.y, step01.y);
403
+ vec4 texelTo = texture(u_valueTexture, at);
404
+ vec4 texelFrom = texture(u_valueTextureFrom, at);
405
+ float a = mix(texelFrom.a, texelTo.a, u_valueFade);
406
+ // Weighted by coverage too, so a no-data neighbour fades the edge instead of dragging the value to zero.
407
+ values += vec2(mix(decodeValue(texelFrom), decodeValue(texelTo), u_valueFade) * a, a) * w;
408
+ weights += vec2(a, 1.0) * w;
409
+ }
410
+ value = values.x / max(values.y, 1e-6);
411
+ coverage = values.y;
412
+
413
+ // A region known to be water paints its gaps here too, the same way the vertex shader fills them.
414
+ float inMask = u_maskWeight * texture(u_maskTexture, uv).a;
415
+ float hasData = step(u_coverageCutoff, coverage);
416
+ value = mix(value, mix(u_maskFillValue, max(value, u_maskFillValue), hasData), inMask * u_maskFill);
417
+ coverage = max(coverage, inMask * u_maskFill);
418
+
419
+ if (u_drapeBand >= 0.0) {
420
+ // The tangent plane falls away from the ellipsoid by distance squared over twice the radius.
421
+ float height = up + (east * east + north * north) / (2.0 * u_drapeGeo.w);
422
+ float level = (sampleGround(uv) + u_groundOffset) * u_groundWeight + u_valueMin + value * u_valueRange * u_exaggeration;
423
+ // Inside a region the water is never below its known floor, so a deck or bank under that floor is still wet.
424
+ level = mix(level, max(level, u_maskFloor), step(0.5, inMask));
425
+ if (height - level > u_drapeBand) {
426
+ return false;
427
+ }
428
+ }
429
+ return true;
430
+ }
431
+
322
432
  //#water
323
433
  /*
324
434
  * Slope of the ripple field at a point, in metres of rise per metre travelled.
@@ -350,17 +460,17 @@ ${WATER_WAVES.map((wave, index) => {
350
460
  * The sheet shaded as a water surface: a flat body colour seen through a sun glint and a grazing
351
461
  * sky reflection, with the ripple field standing in for a geometry it is far too fine to carry.
352
462
  */
353
- vec4 water(vec3 relief, vec4 color) {
354
- float metresPerPixel = czm_metersPerPixel(vec4(v_positionEC, 1.0));
463
+ vec4 water(vec3 relief, vec4 color, vec3 positionEC, vec2 waveMetres, float coverage) {
464
+ float metresPerPixel = czm_metersPerPixel(vec4(positionEC, 1.0));
355
465
  float detail;
356
- vec2 slope = rippleSlope(v_waveMetres, metresPerPixel, detail);
466
+ vec2 slope = rippleSlope(waveMetres, metresPerPixel, detail);
357
467
 
358
468
  // relief arrives normalised, so its horizontal part over its vertical part is the slope it means.
359
469
  vec2 reliefSlope = relief.xy / max(relief.z, 1e-3);
360
470
  vec3 local = normalize(vec3(-(slope + reliefSlope), 1.0));
361
471
  vec3 normalEC = normalize(local.x * v_eastEC + local.y * v_northEC + local.z * v_upEC);
362
472
 
363
- vec3 view = normalize(-v_positionEC);
473
+ vec3 view = normalize(-positionEC);
364
474
  // Drawn with culling off, so the underside of the sheet arrives with its normal pointing away.
365
475
  normalEC = dot(normalEC, view) < 0.0 ? -normalEC : normalEC;
366
476
  vec3 sun = normalize(czm_sunDirectionEC);
@@ -387,46 +497,54 @@ vec4 water(vec3 relief, vec4 color) {
387
497
  /*
388
498
  * The same fog the globe under it is already drawing with.
389
499
  */
390
- lit = czm_fog(length(v_positionEC), lit, u_waterSky);
500
+ lit = czm_fog(length(positionEC), lit, u_waterSky);
391
501
 
392
502
  // A reflection seen through a half-transparent sheet is not a reflection, so the surface is
393
503
  // allowed to close up exactly where it is being reflective.
394
- float alpha = color.a * v_coverage;
504
+ float alpha = color.a * coverage;
395
505
  alpha = clamp(alpha + (1.0 - alpha) * (fresnel * 0.55 + glint), 0.0, 1.0);
396
506
  return vec4(lit, alpha);
397
507
  }
398
508
  //#endwater
399
509
 
400
510
  void main() {
401
- if (v_coverage < u_coverageCutoff) {
511
+ vec2 uv = v_st;
512
+ float value = v_value;
513
+ float coverage = v_coverage;
514
+ vec3 positionEC = v_eyeEC;
515
+ // Clamped: paint what is drawn behind this pixel, so the water sits on it however far off the sheet is.
516
+ if (u_drape > 0.5 && !drawnBehind(uv, value, coverage, positionEC)) {
517
+ discard;
518
+ }
519
+ if (coverage < u_coverageCutoff) {
402
520
  discard;
403
521
  }
404
522
  // The ramp is baked to a lookup rather than lerped between two colours, so a banded style with a
405
523
  // hidden floor reads the same here as it does on the flat drape.
406
524
  // Without it this surface painted water the style hides, and the cell grid then correctly refused to outline any of it.
407
- vec4 color = texture(u_rampTexture, vec2(clamp(v_value, 0.0, 1.0), 0.5));
525
+ vec4 color = texture(u_rampTexture, vec2(clamp(value, 0.0, 1.0), 0.5));
408
526
  if (color.a <= 0.0) {
409
527
  discard;
410
528
  }
411
529
 
412
530
  // Relief shading from the value gradient, so the displacement reads at a distance without
413
531
  // recomputing vertex normals every time the texture changes.
414
- float left = valueAt(v_st - vec2(u_texelSize.x, 0.0));
415
- float right = valueAt(v_st + vec2(u_texelSize.x, 0.0));
416
- float down = valueAt(v_st - vec2(0.0, u_texelSize.y));
417
- float up = valueAt(v_st + vec2(0.0, u_texelSize.y));
532
+ float left = valueAt(uv - vec2(u_texelSize.x, 0.0));
533
+ float right = valueAt(uv + vec2(u_texelSize.x, 0.0));
534
+ float down = valueAt(uv - vec2(0.0, u_texelSize.y));
535
+ float up = valueAt(uv + vec2(0.0, u_texelSize.y));
418
536
  float scale = u_valueRange * u_exaggeration;
419
537
  vec3 n = normalize(vec3((left - right) * scale, (down - up) * scale, 2.0 * u_metresPerTexel));
420
538
 
421
539
  //#water
422
- out_FragColor = water(n, color);
540
+ out_FragColor = water(n, color, positionEC, mix(v_waveMetres, uv * u_extentMetres - u_waveOrigin, u_drape), coverage);
423
541
  return;
424
542
  //#endwater
425
543
 
426
544
  float lambert = clamp(dot(n, normalize(vec3(-0.5, -0.6, 0.62))), 0.0, 1.0);
427
545
  color.rgb *= 0.45 + 0.9 * lambert;
428
546
 
429
- out_FragColor = vec4(color.rgb, color.a * v_coverage);
547
+ out_FragColor = vec4(color.rgb, color.a * coverage);
430
548
  }
431
549
  `;
432
550
  /*
@@ -472,9 +590,25 @@ void main() {
472
590
  // No probe means no evidence the host rewrites anything, so trust the context alone.
473
591
  modernizes = false;
474
592
  }
475
- _glsl300Support = Boolean(context.webgl2) && !modernizes;
593
+ _glsl300Support = context.webgl2 ? !modernizes : demotes(context);
476
594
  return _glsl300Support;
477
595
  }
596
+ /*
597
+ * True when the host takes GLSL 300 and rewrites it down itself on a WebGL1 context, as Cesium 1.102 onwards does.
598
+ */
599
+ function demotes(context) {
600
+ try {
601
+ const probe = new Cesium.ShaderSource({
602
+ sources: ["in float a_probe;\nout float v_probe;\nvoid main() { v_probe = a_probe; gl_Position = vec4(0.0); }"],
603
+ includeBuiltIns: false
604
+ });
605
+ const combined = probe.createCombinedVertexShader(context);
606
+ return combined.indexOf("attribute") >= 0;
607
+ }
608
+ catch (e) {
609
+ return false;
610
+ }
611
+ }
478
612
  /*
479
613
  * Places grid node (fx, fy) on the ellipsoid, stepping the way the raster was sampled.
480
614
  * 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.
@@ -756,9 +890,334 @@ void main() {
756
890
  }
757
891
  return MASK_GROUND_LEVEL_MIN;
758
892
  }
893
+ // Ground under a clamped value surface: coarse everywhere first, then refined block by block nearest the camera.
894
+ let GroundRaster;
895
+ (function (GroundRaster) {
896
+ // Height window the packed raster covers, wide enough for any terrain on Earth.
897
+ GroundRaster.MIN_METRES = -1000;
898
+ GroundRaster.MAX_METRES = 9000;
899
+ const PACKED_MAX = 16777215;
900
+ // Samples per side of the first pass over the whole extent.
901
+ const COARSE_SAMPLES = 64;
902
+ // Samples per side of one refined block.
903
+ GroundRaster.BLOCK_SAMPLES = 64;
904
+ const MAX_SIDE = 2048;
905
+ // Blocks being sampled at once, so a fast camera does not queue the whole model.
906
+ const MAX_IN_FLIGHT = 2;
907
+ // A block is refined once the camera is within this many block widths of it.
908
+ const REFINE_BLOCK_WIDTHS = 12;
909
+ /**
910
+ * Raster side for a value source of the given size: a whole number of blocks, at least one, at most the cap.
911
+ */
912
+ function SideFor(width, height) {
913
+ const wanted = Math.max(1, Math.round(Math.max(width || 0, height || 0)));
914
+ const blocks = Math.ceil(wanted / GroundRaster.BLOCK_SAMPLES);
915
+ return Math.min(MAX_SIDE, Math.max(1, blocks) * GroundRaster.BLOCK_SAMPLES);
916
+ }
917
+ GroundRaster.SideFor = SideFor;
918
+ /**
919
+ * Packs a height into three bytes the way the vertex shader unpacks it.
920
+ */
921
+ function Pack(height, into, at) {
922
+ const known = typeof height === "number" && isFinite(height);
923
+ const clamped = Math.min(GroundRaster.MAX_METRES, Math.max(GroundRaster.MIN_METRES, known ? height : 0));
924
+ const packed = Math.round(((clamped - GroundRaster.MIN_METRES) / (GroundRaster.MAX_METRES - GroundRaster.MIN_METRES)) * PACKED_MAX);
925
+ into[at] = (packed >> 16) & 255;
926
+ into[at + 1] = (packed >> 8) & 255;
927
+ into[at + 2] = packed & 255;
928
+ into[at + 3] = known ? 255 : 0;
929
+ }
930
+ GroundRaster.Pack = Pack;
931
+ /**
932
+ * Bilinear between texel centres, the way the shader reads it.
933
+ */
934
+ function Bilinear(heights, side, u, v) {
935
+ const read = (x, y) => heights[Math.min(side - 1, Math.max(0, y)) * side + Math.min(side - 1, Math.max(0, x))];
936
+ const x = u * side - 0.5;
937
+ const y = v * side - 0.5;
938
+ const x0 = Math.floor(x);
939
+ const y0 = Math.floor(y);
940
+ const fx = x - x0;
941
+ const fy = y - y0;
942
+ const top = read(x0, y0) + (read(x0 + 1, y0) - read(x0, y0)) * fx;
943
+ const bottom = read(x0, y0 + 1) + (read(x0 + 1, y0 + 1) - read(x0, y0 + 1)) * fx;
944
+ return top + (bottom - top) * fy;
945
+ }
946
+ GroundRaster.Bilinear = Bilinear;
947
+ class Raster {
948
+ constructor(extent, side, sampler) {
949
+ this.extent = extent;
950
+ this.sampler = sampler;
951
+ this.inFlight = new Set();
952
+ this.dirty = [];
953
+ this.coarseDone = false;
954
+ this.coarseStarted = false;
955
+ this.disposed = false;
956
+ this.version = 0;
957
+ this.side = Math.max(GroundRaster.BLOCK_SAMPLES, Math.round(side / GroundRaster.BLOCK_SAMPLES) * GroundRaster.BLOCK_SAMPLES);
958
+ this.blocksPerSide = this.side / GroundRaster.BLOCK_SAMPLES;
959
+ this.pixels = new Uint8Array(this.side * this.side * 4);
960
+ this.heights = new Float32Array(this.side * this.side);
961
+ this.refined = new Uint8Array(this.blocksPerSide * this.blocksPerSide);
962
+ }
963
+ Dispose() {
964
+ this.disposed = true;
965
+ }
966
+ HasCoarse() {
967
+ return this.coarseDone;
968
+ }
969
+ /**
970
+ * Changes whenever any height changes.
971
+ */
972
+ GetVersion() {
973
+ return this.version;
974
+ }
975
+ RefinedCount() {
976
+ return this.refined.reduce((sum, value) => sum + value, 0);
977
+ }
978
+ InFlightCount() {
979
+ return this.inFlight.size;
980
+ }
981
+ /**
982
+ * Metres above the ellipsoid at a normalised point, north at v zero.
983
+ */
984
+ HeightAt(u, v) {
985
+ return Bilinear(this.heights, this.side, u, v);
986
+ }
987
+ /**
988
+ * The regions changed since the last call.
989
+ */
990
+ TakeDirty() {
991
+ const dirty = this.dirty;
992
+ this.dirty = [];
993
+ return dirty;
994
+ }
995
+ /**
996
+ * Samples the whole extent once, at the cheap level.
997
+ */
998
+ StartCoarse() {
999
+ if (this.coarseStarted) {
1000
+ return Promise.resolve();
1001
+ }
1002
+ this.coarseStarted = true;
1003
+ const positions = this.grid(0, 0, 1, 1, COARSE_SAMPLES);
1004
+ return this.sampler.coarse(positions)
1005
+ .then((heights) => {
1006
+ if (this.disposed) {
1007
+ return;
1008
+ }
1009
+ const coarse = new Float32Array(COARSE_SAMPLES * COARSE_SAMPLES);
1010
+ for (let i = 0; i < coarse.length; i++) {
1011
+ const h = heights[i];
1012
+ coarse[i] = typeof h === "number" && isFinite(h) ? h : 0;
1013
+ }
1014
+ for (let y = 0; y < this.side; y++) {
1015
+ for (let x = 0; x < this.side; x++) {
1016
+ this.write(x, y, Bilinear(coarse, COARSE_SAMPLES, (x + 0.5) / this.side, (y + 0.5) / this.side));
1017
+ }
1018
+ }
1019
+ this.coarseDone = true;
1020
+ this.markDirty(0, 0, this.side, this.side);
1021
+ })
1022
+ .catch(() => {
1023
+ // Terrain that cannot be sampled leaves the sheet at its base height.
1024
+ });
1025
+ }
1026
+ /*
1027
+ * Starts sampling the unrefined visible blocks nearest the eye (world coordinates), up to the cap.
1028
+ */
1029
+ Refine(eye, isVisible) {
1030
+ if (!this.coarseDone || this.disposed || this.inFlight.size >= MAX_IN_FLIGHT) {
1031
+ return 0;
1032
+ }
1033
+ const candidates = [];
1034
+ const blockMetres = this.blockMetres();
1035
+ for (let by = 0; by < this.blocksPerSide; by++) {
1036
+ for (let bx = 0; bx < this.blocksPerSide; bx++) {
1037
+ const index = by * this.blocksPerSide + bx;
1038
+ if (this.refined[index] || this.inFlight.has(index)) {
1039
+ continue;
1040
+ }
1041
+ const sphere = this.blockSphere(bx, by, blockMetres);
1042
+ const distance = Math.max(0, Cesium.Cartesian3.distance(eye, sphere.center) - sphere.radius);
1043
+ if (distance > blockMetres * REFINE_BLOCK_WIDTHS) {
1044
+ continue;
1045
+ }
1046
+ if (isVisible && !isVisible(sphere)) {
1047
+ continue;
1048
+ }
1049
+ candidates.push({ index, distance });
1050
+ }
1051
+ }
1052
+ candidates.sort((a, b) => a.distance - b.distance);
1053
+ let started = 0;
1054
+ for (const candidate of candidates) {
1055
+ if (this.inFlight.size >= MAX_IN_FLIGHT) {
1056
+ break;
1057
+ }
1058
+ this.refineBlock(candidate.index);
1059
+ started++;
1060
+ }
1061
+ return started;
1062
+ }
1063
+ refineBlock(index) {
1064
+ this.inFlight.add(index);
1065
+ const bx = index % this.blocksPerSide;
1066
+ const by = Math.floor(index / this.blocksPerSide);
1067
+ const u0 = bx / this.blocksPerSide;
1068
+ const v0 = by / this.blocksPerSide;
1069
+ const span = 1 / this.blocksPerSide;
1070
+ const positions = this.grid(u0, v0, span, span, GroundRaster.BLOCK_SAMPLES);
1071
+ const e = this.extent;
1072
+ const box = {
1073
+ West: Cesium.Math.lerp(e.West, e.East, u0),
1074
+ East: Cesium.Math.lerp(e.West, e.East, u0 + span),
1075
+ North: Cesium.Math.lerp(e.North, e.South, v0),
1076
+ South: Cesium.Math.lerp(e.North, e.South, v0 + span)
1077
+ };
1078
+ this.sampler.fine(positions, box)
1079
+ .then((heights) => {
1080
+ if (this.disposed) {
1081
+ return;
1082
+ }
1083
+ for (let row = 0; row < GroundRaster.BLOCK_SAMPLES; row++) {
1084
+ for (let col = 0; col < GroundRaster.BLOCK_SAMPLES; col++) {
1085
+ const h = heights[row * GroundRaster.BLOCK_SAMPLES + col];
1086
+ // Keeping the coarse height where the source has nothing finer.
1087
+ if (typeof h === "number" && isFinite(h)) {
1088
+ this.write(bx * GroundRaster.BLOCK_SAMPLES + col, by * GroundRaster.BLOCK_SAMPLES + row, h);
1089
+ }
1090
+ }
1091
+ }
1092
+ this.markDirty(bx * GroundRaster.BLOCK_SAMPLES, by * GroundRaster.BLOCK_SAMPLES, GroundRaster.BLOCK_SAMPLES, GroundRaster.BLOCK_SAMPLES);
1093
+ })
1094
+ .catch(() => {
1095
+ // A block that cannot be sampled keeps its coarse heights.
1096
+ })
1097
+ .then(() => {
1098
+ this.refined[index] = 1;
1099
+ this.inFlight.delete(index);
1100
+ });
1101
+ }
1102
+ /*
1103
+ * Positions at texel centres of a sub-box, given in normalised extent coordinates, north at v zero.
1104
+ */
1105
+ grid(u0, v0, uSpan, vSpan, samples) {
1106
+ const positions = [];
1107
+ const e = this.extent;
1108
+ for (let row = 0; row < samples; row++) {
1109
+ const v = v0 + vSpan * (row + 0.5) / samples;
1110
+ const latitude = Cesium.Math.lerp(e.North, e.South, v);
1111
+ for (let col = 0; col < samples; col++) {
1112
+ const u = u0 + uSpan * (col + 0.5) / samples;
1113
+ positions.push(Cesium.Cartographic.fromDegrees(Cesium.Math.lerp(e.West, e.East, u), latitude));
1114
+ }
1115
+ }
1116
+ return positions;
1117
+ }
1118
+ write(x, y, height) {
1119
+ const at = y * this.side + x;
1120
+ this.heights[at] = height;
1121
+ Pack(height, this.pixels, at * 4);
1122
+ }
1123
+ markDirty(x, y, width, height) {
1124
+ this.dirty.push({ x, y, width, height });
1125
+ this.version++;
1126
+ }
1127
+ blockMetres() {
1128
+ const e = this.extent;
1129
+ const midLat = (e.North + e.South) / 2;
1130
+ const west = Cesium.Cartesian3.fromDegrees(e.West, midLat);
1131
+ const east = Cesium.Cartesian3.fromDegrees(e.East, midLat);
1132
+ const south = Cesium.Cartesian3.fromDegrees(e.West, e.South);
1133
+ const north = Cesium.Cartesian3.fromDegrees(e.West, e.North);
1134
+ const across = Math.max(Cesium.Cartesian3.distance(west, east), Cesium.Cartesian3.distance(south, north));
1135
+ return across / this.blocksPerSide;
1136
+ }
1137
+ blockSphere(bx, by, blockMetres) {
1138
+ const e = this.extent;
1139
+ const u = (bx + 0.5) / this.blocksPerSide;
1140
+ const v = (by + 0.5) / this.blocksPerSide;
1141
+ const centre = Cesium.Cartesian3.fromDegrees(Cesium.Math.lerp(e.West, e.East, u), Cesium.Math.lerp(e.North, e.South, v), this.HeightAt(u, v));
1142
+ return new Cesium.BoundingSphere(centre, blockMetres * Math.SQRT1_2);
1143
+ }
1144
+ }
1145
+ GroundRaster.Raster = Raster;
1146
+ })(GroundRaster = DisplacedSurfacePrimitive.GroundRaster || (DisplacedSurfacePrimitive.GroundRaster = {}));
1147
+ /**
1148
+ * Drawn ground minus sampled ground: a low percentile, so roofs and canopy over a probe are ignored.
1149
+ */
1150
+ function GroundOffsetFrom(differences) {
1151
+ const known = differences.filter((d) => typeof d === "number" && isFinite(d)).sort((a, b) => a - b);
1152
+ if (!known.length) {
1153
+ return null;
1154
+ }
1155
+ return known[Math.floor(OFFSET_PERCENTILE * (known.length - 1))];
1156
+ }
1157
+ DisplacedSurfacePrimitive.GroundOffsetFrom = GroundOffsetFrom;
1158
+ /*
1159
+ * The first shown tileset standing in for the globe, such as Google's photorealistic tiles.
1160
+ */
1161
+ function findGroundTileset(collection) {
1162
+ if (!collection) {
1163
+ return null;
1164
+ }
1165
+ for (let i = 0; i < collection.length; i++) {
1166
+ const primitive = collection.get(i);
1167
+ if (!primitive || primitive.show === false) {
1168
+ continue;
1169
+ }
1170
+ if (typeof primitive.length === "number" && typeof primitive.get === "function") {
1171
+ const nested = findGroundTileset(primitive);
1172
+ if (nested) {
1173
+ return nested;
1174
+ }
1175
+ }
1176
+ else if (camera_controls_1.CameraControls.IsGroundTileset(primitive)) {
1177
+ return primitive;
1178
+ }
1179
+ }
1180
+ return null;
1181
+ }
1182
+ /*
1183
+ * The finest level a ground block can be sampled at within a few tiles, and no finer than the terrain has there.
1184
+ */
1185
+ function fineLevelFor(box, provider) {
1186
+ const scheme = provider && provider.tilingScheme;
1187
+ let available = FINE_GROUND_LEVEL_MAX;
1188
+ const availability = provider && provider.availability;
1189
+ if (availability && typeof availability.computeMaximumLevelAtPosition === "function") {
1190
+ const centre = Cesium.Cartographic.fromDegrees((box.West + box.East) / 2, (box.North + box.South) / 2);
1191
+ available = Math.min(available, availability.computeMaximumLevelAtPosition(centre));
1192
+ }
1193
+ for (let level = available; level > MASK_GROUND_LEVEL_MIN; level--) {
1194
+ const across = scheme && typeof scheme.getNumberOfXTilesAtLevel === "function"
1195
+ ? scheme.getNumberOfXTilesAtLevel(level)
1196
+ : Math.pow(2, level + 1);
1197
+ const down = scheme && typeof scheme.getNumberOfYTilesAtLevel === "function"
1198
+ ? scheme.getNumberOfYTilesAtLevel(level)
1199
+ : Math.pow(2, level);
1200
+ const tiles = Math.ceil((box.East - box.West) / (360 / across) + 1)
1201
+ * Math.ceil((box.North - box.South) / (180 / down) + 1);
1202
+ if (tiles <= FINE_GROUND_TILE_BUDGET) {
1203
+ return level;
1204
+ }
1205
+ }
1206
+ return MASK_GROUND_LEVEL_MIN;
1207
+ }
1208
+ /*
1209
+ * Heights for a ground raster from a terrain provider: a cheap level first, then the finest in budget per block.
1210
+ */
1211
+ function terrainSampler(provider, extent) {
1212
+ const heightsOf = (sampled) => (sampled || []).map((c) => (c && isFinite(c.height) ? c.height : undefined));
1213
+ return {
1214
+ coarse: (positions) => Promise.resolve(Cesium.sampleTerrain(provider, groundLevelFor(extent, provider), positions)).then(heightsOf),
1215
+ fine: (positions, box) => Promise.resolve(Cesium.sampleTerrain(provider, fineLevelFor(box, provider), positions)).then(heightsOf)
1216
+ };
1217
+ }
759
1218
  class Surface {
760
1219
  constructor(options, hasCoverage) {
761
- var _a, _b, _c, _d;
1220
+ var _a, _b, _c, _d, _e, _f;
762
1221
  this.show = true;
763
1222
  this.valueSource = null;
764
1223
  this.lastPresentVersion = -1;
@@ -779,9 +1238,22 @@ void main() {
779
1238
  this.lastEyePosition = null;
780
1239
  this.lastSelectionMs = -Infinity;
781
1240
  this.selectionDirty = true;
1241
+ this.groundRaster = null;
1242
+ this.groundTextureSide = 0;
1243
+ // Draping reads globe coordinates back from depth, true only in 3D; 2D and Columbus keep the raised sheet.
1244
+ this.drapeActive = false;
1245
+ // Drawn ground minus the ground raster, measured where a ground tileset such as Google's is shown.
1246
+ this.groundOffset = 0;
1247
+ this.offsetProbe = { at: null, busy: false };
1248
+ this.drapeFrame = {
1249
+ centreEC: new Cesium.Cartesian3(),
1250
+ eastEC: new Cesium.Cartesian3(),
1251
+ northEC: new Cesium.Cartesian3(),
1252
+ upEC: new Cesium.Cartesian3(),
1253
+ geo: new Cesium.Cartesian4(),
1254
+ extent: new Cesium.Cartesian4()
1255
+ };
782
1256
  this.groundTexture = null;
783
- this.groundPixels = null;
784
- this.groundRequested = false;
785
1257
  this.groundClearance = null;
786
1258
  this.maskTexture = null;
787
1259
  this.maskPixels = null;
@@ -798,13 +1270,18 @@ void main() {
798
1270
  this.wavePhaseScratch = [new Cesium.Cartesian4(), new Cesium.Cartesian4()];
799
1271
  this.waterSkyScratch = new Cesium.Cartesian3();
800
1272
  this.followGround = Boolean(options.followGround);
1273
+ this.groundRasterSide = options.groundRasterSide;
1274
+ this.scene = options.scene || null;
1275
+ this.drape = Boolean(options.followGround) && options.drape !== false;
1276
+ this.drapeLift = (_a = options.drapeLift) !== null && _a !== void 0 ? _a : DEFAULT_DRAPE_LIFT_METRES;
1277
+ this.drapeBand = (_b = options.drapeBand) !== null && _b !== void 0 ? _b : DEFAULT_DRAPE_BAND_METRES;
801
1278
  this.terrainProvider = options.terrainProvider || null;
802
1279
  this.extent = options.extent;
803
1280
  this.source = options.source || null;
804
- this.valueMin = (_a = options.valueMin) !== null && _a !== void 0 ? _a : 0;
805
- this.valueMax = (_b = options.valueMax) !== null && _b !== void 0 ? _b : 1;
806
- this.exaggeration = (_c = options.exaggeration) !== null && _c !== void 0 ? _c : 1;
807
- this.baseHeight = (_d = options.baseHeight) !== null && _d !== void 0 ? _d : 0;
1281
+ this.valueMin = (_c = options.valueMin) !== null && _c !== void 0 ? _c : 0;
1282
+ this.valueMax = (_d = options.valueMax) !== null && _d !== void 0 ? _d : 1;
1283
+ this.exaggeration = (_e = options.exaggeration) !== null && _e !== void 0 ? _e : 1;
1284
+ this.baseHeight = (_f = options.baseHeight) !== null && _f !== void 0 ? _f : 0;
808
1285
  this.packedValue = Boolean(options.packedValue);
809
1286
  this.pixelPlacement = options.pixelPlacement;
810
1287
  this.tileSkirts = Boolean(options.tileSkirts);
@@ -909,8 +1386,9 @@ void main() {
909
1386
  return;
910
1387
  }
911
1388
  this.terrainProvider = provider;
912
- this.groundPixels = null;
913
- this.groundRequested = false;
1389
+ this.dropGroundRaster();
1390
+ this.groundOffset = 0;
1391
+ this.offsetProbe = { at: null, busy: false };
914
1392
  this.maskGroundPixels = null;
915
1393
  this.maskGroundRequested = false;
916
1394
  this.maskGroundLevel = 0;
@@ -964,15 +1442,15 @@ void main() {
964
1442
  ? (pixels[at] * 256 + pixels[at + 1]) / 65535
965
1443
  : pixels[at] / 255;
966
1444
  const metres = this.valueMin + normalised * (this.valueMax - this.valueMin) * this.exaggeration;
967
- const following = this.followGround && Boolean(this.groundPixels);
968
- const ground = following ? this.groundAt(fx, fy) : 0;
1445
+ const following = this.hasGround();
1446
+ const ground = following ? this.groundRaster.HeightAt(fx, fy) + this.groundOffset : 0;
969
1447
  return this.baseHeight + ground + metres * (following ? coverage : 1);
970
1448
  }
971
1449
  /**
972
1450
  * Changes whenever HeightAt would answer differently for the same frame.
973
1451
  */
974
1452
  GetPlacementKey() {
975
- return [this.groundPixels ? 1 : 0, this.baseHeight, this.exaggeration, this.followGround ? 1 : 0].join("|");
1453
+ return [this.groundRaster ? this.groundRaster.GetVersion() : 0, this.baseHeight, this.exaggeration, this.followGround ? 1 : 0].join("|");
976
1454
  }
977
1455
  /**
978
1456
  * Repaints the sheet with new colours, keeping its geometry and the frames it is reading.
@@ -998,25 +1476,19 @@ void main() {
998
1476
  return this.rampPixels;
999
1477
  }
1000
1478
  /*
1001
- * The packed ground raster read the way sampleGround reads it, bilinear between texel centres.
1479
+ * Whether a clamped sheet has ground to stand on yet.
1002
1480
  */
1003
- groundAt(u, v) {
1004
- const size = GROUND_SAMPLES_PER_SIDE;
1005
- const pixels = this.groundPixels;
1006
- const read = (x, y) => {
1007
- const i = (Math.min(size - 1, Math.max(0, y)) * size + Math.min(size - 1, Math.max(0, x))) * 4;
1008
- const packed = (pixels[i] << 16) + (pixels[i + 1] << 8) + pixels[i + 2];
1009
- return GROUND_MIN_METRES + (packed / 16777215) * (GROUND_MAX_METRES - GROUND_MIN_METRES);
1010
- };
1011
- const x = u * size - 0.5;
1012
- const y = v * size - 0.5;
1013
- const x0 = Math.floor(x);
1014
- const y0 = Math.floor(y);
1015
- const fx = x - x0;
1016
- const fy = y - y0;
1017
- const top = read(x0, y0) + (read(x0 + 1, y0) - read(x0, y0)) * fx;
1018
- const bottom = read(x0, y0 + 1) + (read(x0 + 1, y0 + 1) - read(x0, y0 + 1)) * fx;
1019
- return top + (bottom - top) * fy;
1481
+ hasGround() {
1482
+ return this.followGround && Boolean(this.groundRaster) && this.groundRaster.HasCoarse();
1483
+ }
1484
+ /*
1485
+ * Lets go of the ground raster, so samples still in flight land nowhere.
1486
+ */
1487
+ dropGroundRaster() {
1488
+ if (this.groundRaster) {
1489
+ this.groundRaster.Dispose();
1490
+ this.groundRaster = null;
1491
+ }
1020
1492
  }
1021
1493
  /**
1022
1494
  * Feeds the surface from an animated frame series.
@@ -1070,8 +1542,13 @@ void main() {
1070
1542
  this.syncTexture(context);
1071
1543
  }
1072
1544
  this.syncRampTexture(context);
1073
- this.requestGround();
1545
+ this.requestGround(frameState);
1074
1546
  this.syncGroundTexture(context);
1547
+ this.drapeActive = this.drape && frameState.mode === Cesium.SceneMode.SCENE3D;
1548
+ if (this.drapeActive) {
1549
+ this.probeGroundOffset(frameState);
1550
+ this.updateDrapeFrame(frameState);
1551
+ }
1075
1552
  this.requestMaskGround();
1076
1553
  this.syncMaskTextures(context);
1077
1554
  // A tile needs one mesh before it has a bounding sphere to measure against.
@@ -1128,6 +1605,7 @@ void main() {
1128
1605
  this.groundTexture.destroy();
1129
1606
  this.groundTexture = null;
1130
1607
  }
1608
+ this.dropGroundRaster();
1131
1609
  if (this.maskTexture) {
1132
1610
  this.maskTexture.destroy();
1133
1611
  this.maskTexture = null;
@@ -1139,42 +1617,108 @@ void main() {
1139
1617
  return undefined;
1140
1618
  }
1141
1619
  /*
1142
- * Samples terrain across the extent once and packs it into a texture the vertex shader reads.
1143
- *
1144
- * A texture rather than heights baked into the meshes, because the samples arrive
1145
- * asynchronously and every cached tile mesh would otherwise have to be rebuilt when they land.
1620
+ * The extent centre's frame in eye coordinates, in double precision each frame, for the draped fragment shader.
1146
1621
  */
1147
- requestGround() {
1148
- if (this.groundRequested || !this.followGround) {
1622
+ updateDrapeFrame(frameState) {
1623
+ const e = this.extent;
1624
+ const lon = Cesium.Math.toRadians((e.West + e.East) / 2);
1625
+ const lat = Cesium.Math.toRadians((e.North + e.South) / 2);
1626
+ const centre = Cesium.Cartesian3.fromRadians(lon, lat, 0);
1627
+ const enu = Cesium.Transforms.eastNorthUpToFixedFrame(centre);
1628
+ const view = frameState.camera.viewMatrix;
1629
+ const f = this.drapeFrame;
1630
+ Cesium.Matrix4.multiplyByPoint(view, centre, f.centreEC);
1631
+ const axis = new Cesium.Cartesian3();
1632
+ const columns = [f.eastEC, f.northEC, f.upEC];
1633
+ for (let i = 0; i < 3; i++) {
1634
+ Cesium.Matrix4.getColumn(enu, i, axis);
1635
+ Cesium.Matrix4.multiplyByPointAsVector(view, axis, columns[i]);
1636
+ Cesium.Cartesian3.normalize(columns[i], columns[i]);
1637
+ }
1638
+ const sin = Math.sin(lat);
1639
+ const w = 1 - WGS84_E2 * sin * sin;
1640
+ f.geo = new Cesium.Cartesian4(lon, lat, WGS84_A * (1 - WGS84_E2) / Math.pow(w, 1.5), WGS84_A / Math.sqrt(w));
1641
+ f.extent = new Cesium.Cartesian4(Cesium.Math.toRadians(e.West), Cesium.Math.toRadians(e.East), Cesium.Math.toRadians(e.North), Cesium.Math.toRadians(e.South));
1642
+ }
1643
+ /*
1644
+ * Measures a shown ground tileset such as Google's against the ground raster near the camera.
1645
+ */
1646
+ probeGroundOffset(frameState) {
1647
+ const raster = this.groundRaster;
1648
+ const scene = this.scene;
1649
+ if (!raster || !raster.HasCoarse() || !scene || this.offsetProbe.busy || typeof scene.sampleHeightMostDetailed !== "function") {
1149
1650
  return;
1150
1651
  }
1151
- this.groundRequested = true;
1152
- const sampler = Cesium.sampleTerrain;
1153
- if (!this.terrainProvider || typeof sampler !== "function") {
1652
+ const eye = frameState.camera.positionWC;
1653
+ if (this.offsetProbe.at && Cesium.Cartesian3.distance(this.offsetProbe.at, eye) < OFFSET_REPROBE_METRES) {
1654
+ return;
1655
+ }
1656
+ this.offsetProbe.at = Cesium.Cartesian3.clone(eye);
1657
+ const tileset = findGroundTileset(scene.primitives);
1658
+ if (!tileset || !scene.sampleHeightSupported) {
1659
+ this.groundOffset = 0;
1154
1660
  return;
1155
1661
  }
1156
- const positions = [];
1157
- for (let row = 0; row < GROUND_SAMPLES_PER_SIDE; row++) {
1158
- const fy = row / (GROUND_SAMPLES_PER_SIDE - 1);
1159
- const latitude = Cesium.Math.lerp(this.extent.North, this.extent.South, fy);
1160
- for (let col = 0; col < GROUND_SAMPLES_PER_SIDE; col++) {
1161
- const fx = col / (GROUND_SAMPLES_PER_SIDE - 1);
1162
- const longitude = Cesium.Math.lerp(this.extent.West, this.extent.East, fx);
1163
- positions.push(Cesium.Cartographic.fromDegrees(longitude, latitude));
1662
+ const e = this.extent;
1663
+ const camera = Cesium.Cartographic.fromCartesian(eye);
1664
+ if (!camera) {
1665
+ return;
1666
+ }
1667
+ const toDegrees = 180 / (Math.PI * WGS84_A);
1668
+ const latStep = OFFSET_PROBE_SPACING_METRES * toDegrees;
1669
+ const lonStep = latStep / Math.max(0.1, Math.cos(camera.latitude));
1670
+ const lon0 = Math.min(e.East, Math.max(e.West, Cesium.Math.toDegrees(camera.longitude)));
1671
+ const lat0 = Math.min(e.North, Math.max(e.South, Cesium.Math.toDegrees(camera.latitude)));
1672
+ const probes = [];
1673
+ const half = (OFFSET_PROBES_PER_SIDE - 1) / 2;
1674
+ for (let row = 0; row < OFFSET_PROBES_PER_SIDE; row++) {
1675
+ for (let col = 0; col < OFFSET_PROBES_PER_SIDE; col++) {
1676
+ const lon = Math.min(e.East, Math.max(e.West, lon0 + (col - half) * lonStep));
1677
+ const lat = Math.min(e.North, Math.max(e.South, lat0 + (row - half) * latStep));
1678
+ probes.push(Cesium.Cartographic.fromDegrees(lon, lat));
1164
1679
  }
1165
1680
  }
1166
- Promise.resolve(sampler(this.terrainProvider, GROUND_SAMPLE_LEVEL, positions))
1167
- .then((sampled) => {
1168
- if (this.destroyed || !sampled) {
1681
+ this.offsetProbe.busy = true;
1682
+ Promise.resolve(scene.sampleHeightMostDetailed(probes, [this]))
1683
+ .then((drawn) => {
1684
+ if (this.destroyed || this.groundRaster !== raster) {
1169
1685
  return;
1170
1686
  }
1171
- this.groundPixels = packHeights(sampled);
1687
+ const differences = (drawn || []).map((c) => {
1688
+ const u = (Cesium.Math.toDegrees(c.longitude) - e.West) / (e.East - e.West);
1689
+ const v = (e.North - Cesium.Math.toDegrees(c.latitude)) / (e.North - e.South);
1690
+ return c && isFinite(c.height) ? c.height - raster.HeightAt(u, v) : NaN;
1691
+ });
1692
+ const offset = GroundOffsetFrom(differences);
1693
+ if (offset !== null) {
1694
+ this.groundOffset = offset;
1695
+ }
1172
1696
  })
1173
1697
  .catch(() => {
1174
- // Terrain that cannot be sampled leaves the surface on the ellipsoid, which is
1175
- // where a clamped polygon sat before this existed.
1698
+ // Unmeasured, the sheet keeps its last offset.
1699
+ })
1700
+ .then(() => {
1701
+ this.offsetProbe.busy = false;
1176
1702
  });
1177
1703
  }
1704
+ /*
1705
+ * Starts the ground raster a clamped sheet stands on, and refines it near the camera each frame.
1706
+ */
1707
+ requestGround(frameState) {
1708
+ if (!this.followGround || !this.terrainProvider || !this.sourceDims) {
1709
+ return;
1710
+ }
1711
+ if (!this.groundRaster) {
1712
+ const side = this.groundRasterSide || GroundRaster.SideFor(this.sourceDims.width, this.sourceDims.height);
1713
+ this.groundRaster = new GroundRaster.Raster(this.extent, side, terrainSampler(this.terrainProvider, this.extent));
1714
+ this.groundRaster.StartCoarse();
1715
+ return;
1716
+ }
1717
+ const culling = frameState.cullingVolume;
1718
+ this.groundRaster.Refine(frameState.camera.positionWC, culling
1719
+ ? (sphere) => culling.computeVisibility(sphere) !== Cesium.Intersect.OUTSIDE
1720
+ : undefined);
1721
+ }
1178
1722
  /*
1179
1723
  * Samples the terrain under the clearance regions.
1180
1724
  *
@@ -1203,10 +1747,10 @@ void main() {
1203
1747
  // does not cover are never asked for at all.
1204
1748
  const slots = [];
1205
1749
  for (let row = 0; row < MASK_GROUND_SAMPLES_PER_SIDE; row++) {
1206
- const fy = row / (MASK_GROUND_SAMPLES_PER_SIDE - 1);
1750
+ const fy = (row + 0.5) / MASK_GROUND_SAMPLES_PER_SIDE;
1207
1751
  const latitude = Cesium.Math.lerp(box.North, box.South, fy);
1208
1752
  for (let col = 0; col < MASK_GROUND_SAMPLES_PER_SIDE; col++) {
1209
- const fx = col / (MASK_GROUND_SAMPLES_PER_SIDE - 1);
1753
+ const fx = (col + 0.5) / MASK_GROUND_SAMPLES_PER_SIDE;
1210
1754
  const at = Cesium.Cartographic.fromDegrees(Cesium.Math.lerp(box.West, box.East, fx), latitude);
1211
1755
  // An imported terrain covers a survey area, so asking outside it answers 404 and
1212
1756
  // fills the console with failures for points that were never going to have a height.
@@ -1290,27 +1834,48 @@ void main() {
1290
1834
  * shader always has a texture bound whether or not this surface follows the ground.
1291
1835
  */
1292
1836
  syncGroundTexture(context) {
1293
- if (this.groundTexture && (!this.groundPixels || this.groundTexture.width === GROUND_SAMPLES_PER_SIDE)) {
1837
+ const raster = this.hasGround() ? this.groundRaster : null;
1838
+ const side = raster ? raster.side : 1;
1839
+ if (!this.groundTexture || this.groundTextureSide !== side) {
1840
+ if (this.groundTexture) {
1841
+ this.groundTexture.destroy();
1842
+ }
1843
+ const stand = new Uint8Array(4);
1844
+ GroundRaster.Pack(0, stand, 0);
1845
+ this.groundTexture = new Cesium.Texture({
1846
+ context,
1847
+ pixelFormat: Cesium.PixelFormat.RGBA,
1848
+ source: { width: side, height: side, arrayBufferView: raster ? raster.pixels : stand },
1849
+ flipY: false,
1850
+ sampler: new Cesium.Sampler({
1851
+ wrapS: Cesium.TextureWrap.CLAMP_TO_EDGE,
1852
+ wrapT: Cesium.TextureWrap.CLAMP_TO_EDGE,
1853
+ // Nearest, because the shader interpolates decoded heights itself.
1854
+ minificationFilter: Cesium.TextureMinificationFilter.NEAREST,
1855
+ magnificationFilter: Cesium.TextureMagnificationFilter.NEAREST
1856
+ })
1857
+ });
1858
+ this.groundTextureSide = side;
1859
+ if (raster) {
1860
+ raster.TakeDirty();
1861
+ }
1294
1862
  return;
1295
1863
  }
1296
- if (this.groundTexture) {
1297
- this.groundTexture.destroy();
1864
+ if (!raster) {
1865
+ return;
1866
+ }
1867
+ for (const region of raster.TakeDirty()) {
1868
+ const block = new Uint8Array(region.width * region.height * 4);
1869
+ for (let row = 0; row < region.height; row++) {
1870
+ const from = ((region.y + row) * side + region.x) * 4;
1871
+ block.set(raster.pixels.subarray(from, from + region.width * 4), row * region.width * 4);
1872
+ }
1873
+ this.groundTexture.copyFrom({
1874
+ source: { width: region.width, height: region.height, arrayBufferView: block },
1875
+ xOffset: region.x,
1876
+ yOffset: region.y
1877
+ });
1298
1878
  }
1299
- const size = this.groundPixels ? GROUND_SAMPLES_PER_SIDE : 1;
1300
- const arrayBufferView = this.groundPixels || packHeights([{ height: 0 }]);
1301
- this.groundTexture = new Cesium.Texture({
1302
- context,
1303
- pixelFormat: Cesium.PixelFormat.RGBA,
1304
- source: { width: size, height: size, arrayBufferView },
1305
- flipY: false,
1306
- sampler: new Cesium.Sampler({
1307
- wrapS: Cesium.TextureWrap.CLAMP_TO_EDGE,
1308
- wrapT: Cesium.TextureWrap.CLAMP_TO_EDGE,
1309
- // Nearest, because the shader interpolates decoded heights itself.
1310
- minificationFilter: Cesium.TextureMinificationFilter.NEAREST,
1311
- magnificationFilter: Cesium.TextureMagnificationFilter.NEAREST
1312
- })
1313
- });
1314
1879
  }
1315
1880
  /*
1316
1881
  * Metres the extent spans west to east and north to south, which is what turns the shader's
@@ -1631,9 +2196,9 @@ void main() {
1631
2196
  u_valueFade: () => (self.fade && self.fade.from ? self.fade.mix : 1),
1632
2197
  u_groundTexture: () => self.groundTexture,
1633
2198
  u_valuePacked: () => (self.packedValue ? 1 : 0),
1634
- u_groundWeight: () => (self.followGround && self.groundPixels ? 1 : 0),
2199
+ u_groundWeight: () => (self.hasGround() ? 1 : 0),
1635
2200
  u_groundRange: () => new Cesium.Cartesian2(GROUND_MIN_METRES, GROUND_MAX_METRES),
1636
- u_groundSize: () => new Cesium.Cartesian2(self.groundPixels ? GROUND_SAMPLES_PER_SIDE : 1, self.groundPixels ? GROUND_SAMPLES_PER_SIDE : 1),
2201
+ u_groundSize: () => new Cesium.Cartesian2(self.groundTextureSide || 1, self.groundTextureSide || 1),
1637
2202
  u_maskTexture: () => self.maskTexture,
1638
2203
  u_maskGroundTexture: () => self.maskGroundTexture,
1639
2204
  u_maskWeight: () => (self.groundClearance && self.maskPixels ? 1 : 0),
@@ -1692,7 +2257,17 @@ void main() {
1692
2257
  u_wavePhaseB: () => self.wavePhase(4),
1693
2258
  u_wavePeriod: () => self.wavePeriod(),
1694
2259
  u_waveOrigin: () => self.waveOrigin,
1695
- u_extentMetres: () => self.extentMetres()
2260
+ u_extentMetres: () => self.extentMetres(),
2261
+ u_drape: () => (self.drapeActive ? 1 : 0),
2262
+ u_drapeLift: () => self.drapeLift,
2263
+ u_drapeBand: () => self.drapeBand,
2264
+ u_groundOffset: () => self.groundOffset,
2265
+ u_drapeCentreEC: () => self.drapeFrame.centreEC,
2266
+ u_drapeEastEC: () => self.drapeFrame.eastEC,
2267
+ u_drapeNorthEC: () => self.drapeFrame.northEC,
2268
+ u_drapeUpEC: () => self.drapeFrame.upEC,
2269
+ u_drapeGeo: () => self.drapeFrame.geo,
2270
+ u_extentRadians: () => self.drapeFrame.extent
1696
2271
  }
1697
2272
  });
1698
2273
  }