-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththree.ar.js
1620 lines (1532 loc) · 55.4 KB
/
three.ar.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
/**
* @license
* three.ar.js
* Copyright (c) 2017 Google
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @license
* gl-preserve-state
* Copyright (c) 2016, Brandon Jones.
*
* 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.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three')) :
typeof define === 'function' && define.amd ? define(['exports', 'three'], factory) :
(factory((global['three-ar'] = {}),global.THREE));
}(this, (function (exports,three) { 'use strict';
var global$1 = typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {};
var noop = function noop() {};
var opacityRemap = function opacityRemap(mat) {
if (mat.opacity === 0) {
mat.opacity = 1;
}
};
var loadObj = function loadObj(objPath, materialCreator, OBJLoader) {
return new Promise(function (resolve, reject) {
var loader = new OBJLoader();
if (materialCreator) {
Object.keys(materialCreator.materials).forEach(function (k) {
return opacityRemap(materialCreator.materials[k]);
});
loader.setMaterials(materialCreator);
}
loader.load(objPath, resolve, noop, reject);
});
};
var loadMtl = function loadMtl(mtlPath, MTLLoader) {
return new Promise(function (resolve, reject) {
var loader = new MTLLoader();
loader.setTexturePath(mtlPath.substr(0, mtlPath.lastIndexOf('/') + 1));
loader.setMaterialOptions({ ignoreZeroRGBs: true });
loader.load(mtlPath, resolve, noop, reject);
});
};
var colors = ['#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5', '#2196F3', '#03A9F4', '#00BCD4', '#009688', '#4CAF50', '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800'].map(function (hex) {
return new three.Color(hex);
});
var LEARN_MORE_LINK = 'https://developers.google.com/ar/develop/web/getting-started';
var UNSUPPORTED_MESSAGE = 'This augmented reality experience requires\n WebARonARCore or WebARonARKit, experimental browsers from Google\n for Android and iOS. Learn more at the <a href="' + LEARN_MORE_LINK + '">Google Developers site</a>.';
var ARUtils = Object.create(null);
ARUtils.isTango = function (display) {
return display && display.displayName.toLowerCase().includes('tango');
};
var isTango = ARUtils.isTango;
ARUtils.isARKit = function (display) {
return display && display.displayName.toLowerCase().includes('arkit');
};
var isARKit = ARUtils.isARKit;
ARUtils.isARDisplay = function (display) {
return isARKit(display) || isTango(display);
};
var isARDisplay = ARUtils.isARDisplay;
ARUtils.getARDisplay = function () {
return new Promise(function (resolve, reject) {
if (!navigator.getVRDisplays) {
resolve(null);
return;
}
navigator.getVRDisplays().then(function (displays) {
if (!displays && displays.length === 0) {
resolve(null);
return;
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = displays[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var display = _step.value;
if (isARDisplay(display)) {
resolve(display);
return;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
resolve(null);
});
});
};
ARUtils.loadModel = function () {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return new Promise(function (resolve, reject) {
var mtlPath = config.mtlPath,
objPath = config.objPath;
var OBJLoader = config.OBJLoader || (global$1.THREE ? global$1.THREE.OBJLoader : null);
var MTLLoader = config.MTLLoader || (global$1.THREE ? global$1.THREE.MTLLoader : null);
if (!config.objPath) {
reject(new Error('`objPath` must be specified.'));
return;
}
if (!OBJLoader) {
reject(new Error('Missing OBJLoader as third argument, or window.THREE.OBJLoader existence'));
return;
}
if (config.mtlPath && !MTLLoader) {
reject(new Error('Missing MTLLoader as fourth argument, or window.THREE.MTLLoader existence'));
return;
}
var p = Promise.resolve();
if (mtlPath) {
p = loadMtl(mtlPath, MTLLoader);
}
p.then(function (materialCreator) {
if (materialCreator) {
materialCreator.preload();
}
return loadObj(objPath, materialCreator, OBJLoader);
}).then(resolve, reject);
});
};
var model = new three.Matrix4();
var tempPos = new three.Vector3();
var tempQuat = new three.Quaternion();
var tempScale = new three.Vector3();
ARUtils.placeObjectAtHit = function (object, hit) {
var easing = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
var applyOrientation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
if (!hit || !hit.modelMatrix) {
throw new Error('placeObjectAtHit requires a VRHit object');
}
model.fromArray(hit.modelMatrix);
model.decompose(tempPos, tempQuat, tempScale);
if (easing === 1) {
object.position.copy(tempPos);
if (applyOrientation) {
object.quaternion.copy(tempQuat);
}
} else {
object.position.lerp(tempPos, easing);
if (applyOrientation) {
object.quaternion.slerp(tempQuat, easing);
}
}
};
var placeObjectAtHit = ARUtils.placeObjectAtHit;
ARUtils.getRandomPaletteColor = function () {
return colors[Math.floor(Math.random() * colors.length)];
};
var getRandomPaletteColor = ARUtils.getRandomPaletteColor;
ARUtils.displayUnsupportedMessage = function (customMessage) {
var element = document.createElement('div');
element.id = 'webgl-error-message';
element.style.fontFamily = 'monospace';
element.style.fontSize = '13px';
element.style.fontWeight = 'normal';
element.style.textAlign = 'center';
element.style.background = '#fff';
element.style.border = '1px solid black';
element.style.color = '#000';
element.style.padding = '1.5em';
element.style.width = '400px';
element.style.margin = '5em auto 0';
element.innerHTML = typeof customMessage === 'string' ? customMessage : UNSUPPORTED_MESSAGE;
document.body.appendChild(element);
};
var vertexShader = "precision mediump float;precision mediump int;uniform mat4 modelViewMatrix;uniform mat4 modelMatrix;uniform mat4 projectionMatrix;attribute vec3 position;varying vec3 vPosition;void main(){vPosition=(modelMatrix*vec4(position,1.0)).xyz;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}";
var fragmentShader = "precision highp float;varying vec3 vPosition;\n#define countX 7.0\n#define countY 4.0\n#define gridAlpha 0.75\nuniform float dotRadius;uniform vec3 dotColor;uniform vec3 lineColor;uniform vec3 backgroundColor;uniform float alpha;float Circle(in vec2 p,float r){return length(p)-r;}float Line(in vec2 p,in vec2 a,in vec2 b){vec2 pa=p-a;vec2 ba=b-a;float t=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);vec2 pt=a+t*ba;return length(pt-p);}float Union(float a,float b){return min(a,b);}void main(){vec2 count=vec2(countX,countY);vec2 size=vec2(1.0)/count;vec2 halfSize=size*0.5;vec2 uv=mod(vPosition.xz*1.5,size)-halfSize;float dots=Circle(uv-vec2(halfSize.x,0.0),dotRadius);dots=Union(dots,Circle(uv+vec2(halfSize.x,0.0),dotRadius));dots=Union(dots,Circle(uv+vec2(0.0,halfSize.y),dotRadius));dots=Union(dots,Circle(uv-vec2(0.0,halfSize.y),dotRadius));float lines=Line(uv,vec2(0.0,halfSize.y),-vec2(halfSize.x,0.0));lines=Union(lines,Line(uv,vec2(0.0,-halfSize.y),-vec2(halfSize.x,0.0)));lines=Union(lines,Line(uv,vec2(0.0,-halfSize.y),vec2(halfSize.x,0.0)));lines=Union(lines,Line(uv,vec2(0.0,halfSize.y),vec2(halfSize.x,0.0)));lines=Union(lines,Line(uv,vec2(-halfSize.x,halfSize.y),vec2(halfSize.x,halfSize.y)));lines=Union(lines,Line(uv,vec2(-halfSize.x,-halfSize.y),vec2(halfSize.x,-halfSize.y)));lines=Union(lines,Line(uv,vec2(-halfSize.x,0.0),vec2(halfSize.x,0.0)));lines=clamp(smoothstep(0.0,0.0035,lines),0.0,1.0);dots=clamp(smoothstep(0.0,0.001,dots),0.0,1.0);float result=Union(dots,lines);gl_FragColor=vec4(mix(backgroundColor+mix(dotColor,lineColor,dots),backgroundColor,result),mix(gridAlpha,alpha,result));}";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var asyncGenerator = function () {
function AwaitValue(value) {
this.value = value;
}
function AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function (resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
if (value instanceof AwaitValue) {
Promise.resolve(value.value).then(function (arg) {
resume("next", arg);
}, function (arg) {
resume("throw", arg);
});
} else {
settle(result.done ? "return" : "normal", result.value);
}
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch (type) {
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== "function") {
this.return = undefined;
}
}
if (typeof Symbol === "function" && Symbol.asyncIterator) {
AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
return this;
};
}
AsyncGenerator.prototype.next = function (arg) {
return this._invoke("next", arg);
};
AsyncGenerator.prototype.throw = function (arg) {
return this._invoke("throw", arg);
};
AsyncGenerator.prototype.return = function (arg) {
return this._invoke("return", arg);
};
return {
wrap: function (fn) {
return function () {
return new AsyncGenerator(fn.apply(this, arguments));
};
},
await: function (value) {
return new AwaitValue(value);
}
};
}();
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var DEFAULT_MATERIAL = new three.RawShaderMaterial({
side: three.DoubleSide,
transparent: true,
uniforms: {
dotColor: {
value: new three.Color(0xffffff)
},
lineColor: {
value: new three.Color(0x707070)
},
backgroundColor: {
value: new three.Color(0x404040)
},
dotRadius: {
value: 0.006666666667
},
alpha: {
value: 0.4
}
},
vertexShader: vertexShader,
fragmentShader: fragmentShader
});
var ARPlanes = function (_Object3D) {
inherits(ARPlanes, _Object3D);
function ARPlanes(vrDisplay) {
classCallCheck(this, ARPlanes);
var _this = possibleConstructorReturn(this, (ARPlanes.__proto__ || Object.getPrototypeOf(ARPlanes)).call(this));
_this.addPlane_ = function (plane) {
var planeObj = _this.createPlane(plane);
if (planeObj) {
_this.add(planeObj);
_this.planes.set(plane.identifier, planeObj);
}
};
_this.removePlane_ = function (identifier) {
var existing = _this.planes.get(identifier);
if (existing) {
_this.remove(existing);
}
_this.planes.delete(identifier);
};
_this.onPlaneAdded_ = function (event) {
event.planes.forEach(function (plane) {
return _this.addPlane_(plane);
});
};
_this.onPlaneUpdated_ = function (event) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = event.planes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var plane = _step.value;
_this.removePlane_(plane.identifier);
_this.addPlane_(plane);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
_this.onPlaneRemoved_ = function (event) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = event.planes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var plane = _step2.value;
_this.removePlane_(plane.identifier);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
};
_this.vrDisplay = vrDisplay;
_this.planes = new Map();
_this.materials = new Map();
return _this;
}
createClass(ARPlanes, [{
key: 'enable',
value: function enable() {
this.vrDisplay.getPlanes().forEach(this.addPlane_);
this.vrDisplay.addEventListener('planesadded', this.onPlaneAdded_);
this.vrDisplay.addEventListener('planesupdated', this.onPlaneUpdated_);
this.vrDisplay.addEventListener('planesremoved', this.onPlaneRemoved_);
}
}, {
key: 'disable',
value: function disable() {
this.vrDisplay.removeEventListener('planesadded', this.onPlaneAdded_);
this.vrDisplay.removeEventListener('planesupdated', this.onPlaneUpdated_);
this.vrDisplay.removeEventListener('planesremoved', this.onPlaneRemoved_);
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = this.planes.keys()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var identifier = _step3.value;
this.removePlane_(identifier);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
this.materials.clear();
}
}, {
key: 'createPlane',
value: function createPlane(plane) {
if (plane.vertices.length == 0) {
return null;
}
var geo = new three.Geometry();
for (var pt = 0; pt < plane.vertices.length / 3; pt++) {
geo.vertices.push(new three.Vector3(plane.vertices[pt * 3], plane.vertices[pt * 3 + 1], plane.vertices[pt * 3 + 2]));
}
for (var face = 0; face < geo.vertices.length - 2; face++) {
geo.faces.push(new three.Face3(0, face + 1, face + 2));
}
var material = void 0;
if (this.materials.has(plane.identifier)) {
material = this.materials.get(plane.identifier);
} else {
var color = getRandomPaletteColor();
material = DEFAULT_MATERIAL.clone();
material.uniforms.backgroundColor.value = color;
this.materials.set(plane.identifier, material);
}
var planeObj = new three.Mesh(geo, material);
var mm = plane.modelMatrix;
planeObj.matrixAutoUpdate = false;
planeObj.matrix.set(mm[0], mm[4], mm[8], mm[12], mm[1], mm[5], mm[9], mm[13], mm[2], mm[6], mm[10], mm[14], mm[3], mm[7], mm[11], mm[15]);
this.add(planeObj);
return planeObj;
}
}, {
key: 'size',
value: function size() {
return this.planes.size;
}
}]);
return ARPlanes;
}(three.Object3D);
var DEFAULTS = {
open: true,
showLastHit: true,
showPoseStatus: true,
showPlanes: false
};
var SUCCESS_COLOR = '#00ff00';
var FAILURE_COLOR = '#ff0077';
var PLANES_POLLING_TIMER = 500;
var THROTTLE_SPEED = 500;
var cachedVRDisplayMethods = new Map();
function throttle(fn, timer, scope) {
var lastFired = void 0;
var timeout = void 0;
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var current = +new Date();
var until = void 0;
if (lastFired) {
until = lastFired + timer - current;
}
if (until == undefined || until < 0) {
lastFired = current;
fn.apply(scope, args);
} else if (until >= 0) {
clearTimeout(timeout);
timeout = setTimeout(function () {
lastFired = current;
fn.apply(scope, args);
}, until);
}
};
}
var ARDebug = function () {
function ARDebug(vrDisplay, scene, config) {
classCallCheck(this, ARDebug);
if (typeof config === 'undefined' && scene && scene.type !== 'Scene') {
config = scene;
scene = null;
}
this.config = Object.assign({}, DEFAULTS, config);
this.vrDisplay = vrDisplay;
this._view = new ARDebugView({ open: this.config.open });
if (this.config.showLastHit && this.vrDisplay.hitTest) {
this._view.addRow('hit-test', new ARDebugHitTestRow(vrDisplay));
}
if (this.config.showPoseStatus && this.vrDisplay.getFrameData) {
this._view.addRow('pose-status', new ARDebugPoseRow(vrDisplay));
}
if (this.config.showPlanes && this.vrDisplay.getPlanes) {
if (!scene) {
console.warn('ARDebug `{ showPlanes: true }` option requires ' + 'passing in a THREE.Scene as the second parameter ' + 'in the constructor.');
} else {
this._view.addRow('show-planes', new ARDebugPlanesRow(vrDisplay, scene));
}
}
}
createClass(ARDebug, [{
key: 'open',
value: function open() {
this._view.open();
}
}, {
key: 'close',
value: function close() {
this._view.close();
}
}, {
key: 'getElement',
value: function getElement() {
return this._view.getElement();
}
}]);
return ARDebug;
}();
var ARDebugView = function () {
function ARDebugView() {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, ARDebugView);
this.rows = new Map();
this.el = document.createElement('div');
this.el.style.backgroundColor = '#333';
this.el.style.padding = '5px';
this.el.style.fontFamily = 'Roboto, Ubuntu, Arial, sans-serif';
this.el.style.color = 'rgb(165, 165, 165)';
this.el.style.position = 'absolute';
this.el.style.right = '20px';
this.el.style.top = '0px';
this.el.style.width = '200px';
this.el.style.fontSize = '12px';
this.el.style.zIndex = 9999;
this._rowsEl = document.createElement('div');
this._rowsEl.style.transitionProperty = 'max-height';
this._rowsEl.style.transitionDuration = '0.5s';
this._rowsEl.style.transitionDelay = '0s';
this._rowsEl.style.transitionTimingFunction = 'ease-out';
this._rowsEl.style.overflow = 'hidden';
this._controls = document.createElement('div');
this._controls.style.fontSize = '13px';
this._controls.style.fontWeight = 'bold';
this._controls.style.paddingTop = '5px';
this._controls.style.textAlign = 'center';
this._controls.style.cursor = 'pointer';
this._controls.addEventListener('click', this.toggleControls.bind(this));
config.open ? this.open() : this.close();
this.el.appendChild(this._rowsEl);
this.el.appendChild(this._controls);
}
createClass(ARDebugView, [{
key: 'toggleControls',
value: function toggleControls() {
if (this._isOpen) {
this.close();
} else {
this.open();
}
}
}, {
key: 'open',
value: function open() {
this._rowsEl.style.maxHeight = '100px';
this._isOpen = true;
this._controls.textContent = 'Close ARDebug';
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.rows[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _ref = _step.value;
var _ref2 = slicedToArray(_ref, 2);
var row = _ref2[1];
row.enable();
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}, {
key: 'close',
value: function close() {
this._rowsEl.style.maxHeight = '0px';
this._isOpen = false;
this._controls.textContent = 'Open ARDebug';
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.rows[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var _ref3 = _step2.value;
var _ref4 = slicedToArray(_ref3, 2);
var row = _ref4[1];
row.disable();
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
}, {
key: 'getElement',
value: function getElement() {
return this.el;
}
}, {
key: 'addRow',
value: function addRow(id, row) {
this.rows.set(id, row);
if (this._isOpen) {
row.enable();
}
this._rowsEl.appendChild(row.getElement());
}
}]);
return ARDebugView;
}();
var ARDebugRow = function () {
function ARDebugRow(title) {
classCallCheck(this, ARDebugRow);
this.el = document.createElement('div');
this.el.style.width = '100%';
this.el.style.borderTop = '1px solid rgb(54, 54, 54)';
this.el.style.borderBottom = '1px solid #14171A';
this.el.style.position = 'relative';
this.el.style.padding = '3px 0px';
this.el.style.overflow = 'hidden';
this._titleEl = document.createElement('span');
this._titleEl.style.fontWeight = 'bold';
this._titleEl.textContent = title;
this._dataEl = document.createElement('span');
this._dataEl.style.position = 'absolute';
this._dataEl.style.left = '40px';
this._dataElText = document.createTextNode('');
this._dataEl.appendChild(this._dataElText);
this.el.appendChild(this._titleEl);
this.el.appendChild(this._dataEl);
this._throttledWriteToDOM = throttle(this._writeToDOM, THROTTLE_SPEED, this);
}
createClass(ARDebugRow, [{
key: 'enable',
value: function enable() {
throw new Error('Implement in child class');
}
}, {
key: 'disable',
value: function disable() {
throw new Error('Implement in child class');
}
}, {
key: 'getElement',
value: function getElement() {
return this.el;
}
}, {
key: 'update',
value: function update(value, isSuccess, renderImmediately) {
if (renderImmediately) {
this._writeToDOM(value, isSuccess);
} else {
this._throttledWriteToDOM(value, isSuccess);
}
}
}, {
key: '_writeToDOM',
value: function _writeToDOM(value, isSuccess) {
this._dataElText.nodeValue = value;
this._dataEl.style.color = isSuccess ? SUCCESS_COLOR : FAILURE_COLOR;
}
}]);
return ARDebugRow;
}();
var ARDebugHitTestRow = function (_ARDebugRow) {
inherits(ARDebugHitTestRow, _ARDebugRow);
function ARDebugHitTestRow(vrDisplay) {
classCallCheck(this, ARDebugHitTestRow);
var _this = possibleConstructorReturn(this, (ARDebugHitTestRow.__proto__ || Object.getPrototypeOf(ARDebugHitTestRow)).call(this, 'Hit'));
_this.vrDisplay = vrDisplay;
_this._onHitTest = _this._onHitTest.bind(_this);
_this._nativeHitTest = cachedVRDisplayMethods.get('hitTest') || _this.vrDisplay.hitTest;
cachedVRDisplayMethods.set('hitTest', _this._nativeHitTest);
_this._didPreviouslyHit = null;
return _this;
}
createClass(ARDebugHitTestRow, [{
key: 'enable',
value: function enable() {
this.vrDisplay.hitTest = this._onHitTest;
}
}, {
key: 'disable',
value: function disable() {
this.vrDisplay.hitTest = this._nativeHitTest;
}
}, {
key: '_hitToString',
value: function _hitToString(hit) {
var mm = hit.modelMatrix;
return mm[12].toFixed(2) + ', ' + mm[13].toFixed(2) + ', ' + mm[14].toFixed(2);
}
}, {
key: '_onHitTest',
value: function _onHitTest(x, y) {
var hits = this._nativeHitTest.call(this.vrDisplay, x, y);
var t = (parseInt(performance.now(), 10) / 1000).toFixed(1);
var didHit = hits && hits.length;
var value = (didHit ? this._hitToString(hits[0]) : 'MISS') + ' @ ' + t + 's';
this.update(value, didHit, didHit !== this._didPreviouslyHit);
this._didPreviouslyHit = didHit;
return hits;
}
}]);
return ARDebugHitTestRow;
}(ARDebugRow);
var ARDebugPoseRow = function (_ARDebugRow2) {
inherits(ARDebugPoseRow, _ARDebugRow2);
function ARDebugPoseRow(vrDisplay) {
classCallCheck(this, ARDebugPoseRow);
var _this2 = possibleConstructorReturn(this, (ARDebugPoseRow.__proto__ || Object.getPrototypeOf(ARDebugPoseRow)).call(this, 'Pose'));
_this2.vrDisplay = vrDisplay;
_this2._onGetFrameData = _this2._onGetFrameData.bind(_this2);
_this2._nativeGetFrameData = cachedVRDisplayMethods.get('getFrameData') || _this2.vrDisplay.getFrameData;
cachedVRDisplayMethods.set('getFrameData', _this2._nativeGetFrameData);
_this2.update('Looking for position...', false, true);
_this2._initialPose = false;
return _this2;
}
createClass(ARDebugPoseRow, [{
key: 'enable',
value: function enable() {
this.vrDisplay.getFrameData = this._onGetFrameData;
}
}, {
key: 'disable',
value: function disable() {
this.vrDisplay.getFrameData = this._nativeGetFrameData;
}
}, {
key: '_poseToString',
value: function _poseToString(pose) {
return pose[0].toFixed(2) + ', ' + pose[1].toFixed(2) + ', ' + pose[2].toFixed(2);
}
}, {
key: '_onGetFrameData',
value: function _onGetFrameData(frameData) {
var results = this._nativeGetFrameData.call(this.vrDisplay, frameData);
var pose = frameData && frameData.pose && frameData.pose.position;
var isValidPose = pose && typeof pose[0] === 'number' && typeof pose[1] === 'number' && typeof pose[2] === 'number' && !(pose[0] === 0 && pose[1] === 0 && pose[2] === 0);
if (!this._initialPose && !isValidPose) {
return results;
}
var renderImmediately = isValidPose !== this._lastPoseValid;
if (isValidPose) {
this.update(this._poseToString(pose), true, renderImmediately);
} else if (!isValidPose && this._lastPoseValid !== false) {
this.update('Position lost', false, renderImmediately);
}
this._lastPoseValid = isValidPose;
this._initialPose = true;
return results;
}
}]);
return ARDebugPoseRow;
}(ARDebugRow);
var ARDebugPlanesRow = function (_ARDebugRow3) {