-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathshovel.html
836 lines (549 loc) · 23 KB
/
shovel.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
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
<!DOCTYPE html>
<html translate="no">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TunnelSimulator — Shovel Attachment</title>
<style>
* {
overflow: hidden
}
html {
background: black;
color: white;
}
canvas {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
z-index: -1;
}
</style>
</head>
<body>
<div class="app" data-geolocation="unlocated"></div>
<canvas class="canvas"></canvas>
<button class="find">Get my location</button>
<button class="track">Enable motion sensor</button>
<pre></pre>
<!-- https://unpkg.com/browse/[email protected]/build/three.min.js -->
<script src="js/three.min.js"></script>
<!-- https://unpkg.com/browse/[email protected]/examples/js/controls/OrbitControls.js -->
<script src="js/OrbitControls.js"></script>
<!-- https://unpkg.com/[email protected]/examples/js/renderers/CSS2DRenderer.js -->
<script src="js/CSS2DRenderer.js"></script>
<!-- Custom -->
<script>
let app = {
options : {
firstPerson : true
},
element : document.querySelector( '.app' ),
elements : {
canvas : document.querySelector( '.canvas' ),
trackButton : document.querySelector( '.track' ),
findButton : document.querySelectorAll( '.find' ),
},
data : {
orientation : {
alpha : 0,
beta : 0,
gamma : 0,
},
earth : {
radius : {
crust : 6371
}
},
user : {
latitude : 0,
longitude : 0
},
// user : {
// latitude : -33,
// longitude : -71
// },
// user : {
// latitude : -23.5475,
// longitude : -46.63611
// },
load : () => {
// Gets countries geometries
fetch( './assets/countries-lo.json' )
.then( response => response.json() )
.then( json => {
app.data.countries = json;
app.initialize();
} );
}
},
three : {
renderer : undefined,
camera : undefined,
scene : undefined,
controls : undefined,
raycaster : undefined,
tunnel : undefined, // Group
cylinder : undefined,
chord : undefined,
land : undefined, // Group
countries : undefined,
earth : undefined, // Group
sphere : undefined,
create : {
cylinder : () => {
let geometry = new THREE.CylinderGeometry(
app.data.earth.radius.crust / 20,
app.data.earth.radius.crust / 20,
app.data.earth.radius.crust * 2,
6,
32
);
// Rotates around end, not center
geometry.translate( 0, -app.data.earth.radius.crust, 0);
let material = new THREE.MeshBasicMaterial( {
color: 0xff0000,
wireframe: true,
opacity: 1,
transparent: true
} );
app.three.cylinder = new THREE.Mesh( geometry, material );
// Moves the beggining of the cylinder from Earth’s center to the surface, at latitude 0 and longitude 0
app.three.cylinder.position.y = app.data.earth.radius.crust;
},
chord : () => {
// Creates line from one side of Earth to the other
let points = [
new THREE.Vector3( 0, app.data.earth.radius.crust, 0 ),
new THREE.Vector3( 0, -app.data.earth.radius.crust, 0 )
];
let geometry = new THREE.BufferGeometry().setFromPoints( points );
// Rotates around end, not center
geometry.translate( 0, -app.data.earth.radius.crust, 0);
let material = new THREE.LineBasicMaterial( { color: 0x00ffff } );
app.three.chord = new THREE.Line( geometry, material );
// Moves the beggining of the cylinder from Earth’s center to the surface, at latitude 0 and longitude 0
app.three.chord.position.y = app.data.earth.radius.crust;
// Hides chord
// app.three.chord.visible = false;
},
tunnel : () => {
app.three.tunnel = new THREE.Group();
app.three.tunnel.add(
app.three.cylinder,
app.three.chord,
);
},
sphere : () => {
// Could be replaced by this for asthethic reasons:
// https://unpkg.com/[email protected]/example/graticules/index.html
// Applies satellite texture for debugging
// let texture = new THREE.TextureLoader().load( 'https://vsueiro.com/tunnel-simulator/assets/texture.jpg' );
let geometry = new THREE.SphereGeometry(
app.data.earth.radius.crust * 0.99,
16,
16
);
// Rotates sphere so default location is at latitude 0 and longitude 0
geometry.rotateX( THREE.Math.degToRad( -90 ) );
geometry.rotateZ( THREE.Math.degToRad( 90 ) );
let material = new THREE.MeshBasicMaterial( {
color : 'white',
wireframe: true,
opacity : .1,
transparent : true
} );
// Allows raycaster to detect collision on both sides of the object
material.side = THREE.DoubleSide;
app.three.sphere = new THREE.Mesh( geometry, material );
},
land : () => {
// Creates Land group
app.three.land = new THREE.Group();
// Increases country scale
app.three.land.scale.set(
app.data.earth.radius.crust,
app.data.earth.radius.crust,
app.data.earth.radius.crust
);
// Rotates sphere so default location is at latitude 0 and longitude 0
app.three.land.rotation.x = THREE.Math.degToRad( -90 );
app.three.land.rotation.y = THREE.Math.degToRad( 180 );
},
map3DGeometry : function( data ) {
THREE.Geometry.call (this);
// data.vertices = [lat, lon, ...]
// data.polygons = [[poly indices, hole i-s, ...], ...]
// data.triangles = [tri i-s, ...]
let i, uvs = [];
for (i = 0; i < data.vertices.length; i += 2) {
let lon = data.vertices[i];
let lat = data.vertices[i + 1];
// Colatitude
let phi = +(90 - lat) * 0.01745329252;
// Azimuthal angle
let the = +(180 - lon) * 0.01745329252;
// Translates into XYZ coordinates
let wx = Math.sin (the) * Math.sin (phi) * -1;
let wz = Math.cos (the) * Math.sin (phi);
let wy = Math.cos (phi);
// Equirectangular projection
let wu = 0.25 + lon / 360.0;
let wv = 0.5 + lat / 180.0;
this.vertices.push (new THREE.Vector3 (wx, wy, wz));
uvs.push (new THREE.Vector2 (wu, wv));
}
let n = this.vertices.length;
for (i = 0; i < n; i++) {
let v = this.vertices[i];
this.vertices.push (v.clone ().multiplyScalar (0));
}
for (i = 0; i < data.triangles.length; i += 3) {
let a = data.triangles[i];
let b = data.triangles[i + 1];
let c = data.triangles[i + 2];
this.faces.push( new THREE.Face3( a, b, c, [ this.vertices[a], this.vertices[b], this.vertices[c] ] ) );
this.faceVertexUvs[ 0 ].push( [ uvs[ a ], uvs[ b ], uvs[ c ] ]);
}
this.computeFaceNormals ();
this.boundingSphere = new THREE.Sphere( new THREE.Vector3 (), 1 );
},
countries : ( json ) => {
// Uses data and logic based on this repository:
// https://github.com/makc/makc.github.io/tree/master/three.js/map2globe
app.three.create.map3DGeometry.prototype = Object.create( THREE.Geometry.prototype );
let countries = app.data.countries;
for ( let name in countries ) {
let geometry = new app.three.create.map3DGeometry( countries[ name ] );
// Duplicates every face of the geometry
let faces = [];
for ( let face of geometry.faces ) {
let newFace = face.clone();
newFace.materialIndex = 1;
faces.push( newFace );
}
// Adds the newly cloned face to array of original faces
for ( let face of faces )
geometry.faces.push( face );
// Creates list of two materials
let materials = [
// Internal-facing color
new THREE.MeshBasicMaterial( { color: 0x666666 } ),
// External-facing color
new THREE.MeshBasicMaterial( { color: 0xcccccc } ),
];
materials[ 0 ].side = THREE.BackSide;
materials[ 1 ].side = THREE.FrontSide;
// Groups all countries within the `land` group
app.three.land.add( countries[ name ].mesh = new THREE.Mesh( geometry, materials ) );
// Assigns country name to mesh (to be retrieved by raycaster collision)
countries[ name ].mesh.name = name;
}
},
earth : () => {
app.three.earth = new THREE.Group();
app.three.earth.add(
app.three.sphere,
app.three.land
);
},
universe : () => {
app.three.universe = new THREE.Group();
app.three.universe.add(
app.three.tunnel,
app.three.earth,
);
// Rotates all elements so Earth poles are on the Y axis
app.three.universe.rotation.x = THREE.Math.degToRad( 90 );
},
renderer : () => {
// Creates renderer with transparent background
app.three.renderer = new THREE.WebGLRenderer( {
canvas : app.elements.canvas,
alpha : true,
logarithmicDepthBuffer: true // prevents z fighting
} );
},
camera : () => {
// Creates camera
app.three.camera = new THREE.PerspectiveCamera( 50, 1, .1, app.data.earth.radius.crust * 30 );
app.three.camera.position.z = app.data.earth.radius.crust * 3;
},
controls : () => {
// Makes camera move with mouse
app.three.controls = new THREE.OrbitControls(
app.three.camera,
app.elements.canvas
);
// Makes camera move automatically and with inertia
app.three.controls.enableDamping = true;
app.three.controls.enableZoom = false;
app.three.controls.enablePan = false;
},
scene : () => {
// Creates scene
app.three.scene = new THREE.Scene();
app.three.scene.add(
app.three.universe
);
},
raycaster : () => {
// Creates line to be used for collision check with countries
app.three.raycaster = new THREE.Raycaster();
}
},
initialize : () => {
// Creates Tunnel group
app.three.create.cylinder();
app.three.create.chord();
app.three.create.tunnel();
// Creates Land group
app.three.create.land();
app.three.create.countries();
// Creates Earth group
app.three.create.sphere();
app.three.create.earth();
// Creates Universe group
app.three.create.universe();
// Creates standard objects
app.three.create.renderer();
app.three.create.camera();
app.three.create.controls();
app.three.create.scene();
app.three.create.raycaster();
// Debugs axes
app.three.scene.add( new THREE.AxesHelper( 1000 ) );
// Animates 3D elements
requestAnimationFrame( app.three.render );
},
update : {
dimensions : () => {
let c = app.elements.canvas;
// If canvas dimensions are different from window dimensios
if ( c.width !== c.clientWidth || c.height !== c.clientHeight ) {
// Resizes canvas
app.three.renderer.setSize(
c.clientWidth,
c.clientHeight,
false
);
// Updates camera accordingly
app.three.camera.aspect = c.clientWidth / c.clientHeight;
app.three.camera.updateProjectionMatrix();
}
},
tunnel : () => {
// Enables first-person view
if ( app.options.firstPerson ) {
// Rotates Earth to always match real-world North
app.three.earth.rotation.y = THREE.Math.degToRad( app.data.orientation.alpha * -1 );
// Rotates tunnel only on two axes
app.three.cylinder.rotation.x = THREE.Math.degToRad( app.data.orientation.beta );
app.three.cylinder.rotation.z = THREE.Math.degToRad( app.data.orientation.gamma );
app.three.chord.rotation.x = THREE.Math.degToRad( app.data.orientation.beta );
app.three.chord.rotation.z = THREE.Math.degToRad( app.data.orientation.gamma );
app.three.tunnel.rotation.y = THREE.Math.degToRad( 0 );
// // Deactivates camera controls
app.three.controls.enabled = false;
// Resets camera position
app.three.camera.position.set( 0, 0, app.data.earth.radius.crust * 3 );
app.three.camera.lookAt( new THREE.Vector3( 0, 0, 0 ) );
} else { // Enables third-person view
// Keeps Earth still
app.three.earth.rotation.y = THREE.Math.degToRad( 0 );
// Rotates tunnel on all axes
app.three.cylinder.rotation.x = THREE.Math.degToRad( app.data.orientation.beta );
app.three.tunnel.rotation.y = THREE.Math.degToRad( app.data.orientation.alpha );
app.three.cylinder.rotation.z = THREE.Math.degToRad( app.data.orientation.gamma );
// Activates camera controls
app.three.controls.enabled = true;
}
},
coordinates : () => {
// Rotates sphere so the user location coincides with the tunnel beginning
app.three.sphere.rotation.x = THREE.Math.degToRad( app.data.user.latitude );
app.three.sphere.rotation.z = THREE.Math.degToRad( app.data.user.longitude );
// Rotates countries so the user location coincides with the tunnel beginning
app.three.land.rotation.x = THREE.Math.degToRad( -90 + app.data.user.latitude );
app.three.land.rotation.y = THREE.Math.degToRad( 180 + ( app.data.user.longitude * -1 ) );
},
raycaster : () => {
// Gets position & direction of chord (center of tunnel)
let chordPosition = app.three.chord.geometry.getAttribute( 'position' );
// Converts local position to world position
let vertexOrigin = new THREE.Vector3();
vertexOrigin.fromBufferAttribute( chordPosition, 0 );
let vertexDestination = new THREE.Vector3();
vertexDestination.fromBufferAttribute( chordPosition, 1 );
let worldOrigin = app.three.chord.localToWorld( vertexOrigin );
let worldDestination = app.three.chord.localToWorld( vertexDestination );
let chordDirection = worldDestination.sub(worldOrigin).normalize();
// Makes raycaster match the position and angle of the tunnel
app.three.raycaster.set( worldOrigin, chordDirection );
},
collision : () => {
let matches = [];
let found = {};
// Checks collision of chord (tunnel center) with every country
for ( let country of app.three.land.children ) {
let intersections = app.three.raycaster.intersectObject( country );
// If ray instersects with anything
if ( intersections.length > 0 ) {
for ( let intersection of intersections )
matches.push( intersection )
}
}
// Identifies origin and destination countries
for ( let match of matches ) {
if ( match.distance < 100 ) {
// Found origin
found.origin = true;
// Sets this country as origin
app.element.dataset.origin = match.object.name;
}
if ( match.distance > 1000 ) {
// Found destination
found.destination = true;
// Sets this country as destination
app.element.dataset.destination = match.object.name;
app.element.dataset.distance = match.distance;
}
}
if ( !found.origin ) {
// Calculates distance until crust on the other side
let intersections = app.three.raycaster.intersectObject( app.three.sphere );
// If ray instersects with anything
if ( intersections.length > 0 ) {
// Gets farthest intersection
intersection = intersections[ intersections.length -1 ]
// Stores distance
app.element.dataset.distance = intersection.distance;
}
}
}
},
render : ( time ) => {
// Makes canvas responsive
app.three.update.dimensions();
// Controls tunnel using motion sensor
app.three.update.tunnel();
// Rotates Earth or Tunnel to match origin latitude and longitude
app.three.update.coordinates();
// Updates raycaster position to match chord’s
app.three.update.raycaster();
// Identifies origin country and destination country
app.three.update.collision();
// Makes camera orbit
app.three.controls.update();
// Updates text labels on screen
app.labels.update();
app.three.renderer.render(
app.three.scene,
app.three.camera
);
// Enables recursion (this function calls itself to draw frames of 3D animation)
requestAnimationFrame( app.three.render );
},
},
orientation : {
handle : () => {
// Implements world-based calibration on iOS (alpha is 0 when pointing North), based on:
// https://www.w3.org/2008/geolocation/wiki/images/e/e0/Device_Orientation_%27alpha%27_Calibration-_Implementation_Status_and_Challenges.pdf
let north, offset;
// If alpha is absolute (0 points North)
if ( event.absolute === true ) {
// Uses incoming value
north = event.alpha;
} else { // If alpha is relative
// Calibrates alpha to make it North-based
offset = event.webkitCompassHeading || 0;
north = 360 - offset;
if ( north < 0 )
north += 360;
}
// Prints values for debugging
let pre = document.querySelector( 'pre' )
pre.textContent = ''
pre.textContent += 'origin: ' + ( app.element.dataset.origin || '' ) + '\n';
pre.textContent += 'destination: ' + ( app.element.dataset.destination || '' ) + '\n';
pre.textContent += 'distance: ' + ( app.element.dataset.distance || '' ) + '\n';
pre.textContent += '\n';
pre.textContent += 'north: ' + north.toFixed(2) + '\n';
pre.textContent += 'alpha: ' + event.alpha.toFixed(2) + '\n';
pre.textContent += 'beta: ' + event.beta.toFixed(2) + '\n';
pre.textContent += 'gamma: ' + event.gamma.toFixed(2) + '\n';
pre.textContent += '\n';
pre.textContent += 'absolute: ' + event.absolute;
pre.textContent += '\n';
pre.textContent += 'compass: ' + event.webkitCompassHeading + '\n';
// Updates values to be used by render method
app.data.orientation.alpha = north;
app.data.orientation.beta = event.beta;
app.data.orientation.gamma = event.gamma * -1;
},
request : () => {
// Requests permission for iOS 13+ devices
if ( DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === 'function' ) {
DeviceMotionEvent.requestPermission()
.then( response => {
if ( response == 'granted' ) {
// Enables orientationControl
// app.options.orientationControl = true;
// app.steps.next()
window.addEventListener( 'deviceorientation', app.orientation.handle );
}
} );
}
}
},
geolocation : {
success : ( position ) => {
app.element.dataset.geolocation = 'located';
app.data.user.latitude = position.coords.latitude;
app.data.user.longitude = position.coords.longitude;
},
error : () => {
app.element.dataset.geolocation = 'unlocated';
window.alert( 'Unable to find your location.' );
},
request : () => {
app.element.dataset.geolocation = 'locating';
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(
app.geolocation.success,
app.geolocation.error
);
} else {
app.geolocation.error();
}
}
},
labels : {
update : () => {
let output = document.querySelector( '.output' );
// 'A tunnel in this direction would lead'
// output.textContent =
}
},
events : {
initialize : () => {
// Tracks phone’s orientation when clicked
app.elements.trackButton.addEventListener( 'click', app.orientation.request, true );
// Finds user’s location when button is clicked
app.elements.findButton.forEach( button => button.addEventListener( 'click', app.geolocation.request ) );
}
},
initialize : () => {
app.three.initialize();
app.events.initialize();
}
}
app.data.load();
</script>
</body>
</html>