Repository navigation
Expand file tree
/
Copy pathpanoCapture.html
More file actions
3074 lines (2878 loc) · 133 KB
/
Copy pathpanoCapture.html
File metadata and controls
3074 lines (2878 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Stellarium panorama — open-data capture</title>
<link
href="https://cdn.jsdelivr.net/npm/cesium@1.119.0/Build/Cesium/Widgets/widgets.css"
rel="stylesheet"
/>
<link
href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css"
rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.js"></script>
<style>
body {
font-family: sans-serif;
margin: 1em;
max-width: 900px;
}
#cesiumContainer {
width: 1024px;
height: 1024px;
position: absolute;
left: -10000px;
top: 0;
}
#previewWrap {
position: relative;
display: inline-block;
width: 100%;
max-width: 800px;
line-height: 0;
}
#previewGrid {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 0;
}
#preview {
width: 100%;
border: 1px solid #ccc;
image-rendering: pixelated;
position: relative;
z-index: 1;
}
#previewHorizon {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 2;
}
fieldset {
margin: 1em 0;
}
label {
display: inline-block;
min-width: 4em;
}
progress {
width: 100%;
}
.log {
font-family: monospace;
font-size: 12px;
background: #f4f4f4;
padding: 0.5em;
height: 200px;
overflow-y: auto;
white-space: pre-wrap;
}
.warning {
background: #fff3cd;
border-left: 4px solid #ffa500;
padding: 0.75em;
margin: 1em 0;
}
/* ---- Optional first-person 360° viewer ---- */
#viewer360 {
position: fixed;
inset: 0;
z-index: 1000;
display: none;
background: #000;
touch-action: none;
cursor: grab;
}
#viewer360.open {
display: block;
}
#viewer360.dragging {
cursor: grabbing;
}
#viewer360 canvas {
display: block;
width: 100%;
height: 100%;
}
#viewer360 .hud {
position: absolute;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
font: 13px sans-serif;
color: #fff;
background: rgba(0, 0, 0, 0.45);
padding: 6px 12px;
border-radius: 14px;
pointer-events: none;
user-select: none;
}
#viewer360 .readout {
position: absolute;
top: 14px;
left: 16px;
font: 13px/1.2 ui-monospace, Menlo, Consolas, monospace;
color: #fff;
background: rgba(0, 0, 0, 0.5);
padding: 6px 10px;
border-radius: 10px;
pointer-events: none;
user-select: none;
white-space: pre;
}
#viewer360 .close {
position: absolute;
top: 14px;
right: 16px;
width: 36px;
height: 36px;
border: none;
border-radius: 50%;
background: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 22px;
line-height: 36px;
cursor: pointer;
text-align: center;
}
#viewer360 .close:hover {
background: rgba(0, 0, 0, 0.75);
}
#viewer360 .controls {
position: absolute;
top: 14px;
right: 64px;
font: 13px sans-serif;
color: #fff;
background: rgba(0, 0, 0, 0.5);
padding: 8px 12px;
border-radius: 10px;
user-select: none;
display: flex;
gap: 14px;
flex-wrap: wrap;
max-width: calc(100vw - 96px);
}
#viewer360 .controls label {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
cursor: pointer;
}
#viewer360 .controls input[type="checkbox"] {
margin: 0;
cursor: pointer;
}
#viewer360 .controls input[type="number"] {
background: rgba(255, 255, 255, 0.12);
color: #fff;
border: 1px solid rgba(255, 255, 255, 0.25);
border-radius: 4px;
padding: 1px 4px;
width: 4.2em;
font: inherit;
}
#viewer360 .controls .point-count {
opacity: 0.7;
font-variant-numeric: tabular-nums;
}
/* ---- Location picker popup ---- */
#mapPickerBtn {
margin-left: 0.5em;
cursor: pointer;
}
#mapPicker {
position: fixed;
inset: 0;
z-index: 2000;
display: none;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.55);
}
#mapPicker.open {
display: flex;
}
#mapPicker .dialog {
background: #fff;
width: min(720px, 92vw);
max-height: 90vh;
border-radius: 8px;
overflow: hidden;
display: flex;
flex-direction: column;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
}
#mapPicker .head {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border-bottom: 1px solid #ddd;
}
#mapPicker .head strong {
flex: 0 0 auto;
}
#mapPickerSearch {
flex: 1 1 auto;
min-width: 0;
padding: 4px 8px;
font: inherit;
}
#mapPicker .head button {
flex: 0 0 auto;
padding: 4px 10px;
cursor: pointer;
}
#mapPickerMap {
flex: 1 1 auto;
height: 420px;
}
#mapPicker .foot {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-top: 1px solid #ddd;
font-size: 14px;
}
#mapPickerCoords {
font-family: monospace;
flex: 1 1 auto;
}
#mapPicker .foot button {
padding: 5px 14px;
cursor: pointer;
}
#mapPickerUse {
font-weight: bold;
}
</style>
</head>
<body>
<h1>Stellarium panorama — open-data capture</h1>
<p>
This page renders a 3D globe locally in a hidden Cesium viewer using
only open data (<a
href="https://www.esri.com/en-us/legal/terms/full-master-agreement"
>Esri World Imagery</a
>
+
<a href="https://registry.opendata.aws/terrain-tiles/"
>AWS Terrain Tiles</a
>), sweeps a virtual camera through 37 directions, and stitches the
captures into an equirectangular PNG suitable for Stellarium's
<code>maptex</code>.
</p>
<div class="warning">
<strong>What you get:</strong> accurate satellite imagery draped on
global terrain (SRTM-based), so distant mountain silhouettes appear
correctly on the horizon. <strong>What you don't get:</strong>
buildings — this data source has no 3D structures. Best suited to
rural / landscape observing sites. Attribution to Esri / AWS terrain
providers is required for non-personal use.
</div>
<fieldset>
<legend>Site</legend>
<label>Name</label>
<input id="siteName" value="My panorama site" size="32" /><br />
<label>Author</label>
<input
id="siteAuthor"
value=""
size="32"
placeholder="Your name (for landscape.ini)"
/><br />
<label>Lat</label> <input id="lat" value="48.858" size="12" /><br />
<label>Lon</label> <input id="lon" value="16.295" size="12" />
<button type="button" id="mapPickerBtn">🗺️ Pick on map…</button><br />
<label>Eye h.</label> <input id="eyeH" value="2" size="12" /> m
(above local terrain — sampled automatically)<br />
<label>Ground</label> <span id="groundEl">—</span> m (sea level,
filled in after capture)<br />
<label>Timezone</label>
<input
id="timezone"
value=""
size="20"
placeholder="e.g. Europe/Vienna (blank = system)"
/><br />
<label>Light pol.</label>
<input
id="lightPol"
type="number"
min="1"
max="9"
value="5"
size="3"
/>
Bortle (1 = darkest, 9 = inner city)<br />
<label>Atm. ext.</label>
<input
id="atmExt"
type="number"
min="0.05"
max="0.5"
step="0.01"
value="0.2"
size="5"
/>
extinction coefficient (Stellarium default 0.2)<br />
</fieldset>
<fieldset>
<legend>Output</legend>
<label>Preset</label>
<select id="resPreset">
<option value="2048">2048 × 1024 (Raspberry Pi)</option>
<option value="4096">4096 × 2048 (fast)</option>
<option value="8192" selected>
8192 × 4096 (recommended)
</option>
<option value="16384">16384 × 8192 (max)</option>
<option value="custom">Custom</option>
</select><br />
<label>Size</label>
<input id="outW" value="8192" size="6" /> ×
<input id="outH" value="4096" size="6" /> px (equirectangular)<br />
<label>FOV</label> <input id="fov" value="60" size="6" /> °
horizontal (per-capture)<br />
<label
><input type="checkbox" id="cropSky" checked /> Crop sky
above</label
>
<input
id="cropSkyAlt"
type="number"
min="0"
max="89"
step="0.125"
value="33.75"
size="6"
/>
° (sets maptex_top)<br />
<label
><input type="checkbox" id="cropNadir" checked /> Crop nadir
below</label
>
<input
id="cropNadirAlt"
type="number"
min="-89"
max="0"
step="0.125"
value="-50.625"
size="6"
/>
° (sets maptex_bottom)<br />
<label>Horizon bias</label>
<input
id="horizonBias"
type="number"
step="0.1"
value="0"
size="5"
/>
° (lift polygonal horizon — compensates for trees/buildings missing
from SRTM)<br />
<label
><input type="checkbox" id="simplifyHorizon" /> Simplify
horizon</label
>
Tolerance
<input
id="horizonTolerance"
type="number"
value="0.5"
min="0.05"
max="10"
step="0.05"
size="4"
/>
° (Douglas-Peucker — fewer points in horizon.txt)
<span id="simplifyPointCount" style="color: #666"></span>
</fieldset>
<button id="run">Capture panorama</button>
<button id="downloadZip" disabled>
<strong>Download landscape ZIP</strong>
</button>
<button id="open360" disabled>Open 360° viewer</button>
<details style="display: inline-block; margin-left: 0.5em">
<summary>Individual files</summary>
<button id="downloadPng" disabled>PNG</button>
<button id="downloadIni" disabled>landscape.ini</button>
<button id="downloadHorizon" disabled>horizon.txt</button>
<button id="downloadDesc" disabled>description.en.utf8</button>
</details>
<p><progress id="prog" value="0" max="37"></progress></p>
<h3>Preview</h3>
<p>
<label
><input type="checkbox" id="showHorizon" checked /> Show horizon
line</label
>
Thickness
<input
type="number"
id="horizonThickness"
value="4"
min="1"
max="20"
size="3"
/>
px |
<label
><input type="checkbox" id="showGrid" checked /> Show az/alt
grid</label
>
</p>
<div id="previewWrap">
<canvas id="previewGrid" width="8192" height="4096"></canvas>
<canvas id="preview" width="8192" height="4096"></canvas>
<canvas id="previewHorizon" width="8192" height="4096"></canvas>
</div>
<h3>Log</h3>
<div id="log" class="log"></div>
<div id="cesiumContainer"></div>
<!-- Optional first-person panorama viewer (hidden until opened) -->
<div id="viewer360">
<canvas></canvas>
<div class="controls">
<label
><input type="checkbox" id="showHorizon360" checked /> Show
horizon line</label
>
<label
><input type="checkbox" id="showGrid360" checked /> Show
az/alt grid</label
>
<label
><input type="checkbox" id="simplifyHorizon360" /> Simplify
horizon</label
>
<label
>Tolerance
<input
id="horizonTolerance360"
type="number"
value="0.5"
min="0.05"
max="10"
step="0.05"
/>°<span
id="simplifyPointCount360"
class="point-count"
></span
></label>
</div>
<button class="close" title="Close (Esc)">×</button>
<div class="readout" id="lookReadout">Az 000.0° Alt +00.0°</div>
<div class="hud">
Drag to look · scroll or pinch to zoom · Esc to close
</div>
</div>
<div id="mapPicker">
<div class="dialog">
<div class="head">
<strong>Pick location</strong>
<input
id="mapPickerSearch"
type="text"
placeholder="Search place name and press Enter…"
/>
<button type="button" id="mapPickerSearchBtn">Search</button>
<button type="button" id="mapPickerClose">×</button>
</div>
<div id="mapPickerMap"></div>
<div class="foot">
<span id="mapPickerCoords">Click the map to choose a point</span>
<button type="button" id="mapPickerCancel">Cancel</button>
<button type="button" id="mapPickerUse">Use this location</button>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/cesium@1.119.0/Build/Cesium/Cesium.js"></script>
<script>
// =============================================================================
// Data sources — open, no key required
// =============================================================================
// Esri World Imagery: high-resolution satellite imagery, publicly served.
const ESRI_IMAGERY_URL =
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}";
// AWS Open Data — Terrain Tiles in Mapzen "Terrarium" PNG-encoded format.
// Each pixel: height (m) = (R * 256 + G + B / 256) - 32768.
const TERRARIUM_URL_TPL =
"https://elevation-tiles-prod.s3.amazonaws.com/terrarium/{z}/{x}/{y}.png";
const TERRARIUM_MAX_LEVEL = 14; // dataset stops being useful past ~z14
const TERRARIUM_TILE_SIZE = 256;
// =============================================================================
// Capture plan — same camera angles the original PHP/KML produced.
// KML <tilt> is measured from local vertical (0 = nadir, 90 = horizon).
// Cesium pitch is measured from local horizon (0 = horizon, -90 = nadir).
// Conversion: cesiumPitch = tilt - 90.
// =============================================================================
const CIRCLES = [
{ tilt: 0, n: 1 },
{ tilt: 30, n: 6 },
{ tilt: 55, n: 8 },
{ tilt: 80, n: 8 },
{ tilt: 105, n: 8 },
{ tilt: 130, n: 8 },
{ tilt: 155, n: 6 },
];
const TILE_W = 1920; // each capture; 16:9 so horizontal FOV is honored
const TILE_H = 1080;
// Stellarium's spherical landscape default places the texture's left
// edge at azimuth 90° (East), with positive angle_rotatez rotating the
// panorama counter-clockwise as viewed from the zenith. This stitcher
// writes column 0 = south (yaw = ±π) and column W/2 = north (yaw = 0).
// East→South is a quarter turn — its sign depends on which CCW
// convention applies in your Stellarium build, so we emit 90° (matches
// the long-standing Zotti workflow) and add a verification note in
// landscape.ini. If cardinals appear rotated 180° in Stellarium, flip
// this to 270.
const ANGLE_ROTATEZ_DEFAULT = 90;
// Earth tones for the nadir cap (closes the "hole in ground" left when
// maptex_bottom > -90). Matches the muted brown the course recommends.
const BOTTOM_CAP_COLOR = "0.15,0.10,0.05";
const log = (...args) => {
const el = document.getElementById("log");
el.textContent += args.join(" ") + "\n";
el.scrollTop = el.scrollHeight;
};
function buildShots() {
const out = [];
for (const { tilt, n } of CIRCLES) {
for (let i = 0; i < n; i++) {
out.push({ tilt, heading: (i * 360) / n });
}
}
return out;
}
// Wait until the current view has finished streaming, then let a few frames
// settle so the WebGL framebuffer reflects the final terrain + imagery.
//
// The original implementation insisted on `tilesLoaded` being true for 8
// straight frames and otherwise spun for a full 30 s. In practice tile loading
// often plateaus a hair short of "fully loaded" (a handful of edge tiles that
// 404 or never satisfy refinement), so almost every one of the 37 views ran
// out the entire 30 s timeout — that wait dominated the runtime.
//
// Instead we watch `tileLoadProgressEvent`, which reports how many tiles are
// still queued, and finish as soon as EITHER (a) the globe reports fully loaded
// for a few frames, or (b) that pending count stops changing for `quietMs`
// (loading has genuinely stalled — capturing now is correct, not a compromise).
// Note (b) only triggers when the queue is *static*; while tiles are actively
// streaming the count keeps changing, so an in-progress view is never cut off
// early and the horizon is never captured half-loaded. The hard timeout is just
// a last-resort backstop.
function waitForRender(
viewer,
{ quietMs = 800, stableFrames = 4, hardTimeoutMs = 20000 } = {},
) {
return new Promise((resolve) => {
const scene = viewer.scene;
const globe = scene.globe;
const start = performance.now();
let lastProgressAt = start;
let lastPending = -1;
let stable = 0;
let finished = false;
const stopListening =
globe.tileLoadProgressEvent.addEventListener(
(pending) => {
if (pending !== lastPending) {
lastPending = pending;
lastProgressAt = performance.now();
}
},
);
const finish = () => {
if (finished) return;
finished = true;
stopListening();
let settle = 3;
const settleTick = () =>
settle-- > 0
? requestAnimationFrame(settleTick)
: resolve();
requestAnimationFrame(settleTick);
};
const tick = () => {
if (finished) return;
scene.requestRender();
const now = performance.now();
if (globe.tilesLoaded) {
if (++stable >= stableFrames) return finish();
} else {
stable = 0;
}
if (now - start > 600 && now - lastProgressAt > quietMs)
return finish();
if (now - start > hardTimeoutMs) {
log(
" [warn] render wait hit hard timeout — capturing anyway",
);
return finish();
}
requestAnimationFrame(tick);
};
tick();
});
}
// Cesium's PerspectiveFrustum.fov is the HORIZONTAL FOV when aspectRatio > 1
// (wide canvases) and the vertical FOV when aspectRatio <= 1. Since we render
// at 1920x1080 (aspect 16:9 > 1), we pass the horizontal FOV directly.
function setCameraHFov(viewer, hFovDeg, aspect) {
if (aspect > 1) {
viewer.scene.camera.frustum.fov =
Cesium.Math.toRadians(hFovDeg);
} else {
// Narrow/portrait — convert hFov to vFov manually.
const hFovRad = Cesium.Math.toRadians(hFovDeg);
viewer.scene.camera.frustum.fov =
2 * Math.atan(Math.tan(hFovRad / 2) / aspect);
}
}
// =============================================================================
// Equirectangular stitcher — projects each perspective capture into a 2:1
// lat/lon image using a WebGL shader. Runs once per frame and accumulates.
// =============================================================================
const STITCH_VS = `
attribute vec2 a_pos;
varying vec2 v_uv;
void main() {
v_uv = a_pos * 0.5 + 0.5;
gl_Position = vec4(a_pos, 0.0, 1.0);
}
`;
const STITCH_FS = `
precision highp float;
varying vec2 v_uv;
uniform sampler2D u_tex; // perspective capture
uniform mat3 u_R; // world->camera rotation
uniform float u_tanHalfHFov; // tan(hFov/2) — horizontal focal length
uniform float u_tanHalfV; // tan(vFov/2) — vertical focal length
uniform vec2 u_outSize;
void main() {
// Equirectangular pixel -> spherical direction (yaw=lon, pitch=lat).
// v_uv.x in [0,1] maps to yaw [-pi, pi] (heading from north, clockwise).
// v_uv.y in [0,1] maps to pitch [-pi/2 .. +pi/2]. Because gl_Position.y=+1
// (top of canvas) corresponds to v_uv.y=1, the top of the output image is
// the zenith and the bottom is the nadir — standard equirectangular.
float yaw = (v_uv.x - 0.5) * 6.2831853;
float pitch = (v_uv.y - 0.5) * 3.1415926;
// Direction in world frame: ENU with x=east, y=north, z=up.
// heading 0 = +y (north), heading 90 = +x (east).
vec3 dir;
dir.x = sin(yaw) * cos(pitch);
dir.y = cos(yaw) * cos(pitch);
dir.z = sin(pitch);
// Rotate into camera frame. Camera looks down -Z_cam, +X_cam right, +Y_cam up.
vec3 dc = u_R * dir;
// Behind camera? skip.
if (dc.z >= 0.0) { discard; }
// Project to image plane (pinhole). u spans the horizontal FOV, v the
// vertical FOV, using the EXACT focal lengths the capture was rendered with.
float u = (dc.x / -dc.z) / u_tanHalfHFov; // [-1, +1] across hFov
float v = (dc.y / -dc.z) / u_tanHalfV; // [-1, +1] across vFov
// Inside this capture's frame?
if (abs(u) > 1.0 || abs(v) > 1.0) { discard; }
// Texture V is inverted vs. our camera-frame Y because WebGL's default
// UNPACK_FLIP_Y_WEBGL=false stores the source canvas's top row at
// texture v=0 (i.e. texUv.y=0 reads the top of the source).
vec2 texUv = vec2(u * 0.5 + 0.5, 0.5 - v * 0.5);
gl_FragColor = texture2D(u_tex, texUv);
}
`;
function makeStitcher(outCanvas) {
const gl = outCanvas.getContext("webgl", {
preserveDrawingBuffer: true,
});
if (!gl) throw new Error("WebGL unavailable");
const compile = (type, src) => {
const s = gl.createShader(type);
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS))
throw new Error(gl.getShaderInfoLog(s));
return s;
};
const prog = gl.createProgram();
gl.attachShader(prog, compile(gl.VERTEX_SHADER, STITCH_VS));
gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, STITCH_FS));
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS))
throw new Error(gl.getProgramInfoLog(prog));
gl.useProgram(prog);
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1,
]),
gl.STATIC_DRAW,
);
const aPos = gl.getAttribLocation(prog, "a_pos");
gl.enableVertexAttribArray(aPos);
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(
gl.TEXTURE_2D,
gl.TEXTURE_WRAP_S,
gl.CLAMP_TO_EDGE,
);
gl.texParameteri(
gl.TEXTURE_2D,
gl.TEXTURE_WRAP_T,
gl.CLAMP_TO_EDGE,
);
gl.texParameteri(
gl.TEXTURE_2D,
gl.TEXTURE_MIN_FILTER,
gl.LINEAR,
);
gl.texParameteri(
gl.TEXTURE_2D,
gl.TEXTURE_MAG_FILTER,
gl.LINEAR,
);
gl.viewport(0, 0, outCanvas.width, outCanvas.height);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
const uTex = gl.getUniformLocation(prog, "u_tex");
const uR = gl.getUniformLocation(prog, "u_R");
const uTan = gl.getUniformLocation(prog, "u_tanHalfHFov");
const uTanV = gl.getUniformLocation(prog, "u_tanHalfV");
gl.uniform1i(uTex, 0);
return {
addCapture(sourceCanvas, headingDeg, tiltDeg, frustum) {
// Build rotation matrix that takes a world-frame direction
// (ENU: x=east, y=north, z=up) and yields a camera-frame vector
// where +X is right, +Y is up, and -Z is the look direction.
const h = (headingDeg * Math.PI) / 180; // 0 = north, clockwise
const p = ((tiltDeg - 90) * Math.PI) / 180; // Cesium pitch: 0=horizon, -90=down
const ch = Math.cos(h),
sh = Math.sin(h);
const cp = Math.cos(p),
sp = Math.sin(p);
// Forward (look) direction in world ENU, given heading h and pitch p:
// fwd = (sin h cos p, cos h cos p, sin p)
// Right vector (perpendicular, horizontal):
// right = (cos h, -sin h, 0)
// Up vector = right x fwd (gives world-up consistent orientation):
const fx = sh * cp,
fy = ch * cp,
fz = sp;
const rx = ch,
ry = -sh,
rz = 0;
const ux = ry * fz - rz * fy;
const uy = rz * fx - rx * fz;
const uz = rx * fy - ry * fx;
// Camera-frame basis as rows: rotation R such that R * world = cam.
// cam_x = right . world, cam_y = up . world, cam_z = -fwd . world (look = -Z).
const R = new Float32Array([
rx,
ux,
-fx,
ry,
uy,
-fy,
rz,
uz,
-fz,
]);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE,
sourceCanvas,
);
gl.uniformMatrix3fv(uR, false, R);
// Read the focal lengths Cesium actually rendered with, straight from its
// perspective projection matrix (column-major Matrix4): m00 = 1/tanHalfH,
// m11 = 1/tanHalfV. This makes the reprojection exact regardless of how
// Cesium resolved the field of view vs. the canvas aspect ratio — no more
// guessing the vertical FOV from the canvas shape.
const pm = frustum.projectionMatrix;
gl.uniform1f(uTan, 1.0 / pm[0]); // tan(hFov/2)
gl.uniform1f(uTanV, 1.0 / pm[5]); // tan(vFov/2)
gl.drawArrays(gl.TRIANGLES, 0, 6);
},
};
}
// =============================================================================
// Terrain provider — decodes AWS Terrarium PNG tiles into Cesium heightmaps.
//
// We can't use Cesium.CustomHeightmapTerrainProvider directly because it
// hard-codes skirtHeight=0, which leaves visible cracks at every tile/LOD
// boundary. The cracks manifest as a thin horizontal band of "missing"
// geometry, very obvious at grazing angles like the horizon. Here we
// implement the TerrainProvider interface ourselves and return
// HeightmapTerrainData with a per-tile skirt sized to the local relief.
// =============================================================================
function makeTerrariumTerrainProvider() {
const tilingScheme = new Cesium.WebMercatorTilingScheme();
const tileSize = TERRARIUM_TILE_SIZE;
// Off-screen canvas reused for every tile decode.
const decodeCanvas = document.createElement("canvas");
decodeCanvas.width = decodeCanvas.height = tileSize;
const decodeCtx = decodeCanvas.getContext("2d", {
willReadFrequently: true,
});
// Decode cache. Each Terrarium PNG is fetched + decoded once and its height
// grid is kept in memory. Across a 360° sweep from a single eye point the
// same tiles are requested repeatedly (LOD churn, re-entry when panning back
// around, the initial terrain elevation sample), so caching turns all but the
// first request for a tile into a synchronous memory hit. `inflight` also
// collapses concurrent requests for the same tile into a single fetch.
const heightCache = new Map(); // "z/x/y" -> { heights, minH, maxH }
const inflight = new Map(); // "z/x/y" -> Promise<{ heights, minH, maxH }>
// Cesium removed this static helper in 1.111; replicate its formula directly.
const levelZeroMGE =
(tilingScheme.ellipsoid.maximumRadius * 2 * Math.PI * 0.25) /
(tileSize * tilingScheme.getNumberOfXTilesAtLevel(0));
const errorEvent = new Cesium.Event();
const credit = new Cesium.Credit("AWS Terrain Tiles", false);
async function fetchPixelData(x, y, level) {
const url = TERRARIUM_URL_TPL.replace("{z}", level)
.replace("{x}", x)
.replace("{y}", y);
const img = new Image();
img.crossOrigin = "anonymous";
await new Promise((res, rej) => {
img.onload = res;
img.onerror = () =>
rej(new Error("terrain tile fetch failed: " + url));
img.src = url;
});
decodeCtx.clearRect(0, 0, tileSize, tileSize);
decodeCtx.drawImage(img, 0, 0);
return decodeCtx.getImageData(0, 0, tileSize, tileSize)
.data;
}
function buildHeights(pixels) {
const heights = new Float32Array(tileSize * tileSize);
let minH = Infinity,
maxH = -Infinity;
for (let i = 0; i < heights.length; i++) {
const r = pixels[i * 4],
g = pixels[i * 4 + 1],
b = pixels[i * 4 + 2];
const h = r * 256 + g + b / 256 - 32768;
heights[i] = h;
if (h < minH) minH = h;
if (h > maxH) maxH = h;
}
return { heights, minH, maxH };
}
function flatTile(skirt = 100) {
return new Cesium.HeightmapTerrainData({
buffer: new Float32Array(tileSize * tileSize),
width: tileSize,
height: tileSize,
skirtHeight: skirt,
});
}
// Cached, de-duplicated tile decode. Returns the same { heights, minH, maxH }
// object for repeat requests instead of hitting the network again.
async function decodeTile(x, y, level) {
const key = level + "/" + x + "/" + y;
const cached = heightCache.get(key);
if (cached) return cached;
let p = inflight.get(key);
if (!p) {
p = (async () => {
const px = await fetchPixelData(x, y, level);
return buildHeights(px);
})();
inflight.set(key, p);
}
try {
const result = await p;
heightCache.set(key, result);
return result;
} finally {
inflight.delete(key);
}
}
return {
get tilingScheme() {
return tilingScheme;
},
get ready() {
return true;
},
get readyPromise() {
return Promise.resolve(true);
},
get errorEvent() {
return errorEvent;
},
get credit() {
return credit;
},
get hasWaterMask() {
return false;
},
get hasVertexNormals() {
return false;
},
get availability() {
return undefined;