forked from sevamoo/3d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
executable file
·511 lines (406 loc) · 15.1 KB
/
index.html
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
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<title>3D Earth with Mapbox GL, D3.js and Three.js</title>
<style>
html, body { margin: 0; padding: 0; overflow: hidden; }
html { background-color: #000; color: #fff; font-family: sans-serif; }
select { font: inherit; }
canvas { image-rendering: crisp-edges; image-rendering: pixelated; }
#map, #equirectangular-map { position: absolute; pointer-events: none; right: 0; opacity: 0; }
.DEBUG #map, .DEBUG #equirectangular-map { opacity: 1; }
#map { bottom: 0; transform: scale(.1); transform-origin: bottom right; }
#equirectangular-map { transform: scale(.1); transform-origin: top right; }
#options { position: absolute; top: 10px; right: 10px; z-index: 99999; text-align: right; }
#options[hidden] { display: block; opacity: .5; pointer-events: none; }
#options select, #options label { padding: .5em; display: inline-block; vertical-align: middle; }
#container canvas { vertical-align: top; }
#container > div { bottom: 0; top: auto !important; }
footer { position: absolute; bottom: 10px; right: 10px; opacity: .75; }
footer a { color: inherit; }
#loader { position: absolute; left: 10px; top: 10px; animation: fade .5s infinite ease-in-out alternate; }
@keyframes fade {
0% { opacity: .3 }
100% { opacity: 1 }
}
.fullscreen #options, .fullscreen footer { display: none; }
</style>
<div id="map"></div>
<canvas id="equirectangular-map"></canvas>
<div id="container"></div>
<div id="loader">Loading…</div>
<div id="options">
<select id="style-selector" onChange="generateMap(this.value)">
<!-- <option value="satellite">Satellite</option> -->
<option value="streets">Streets</option>
<option value="dark" selected>Dark</option>
<option value="light">Light</option>
</select>
<br>
<label><input type="checkbox" id="buildings-checkbox" onChange="toggleBuildings(this.checked)"> Buildings</label>
<br>
<!-- <label><input type="checkbox" id="roads0-checkbox" onChange="toggleRoads0(this.checked)">roads(kmh<=30)</label>
<br>
<label><input type="checkbox" id="roads1-checkbox" onChange="toggleRoads1(this.checked)">roads(30<kmh<=60)</label>
<br>
<label><input type="checkbox" id="roads2-checkbox" onChange="toggleRoads2(this.checked)">roads(60<kmh<=100)</label>
<br>
<label><input type="checkbox" id="roads3-checkbox" onChange="toggleRoads3(this.checked)">roads(100<kmh<=120)</label>
<br>
<label><input type="checkbox" id="roads4-checkbox" onChange="toggleRoads4(this.checked)">roads(kmh>120)</label>
<br> -->
<label><input type="checkbox" id="roads5-checkbox" onChange="toggleRoads5(this.checked)">Roads</label>
<br>
<label><input type="checkbox" id="city3-checkbox" onChange="toggleCities(this.checked)">Urban Centers</label>
<br>
<label><input type="checkbox" id="UHI-checkbox" onChange="toggleUHI(this.checked)">Urban Heat Islands</label>
</div>
<footer>
<a href="https://www.vahidmoosavi.com" target="_blank"><font size="1">Planetary Urban Density Project by Vahid Moosavi</font></a>
<br>
<a href="https://github.com/cheeaun/3d-earth" target="_blank"><font size="1">The original webgl framework</font></a>
</footer>
<script src="https://api.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-geo/1.6.4/d3-geo.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>
<script src="https://unpkg.com/camera-controls@0.0.6/dist/camera-controls.min.js"></script>
<script src="https://rawgit.com/mrdoob/stats.js/master/build/stats.min.js"></script>
<script>
mapboxgl.accessToken = 'pk.eyJ1Ijoic2V2YW1vbyIsImEiOiJjamUzM2N5ZWQyZms3MnJzNmJtOGprbDlkIn0.fGd1eu_9xugbpQLGemzEvw';
// mapboxgl.accessToken = 'pk.eyJ1Ijoic2V2YW1vbyIsImEiOiJjamUzM2N5ZWQyZms3MnJzNmJtOGprbDlkIn0.fGd1eu_9xugbpQLGemzEvw';
var zoom =1;
var mapWidth = 1200 * zoom;
var mapHeight = 1200 * zoom;
var DEBUG = location.hash == '#DEBUG';
var $map = document.getElementById('map');
var $eMap = document.getElementById('equirectangular-map');
var $loader = document.getElementById('loader');
var $options = document.getElementById('options');
$map.style.width = mapWidth + 'px';
$map.style.height = mapHeight + 'px';
var dpr = window.devicePixelRatio;
var width = mapWidth * dpr;
var height = mapHeight * dpr;
var halfHeight = height / 2;
$eMap.width = width;
$eMap.height = halfHeight;
// 3D stuff
var container = document.getElementById('container');
var renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true,
stencil: false,
});
renderer.setPixelRatio(dpr);
renderer.setSize(window.innerWidth, window.innerHeight);
// Fix "GL_ARB_gpu_shader5" bug: https://github.com/mrdoob/three.js/issues/9716
renderer.context.getShaderInfoLog = function(){ return '' };
container.appendChild(renderer.domElement);
// Camera
var camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.z = 500;
var CameraControls = cameraControlsFactory(THREE);
var cameraControls = new CameraControls(camera, renderer.domElement);
cameraControls.rotate(0, -1, true); // Tilt down to show North pole a bit
cameraControls.update();
// Hack cameraControls to have min & max distance
var _dolly = cameraControls.dolly;
cameraControls.dolly = function(distance, enableTransition){
var d = Math.abs(distance);
if (d < 12 || d > 60) return;
_dolly.call(cameraControls, distance, enableTransition);
}
// Scene
var scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);
// Earth
var texture = new THREE.CanvasTexture($eMap);
texture.minFilter = THREE.LinearFilter; // Fix "Textures should be of a power of two" warning
var geometry = new THREE.SphereGeometry(200, 50, 50);
var material = new THREE.MeshPhongMaterial({
overdraw: .5, // fill in the gaps between triangles
});
var earth = new THREE.Mesh(geometry, material);
scene.add(earth);
// // Roads0
// var roads0Material = new THREE.MeshLambertMaterial({
// opacity: 1.00,
// transparent: true,
// // alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
// map: THREE.ImageUtils.loadTexture( 'roads0.png' )
// });
// var roads0 = new THREE.Mesh(geometry, roads0Material);
// roads0.visible = false;
// earth.add(roads0);
// function toggleRoads0(checked){
// roads0.visible = checked;
// };
// // Roads1
// var roads1Material = new THREE.MeshLambertMaterial({
// opacity: 1.00,
// transparent: true,
// // alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
// map: THREE.ImageUtils.loadTexture( 'roads1.png' )
// });
// var roads1 = new THREE.Mesh(geometry, roads1Material);
// roads1.visible = false;
// earth.add(roads1);
// function toggleRoads1(checked){
// roads1.visible = checked;
// };
// // Roads2
// var roads2Material = new THREE.MeshLambertMaterial({
// opacity: 1.00,
// transparent: true,
// // alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
// map: THREE.ImageUtils.loadTexture( 'roads2.png' )
// });
// var roads2 = new THREE.Mesh(geometry, roads2Material);
// roads2.visible = false;
// earth.add(roads2);
// function toggleRoads2(checked){
// roads2.visible = checked;
// };
// // Roads3
// var roads3Material = new THREE.MeshLambertMaterial({
// opacity: 1.00,
// transparent: true,
// // alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
// map: THREE.ImageUtils.loadTexture( 'roads3.png' )
// });
// var roads3 = new THREE.Mesh(geometry, roads3Material);
// roads3.visible = false;
// earth.add(roads3);
// function toggleRoads3(checked){
// roads3.visible = checked;
// };
// // Roads4
// var roads4Material = new THREE.MeshLambertMaterial({
// opacity: 1.00,
// transparent: true,
// // alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
// map: THREE.ImageUtils.loadTexture( 'roads4.png' )
// });
// var roads4 = new THREE.Mesh(geometry, roads4Material);
// roads4.visible = false;
// earth.add(roads4);
// function toggleRoads4(checked){
// roads4.visible = checked;
// };
// Roads5
var roads5Material = new THREE.MeshLambertMaterial({
opacity: 1.00,
transparent: true,
// alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
map: THREE.ImageUtils.loadTexture( 'roads5.png' )
});
var roads5 = new THREE.Mesh(geometry, roads5Material);
roads5.visible = false;
earth.add(roads5);
function toggleRoads5(checked){
roads5.visible = checked;
};
//Buildings
var buildingsMaterial = new THREE.MeshLambertMaterial({
opacity: 1.00,
transparent: true,
// alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
map: THREE.ImageUtils.loadTexture( 'buildings4.png' )
});
var buildings = new THREE.Mesh(geometry, buildingsMaterial);
buildings.visible = false;
earth.add(buildings);
function toggleBuildings(checked){
buildings.visible = checked;
};
//Urban centers
// var texture = new THREE.TextureLoader().load( 'city.png' );
var citiesMaterial = new THREE.MeshLambertMaterial({
opacity: 1.00,
transparent: true,
// alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
map: THREE.ImageUtils.loadTexture( 'centers_all_.png' )
// map: texture
});
var cities = new THREE.Mesh(geometry, citiesMaterial);
cities.visible = false;
earth.add(cities);
function toggleCities(checked){
cities.visible = checked;
};
//Urban Heat Island
// var texture = new THREE.TextureLoader().load( 'city.png' );
var UHIMaterial = new THREE.MeshLambertMaterial({
opacity: 1.00,
transparent: true,
// alphaMap: THREE.ImageUtils.loadTexture( 'roads.jpg' )
map: THREE.ImageUtils.loadTexture( 'UHI_D_T_DIFF_.png' )
// map: texture
});
var UHI = new THREE.Mesh(geometry, UHIMaterial);
UHI.visible = false;
earth.add(UHI);
function toggleUHI(checked){
UHI.visible = checked;
};
// Stars
var starsGeometry = new THREE.SphereGeometry(1000);
var starsMaterial = new THREE.MeshBasicMaterial({
side: THREE.BackSide,
});
var stars = new THREE.Mesh(starsGeometry, starsMaterial);
scene.add(stars);
(new THREE.TextureLoader()).load('galaxystarfield.png', function(texture){
starsMaterial.map = texture;
});
// Light
var light = new THREE.DirectionalLight(0xffffff);
light.target = earth;
scene.add(light);
// Stats: https://github.com/mrdoob/stats.js
if (DEBUG){
var stats = new Stats();
container.appendChild(stats.domElement);
}
// Stop auto-rotating earth when dragging it
var stopRotating = false;
container.ontouchstart = container.onmousedown = function(){
stopRotating = true;
}
container.ontouchend = container.ontouchcancel = container.onmouseup = function(){
stopRotating = false;
}
window.onresize = function(){
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
const clock = new THREE.Clock();
function render(){
var delta = clock.getDelta();
cameraControls.update(delta);
if (!stopRotating){
var y = .001;
earth.rotation.y += y;
stars.rotation.y -= y/2;
}
light.position.copy(camera.position);
renderer.render(scene, camera);
}
function animate(){
requestAnimationFrame(animate);
render();
if (DEBUG) stats.update();
}
// Projections stuff
var equirectangular = d3.geoEquirectangular()
.scale(width / 2 / Math.PI)
.translate([width / 2, height * .75]);
var mercator = d3.geoMercator()
.scale(width / 2 / Math.PI)
.translate([width / 2, height / 2]);
var invert = equirectangular.invert;
var context = $eMap.getContext('2d', { alpha: false });
function generateMap(style){
console.log('Generate map: ' + style);
$options.hidden = true;
$loader.hidden = false;
var map = new mapboxgl.Map({
container: 'map',
// optimize=true -> https://blog.mapbox.com/style-optimized-vector-tiles-39868da81275
style: 'mapbox://styles/mapbox/' + style + '-v9?optimize=true',
// styel: 'mapbox://styles/sevamoo/cjmrogwk03xnz2spgpuj24gk6',
// style: 'mapbox://styles/sevamoo/cj6dfqqoy0lsi2qpi9e18qsen',
// style: 'mapbox://styles/sevamoo/cjml03d6rq5dr2rni6izdlioq',
center: [0, 0],
zoom: zoom,
interactive: false,
renderWorldCopies: false,
attributionControl: false,
trackResize: false,
preserveDrawingBuffer: true,
});
map.on('load', function(){
var canvas = map.getCanvas();
var gl = canvas.getContext('webgl', { alpha: false, antialias: false });
console.log('Map loaded');
setTimeout(function(){
console.log('Render map start');
var source = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, source);
var sourceData = new Uint8ClampedArray(source.buffer);
var targetData = new Uint8ClampedArray(sourceData.length/2).fill(255);
// This part is really slow >:(
console.time('Reprojection');
var w = width;
var h = height;
var x = 0;
var y;
for (; x < w; x++){
for (y = 0; y < h; y++){
var pixels = mercator(invert([x, y]));
if (!isNaN(pixels[1])){
var sourceIndex = 4 * (~~pixels[0] + w * ~~pixels[1]);
// Would have been x + w + h if it's not WebGL context
// (h-y-1) is to flip the Y (vertical) because WebGL texture starts at the bottom
var targetIndex = 4 * (x + w * (h-y-1));
targetData[targetIndex] = sourceData[sourceIndex];
targetData[targetIndex + 1] = sourceData[sourceIndex + 1];
targetData[targetIndex + 2] = sourceData[sourceIndex + 2];
// targetData[targetIndex + 3] = 255; // Already filled
}
}
}
console.timeEnd('Reprojection');
// $eMap.width = $eMap.width;
var target = context.createImageData(width, halfHeight);
target.data.set(targetData);
// Draw the equirectangular projection canvas
context.clearRect(0, 0, $eMap.width, $eMap.height);
context.putImageData(target, 0, 0);
// Cover the North pole
for (var y=0; y<halfHeight; y++){
var index = y * w * 4;
var firstColor = targetData[index];
if (firstColor !== 0){
var color = 'rgb(' + targetData[index] + ',' + targetData[index+1] + ',' + targetData[index+2] + ')';
context.fillStyle = color;
context.fillRect(0, 0, w, y);
break;
}
}
// Cover the South pole
for (var y=halfHeight-1; y>=0; --y){
var index = y * w * 4;
var firstColor = targetData[index];
if (firstColor !== 0){
var color = 'rgb(' + targetData[index] + ',' + targetData[index+1] + ',' + targetData[index+2] + ')';
context.fillStyle = color;
context.fillRect(0, y+1, w, halfHeight-y);
break;
}
}
console.log('Render map end');
$options.hidden = false;
$loader.hidden = true;
// Set texture on first load
if (!material.map){
material.map = texture;
material.needsUpdate = true;
animate();
}
// Update texture
texture.needsUpdate = true;
map.remove();
}, 350); // Delay for the tiles to render properly
});
};
generateMap('dark');
$options.ondblclick = $options.ongestureend = function(){
document.body.classList.toggle('fullscreen');
}
// Debugging
if (DEBUG){
document.body.className = 'DEBUG';
}
</script>