-
Notifications
You must be signed in to change notification settings - Fork 961
/
photo-sphere-viewer.js
3042 lines (2476 loc) · 88.2 KB
/
photo-sphere-viewer.js
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
/*
* Photo Sphere Viewer v2.9
* http://jeremyheleine.me/photo-sphere-viewer
*
* Copyright (c) 2014,2015 Jérémy Heleine
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Represents a panorama viewer.
* @class
* @param {object} args - Settings to apply to the viewer
* @param {string} args.panorama - Panorama URL or path (absolute or relative)
* @param {HTMLElement|string} args.container - Panorama container (should be a `div` or equivalent), can be a string (the ID of the element to retrieve)
* @param {object} args.overlay - Image to add over the panorama
* @param {string} args.overlay.image - Image URL or path
* @param {object} [args.overlay.position=null] - Image position (default to the bottom left corner)
* @param {string} [args.overlay.position.x=null] - Horizontal image position ('left' or 'right')
* @param {string} [args.overlay.position.y=null] - Vertical image position ('top' or 'bottom')
* @param {object} [args.overlay.size=null] - Image size (if it needs to be resized)
* @param {number|string} [args.overlay.size.width=null] - Image width (in pixels or a percentage, like '20%')
* @param {number|string} [args.overlay.size.height=null] - Image height (in pixels or a percentage, like '20%')
* @param {integer} [args.segments=100] - Number of segments on the sphere
* @param {integer} [args.rings=100] - Number of rings on the sphere
* @param {boolean} [args.autoload=true] - `true` to automatically load the panorama, `false` to load it later (with the {@link PhotoSphereViewer#load|`.load`} method)
* @param {boolean} [args.usexmpdata=true] - `true` if Photo Sphere Viewer must read XMP data, `false` if it is not necessary
* @param {boolean} [args.cors_anonymous=true] - `true` to disable the exchange of user credentials via cookies, `false` otherwise
* @param {object} [args.pano_size=null] - The panorama size, if cropped (unnecessary if XMP data can be read)
* @param {number} [args.pano_size.full_width=null] - The full panorama width, before crop (the image width if `null`)
* @param {number} [args.pano_size.full_height=null] - The full panorama height, before crop (the image height if `null`)
* @param {number} [args.pano_size.cropped_width=null] - The cropped panorama width (the image width if `null`)
* @param {number} [args.pano_size.cropped_height=null] - The cropped panorama height (the image height if `null`)
* @param {number} [args.pano_size.cropped_x=null] - The cropped panorama horizontal offset relative to the full width (middle if `null`)
* @param {number} [args.pano_size.cropped_y=null] - The cropped panorama vertical offset relative to the full height (middle if `null`)
* @param {object} [args.captured_view=null] - The real captured view, compared to the theoritical 360°×180° possible view
* @param {number} [args.captured_view.horizontal_fov=360] - The horizontal captured field of view in degrees (default to 360°)
* @param {number} [args.captured_view.vertical_fov=180] - The vertical captured field of view in degrees (default to 180°)
* @param {object} [args.default_position] - Defines the default position (the first point seen by the user)
* @param {number|string} [args.default_position.long=0] - Default longitude, in radians (or in degrees if indicated, e.g. `'45deg'`)
* @param {number|string} [args.default_position.lat=0] - Default latitude, in radians (or in degrees if indicated, e.g. `'45deg'`)
* @param {number} [args.min_fov=30] - The minimal field of view, in degrees, between 1 and 179
* @param {number} [args.max_fov=90] - The maximal field of view, in degrees, between 1 and 179
* @param {boolean} [args.allow_user_interactions=true] - If set to `false`, the user won't be able to interact with the panorama (navigation bar is then disabled)
* @param {boolean} [args.allow_scroll_to_zoom=true] - It set to `false`, the user won't be able to scroll with their mouse to zoom
* @param {number} [args.zoom_speed=1] - Indicate a number greater than 1 to increase the zoom speed
* @param {number|string} [args.tilt_up_max=π/2] - The maximal tilt up angle, in radians (or in degrees if indicated, e.g. `'30deg'`)
* @param {number|string} [args.tilt_down_max=π/2] - The maximal tilt down angle, in radians (or in degrees if indicated, e.g. `'30deg'`)
* @param {number|string} [args.min_longitude=0] - The minimal longitude to show
* @param {number|string} [args.max_longitude=2π] - The maximal longitude to show
* @param {number} [args.zoom_level=0] - The default zoom level, between 0 and 100
* @param {boolean} [args.smooth_user_moves=true] - If set to `false` user moves have a speed fixed by `long_offset` and `lat_offset`
* @param {number} [args.long_offset=π/360] - The longitude to travel per pixel moved by mouse/touch
* @param {number} [args.lat_offset=π/180] - The latitude to travel per pixel moved by mouse/touch
* @param {number|string} [args.keyboard_long_offset=π/60] - The longitude to travel when the user hits the left/right arrow
* @param {number|string} [args.keyboard_lat_offset=π/120] - The latitude to travel when the user hits the up/down arrow
* @param {integer} [args.time_anim=2000] - Delay before automatically animating the panorama in milliseconds, `false` to not animate
* @param {boolean} [args.reverse_anim=true] - `true` if horizontal animation must be reversed when min/max longitude is reached (only if the whole circle is not described)
* @param {string} [args.anim_speed=2rpm] - Animation speed in radians/degrees/revolutions per second/minute
* @param {string} [args.vertical_anim_speed=2rpm] - Vertical animation speed in radians/degrees/revolutions per second/minute
* @param {number|string} [args.vertical_anim_target=0] - Latitude to target during the autorotate animation, default to the equator
* @param {boolean} [args.navbar=false] - Display the navigation bar if set to `true`
* @param {object} [args.navbar_style] - Style of the navigation bar
* @param {string} [args.navbar_style.backgroundColor=rgba(61, 61, 61, 0.5)] - Navigation bar background color
* @param {string} [args.navbar_style.buttonsColor=rgba(255, 255, 255, 0.7)] - Buttons foreground color
* @param {string} [args.navbar_style.buttonsBackgroundColor=transparent] - Buttons background color
* @param {string} [args.navbar_style.activeButtonsBackgroundColor=rgba(255, 255, 255, 0.1)] - Active buttons background color
* @param {number} [args.navbar_style.buttonsHeight=20] - Buttons height in pixels
* @param {number} [args.navbar_style.autorotateThickness=1] - Autorotate icon thickness in pixels
* @param {number} [args.navbar_style.zoomRangeWidth=50] - Zoom range width in pixels
* @param {number} [args.navbar_style.zoomRangeThickness=1] - Zoom range thickness in pixels
* @param {number} [args.navbar_style.zoomRangeDisk=7] - Zoom range disk diameter in pixels
* @param {number} [args.navbar_style.fullscreenRatio=4/3] - Fullscreen icon ratio (width/height)
* @param {number} [args.navbar_style.fullscreenThickness=2] - Fullscreen icon thickness in pixels
* @param {number} [args.eyes_offset=5] - Eyes offset in VR mode
* @param {string} [args.loading_msg=Loading…] - Loading message
* @param {string} [args.loading_img=null] - Loading image URL or path (absolute or relative)
* @param {HTMLElement|string} [args.loading_html=null] - An HTML loader (element to append to the container or string representing the HTML)
* @param {object} [args.size] - Final size of the panorama container (e.g. {width: 500, height: 300})
* @param {(number|string)} [args.size.width] - Final width in percentage (e.g. `'50%'`) or pixels (e.g. `500` or `'500px'`) ; default to current width
* @param {(number|string)} [args.size.height] - Final height in percentage or pixels ; default to current height
* @param {PhotoSphereViewer~onReady} [args.onready] - Function called once the panorama is ready and the first image is displayed
**/
var PhotoSphereViewer = function(args) {
/**
* Detects whether canvas is supported.
* @private
* @return {boolean} `true` if canvas is supported, `false` otherwise
**/
var isCanvasSupported = function() {
var canvas = document.createElement('canvas');
return !!(canvas.getContext && canvas.getContext('2d'));
};
/**
* Detects whether WebGL is supported.
* @private
* @return {boolean} `true` if WebGL is supported, `false` otherwise
**/
var isWebGLSupported = function() {
var canvas = document.createElement('canvas');
return !!(window.WebGLRenderingContext && canvas.getContext('webgl'));
};
/**
* Attaches an event handler function to an element.
* @private
* @param {HTMLElement} elt - The element
* @param {string} evt - The event name
* @param {function} f - The handler function
* @return {void}
**/
var addEvent = function(elt, evt, f) {
if (!!elt.addEventListener)
elt.addEventListener(evt, f, false);
else
elt.attachEvent('on' + evt, f);
};
/**
* Ensures that a number is in a given interval.
* @private
* @param {number} x - The number to check
* @param {number} min - First endpoint
* @param {number} max - Second endpoint
* @return {number} The checked number
**/
var stayBetween = function(x, min, max) {
return Math.max(min, Math.min(max, x));
};
/**
* Calculates the distance between two points (square of the distance is enough).
* @private
* @param {number} x1 - First point horizontal coordinate
* @param {number} y1 - First point vertical coordinate
* @param {number} x2 - Second point horizontal coordinate
* @param {number} y2 - Second point vertical coordinate
* @return {number} Square of the wanted distance
**/
var dist = function(x1, y1, x2, y2) {
var x = x2 - x1;
var y = y2 - y1;
return x*x + y*y;
};
/**
* Returns the measure of an angle (between 0 and 2π).
* @private
* @param {number} angle - The angle to reduce
* @param {boolean} [is_2pi_allowed=false] - Can the measure be equal to 2π?
* @return {number} The wanted measure
**/
var getAngleMeasure = function(angle, is_2pi_allowed) {
is_2pi_allowed = (is_2pi_allowed !== undefined) ? !!is_2pi_allowed : false;
return (is_2pi_allowed && angle == 2 * Math.PI) ? 2 * Math.PI : angle - Math.floor(angle / (2.0 * Math.PI)) * 2.0 * Math.PI;
};
/**
* Starts to load the panorama.
* @public
* @return {void}
**/
this.load = function() {
container.innerHTML = '';
// Loading HTML: HTMLElement
if (!!loading_html && loading_html.nodeType === 1)
container.appendChild(loading_html);
// Loading HTML: string
else if (!!loading_html && typeof loading_html == 'string')
container.innerHTML = loading_html;
// Loading image
else if (!!loading_img) {
var loading = document.createElement('img');
loading.setAttribute('src', loading_img);
loading.setAttribute('alt', loading_msg);
container.appendChild(loading);
}
// Loading text
else
container.textContent = loading_msg;
// Adds a new container
root = document.createElement('div');
root.style.width = '100%';
root.style.height = '100%';
root.style.position = 'relative';
root.style.overflow = 'hidden';
// Is canvas supported?
if (!isCanvasSupported()) {
container.textContent = 'Canvas is not supported, update your browser!';
return;
}
// Is Three.js loaded?
if (window.THREE === undefined) {
console.log('PhotoSphereViewer: Three.js is not loaded.');
return;
}
// Current viewer size
viewer_size = {
width: 0,
height: 0,
ratio: 0
};
// XMP data?
if (readxmp && !panorama.match(/^data:image\/[a-z]+;base64/))
loadXMP();
else
createBuffer();
};
/**
* Returns Google's XMP data.
* @private
* @param {string} file - Binary file
* @return {string} The data
**/
var getXMPData = function(file) {
var a = 0, b = 0;
var data = '';
while ((a = file.indexOf('<x:xmpmeta', b)) != -1 && (b = file.indexOf('</x:xmpmeta>', a)) != -1) {
data = file.substring(a, b);
if (data.indexOf('GPano:') != -1)
return data;
}
return '';
};
/**
* Returns the value of a given attribute in the panorama metadata.
* @private
* @param {string} data - The panorama metadata
* @param {string} attr - The wanted attribute
* @return {string} The value of the attribute
**/
var getAttribute = function(data, attr) {
var a = data.indexOf('GPano:' + attr) + attr.length + 8, b = data.indexOf('"', a);
if (b == -1) {
// XML-Metadata
a = data.indexOf('GPano:' + attr) + attr.length + 7;
b = data.indexOf('<', a);
}
return data.substring(a, b);
};
/**
* Loads the XMP data with AJAX.
* @private
* @return {void}
**/
var loadXMP = function() {
var xhr = null;
if (window.XMLHttpRequest)
xhr = new XMLHttpRequest();
else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else {
container.textContent = 'XHR is not supported, update your browser!';
return;
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Metadata
var data = getXMPData(xhr.responseText);
if (!data.length) {
createBuffer();
return;
}
// Useful values
pano_size = {
full_width: parseInt(getAttribute(data, 'FullPanoWidthPixels')),
full_height: parseInt(getAttribute(data, 'FullPanoHeightPixels')),
cropped_width: parseInt(getAttribute(data, 'CroppedAreaImageWidthPixels')),
cropped_height: parseInt(getAttribute(data, 'CroppedAreaImageHeightPixels')),
cropped_x: parseInt(getAttribute(data, 'CroppedAreaLeftPixels')),
cropped_y: parseInt(getAttribute(data, 'CroppedAreaTopPixels')),
};
recalculate_coords = true;
createBuffer();
}
};
xhr.open('GET', panorama, true);
xhr.send(null);
};
/**
* Creates an image in the right dimensions.
* @private
* @return {void}
**/
var createBuffer = function() {
var img = new Image();
img.onload = function() {
// Must the pano size be changed?
var default_pano_size = {
full_width: img.width,
full_height: img.height,
cropped_width: img.width,
cropped_height: img.height,
cropped_x: null,
cropped_y: null
};
// Captured view?
if (captured_view.horizontal_fov != 360 || captured_view.vertical_fov != 180) {
// The indicated view is the cropped panorama
pano_size.cropped_width = default_pano_size.cropped_width;
pano_size.cropped_height = default_pano_size.cropped_height;
pano_size.full_width = default_pano_size.full_width;
pano_size.full_height = default_pano_size.full_height;
// Horizontal FOV indicated
if (captured_view.horizontal_fov != 360) {
var rh = captured_view.horizontal_fov / 360.0;
pano_size.full_width = pano_size.cropped_width / rh;
}
// Vertical FOV indicated
if (captured_view.vertical_fov != 180) {
var rv = captured_view.vertical_fov / 180.0;
pano_size.full_height = pano_size.cropped_height / rv;
}
}
else {
// Cropped panorama: dimensions defined by the user
for (var attr in pano_size) {
if (pano_size[attr] === null && default_pano_size[attr] !== undefined)
pano_size[attr] = default_pano_size[attr];
}
// Do we have to recalculate the coordinates?
if (recalculate_coords) {
if (pano_size.cropped_width != default_pano_size.cropped_width) {
var rx = default_pano_size.cropped_width / pano_size.cropped_width;
pano_size.cropped_width = default_pano_size.cropped_width;
pano_size.full_width *= rx;
pano_size.cropped_x *= rx;
}
if (pano_size.cropped_height != default_pano_size.cropped_height) {
var ry = default_pano_size.cropped_height / pano_size.cropped_height;
pano_size.cropped_height = default_pano_size.cropped_height;
pano_size.full_height *= ry;
pano_size.cropped_y *= ry;
}
}
}
// Middle if cropped_x/y is null
if (pano_size.cropped_x === null)
pano_size.cropped_x = (pano_size.full_width - pano_size.cropped_width) / 2;
if (pano_size.cropped_y === null)
pano_size.cropped_y = (pano_size.full_height - pano_size.cropped_height) / 2;
// Size limit for mobile compatibility
var max_width = 2048;
if (isWebGLSupported()) {
var canvas_tmp = document.createElement('canvas');
var ctx_tmp = canvas_tmp.getContext('webgl');
max_width = ctx_tmp.getParameter(ctx_tmp.MAX_TEXTURE_SIZE);
}
// Buffer width (not too big)
var new_width = Math.min(pano_size.full_width, max_width);
var r = new_width / pano_size.full_width;
pano_size.full_width = new_width;
pano_size.cropped_width *= r;
pano_size.cropped_x *= r;
img.width = pano_size.cropped_width;
// Buffer height (proportional to the width)
pano_size.full_height *= r;
pano_size.cropped_height *= r;
pano_size.cropped_y *= r;
img.height = pano_size.cropped_height;
// Buffer creation
var buffer = document.createElement('canvas');
buffer.width = pano_size.full_width;
buffer.height = pano_size.full_height;
var ctx = buffer.getContext('2d');
ctx.drawImage(img, pano_size.cropped_x, pano_size.cropped_y, pano_size.cropped_width, pano_size.cropped_height);
loadTexture(buffer.toDataURL('image/jpeg'));
};
// CORS when the panorama is not given as a base64 string
if (cors_anonymous && !panorama.match(/^data:image\/[a-z]+;base64/))
img.setAttribute('crossOrigin', 'anonymous');
img.src = panorama;
};
/**
* Loads the sphere texture.
* @private
* @param {string} path - Path to the panorama
* @return {void}
**/
var loadTexture = function(path) {
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader();
var onLoad = function(img) {
texture.needsUpdate = true;
texture.image = img;
createScene(texture);
};
loader.load(path, onLoad);
};
/**
* Creates the 3D scene.
* @private
* @param {THREE.Texture} texture - The sphere texture
* @return {void}
**/
var createScene = function(texture) {
// New size?
if (new_viewer_size.width !== undefined)
container.style.width = new_viewer_size.width.css;
if (new_viewer_size.height !== undefined)
container.style.height = new_viewer_size.height.css;
fitToContainer();
// The chosen renderer depends on whether WebGL is supported or not
renderer = (isWebGLSupported()) ? new THREE.WebGLRenderer() : new THREE.CanvasRenderer();
renderer.setSize(viewer_size.width, viewer_size.height);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(PSV_FOV_MAX, viewer_size.ratio, 1, 300);
camera.position.set(0, 0, 0);
scene.add(camera);
// Sphere
var geometry = new THREE.SphereGeometry(200, rings, segments);
var material = new THREE.MeshBasicMaterial({map: texture, overdraw: true});
var mesh = new THREE.Mesh(geometry, material);
mesh.scale.x = -1;
scene.add(mesh);
// Canvas container
canvas_container = document.createElement('div');
canvas_container.style.position = 'absolute';
canvas_container.style.zIndex = 0;
root.appendChild(canvas_container);
// Navigation bar?
if (display_navbar) {
navbar.setStyle(navbar_style);
navbar.create();
root.appendChild(navbar.getBar());
}
// Overlay?
if (overlay !== null) {
// Add the image
var overlay_img = document.createElement('img');
overlay_img.onload = function() {
overlay_img.style.display = 'block';
// Image position
overlay_img.style.position = 'absolute';
overlay_img.style[overlay.position.x] = '5px';
overlay_img.style[overlay.position.y] = '5px';
if (overlay.position.y == 'bottom' && display_navbar)
overlay_img.style.bottom = (navbar.getBar().offsetHeight + 5) + 'px';
// Should we resize the image?
if (overlay.size !== undefined) {
overlay_img.style.width = overlay.size.width;
overlay_img.style.height = overlay.size.height;
}
root.appendChild(overlay_img);
};
overlay_img.src = overlay.image;
}
// Adding events
addEvent(window, 'resize', fitToContainer);
if (user_interactions_allowed) {
addEvent(canvas_container, 'mousedown', onMouseDown);
addEvent(document, 'mousemove', onMouseMove);
addEvent(canvas_container, 'mousemove', showNavbar);
addEvent(document, 'mouseup', onMouseUp);
addEvent(canvas_container, 'touchstart', onTouchStart);
addEvent(document, 'touchend', onMouseUp);
addEvent(document, 'touchmove', onTouchMove);
if (scroll_to_zoom) {
addEvent(canvas_container, 'mousewheel', onMouseWheel);
addEvent(canvas_container, 'DOMMouseScroll', onMouseWheel);
}
self.addAction('fullscreen-mode', toggleArrowKeys);
}
addEvent(document, 'fullscreenchange', fullscreenToggled);
addEvent(document, 'mozfullscreenchange', fullscreenToggled);
addEvent(document, 'webkitfullscreenchange', fullscreenToggled);
addEvent(document, 'MSFullscreenChange', fullscreenToggled);
sphoords.addListener(onDeviceOrientation);
// First render
container.innerHTML = '';
container.appendChild(root);
var canvas = renderer.domElement;
canvas.style.display = 'block';
canvas_container.appendChild(canvas);
render();
// Zoom?
if (zoom_lvl > 0)
zoom(zoom_lvl);
// Animation?
anim();
/**
* Indicates that the loading is finished: the first image is rendered
* @callback PhotoSphereViewer~onReady
**/
triggerAction('ready');
};
/**
* Renders an image.
* @private
* @return {void}
**/
var render = function() {
var point = new THREE.Vector3();
point.setX(Math.cos(lat) * Math.sin(long));
point.setY(Math.sin(lat));
point.setZ(Math.cos(lat) * Math.cos(long));
camera.lookAt(point);
// Stereo?
if (stereo_effect !== null)
stereo_effect.render(scene, camera);
else
renderer.render(scene, camera);
};
/**
* Starts the stereo effect.
* @private
* @return {void}
**/
var startStereo = function() {
stereo_effect = new THREE.StereoEffect(renderer);
stereo_effect.eyeSeparation = eyes_offset;
stereo_effect.setSize(viewer_size.width, viewer_size.height);
startDeviceOrientation();
enableFullscreen();
navbar.mustBeHidden();
render();
/**
* Indicates that the stereo effect has been toggled.
* @callback PhotoSphereViewer~onStereoEffectToggled
* @param {boolean} enabled - `true` if stereo effect is enabled, `false` otherwise
**/
triggerAction('stereo-effect', true);
};
/**
* Stops the stereo effect.
* @private
* @return {void}
**/
var stopStereo = function() {
stereo_effect = null;
renderer.setSize(viewer_size.width, viewer_size.height);
navbar.mustBeHidden(false);
render();
triggerAction('stereo-effect', false);
};
/**
* Toggles the stereo effect (virtual reality).
* @public
* @return {void}
**/
this.toggleStereo = function() {
if (stereo_effect !== null)
stopStereo();
else
startStereo();
};
/**
* Automatically animates the panorama.
* @private
* @return {void}
**/
var anim = function() {
if (anim_delay !== false)
anim_timeout = setTimeout(startAutorotate, anim_delay);
};
/**
* Automatically rotates the panorama.
* @private
* @return {void}
**/
var autorotate = function() {
lat -= (lat - anim_lat_target) * anim_lat_offset;
long += anim_long_offset;
var again = true;
if (!whole_circle) {
long = stayBetween(long, PSV_MIN_LONGITUDE, PSV_MAX_LONGITUDE);
if (long == PSV_MIN_LONGITUDE || long == PSV_MAX_LONGITUDE) {
// Must we reverse the animation or simply stop it?
if (reverse_anim)
anim_long_offset *= -1;
else {
stopAutorotate();
again = false;
}
}
}
long = getAngleMeasure(long, true);
triggerAction('position-updated', {
longitude: long,
latitude: lat
});
render();
if (again)
autorotate_timeout = setTimeout(autorotate, PSV_ANIM_TIMEOUT);
};
/**
* Starts the autorotate animation.
* @private
* @return {void}
**/
var startAutorotate = function() {
autorotate();
/**
* Indicates that the autorotate animation state has changed.
* @callback PhotoSphereViewer~onAutorotateChanged
* @param {boolean} enabled - `true` if animation is enabled, `false` otherwise
**/
triggerAction('autorotate', true);
};
/**
* Stops the autorotate animation.
* @private
* @return {void}
**/
var stopAutorotate = function() {
clearTimeout(anim_timeout);
anim_timeout = null;
clearTimeout(autorotate_timeout);
autorotate_timeout = null;
triggerAction('autorotate', false);
};
/**
* Launches/stops the autorotate animation.
* @public
* @return {void}
**/
this.toggleAutorotate = function() {
clearTimeout(anim_timeout);
if (!!autorotate_timeout)
stopAutorotate();
else
startAutorotate();
};
/**
* Resizes the canvas to make it fit the container.
* @private
* @return {void}
**/
var fitToContainer = function() {
if (container.clientWidth != viewer_size.width || container.clientHeight != viewer_size.height) {
resize({
width: container.clientWidth,
height: container.clientHeight
});
}
};
/**
* Resizes the canvas to make it fit the container.
* @public
* @return {void}
**/
this.fitToContainer = function() {
fitToContainer();
};
/**
* Resizes the canvas.
* @private
* @param {object} size - New dimensions
* @param {number} [size.width] - The new canvas width (default to previous width)
* @param {number} [size.height] - The new canvas height (default to previous height)
* @return {void}
**/
var resize = function(size) {
viewer_size.width = (size.width !== undefined) ? parseInt(size.width) : viewer_size.width;
viewer_size.height = (size.height !== undefined) ? parseInt(size.height) : viewer_size.height;
viewer_size.ratio = viewer_size.width / viewer_size.height;
if (!!camera) {
camera.aspect = viewer_size.ratio;
camera.updateProjectionMatrix();
}
if (!!renderer) {
renderer.setSize(viewer_size.width, viewer_size.height);
render();
}
if (!!stereo_effect) {
stereo_effect.setSize(viewer_size.width, viewer_size.height);
render();
}
};
/**
* Returns the current position in radians
* @return {object} A longitude/latitude couple
**/
this.getPosition = function() {
return {
longitude: long,
latitude: lat
};
};
/**
* Returns the current position in degrees
* @return {object} A longitude/latitude couple
**/
this.getPositionInDegrees = function() {
return {
longitude: long * 180.0 / Math.PI,
latitude: lat * 180.0 / Math.PI
};
};
/**
* Moves to a specific position
* @private
* @param {number|string} longitude - The longitude of the targeted point
* @param {number|string} latitude - The latitude of the targeted point
* @return {void}
**/
var moveTo = function(longitude, latitude) {
var long_tmp = parseAngle(longitude);
if (!whole_circle)
long_tmp = stayBetween(long_tmp, PSV_MIN_LONGITUDE, PSV_MAX_LONGITUDE);
var lat_tmp = parseAngle(latitude);
if (lat_tmp > Math.PI)
lat_tmp -= 2 * Math.PI;
lat_tmp = stayBetween(lat_tmp, PSV_TILT_DOWN_MAX, PSV_TILT_UP_MAX);
long = long_tmp;
lat = lat_tmp;
/**
* Indicates that the position has been modified.
* @callback PhotoSphereViewer~onPositionUpdateed
* @param {object} position - The new position
* @param {number} position.longitude - The longitude in radians
* @param {number} position.latitude - The latitude in radians
**/
triggerAction('position-updated', {
longitude: long,
latitude: lat
});
render();
};
/**
* Moves to a specific position
* @public
* @param {number|string} longitude - The longitude of the targeted point
* @param {number|string} latitude - The latitude of the targeted point
* @return {void}
**/
this.moveTo = function(longitude, latitude) {
moveTo(longitude, latitude);
};
/**
* Rotates the view
* @private
* @param {number|string} dlong - The rotation to apply horizontally
* @param {number|string} dlat - The rotation to apply vertically
* @return {void}
**/
var rotate = function(dlong, dlat) {
dlong = parseAngle(dlong);
dlat = parseAngle(dlat);
moveTo(long + dlong, lat + dlat);
};
/**
* Rotates the view
* @public
* @param {number|string} dlong - The rotation to apply horizontally
* @param {number|string} dlat - The rotation to apply vertically
* @return {void}
**/
this.rotate = function(dlong, dlat) {
rotate(dlong, dlat);
};
/**
* Attaches or detaches the keyboard events
* @private
* @param {boolean} attach - `true` to attach the event, `false` to detach it
* @return {void}
**/
var toggleArrowKeys = function(attach) {
var action = (attach) ? window.addEventListener : window.removeEventListener;
action('keydown', keyDown);
};
/**
* Tries to standardize the code sent by a keyboard event
* @private
* @param {KeyboardEvent} evt - The event
* @return {string} The code
**/
var retrieveKey = function(evt) {
// The Holy Grail
if (evt.key) {
var key = (/^Arrow/.test(evt.key)) ? evt.key : 'Arrow' + evt.key;
return key;
}
// Deprecated but still used
if (evt.keyCode || evt.which) {
var key_code = (evt.keyCode) ? evt.keyCode : evt.which;
var keycodes_map = {
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
37: 'ArrowLeft'
};
if (keycodes_map[key_code] !== undefined)
return keycodes_map[key_code];
}
// :/
return '';
};
/**
* Rotates the view through keyboard arrows
* @private
* @param {KeyboardEvent} evt - The event
* @return {void}
**/
var keyDown = function(evt) {
var dlong = 0, dlat = 0;
switch (retrieveKey(evt)) {
case 'ArrowUp':
dlat = PSV_KEYBOARD_LAT_OFFSET;
break;
case 'ArrowRight':