-
-
Notifications
You must be signed in to change notification settings - Fork 726
/
pannellum.js
3390 lines (3096 loc) · 113 KB
/
pannellum.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
/*
* Pannellum - An HTML5 based Panorama Viewer
* Copyright (c) 2011-2022 Matthew Petroff
*
* 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.
*/
window.pannellum = (function(window, document, undefined) {
'use strict';
/**
* Creates a new panorama viewer.
* @constructor
* @param {HTMLElement|string} container - The container (div) element for the
* viewer, or its ID.
* @param {Object} initialConfig - Initial configuration for viewer.
*/
function Viewer(container, initialConfig) {
var _this = this;
// Declare variables
var config,
renderer,
preview,
draggingHotSpot,
isUserInteracting = false,
latestInteraction = Date.now(),
onPointerDownPointerX = 0,
onPointerDownPointerY = 0,
onPointerDownPointerDist = -1,
onPointerDownYaw = 0,
onPointerDownPitch = 0,
keysDown = new Array(10),
fullscreenActive = false,
loaded,
error = false,
isTimedOut = false,
listenersAdded = false,
panoImage,
prevTime,
speed = {'yaw': 0, 'pitch': 0, 'hfov': 0},
animating = false,
orientation = false,
orientationYawOffset = 0,
autoRotateStart,
autoRotateSpeed = 0,
origHfov,
origPitch,
animatedMove = {},
externalEventListeners = {},
specifiedPhotoSphereExcludes = [],
update = false, // Should we update when still to render dynamic content
eps = 1e-6,
resizeObserver,
hotspotsCreated = false,
xhr,
destroyed = false;
var defaultConfig = {
hfov: 100,
minHfov: 50,
multiResMinHfov: false,
maxHfov: 120,
pitch: 0,
minPitch: undefined,
maxPitch: undefined,
yaw: 0,
minYaw: -180,
maxYaw: 180,
roll: 0,
haov: 360,
vaov: 180,
vOffset: 0,
autoRotate: false,
autoRotateInactivityDelay: -1,
autoRotateStopDelay: undefined,
type: 'equirectangular',
northOffset: 0,
showFullscreenCtrl: true,
dynamic: false,
dynamicUpdate: false,
doubleClickZoom: true,
keyboardZoom: true,
mouseZoom: true,
showZoomCtrl: true,
autoLoad: false,
showControls: true,
orientationOnByDefault: false,
hotSpotDebug: false,
backgroundColor: [0, 0, 0],
avoidShowingBackground: false,
animationTimingFunction: timingFunction,
draggable: true,
dragConfirm: false,
disableKeyboardCtrl: false,
crossOrigin: 'anonymous',
targetBlank: false,
touchPanSpeedCoeffFactor: 1,
capturedKeyNumbers: [16, 17, 27, 37, 38, 39, 40, 61, 65, 68, 83, 87, 107, 109, 173, 187, 189],
friction: 0.15
};
// Translatable / configurable strings
// Some strings contain '%s', which is a placeholder for inserted values
// When setting strings in external configuration, `\n` should be used instead of `<br>` to insert line breaks
defaultConfig.strings = {
// Labels
loadButtonLabel: 'Click to<br>Load<br>Panorama',
loadingLabel: 'Loading...',
bylineLabel: 'by %s', // One substitution: author
// Errors
noPanoramaError: 'No panorama image was specified.',
fileAccessError: 'The file %s could not be accessed.', // One substitution: file URL
malformedURLError: 'There is something wrong with the panorama URL.',
iOS8WebGLError: "Due to iOS 8's broken WebGL implementation, only " +
"progressive encoded JPEGs work for your device (this " +
"panorama uses standard encoding).",
genericWebGLError: 'Your browser does not have the necessary WebGL support to display this panorama.',
textureSizeError: 'This panorama is too big for your device! It\'s ' +
'%spx wide, but your device only supports images up to ' +
'%spx wide. Try another device.' +
' (If you\'re the author, try scaling down the image.)', // Two substitutions: image width, max image width
unknownError: 'Unknown error. Check developer console.',
twoTouchActivate: 'Use two fingers together to pan the panorama.',
twoTouchXActivate: 'Use two fingers together to pan the panorama horizontally.',
twoTouchYActivate: 'Use two fingers together to pan the panorama vertically.',
ctrlZoomActivate: 'Use %s + scroll to zoom the panorama.', // One substitution: key name
};
// Initialize container
container = typeof container === 'string' ? document.getElementById(container) : container;
container.classList.add('pnlm-container');
container.tabIndex = 0;
// Create container for ui
var uiContainer = document.createElement('div');
uiContainer.className = 'pnlm-ui';
container.appendChild(uiContainer);
// Create container for renderer
var renderContainer = document.createElement('div');
renderContainer.className = 'pnlm-render-container';
container.appendChild(renderContainer);
var dragFix = document.createElement('div');
dragFix.className = 'pnlm-dragfix';
uiContainer.appendChild(dragFix);
// Display about information on right click
var aboutMsg = document.createElement('span');
aboutMsg.className = 'pnlm-about-msg';
var aboutMsgLink = document.createElement('a');
aboutMsgLink.href = 'https://pannellum.org/';
aboutMsgLink.textContent = 'Pannellum';
aboutMsg.appendChild(aboutMsgLink);
var aboutMsgVersion = document.createElement('span');
// VERSION PLACEHOLDER FOR BUILD
aboutMsg.appendChild(aboutMsgVersion);
uiContainer.appendChild(aboutMsg);
dragFix.addEventListener('contextmenu', aboutMessage);
// Create info display
var infoDisplay = {};
// Hot spot debug indicator
var hotSpotDebugIndicator = document.createElement('div');
hotSpotDebugIndicator.className = 'pnlm-sprite pnlm-hot-spot-debug-indicator';
uiContainer.appendChild(hotSpotDebugIndicator);
// Panorama info
infoDisplay.container = document.createElement('div');
infoDisplay.container.className = 'pnlm-panorama-info';
infoDisplay.title = document.createElement('div');
infoDisplay.title.className = 'pnlm-title-box';
infoDisplay.container.appendChild(infoDisplay.title);
infoDisplay.author = document.createElement('div');
infoDisplay.author.className = 'pnlm-author-box';
infoDisplay.container.appendChild(infoDisplay.author);
uiContainer.appendChild(infoDisplay.container);
// Load box
infoDisplay.load = {};
infoDisplay.load.box = document.createElement('div');
infoDisplay.load.box.className = 'pnlm-load-box';
infoDisplay.load.boxp = document.createElement('p');
infoDisplay.load.box.appendChild(infoDisplay.load.boxp);
infoDisplay.load.lbox = document.createElement('div');
infoDisplay.load.lbox.className = 'pnlm-lbox';
infoDisplay.load.lbox.innerHTML = '<div class="pnlm-loading"></div>';
infoDisplay.load.box.appendChild(infoDisplay.load.lbox);
infoDisplay.load.lbar = document.createElement('div');
infoDisplay.load.lbar.className = 'pnlm-lbar';
infoDisplay.load.lbarFill = document.createElement('div');
infoDisplay.load.lbarFill.className = 'pnlm-lbar-fill';
infoDisplay.load.lbar.appendChild(infoDisplay.load.lbarFill);
infoDisplay.load.box.appendChild(infoDisplay.load.lbar);
infoDisplay.load.msg = document.createElement('p');
infoDisplay.load.msg.className = 'pnlm-lmsg';
infoDisplay.load.box.appendChild(infoDisplay.load.msg);
uiContainer.appendChild(infoDisplay.load.box);
// Error message
infoDisplay.errorMsg = document.createElement('div');
infoDisplay.errorMsg.className = 'pnlm-error-msg pnlm-info-box';
uiContainer.appendChild(infoDisplay.errorMsg);
// Interaction message
infoDisplay.interactionMsg = document.createElement('div');
infoDisplay.interactionMsg.className = 'pnlm-interaction-msg pnlm-info-box';
uiContainer.appendChild(infoDisplay.interactionMsg);
// Create controls
var controls = {};
controls.container = document.createElement('div');
controls.container.className = 'pnlm-controls-container';
uiContainer.appendChild(controls.container);
// Load button
controls.load = document.createElement('button');
controls.load.className = 'pnlm-load-button';
controls.load.addEventListener('click', function() {
processOptions();
load();
});
uiContainer.appendChild(controls.load);
// Zoom controls
controls.zoom = document.createElement('div');
controls.zoom.className = 'pnlm-zoom-controls pnlm-controls';
controls.zoomIn = document.createElement('div');
controls.zoomIn.className = 'pnlm-zoom-in pnlm-sprite pnlm-control';
controls.zoomIn.addEventListener('click', zoomIn);
controls.zoom.appendChild(controls.zoomIn);
controls.zoomOut = document.createElement('div');
controls.zoomOut.className = 'pnlm-zoom-out pnlm-sprite pnlm-control';
controls.zoomOut.addEventListener('click', zoomOut);
controls.zoom.appendChild(controls.zoomOut);
controls.container.appendChild(controls.zoom);
// Fullscreen toggle
controls.fullscreen = document.createElement('div');
controls.fullscreen.addEventListener('click', toggleFullscreen);
controls.fullscreen.className = 'pnlm-fullscreen-toggle-button pnlm-sprite pnlm-fullscreen-toggle-button-inactive pnlm-controls pnlm-control';
if (document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled)
controls.container.appendChild(controls.fullscreen);
// Device orientation toggle
controls.orientation = document.createElement('div');
controls.orientation.addEventListener('click', function(e) {
if (orientation)
stopOrientation();
else
startOrientation();
});
controls.orientation.addEventListener('mousedown', function(e) {e.stopPropagation();});
controls.orientation.addEventListener('touchstart', function(e) {e.stopPropagation();});
controls.orientation.addEventListener('pointerdown', function(e) {e.stopPropagation();});
controls.orientation.className = 'pnlm-orientation-button pnlm-orientation-button-inactive pnlm-sprite pnlm-controls pnlm-control';
var orientationSupport = false;
if (window.DeviceOrientationEvent && location.protocol == 'https:' &&
navigator.userAgent.toLowerCase().indexOf('mobi') >= 0) {
// This user agent check is here because there's no way to check if a
// device has an inertia measurement unit. We used to be able to check if a
// DeviceOrientationEvent had non-null values, but with iOS 13 requiring a
// permission prompt to access such events, this is no longer possible.
controls.container.appendChild(controls.orientation);
orientationSupport = true;
}
// Compass
var compass = document.createElement('div');
compass.className = 'pnlm-compass pnlm-controls pnlm-control';
uiContainer.appendChild(compass);
// Load and process configuration
if (initialConfig.firstScene) {
// Activate first scene if specified in URL
mergeConfig(initialConfig.firstScene);
} else if (initialConfig.default && initialConfig.default.firstScene) {
// Activate first scene if specified in file
mergeConfig(initialConfig.default.firstScene);
} else {
mergeConfig(null);
}
processOptions(true);
/**
* Initializes viewer.
* @private
*/
function init() {
// Display an error for IE 9 as it doesn't work but also doesn't otherwise
// show an error (older versions don't work at all)
// Based on: http://stackoverflow.com/a/10965203
var div = document.createElement("div");
div.innerHTML = "<!--[if lte IE 9]><i></i><![endif]-->";
if (div.getElementsByTagName("i").length == 1) {
anError();
return;
}
origHfov = config.hfov;
origPitch = config.pitch;
var i, p;
if (config.type == 'cubemap') {
panoImage = [];
for (i = 0; i < 6; i++) {
panoImage.push(new Image());
panoImage[i].crossOrigin = config.crossOrigin;
}
infoDisplay.load.lbox.style.display = 'block';
infoDisplay.load.lbar.style.display = 'none';
} else if (config.type == 'multires') {
var c = JSON.parse(JSON.stringify(config.multiRes)); // Deep copy
// Avoid "undefined" in path, check (optional) multiRes.basePath, too
// Use only multiRes.basePath if it's an absolute URL
if (config.basePath && config.multiRes.basePath &&
!(/^(?:[a-z]+:)?\/\//i.test(config.multiRes.basePath))) {
c.basePath = config.basePath + config.multiRes.basePath;
} else if (config.multiRes.basePath) {
c.basePath = config.multiRes.basePath;
} else if(config.basePath) {
c.basePath = config.basePath;
}
panoImage = c;
} else {
if (config.dynamic === true) {
panoImage = config.panorama;
} else {
if (config.panorama === undefined) {
anError(config.strings.noPanoramaError);
return;
}
panoImage = new Image();
}
}
// Configure image loading
if (config.type == 'cubemap') {
// Quick loading counter for synchronous loading
var itemsToLoad = 6;
var onLoad = function() {
itemsToLoad--;
if (itemsToLoad === 0) {
onImageLoad();
}
};
var onError = function(e) {
var a = document.createElement('a');
a.href = e.target.src;
a.textContent = a.href;
anError(config.strings.fileAccessError.replace('%s', a.outerHTML));
};
for (i = 0; i < panoImage.length; i++) {
p = config.cubeMap[i];
if (p == "null") { // support partial cubemap image with explicitly empty faces
console.log('Will use background instead of missing cubemap face ' + i);
onLoad();
} else {
if (config.basePath && !absoluteURL(p)) {
p = config.basePath + p;
}
panoImage[i].onload = onLoad;
panoImage[i].onerror = onError;
panoImage[i].src = sanitizeURL(p);
}
}
} else if (config.type == 'multires') {
onImageLoad();
} else {
p = '';
if (config.basePath) {
p = config.basePath;
}
if (config.dynamic !== true) {
// Still image
if (config.panorama instanceof Image || config.panorama instanceof ImageData ||
(window.ImageBitmap && config.panorama instanceof ImageBitmap)) {
panoImage = config.panorama;
onImageLoad();
return;
}
p = absoluteURL(config.panorama) ? config.panorama : p + config.panorama;
panoImage.onload = function() {
window.URL.revokeObjectURL(this.src); // Clean up
onImageLoad();
};
xhr = new XMLHttpRequest();
xhr.onloadend = function() {
if (xhr.status != 200) {
// Display error if image can't be loaded
var a = document.createElement('a');
a.href = p;
a.textContent = a.href;
anError(config.strings.fileAccessError.replace('%s', a.outerHTML));
return;
}
var img = this.response;
parseGPanoXMP(img, p);
infoDisplay.load.msg.innerHTML = '';
};
xhr.onprogress = function(e) {
if (e.lengthComputable) {
// Display progress
var percent = e.loaded / e.total * 100;
infoDisplay.load.lbarFill.style.width = percent + '%';
var unit, numerator, denominator;
if (e.total > 1e6) {
unit = 'MB';
numerator = (e.loaded / 1e6).toFixed(2);
denominator = (e.total / 1e6).toFixed(2);
} else if (e.total > 1e3) {
unit = 'kB';
numerator = (e.loaded / 1e3).toFixed(1);
denominator = (e.total / 1e3).toFixed(1);
} else {
unit = 'B';
numerator = e.loaded;
denominator = e.total;
}
infoDisplay.load.msg.innerHTML = numerator + ' / ' + denominator + ' ' + unit;
} else {
// Display loading spinner
infoDisplay.load.lbox.style.display = 'block';
infoDisplay.load.lbar.style.display = 'none';
}
};
try {
xhr.open('GET', p, true);
} catch (e) {
// Malformed URL
anError(config.strings.malformedURLError);
}
xhr.responseType = 'blob';
xhr.setRequestHeader('Accept', 'image/*,*/*;q=0.9');
xhr.withCredentials = config.crossOrigin === 'use-credentials';
xhr.send();
}
}
if (config.draggable)
uiContainer.classList.add('pnlm-grab');
uiContainer.classList.remove('pnlm-grabbing');
// Properly handle switching to dynamic scenes
update = config.dynamicUpdate === true;
if (config.dynamic && update) {
panoImage = config.panorama;
onImageLoad();
}
}
/**
* Test if URL is absolute or relative.
* @private
* @param {string} url - URL to test
* @returns {boolean} True if absolute, else false
*/
function absoluteURL(url) {
// From http://stackoverflow.com/a/19709846
return new RegExp('^(?:[a-z]+:)?//', 'i').test(url) || url[0] == '/' || url.slice(0, 5) == 'blob:';
}
/**
* Create renderer and initialize event listeners once image is loaded.
* @private
*/
function onImageLoad() {
if (!renderer)
renderer = new libpannellum.renderer(renderContainer);
// Only add event listeners once
if (!listenersAdded) {
listenersAdded = true;
dragFix.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('mouseup', onDocumentMouseUp, false);
if (config.mouseZoom) {
uiContainer.addEventListener('mousewheel', onDocumentMouseWheel, false);
uiContainer.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false);
}
if (config.doubleClickZoom) {
dragFix.addEventListener('dblclick', onDocumentDoubleClick, false);
}
container.addEventListener('mozfullscreenchange', onFullScreenChange, false);
container.addEventListener('webkitfullscreenchange', onFullScreenChange, false);
container.addEventListener('msfullscreenchange', onFullScreenChange, false);
container.addEventListener('fullscreenchange', onFullScreenChange, false);
if (typeof ResizeObserver === 'function') {
resizeObserver = new ResizeObserver(onDocumentResize);
resizeObserver.observe(container);
} else {
window.addEventListener('resize', onDocumentResize, false);
window.addEventListener('orientationchange', onDocumentResize, false);
}
if (!config.disableKeyboardCtrl) {
container.addEventListener('keydown', onDocumentKeyPress, false);
container.addEventListener('keyup', onDocumentKeyUp, false);
container.addEventListener('blur', clearKeys, false);
}
document.addEventListener('mouseleave', onDocumentMouseUp, false);
if (document.documentElement.style.pointerAction === '' &&
document.documentElement.style.touchAction === '') {
dragFix.addEventListener('pointerdown', onDocumentPointerDown, false);
dragFix.addEventListener('pointermove', onDocumentPointerMove, false);
dragFix.addEventListener('pointerup', onDocumentPointerUp, false);
dragFix.addEventListener('pointerleave', onDocumentPointerUp, false);
} else {
dragFix.addEventListener('touchstart', onDocumentTouchStart, false);
dragFix.addEventListener('touchmove', onDocumentTouchMove, false);
dragFix.addEventListener('touchend', onDocumentTouchEnd, false);
}
// Deal with MS pointer events
if (window.navigator.pointerEnabled)
container.style.touchAction = 'none';
}
renderInit();
setHfov(config.hfov); // Possibly adapt HFOV after configuration and canvas is complete; prevents empty space on top or bottom by zooming out too much
setTimeout(function(){isTimedOut = true;}, 500);
}
/**
* Parses Google Photo Sphere XMP Metadata.
* https://developers.google.com/photo-sphere/metadata/
* @private
* @param {Image} image - Image to read XMP metadata from.
*/
function parseGPanoXMP(image, url) {
var reader = new FileReader();
reader.addEventListener('loadend', function() {
var img = reader.result;
// This awful browser specific test exists because iOS 8 does not work
// with non-progressive encoded JPEGs.
if (navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad).* os 8_/)) {
var flagIndex = img.indexOf('\xff\xc2');
if (flagIndex < 0 || flagIndex > 65536)
anError(config.strings.iOS8WebGLError);
}
var start = img.indexOf('<x:xmpmeta');
if (start > -1 && config.ignoreGPanoXMP !== true) {
var xmpData = img.substring(start, img.indexOf('</x:xmpmeta>') + 12);
// Extract the requested tag from the XMP data
var getTag = function(tag) {
var result;
if (xmpData.indexOf(tag + '="') >= 0) {
result = xmpData.substring(xmpData.indexOf(tag + '="') + tag.length + 2);
result = result.substring(0, result.indexOf('"'));
} else if (xmpData.indexOf(tag + '>') >= 0) {
result = xmpData.substring(xmpData.indexOf(tag + '>') + tag.length + 1);
result = result.substring(0, result.indexOf('<'));
}
if (result !== undefined) {
return Number(result);
}
return null;
};
// Relevant XMP data
var xmp = {
fullWidth: getTag('GPano:FullPanoWidthPixels'),
croppedWidth: getTag('GPano:CroppedAreaImageWidthPixels'),
fullHeight: getTag('GPano:FullPanoHeightPixels'),
croppedHeight: getTag('GPano:CroppedAreaImageHeightPixels'),
topPixels: getTag('GPano:CroppedAreaTopPixels'),
heading: getTag('GPano:PoseHeadingDegrees'),
horizonPitch: getTag('GPano:PosePitchDegrees'),
horizonRoll: getTag('GPano:PoseRollDegrees'),
pitch: getTag('GPano:InitialViewPitchDegrees'),
yaw: getTag('GPano:InitialViewHeadingDegrees'),
hfov: getTag('GPano:InitialHorizontalFOVDegrees')
};
if (xmp.fullWidth !== null && xmp.croppedWidth !== null &&
xmp.fullHeight !== null && xmp.croppedHeight !== null &&
xmp.topPixels !== null) {
// Set up viewer using GPano XMP data
if (specifiedPhotoSphereExcludes.indexOf('haov') < 0)
config.haov = xmp.croppedWidth / xmp.fullWidth * 360;
if (specifiedPhotoSphereExcludes.indexOf('vaov') < 0)
config.vaov = xmp.croppedHeight / xmp.fullHeight * 180;
if (specifiedPhotoSphereExcludes.indexOf('vOffset') < 0)
config.vOffset = ((xmp.topPixels + xmp.croppedHeight / 2) / xmp.fullHeight - 0.5) * -180;
if (xmp.heading !== null && specifiedPhotoSphereExcludes.indexOf('northOffset') < 0) {
// TODO: make sure this works correctly for partial panoramas
config.northOffset = xmp.heading;
if (config.compass !== false) {
config.compass = true;
}
}
if (xmp.horizonPitch !== null && xmp.horizonRoll !== null) {
if (specifiedPhotoSphereExcludes.indexOf('horizonPitch') < 0)
config.horizonPitch = xmp.horizonPitch;
if (specifiedPhotoSphereExcludes.indexOf('horizonRoll') < 0)
config.horizonRoll = xmp.horizonRoll;
}
if (xmp.pitch != null && specifiedPhotoSphereExcludes.indexOf('pitch') < 0)
config.pitch = xmp.pitch;
if (xmp.yaw != null && specifiedPhotoSphereExcludes.indexOf('yaw') < 0)
config.yaw = xmp.yaw;
if (xmp.hfov != null && specifiedPhotoSphereExcludes.indexOf('hfov') < 0)
config.hfov = xmp.hfov;
}
}
// Load panorama
panoImage.src = window.URL.createObjectURL(image);
panoImage.onerror = function() {
// If the image fails to load, we check the Content Security Policy
// headers and see if they block loading images as blobs. If they
// do, we load the image directly from the URL. While this should
// allow the image to load, it does prevent parsing of XMP data.
function getCspHeaders() {
if (!window.fetch)
return null;
return window.fetch(document.location.href)
.then(function(resp){
return resp.headers.get('Content-Security-Policy');
});
}
getCspHeaders().then(function(cspHeaders) {
if (cspHeaders) {
var invalidImgSource = cspHeaders.split(";").find(function(p) {
var matchstring = p.match(/img-src(.*)/);
if (matchstring) {
return !matchstring[1].includes("blob");
}
});
if (invalidImgSource) {
console.log('CSP blocks blobs; reverting to URL.');
panoImage.crossOrigin = config.crossOrigin;
panoImage.src = url;
}
}
});
}
});
if (reader.readAsBinaryString !== undefined)
reader.readAsBinaryString(image);
else
reader.readAsText(image);
}
/**
* Displays an error message.
* @private
* @param {string} errorMsg - Error message to display. If not specified, a
* generic WebGL error is displayed.
*/
function anError(errorMsg) {
if (errorMsg === undefined)
errorMsg = config.strings.genericWebGLError;
infoDisplay.errorMsg.innerHTML = '<p>' + errorMsg + '</p>';
controls.load.style.display = 'none';
infoDisplay.load.box.style.display = 'none';
infoDisplay.errorMsg.style.display = 'table';
error = true;
loaded = undefined;
renderContainer.style.display = 'none';
fireEvent('error', errorMsg);
}
/**
* Hides error message display.
* @private
*/
function clearError() {
if (error) {
infoDisplay.load.box.style.display = 'none';
infoDisplay.errorMsg.style.display = 'none';
error = false;
renderContainer.style.display = 'block';
fireEvent('errorcleared');
}
}
/**
* Displays an interaction message.
* @private
* @param {string} msg - Message to display.
*/
function showInteractionMessage(interactionMsg) {
infoDisplay.interactionMsg.style.opacity = 1;
infoDisplay.interactionMsg.innerHTML = '<p>' + interactionMsg + '</p>';
infoDisplay.interactionMsg.style.display = 'table';
fireEvent('messageshown');
clearTimeout(infoDisplay.interactionMsg.timeout);
infoDisplay.interactionMsg.removeEventListener('transitionend', clearInteractionMessage);
infoDisplay.interactionMsg.timeout = setTimeout(function() {
infoDisplay.interactionMsg.style.opacity = 0;
infoDisplay.interactionMsg.addEventListener('transitionend', clearInteractionMessage);
}, 2000);
}
/**
* Hides interaction message display.
* @private
*/
function clearInteractionMessage() {
infoDisplay.interactionMsg.style.opacity = 0;
infoDisplay.interactionMsg.style.display = 'none';
fireEvent('messagecleared');
}
/**
* Displays about message.
* @private
* @param {MouseEvent} event - Right click location
*/
function aboutMessage(event) {
var pos = mousePosition(event);
aboutMsg.style.left = pos.x + 'px';
aboutMsg.style.top = pos.y + 'px';
clearTimeout(aboutMessage.t1);
clearTimeout(aboutMessage.t2);
aboutMsg.style.display = 'block';
aboutMsg.style.opacity = 1;
aboutMessage.t1 = setTimeout(function() {aboutMsg.style.opacity = 0;}, 2000);
aboutMessage.t2 = setTimeout(function() {aboutMsg.style.display = 'none';}, 2500);
event.preventDefault();
}
/**
* Calculate mouse position relative to top left of viewer container.
* @private
* @param {MouseEvent} event - Mouse event to use in calculation
* @returns {Object} Calculated X and Y coordinates
*/
function mousePosition(event) {
var bounds = container.getBoundingClientRect();
var pos = {};
// pageX / pageY needed for iOS
pos.x = (event.clientX || event.pageX) - bounds.left;
pos.y = (event.clientY || event.pageY) - bounds.top;
return pos;
}
/**
* Event handler for mouse clicks. Initializes panning. Prints center and click
* location coordinates when hot spot debugging is enabled.
* @private
* @param {MouseEvent} event - Document mouse down event.
*/
function onDocumentMouseDown(event) {
// Override default action
event.preventDefault();
// But not all of it
container.focus();
// Only do something if the panorama is loaded
if (!loaded || !config.draggable || config.draggingHotSpot) {
return;
}
// Calculate mouse position relative to top left of viewer container
var pos = mousePosition(event);
// Log pitch / yaw of mouse click when debugging / placing hot spots
if (config.hotSpotDebug) {
var coords = mouseEventToCoords(event);
console.log('Pitch: ' + coords[0] + ', Yaw: ' + coords[1] + ', Center Pitch: ' +
config.pitch + ', Center Yaw: ' + config.yaw + ', HFOV: ' + config.hfov);
}
// Turn off auto-rotation if enabled
stopAnimation();
stopOrientation();
config.roll = 0;
speed.hfov = 0;
isUserInteracting = true;
latestInteraction = Date.now();
onPointerDownPointerX = pos.x;
onPointerDownPointerY = pos.y;
onPointerDownYaw = config.yaw;
onPointerDownPitch = config.pitch;
uiContainer.classList.add('pnlm-grabbing');
uiContainer.classList.remove('pnlm-grab');
fireEvent('mousedown', event);
animateInit();
}
/**
* Event handler for double clicks. Zooms in at clicked location
* @private
* @param {MouseEvent} event - Document mouse down event.
*/
function onDocumentDoubleClick(event) {
if (config.minHfov === config.hfov) {
_this.setHfov(origHfov, 1000);
} else {
var coords = mouseEventToCoords(event);
_this.lookAt(coords[0], coords[1], config.minHfov, 1000);
}
}
/**
* Calculate panorama pitch and yaw from location of mouse event.
* @private
* @param {MouseEvent} event - Document mouse down event.
* @returns {number[]} [pitch, yaw]
*/
function mouseEventToCoords(event) {
var pos = mousePosition(event);
var canvas = renderer.getCanvas();
var canvasWidth = canvas.clientWidth,
canvasHeight = canvas.clientHeight;
var x = pos.x / canvasWidth * 2 - 1;
var y = (1 - pos.y / canvasHeight * 2) * canvasHeight / canvasWidth;
var focal = 1 / Math.tan(config.hfov * Math.PI / 360);
var s = Math.sin(config.pitch * Math.PI / 180);
var c = Math.cos(config.pitch * Math.PI / 180);
var a = focal * c - y * s;
var root = Math.sqrt(x*x + a*a);
var pitch = Math.atan((y * c + focal * s) / root) * 180 / Math.PI;
var yaw = Math.atan2(x / root, a / root) * 180 / Math.PI + config.yaw;
if (yaw < -180)
yaw += 360;
if (yaw > 180)
yaw -= 360;
return [pitch, yaw];
}
/**
* Event handler for mouse moves. Pans center of view.
* @private
* @param {MouseEvent} event - Document mouse move event.
*/
function onDocumentMouseMove(event) {
if (draggingHotSpot) {
moveHotSpot(draggingHotSpot, event);
} else if (isUserInteracting && loaded) {
latestInteraction = Date.now();
var canvas = renderer.getCanvas();
var canvasWidth = canvas.clientWidth,
canvasHeight = canvas.clientHeight;
var pos = mousePosition(event);
//TODO: This still isn't quite right
var yaw = ((Math.atan(onPointerDownPointerX / canvasWidth * 2 - 1) - Math.atan(pos.x / canvasWidth * 2 - 1)) * 180 / Math.PI * config.hfov / 90) + onPointerDownYaw;
speed.yaw = (yaw - config.yaw) % 360 * 0.2;
config.yaw = yaw;
var vfov = 2 * Math.atan(Math.tan(config.hfov/360*Math.PI) * canvasHeight / canvasWidth) * 180 / Math.PI;
var pitch = ((Math.atan(pos.y / canvasHeight * 2 - 1) - Math.atan(onPointerDownPointerY / canvasHeight * 2 - 1)) * 180 / Math.PI * vfov / 90) + onPointerDownPitch;
speed.pitch = (pitch - config.pitch) * 0.2;
config.pitch = pitch;
}
}
/**
* Event handler for mouse up events. Stops panning.
* @private
*/
function onDocumentMouseUp(event) {
if (draggingHotSpot && draggingHotSpot.dragHandlerFunc)
draggingHotSpot.dragHandlerFunc(event, draggingHotSpot.dragHandlerArgs);
draggingHotSpot = null;
if (!isUserInteracting) {
return;
}
isUserInteracting = false;
if (Date.now() - latestInteraction > 15) {
// Prevents jump when user rapidly moves mouse, stops, and then
// releases the mouse button
speed.pitch = speed.yaw = 0;
}
uiContainer.classList.add('pnlm-grab');
uiContainer.classList.remove('pnlm-grabbing');
latestInteraction = Date.now();
fireEvent('mouseup', event);
}
/**
* Event handler for touches. Initializes panning if one touch or zooming if
* two touches.
* @private
* @param {TouchEvent} event - Document touch start event.
*/
function onDocumentTouchStart(event) {
// Only do something if the panorama is loaded
if (!loaded || !config.draggable || draggingHotSpot) {
return;
}
// Turn off auto-rotation if enabled
stopAnimation();
stopOrientation();
config.roll = 0;
speed.hfov = 0;
// Calculate touch position relative to top left of viewer container
var pos0 = mousePosition(event.targetTouches[0]);
onPointerDownPointerX = pos0.x;
onPointerDownPointerY = pos0.y;
if (event.targetTouches.length == 2) {
// Down pointer is the center of the two fingers
var pos1 = mousePosition(event.targetTouches[1]);
onPointerDownPointerX += (pos1.x - pos0.x) * 0.5;
onPointerDownPointerY += (pos1.y - pos0.y) * 0.5;
onPointerDownPointerDist = Math.sqrt((pos0.x - pos1.x) * (pos0.x - pos1.x) +
(pos0.y - pos1.y) * (pos0.y - pos1.y));
}
isUserInteracting = true;
latestInteraction = Date.now();
onPointerDownYaw = config.yaw;
onPointerDownPitch = config.pitch;
fireEvent('touchstart', event);
animateInit();
}
/**
* Event handler for touch movements. Pans center of view if one touch or
* adjusts zoom if two touches.
* @private
* @param {TouchEvent} event - Document touch move event.
*/
function onDocumentTouchMove(event) {
if (!config.draggable) {
return;
}
// Override default action
if (!config.dragConfirm)
event.preventDefault();
if (loaded) {
latestInteraction = Date.now();
}
if (isUserInteracting && loaded) {
var pos0 = mousePosition(event.targetTouches[0]);
var clientX = pos0.x;
var clientY = pos0.y;
if (event.targetTouches.length == 2 && onPointerDownPointerDist != -1) {
var pos1 = mousePosition(event.targetTouches[1]);
clientX += (pos1.x - pos0.x) * 0.5;
clientY += (pos1.y - pos0.y) * 0.5;
var clientDist = Math.sqrt((pos0.x - pos1.x) * (pos0.x - pos1.x) +
(pos0.y - pos1.y) * (pos0.y - pos1.y));
setHfov(config.hfov + (onPointerDownPointerDist - clientDist) * 0.1);
onPointerDownPointerDist = clientDist;
}
// The smaller the config.hfov value (the more zoomed-in the user is), the faster
// yaw/pitch are perceived to change on one-finger touchmove (panning) events and vice versa.
// To improve usability at both small and large zoom levels (config.hfov values)
// we introduce a dynamic pan speed coefficient.
//
// Currently this seems to *roughly* keep initial drag/pan start position close to
// the user's finger while panning regardless of zoom level / config.hfov value.
var touchmovePanSpeedCoeff = (config.hfov / 360) * config.touchPanSpeedCoeffFactor;