-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathterrain2stl.js
More file actions
361 lines (290 loc) · 10.6 KB
/
terrain2stl.js
File metadata and controls
361 lines (290 loc) · 10.6 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
var map;
var gridlines;
var rectangle;
var latBox;
var lngBox;
var mapCenter;
var minBoxWidth = 0.03333; //width of box in degrees = 40 arc seconds
var boxWidth = 0.03333;
var boxHeight = 0.03333;
var boxRotation = 0;
var sizeSlider;
var sizeLabel;
var scaleSlider;
var scaleLabel;
var rotationSlider;
var rotationLabel;
var vScaleSlider;
var vScaleLabel;
var waterDropSlider;
var waterDropLabel;
var baseHeightSlider;
var baseHeightLabel;
// Initialize the application
document.addEventListener('DOMContentLoaded', initializePage);
function initializePage(){
initializeControls();
initializeMap();
initializeForm();
}
function initializeControls(){
latBox = document.getElementById("c-lat");
lngBox = document.getElementById("c-lng");
widthSlider = document.getElementsByName("boxWidth")[0];
widthLabel = document.getElementById("boxWidthLabel");
heightSlider = document.getElementsByName("boxHeight")[0];
heightLabel = document.getElementById("boxHeightLabel");
scaleSlider = document.getElementsByName("boxScale")[0];
scaleLabel = document.getElementById("boxScaleLabel");
rotationSlider = document.getElementsByName("rotation")[0];
rotationLabel = document.getElementById("rotationLabel");
vScaleSlider = document.getElementsByName("vScale")[0];
vScaleLabel = document.getElementById("vScaleLabel");
waterDropSlider = document.getElementsByName("waterDrop")[0];
waterDropLabel = document.getElementById("waterDropLabel");
baseHeightSlider = document.getElementsByName("baseHeight")[0];
baseHeightLabel = document.getElementById("baseHeightLabel");
}
function hillshadecolor(values){
gray = values[0]
//alpha = Math.abs(gray - 182) > 8 ? 0.1 : 0;
//return `rgba(${gray},${gray},${gray},${alpha})`;
color = Math.abs(gray - 182) > 8 ? `rgb(${gray},${gray},${gray})` : null;
return color;
}
function initializeMap(){
map = L.map('webmap', {
minZoom: 3,
maxZoom: 12,
}).setView([44.191442, -69.074608], 6);
/*
osmlayer = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
minZoom: 3,
maxZoom: 13,
zoomDelta: 0.1,
// NOTE: Only use OSM tiles for dev! Use a paid provider for prod
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
})
.addTo(map);
*/
L.maplibreGL({
style: 'https://tiles.openfreemap.org/styles/liberty',
minZoom: 3,
maxZoom: 12
}).addTo(map)
var url_to_geotiff_file = "https://hillshades.us-east-1.linodeobjects.com/srtm-hillshade-web-mercator-cog-unset-q60.tif"
// from https://github.com/GeoTIFF/georaster-layer-for-leaflet-example/blob/42c4d84b8734c6747cba7a0e221fc6f6d260f6f1/examples/load-cog-via-url-param.html#L43C1-L63C12
parseGeoraster(url_to_geotiff_file).then(georaster => {
/*
GeoRasterLayer is an extension of GridLayer,
which means can use GridLayer options like opacity.
Just make sure to include the georaster option!
http://leafletjs.com/reference-1.2.0.html#gridlayer
*/
var layer = new GeoRasterLayer({
attribution: "jthatch.com SRTM hillshade",
georaster,
opacity: 0.2,
//opacity: 0.1,
pixelValuesToColorFn: hillshadecolor,
resolution: 512
});
layer.addTo(map);
layer.getContainer().classList.add('georaster-hillshade');
});
var c = map.getCenter()
var rectCorners = rectanglePoints(c.lat, c.lng,boxWidth)
rectangle = L.polygon(rectCorners, {color: 'Tomato',draggable: true}).addTo(map);
rectangle.on('dragend', postDrag)
initializeForm();
ingestURLParams();
updateSelection();
changeVScale();
changeWaterDrop();
changeBaseHeight();
map.panTo(rectangle.getLatLngs()[0][3]);
}
// set form values from any URL parameters that may be present
function ingestURLParams(){
// Get URL parameters
const urlParams = new URLSearchParams(window.location.search);
// Get form element
const form = document.getElementById('paramForm');
// If no form is found, exit
if (!form) return;
// Get all form inputs, selects, and textareas
// const formElements = form.querySelectorAll('input, select, textarea');
const formElements = form.querySelectorAll('input');
// Keep track of which update functions we'll need to call
const functionsToCall = new Set();
// Loop through all form elements
formElements.forEach(function(element) {
// Try to match by name attribute first
let paramName = element.name;
// If no name, try id attribute (removing any prefix like 'c-')
if (!paramName && element.id) {
paramName = element.id.replace(/^[a-z]-/i, '');
}
// Skip elements without a usable identifier
if (!paramName) return;
// Check if this parameter exists in the URL
if (urlParams.has(paramName)) {
// Set the value
element.value = urlParams.get(paramName);
// Trigger change event
const event = new Event('change');
element.dispatchEvent(event);
}
});
}
// Function to generate a shareable URL with modified form parameters
function createShareableURL() {
// Get the form element
const form = document.getElementById('paramForm');
if (!form) return;
// Create a new URLSearchParams object
const shareParams = new URLSearchParams();
// Get all form inputs, selects, and textareas
const formElements = form.querySelectorAll('input');
// Loop through all form elements
formElements.forEach(function(element) {
// Skip buttons and submit inputs
if (element.type === 'button' || element.type === 'submit') return;
// Get element name or ID
let paramName = element.name;
// Skip elements without a usable identifier
if (!paramName) return;
// Get current value and default value
const currentValue = element.value;
const defaultValue = element.defaultValue;
// Only add parameter if value is different from default
if (currentValue !== defaultValue) {
shareParams.append(paramName, currentValue);
}
});
// Build the URL
const url = new URL(window.location.href);
// Clear existing search parameters
url.search = '';
// Only add the search parameters if we have any
if (shareParams.toString()) {
url.search = shareParams.toString();
}
return url.href;
}
//https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript#Sending_form_data
function initializeForm() {
var form = document.getElementById("paramForm");
var downloadButton = document.getElementById("downloadbtn");
var genButton = document.getElementById("genButton");
// block the input's form "press enter to submit form" behavior
form.addEventListener("keypress", (e) => {
var key = e.key || 0;
if (key == "Enter") {
e.preventDefault();
}
})
form.addEventListener("submit", function(event) {
// Create URL-encoded form data string manually instead of jQuery serialize
const formData = new FormData(form);
const serializedData = new URLSearchParams(formData).toString();
sendData(serializedData);
event.preventDefault();
});
function sendData(str) {
genButton.classList.add("disabled");
genButton.innerHTML = "<i>Generating...</i>";
downloadButton.style.visibility = "hidden";
var XHR = new XMLHttpRequest();
// Define what happens on successful data submission
XHR.addEventListener("load", function(event) {
var modelNumber = event.target.responseText;
var modelName = "stls/terrain-" + modelNumber + ".zip";
// Make download button visible
downloadButton.style.visibility = "visible";
// Set the href attribute
downloadButton.href = modelName;
genButton.classList.remove("disabled");
genButton.innerHTML = "Generate Model";
});
// Define what happens in case of error
XHR.addEventListener("error", function(event) {
console.log('Oops! Something went wrong.');
});
// Set up our request
XHR.open("POST", "gen", true);
XHR.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// The data sent is what the user provided in the form
XHR.send(str);
}
}
function rectanglePoints(centerlat, centerlng, boxsize){
var _lat = centerlat+boxHeight/2;
var _lng = centerlng-boxWidth/2;
return [ [_lat-boxHeight, _lng],
[_lat-boxHeight, _lng+boxWidth],
[_lat, _lng+boxWidth],
[_lat, _lng],
]
}
// TODO! UPdate this to use the new function
function centerToView(){
mapCenter = map.getCenter();
var _lat = mapCenter.lat + boxHeight/2;
var _lng = mapCenter.lng - boxWidth/2;
latBox.value = _lat;
lngBox.value = _lng;
updateSelection()
/*
updateRectangle(
[ {lat: _lat-boxHeight, lng: _lng},
{lat: _lat-boxHeight, lng: _lng+boxWidth},
{lat: _lat, lng:_lng+boxWidth},
{lat: _lat, lng: _lng},
]);
*/
}
function updateRectangle(corners){
rectangle.setLatLngs(corners);
postDrag();
}
function postDrag(){ //called after rectangle is dragged
var _lat = rectangle.getLatLngs()[0][3].lat;
var _lng = rectangle.getLatLngs()[0][3].lng;
latBox.value = _lat.toFixed(4);
lngBox.value = _lng.toFixed(4);
}
function changeVScale(){
vScaleLabel.innerHTML = vScaleSlider.value;
}
function changeWaterDrop(){
waterDropLabel.innerHTML = waterDropSlider.value;
}
function changeBaseHeight(){
baseHeightLabel.innerHTML = baseHeightSlider.value;
}
function updateSelection(){
var boxScale = scaleSlider.value;
boxRotation = rotationSlider.value*Math.PI/180;
var _lat = Math.min(Math.max(parseFloat(document.getElementById('c-lat').value),-69),84);
var _lng = Math.min(Math.max(parseFloat(document.getElementById('c-lng').value),-179),180);
document.getElementById('c-lat').value = _lat;
document.getElementById('c-lng').value = _lng;
scaleLabel.innerHTML = scaleSlider.value;
rotationLabel.innerHTML = rotationSlider.value;
boxWidth=minBoxWidth*widthSlider.value*boxScale/120;
boxHeight=minBoxWidth*heightSlider.value*boxScale/120;
widthLabel.innerHTML = (widthSlider.value*boxScale /3600).toFixed(2)+"\xB0";
heightLabel.innerHTML = (heightSlider.value*boxScale/3600).toFixed(2)+"\xB0";
var base = rectangle.getLatLngs()[0][3];
var rotLat = {lat: Math.sin(boxRotation)*boxHeight,lng:Math.cos(boxRotation)*boxWidth};
var rotLng = {lat: Math.cos(boxRotation)*boxHeight, lng:Math.sin(boxRotation)*boxWidth};
if(_lat && _lng){
updateRectangle(
[ {lat: _lat+rotLat.lat, lng: _lng+rotLat.lng},
{lat: _lat+rotLat.lat-rotLng.lat, lng: _lng+rotLat.lng+rotLng.lng},
{lat: _lat-rotLng.lat, lng:_lng+rotLng.lng},
{lat: _lat, lng: _lng},
]);
}
}