-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrop.html
More file actions
1064 lines (907 loc) · 40 KB
/
crop.html
File metadata and controls
1064 lines (907 loc) · 40 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">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bay Area DEM Crop Tool</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
overflow: hidden;
background: linear-gradient(135deg, #1e3c72, #2a5298);
}
#container {
width: 100vw;
height: 100vh;
position: relative;
}
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
background: rgba(0, 0, 0, 0.7);
padding: 15px;
border-radius: 8px;
font-size: 14px;
max-width: 350px;
backdrop-filter: blur(10px);
z-index: 100;
}
#controls {
position: absolute;
top: 10px;
right: 10px;
background: rgba(0, 0, 0, 0.7);
padding: 15px;
border-radius: 8px;
color: white;
min-width: 280px;
backdrop-filter: blur(10px);
z-index: 100;
}
#controls h3 {
margin-bottom: 10px;
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
padding-bottom: 5px;
}
.control-group {
margin: 10px 0;
}
.control-group label {
display: block;
margin-bottom: 5px;
font-size: 12px;
color: #aaa;
}
.coord-display {
background: rgba(255, 255, 255, 0.1);
padding: 8px;
border-radius: 4px;
font-family: monospace;
font-size: 12px;
margin: 5px 0;
}
.coord-row {
display: flex;
justify-content: space-between;
margin: 2px 0;
}
input[type="text"] {
width: 100%;
padding: 5px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 4px;
color: white;
margin: 5px 0;
}
button {
background: #4CAF50;
border: none;
color: white;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
width: 100%;
margin-top: 5px;
transition: background 0.3s;
}
button:hover {
background: #45a049;
}
button:disabled {
background: #666;
cursor: not-allowed;
}
#loading {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 24px;
text-align: center;
z-index: 200;
}
.spinner {
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid white;
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
#stats {
position: absolute;
bottom: 10px;
left: 10px;
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 10px;
border-radius: 8px;
font-size: 12px;
font-family: monospace;
backdrop-filter: blur(10px);
z-index: 100;
}
/* Crop overlay styles */
#cropOverlay {
position: absolute;
pointer-events: none;
z-index: 50;
}
.crop-handle {
position: absolute;
width: 20px;
height: 20px;
background: #4CAF50;
border: 2px solid white;
border-radius: 50%;
cursor: move;
pointer-events: all;
z-index: 60;
transform: translate(-50%, -50%);
}
.crop-handle:hover {
background: #45a049;
width: 24px;
height: 24px;
}
.crop-border {
position: absolute;
border: 2px solid #4CAF50;
background: rgba(76, 175, 80, 0.1);
pointer-events: none;
}
</style>
</head>
<body>
<div id="container">
<div id="info">
<h2>Bay Area DEM Crop Tool</h2>
<p>Drag the corner handles to define your crop area</p>
<ul style="margin-top: 10px; font-size: 12px; list-style: none;">
<li>📍 Drag green handles to adjust crop area</li>
<li>🖱️ Scroll: Zoom in/out</li>
<li>🖱️ Click + drag: Pan view</li>
</ul>
</div>
<div id="controls">
<h3>Crop Settings</h3>
<div class="control-group">
<label>Current Selection:</label>
<div class="coord-display">
<div class="coord-row">
<span>Top-Left:</span>
<span id="tlCoords">-</span>
</div>
<div class="coord-row">
<span>Bottom-Right:</span>
<span id="brCoords">-</span>
</div>
<div class="coord-row">
<span>Size:</span>
<span id="cropSize">-</span>
</div>
<div class="coord-row">
<span>Pixels:</span>
<span id="cropPixels">-</span>
</div>
</div>
</div>
<div class="control-group">
<label for="fileName">Output Filename:</label>
<input type="text" id="fileName" placeholder="cropped_bayarea.tif" value="cropped_bayarea.tif">
</div>
<div class="control-group">
<button id="resetCrop">Reset to Full Area</button>
<button id="saveCrop">Save Cropped Data</button>
</div>
</div>
<div id="loading" style="display: none;">
<div class="spinner"></div>
<p>Loading elevation data...</p>
</div>
<div id="stats"></div>
<!-- Crop overlay will be added dynamically -->
<div id="cropOverlay" style="display: none;">
<div class="crop-border"></div>
<div class="crop-handle" id="handle-tl" data-corner="tl"></div>
<div class="crop-handle" id="handle-tr" data-corner="tr"></div>
<div class="crop-handle" id="handle-bl" data-corner="bl"></div>
<div class="crop-handle" id="handle-br" data-corner="br"></div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/geotiff@2.1.0/dist-browser/geotiff.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.159.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.159.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
let scene, camera, renderer, controls;
let terrain = null;
let terrainData = null;
let dataWidth = 0;
let dataHeight = 0;
let tiff = null; // Store the GeoTIFF object
let cityMarkers = []; // Store city marker meshes
let geoBounds = null; // Store actual geographic bounds from GeoTIFF
// Crop area coordinates (in data pixels)
let cropArea = {
x1: 0,
y1: 0,
x2: 100,
y2: 100
};
// Initialize Three.js scene
function initScene() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0x1e3c72);
// Camera - top-down view
camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
0.1,
20000
);
// Set camera for top-down view pointing north
camera.position.set(0, 1500, 1);
camera.up.set(0, 1, 0);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.getElementById('container').appendChild(renderer.domElement);
// Controls - restricted for top view
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.minDistance = 100;
controls.maxDistance = 3000;
controls.enableRotate = false; // Lock rotation for top view
controls.target.set(0, 0, 0);
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(0, 100, 0);
scene.add(directionalLight);
// Grid helper
const gridHelper = new THREE.GridHelper(1000, 50, 0x444444, 0x222222);
gridHelper.position.y = -10;
scene.add(gridHelper);
animate();
}
// Animation loop
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
// Load GeoTIFF file
async function loadGeoTIFF() {
document.getElementById('loading').style.display = 'block';
try {
console.log('Fetching bayarea.tif...');
const response = await fetch('bayarea.tif');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const arrayBuffer = await response.arrayBuffer();
console.log('Parsing GeoTIFF...');
tiff = await GeoTIFF.fromArrayBuffer(arrayBuffer);
const image = await tiff.getImage();
dataWidth = image.getWidth();
dataHeight = image.getHeight();
console.log('Image dimensions:', dataWidth, 'x', dataHeight);
const rasters = await image.readRasters();
terrainData = rasters[0];
// Get and store geographic bounds
geoBounds = image.getBoundingBox();
const fileInfo = image.getFileDirectory();
console.log('Geographic bounds:', geoBounds);
console.log('File directory info:', fileInfo);
// Check if bounds are in UTM (large numbers) or lat/lon (small numbers)
if (geoBounds && Math.abs(geoBounds[0]) > 180) {
console.log('Data appears to be in UTM projection');
// For UTM Zone 10N (Bay Area), approximate conversion
// This is a rough approximation - proper conversion would need proj4js
const utmCenterX = (geoBounds[0] + geoBounds[2]) / 2;
const utmCenterY = (geoBounds[1] + geoBounds[3]) / 2;
console.log('UTM Center:', utmCenterX, utmCenterY);
}
// Initialize crop area to full image
cropArea = {
x1: 0,
y1: 0,
x2: dataWidth,
y2: dataHeight
};
// Create terrain mesh
createTerrainMesh(terrainData, dataWidth, dataHeight);
// Add city markers
addCityMarkers();
// Initialize crop overlay after a delay
setTimeout(() => {
initializeCropOverlay();
updateCropDisplay();
}, 500);
document.getElementById('loading').style.display = 'none';
console.log('Terrain loaded successfully');
} catch (error) {
console.error('Error loading GeoTIFF:', error);
alert('Error loading bayarea.tif: ' + error.message);
document.getElementById('loading').style.display = 'none';
}
}
// Create 3D terrain mesh from elevation data
function createTerrainMesh(elevationData, width, height) {
console.log('Creating terrain mesh:', width, 'x', height);
// Remove existing terrain
if (terrain) {
scene.remove(terrain);
terrain.geometry.dispose();
terrain.material.dispose();
}
// Use lower quality for faster interaction
const step = Math.max(4, Math.floor(Math.min(width, height) / 256));
const meshWidth = Math.floor(width / step);
const meshHeight = Math.floor(height / step);
console.log('Mesh dimensions:', meshWidth, 'x', meshHeight, 'step:', step);
// Create geometry
const geometry = new THREE.PlaneGeometry(
1000,
1000,
meshWidth - 1,
meshHeight - 1
);
// Get min/max elevation
let minElev = Infinity;
let maxElev = -Infinity;
for (let i = 0; i < elevationData.length; i += step) {
const value = elevationData[i];
if (!isNaN(value) && value !== -9999) {
minElev = Math.min(minElev, value);
maxElev = Math.max(maxElev, value);
}
}
// Update vertices with elevation
const vertices = geometry.attributes.position.array;
const actualStepX = width / meshWidth;
const actualStepY = height / meshHeight;
for (let j = 0; j < meshHeight; j++) {
for (let i = 0; i < meshWidth; i++) {
const index = (j * meshWidth + i) * 3;
const dataX = Math.floor(i * actualStepX);
const dataY = Math.floor(j * actualStepY);
const dataIndex = Math.min(dataY * width + dataX, elevationData.length - 1);
let elevation = elevationData[dataIndex];
if (isNaN(elevation) || elevation === -9999) {
elevation = minElev;
}
// Very subtle elevation for top view
const normalizedElev = (elevation - minElev) / (maxElev - minElev);
vertices[index + 2] = normalizedElev * 20; // Minimal vertical exaggeration
}
}
geometry.computeVertexNormals();
geometry.attributes.position.needsUpdate = true;
// Create colors based on elevation
const colors = new Float32Array(meshWidth * meshHeight * 3);
for (let j = 0; j < meshHeight; j++) {
for (let i = 0; i < meshWidth; i++) {
const index = (j * meshWidth + i) * 3;
const dataX = Math.floor(i * actualStepX);
const dataY = Math.floor(j * actualStepY);
const dataIndex = Math.min(dataY * width + dataX, elevationData.length - 1);
let elevation = elevationData[dataIndex];
if (isNaN(elevation) || elevation === -9999) {
elevation = minElev;
}
const normalized = (elevation - minElev) / (maxElev - minElev);
const color = getColorForElevation(normalized);
colors[index] = color.r;
colors[index + 1] = color.g;
colors[index + 2] = color.b;
}
}
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
// Create material
const material = new THREE.MeshPhongMaterial({
vertexColors: true,
side: THREE.DoubleSide,
flatShading: false
});
// Create mesh
terrain = new THREE.Mesh(geometry, material);
terrain.rotation.x = -Math.PI / 2;
terrain.castShadow = true;
terrain.receiveShadow = true;
scene.add(terrain);
// Update stats
document.getElementById('stats').innerHTML = `
Data: ${width}x${height} pixels<br>
Display: ${meshWidth}x${meshHeight} vertices<br>
Elevation: ${minElev.toFixed(1)}m - ${maxElev.toFixed(1)}m
`;
}
// Get color based on elevation (elevation scheme)
function getColorForElevation(normalized) {
// Black for water, then green to brown to white for land
if (normalized < 0.1) {
// Water - very dark/black
return {
r: 0,
g: 0,
b: 0.05
};
} else if (normalized < 0.25) {
// Shallow water to coast - dark to green transition
const t = (normalized - 0.1) / 0.15;
return {
r: 0,
g: 0.2 * t,
b: 0.05 + 0.15 * t
};
} else if (normalized < 0.5) {
return {
r: (normalized - 0.25) * 2,
g: 0.7,
b: 0.2
};
} else if (normalized < 0.75) {
return {
r: 0.5 + (normalized - 0.5),
g: 0.4,
b: 0.2
};
} else {
const snow = (normalized - 0.75) * 4;
return {
r: 0.7 + snow * 0.3,
g: 0.7 + snow * 0.3,
b: 0.7 + snow * 0.3
};
}
}
// Add city markers for reference
function addCityMarkers() {
// Remove existing markers
cityMarkers.forEach(marker => {
scene.remove(marker.mesh);
if (marker.label) scene.remove(marker.label);
});
cityMarkers = [];
// City locations with actual lat/lon coordinates
const cities = [
{
name: 'San Francisco',
lat: 37.7338,
lon: -122.4467,
color: 0xff0000
},
{
name: 'Berkeley',
lat: 37.8716,
lon: -122.2728,
color: 0x00ff00
},
{
name: 'Palo Alto',
lat: 37.4419,
lon: -122.1430,
color: 0x0088ff
},
{
name: 'San Jose',
lat: 37.3353,
lon: -121.8919,
color: 0xffff00
}
];
// Determine bounds based on actual data
let minLat, maxLat, minLon, maxLon;
if (geoBounds && Math.abs(geoBounds[0]) > 180) {
// Data is in UTM projection (meters)
// UTM Zone 10N approximate bounds for Bay Area
// These are VERY rough conversions - proper proj4js would be better
// Approximate UTM to lat/lon for Zone 10N
// UTM Zone 10N has central meridian at -123°
// Very rough approximation:
const utmMinX = geoBounds[0];
const utmMaxX = geoBounds[2];
const utmMinY = geoBounds[1];
const utmMaxY = geoBounds[3];
// Rough conversion (this is not accurate but gives ballpark)
// Bay Area is roughly at 37-38°N, -122 to -121°W
minLon = -123.0 + (utmMinX - 500000) / 111000;
maxLon = -123.0 + (utmMaxX - 500000) / 111000;
minLat = (utmMinY - 4100000) / 111000;
maxLat = (utmMaxY - 4100000) / 111000;
console.log('Estimated lat/lon bounds from UTM:', minLat, maxLat, minLon, maxLon);
} else if (geoBounds) {
// Data is already in lat/lon
minLon = geoBounds[0];
minLat = geoBounds[1];
maxLon = geoBounds[2];
maxLat = geoBounds[3];
console.log('Using lat/lon bounds from GeoTIFF:', minLat, maxLat, minLon, maxLon);
} else {
// Fallback to approximate Bay Area bounds
minLat = 37.0;
maxLat = 38.0;
minLon = -122.6;
maxLon = -121.6;
console.log('Using fallback Bay Area bounds');
}
cities.forEach(city => {
// Convert lat/lon to normalized position
const x = (city.lon - minLon) / (maxLon - minLon);
const y = 1 - (city.lat - minLat) / (maxLat - minLat); // Flip Y for correct orientation
// Create a circle geometry for the marker
const geometry = new THREE.RingGeometry(8, 12, 32);
const material = new THREE.MeshBasicMaterial({
color: city.color,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.8
});
const mesh = new THREE.Mesh(geometry, material);
// Position marker on the terrain
const worldX = (x - 0.5) * 1000;
const worldZ = (y - 0.5) * 1000;
mesh.position.set(worldX, 5, worldZ); // Slightly above terrain
mesh.rotation.x = -Math.PI / 2; // Lay flat
scene.add(mesh);
// Create text sprite for label
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = 256;
canvas.height = 64;
context.fillStyle = 'rgba(0, 0, 0, 0.5)';
context.fillRect(0, 0, canvas.width, canvas.height);
context.font = 'Bold 24px Arial';
context.fillStyle = 'white';
context.textAlign = 'center';
context.fillText(city.name, 128, 40);
const texture = new THREE.CanvasTexture(canvas);
const spriteMaterial = new THREE.SpriteMaterial({
map: texture,
transparent: true
});
const sprite = new THREE.Sprite(spriteMaterial);
sprite.position.set(worldX, 15, worldZ);
sprite.scale.set(50, 12.5, 1);
scene.add(sprite);
cityMarkers.push({ mesh, label: sprite, city });
});
}
// Initialize crop overlay
function initializeCropOverlay() {
const overlay = document.getElementById('cropOverlay');
overlay.style.display = 'block';
// Add drag functionality to handles
const handles = document.querySelectorAll('.crop-handle');
handles.forEach(handle => {
handle.addEventListener('mousedown', startDrag);
});
// Delay the initial update to ensure scene is ready
setTimeout(() => {
updateCropOverlay();
}, 100);
}
// Update crop overlay position
function updateCropOverlay() {
if (!terrain) return;
// Convert data coordinates to screen coordinates
const tl = dataToScreen(cropArea.x1, cropArea.y1);
const br = dataToScreen(cropArea.x2, cropArea.y2);
const border = document.querySelector('.crop-border');
border.style.left = tl.x + 'px';
border.style.top = tl.y + 'px';
border.style.width = (br.x - tl.x) + 'px';
border.style.height = (br.y - tl.y) + 'px';
// Update handle positions
document.getElementById('handle-tl').style.left = tl.x + 'px';
document.getElementById('handle-tl').style.top = tl.y + 'px';
document.getElementById('handle-tr').style.left = br.x + 'px';
document.getElementById('handle-tr').style.top = tl.y + 'px';
document.getElementById('handle-bl').style.left = tl.x + 'px';
document.getElementById('handle-bl').style.top = br.y + 'px';
document.getElementById('handle-br').style.left = br.x + 'px';
document.getElementById('handle-br').style.top = br.y + 'px';
}
// Convert data coordinates to screen coordinates
function dataToScreen(dataX, dataY) {
// Map data coordinates to 3D world coordinates
const worldX = (dataX / dataWidth - 0.5) * 1000;
const worldZ = (dataY / dataHeight - 0.5) * 1000;
// Create a 3D vector and project to screen
const vector = new THREE.Vector3(worldX, 0, worldZ);
vector.project(camera);
// Convert to screen coordinates
const x = (vector.x * 0.5 + 0.5) * window.innerWidth;
const y = (-vector.y * 0.5 + 0.5) * window.innerHeight;
return { x, y };
}
// Convert screen coordinates to data coordinates
function screenToData(screenX, screenY) {
// Create normalized device coordinates
const x = (screenX / window.innerWidth) * 2 - 1;
const y = -(screenY / window.innerHeight) * 2 + 1;
// Create a raycaster
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(new THREE.Vector2(x, y), camera);
// Intersect with the terrain plane
const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const intersection = new THREE.Vector3();
raycaster.ray.intersectPlane(plane, intersection);
// Convert world coordinates to data coordinates
const dataX = Math.round((intersection.x / 1000 + 0.5) * dataWidth);
const dataY = Math.round((intersection.z / 1000 + 0.5) * dataHeight);
return {
x: Math.max(0, Math.min(dataWidth, dataX)),
y: Math.max(0, Math.min(dataHeight, dataY))
};
}
// Handle dragging
let isDragging = false;
let dragHandle = null;
function startDrag(e) {
isDragging = true;
dragHandle = e.target.dataset.corner;
document.addEventListener('mousemove', onDrag);
document.addEventListener('mouseup', stopDrag);
e.preventDefault();
}
function onDrag(e) {
if (!isDragging || !dragHandle) return;
const data = screenToData(e.clientX, e.clientY);
switch(dragHandle) {
case 'tl':
cropArea.x1 = Math.min(data.x, cropArea.x2 - 10);
cropArea.y1 = Math.min(data.y, cropArea.y2 - 10);
break;
case 'tr':
cropArea.x2 = Math.max(data.x, cropArea.x1 + 10);
cropArea.y1 = Math.min(data.y, cropArea.y2 - 10);
break;
case 'bl':
cropArea.x1 = Math.min(data.x, cropArea.x2 - 10);
cropArea.y2 = Math.max(data.y, cropArea.y1 + 10);
break;
case 'br':
cropArea.x2 = Math.max(data.x, cropArea.x1 + 10);
cropArea.y2 = Math.max(data.y, cropArea.y1 + 10);
break;
}
updateCropOverlay();
updateCropDisplay();
}
function stopDrag() {
isDragging = false;
dragHandle = null;
document.removeEventListener('mousemove', onDrag);
document.removeEventListener('mouseup', stopDrag);
}
// Update crop display information
function updateCropDisplay() {
const width = cropArea.x2 - cropArea.x1;
const height = cropArea.y2 - cropArea.y1;
document.getElementById('tlCoords').textContent = `${cropArea.x1}, ${cropArea.y1}`;
document.getElementById('brCoords').textContent = `${cropArea.x2}, ${cropArea.y2}`;
document.getElementById('cropSize').textContent = `${width}x${height}`;
document.getElementById('cropPixels').textContent = `${(width * height).toLocaleString()} pixels`;
}
// Reset crop area
document.getElementById('resetCrop').addEventListener('click', () => {
cropArea = {
x1: 0,
y1: 0,
x2: dataWidth,
y2: dataHeight
};
updateCropOverlay();
updateCropDisplay();
});
// Save cropped data
document.getElementById('saveCrop').addEventListener('click', async () => {
const fileName = document.getElementById('fileName').value || 'cropped_bayarea.tif';
if (!terrainData) {
alert('No data loaded');
return;
}
// Extract cropped region
const cropWidth = cropArea.x2 - cropArea.x1;
const cropHeight = cropArea.y2 - cropArea.y1;
const croppedData = new Float32Array(cropWidth * cropHeight);
for (let y = 0; y < cropHeight; y++) {
for (let x = 0; x < cropWidth; x++) {
const srcIndex = (y + cropArea.y1) * dataWidth + (x + cropArea.x1);
const dstIndex = y * cropWidth + x;
croppedData[dstIndex] = terrainData[srcIndex];
}
}
// Create a basic TIFF file
try {
// Calculate new bounds for cropped area
let newBounds = null;
let pixelScale = [1, 1]; // Default pixel scale
if (geoBounds) {
const xScale = (geoBounds[2] - geoBounds[0]) / dataWidth;
const yScale = (geoBounds[3] - geoBounds[1]) / dataHeight;
const newMinX = geoBounds[0] + cropArea.x1 * xScale;
const newMaxX = geoBounds[0] + cropArea.x2 * xScale;
const newMinY = geoBounds[1] + cropArea.y1 * yScale;
const newMaxY = geoBounds[1] + cropArea.y2 * yScale;
newBounds = [newMinX, newMinY, newMaxX, newMaxY];
pixelScale = [Math.abs(xScale), Math.abs(yScale)];
console.log('Cropped bounds:', newBounds);
console.log('Pixel scale:', pixelScale);
}
// We need space for GeoTIFF tags
// ModelTiepointTag: 6 doubles = 48 bytes
// ModelPixelScaleTag: 3 doubles = 24 bytes
const geoDataSize = 48 + 24;
// Calculate offsets to ensure 4-byte alignment for Float32Array
const headerSize = 8; // TIFF header
const ifdSize = 2 + (16 * 12) + 4; // IFD: count + tags + next offset (16 tags now)
// Place geo data after IFD
let geoDataOffset = headerSize + ifdSize;
// Ensure geo data is 8-byte aligned for doubles
const geoAlignment = geoDataOffset % 8;
if (geoAlignment !== 0) {
geoDataOffset += (8 - geoAlignment);
}
// Place elevation data after geo data
let dataOffset = geoDataOffset + geoDataSize;
// Ensure data offset is 4-byte aligned for Float32Array
const alignment = dataOffset % 4;
if (alignment !== 0) {
dataOffset += (4 - alignment);
}
// Create buffer with proper size
const totalSize = dataOffset + croppedData.byteLength;
const buffer = new ArrayBuffer(totalSize);
const view = new DataView(buffer);
let offset = 0;
// TIFF header
view.setUint16(offset, 0x4949, true); // Little endian
offset += 2;
view.setUint16(offset, 42, true); // TIFF magic number
offset += 2;
view.setUint32(offset, 8, true); // IFD offset
offset += 4;
// IFD (Image File Directory)
view.setUint16(offset, 16, true); // Number of tags (increased to 16)
offset += 2;
// Basic tags for a simple grayscale TIFF with GeoTIFF tags
const tags = [
[256, 4, 1, cropWidth], // ImageWidth
[257, 4, 1, cropHeight], // ImageLength
[258, 3, 1, 32], // BitsPerSample
[259, 3, 1, 1], // Compression (none)
[262, 3, 1, 1], // PhotometricInterpretation
[273, 4, 1, dataOffset], // StripOffsets (aligned)
[277, 3, 1, 1], // SamplesPerPixel
[278, 4, 1, cropHeight], // RowsPerStrip
[279, 4, 1, croppedData.byteLength], // StripByteCounts
[282, 5, 1, 0], // XResolution
[283, 5, 1, 0], // YResolution
[284, 3, 1, 1], // PlanarConfiguration
[296, 3, 1, 2], // ResolutionUnit
[339, 3, 1, 3], // SampleFormat (float)
[33550, 12, 3, geoDataOffset + 48], // ModelPixelScaleTag (points to scale data)
[33922, 12, 6, geoDataOffset] // ModelTiepointTag (points to tiepoint data)
];
// Write tags
tags.forEach(tag => {
view.setUint16(offset, tag[0], true); // Tag
offset += 2;
view.setUint16(offset, tag[1], true); // Type
offset += 2;
view.setUint32(offset, tag[2], true); // Count
offset += 4;
view.setUint32(offset, tag[3], true); // Value/Offset
offset += 4;
});
// Next IFD offset (0 = no more)
view.setUint32(offset, 0, true);
offset += 4;
// Add padding to reach geo data offset
while (offset < geoDataOffset) {
view.setUint8(offset, 0);
offset++;
}
// Write ModelTiepointTag data (6 doubles)
// Format: I, J, K, X, Y, Z
// I,J,K = pixel coordinates (0,0,0 for top-left)
// X,Y,Z = geographic coordinates of that pixel
view.setFloat64(offset, 0, true); // I (pixel x)
offset += 8;
view.setFloat64(offset, 0, true); // J (pixel y)
offset += 8;
view.setFloat64(offset, 0, true); // K (pixel z)
offset += 8;
view.setFloat64(offset, newBounds ? newBounds[0] : 0, true); // X (geo x)
offset += 8;
view.setFloat64(offset, newBounds ? newBounds[3] : cropHeight, true); // Y (geo y - from top)
offset += 8;
view.setFloat64(offset, 0, true); // Z (geo z)
offset += 8;
// Write ModelPixelScaleTag data (3 doubles)
// Format: ScaleX, ScaleY, ScaleZ