-
Notifications
You must be signed in to change notification settings - Fork 67
/
ARKitWrapper.js
1352 lines (1220 loc) · 41.4 KB
/
ARKitWrapper.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
import EventHandlerBase from '../fill/EventHandlerBase.js'
import * as glMatrix from "../fill/gl-matrix/common.js";
import * as mat4 from "../fill/gl-matrix/mat4.js";
import * as quat from "../fill/gl-matrix/quat.js";
import * as vec3 from "../fill/gl-matrix/vec3.js";
import base64 from "../fill/base64-binary.js";
import Quaternion from '../fill/Quaternion.js';
import MatrixMath from '../fill/MatrixMath.js';
/*
ARKitWrapper talks to Apple ARKit, as exposed by Mozilla's test ARDemo app.
It won't function inside a browser like Firefox.
ARKitWrapper is a singleton. Use ARKitWrapper.GetOrCreate() to get the instance, then add event listeners like so:
if(ARKitWrapper.HasARKit()){
let arKitWrapper = ARKitWrapper.GetOrCreate()
arKitWrapper.addEventListener(ARKitWrapper.INIT_EVENT, ev => { console.log('ARKit initialized', ev) })
arKitWrapper.addEventListener(ARKitWrapper.WATCH_EVENT, ev => { console.log('ARKit update', ev) })
arKitWrapper.watch({
location: boolean,
camera: boolean,
objects: boolean,
light_intensity: boolean
})
}
*/
export default class ARKitWrapper extends EventHandlerBase {
constructor(){
super()
if(ARKitWrapper.HasARKit() === false){
throw 'ARKitWrapper will only work in Mozilla\'s ARDemo test app'
}
if(typeof ARKitWrapper.GLOBAL_INSTANCE !== 'undefined'){
throw 'ARKitWrapper is a singleton. Use ARKitWrapper.GetOrCreate() to get the global instance.'
}
this._deviceId = null
this._isWatching = false
this._isInitialized = false
this._rawARData = null
// worker to convert buffers
// var blobURL = this._buildWorkerBlob()
// this._worker = new Worker(blobURL);
// URL.revokeObjectURL(blobURL);
// var self = this;
// this._worker.onmessage = function (ev) {
// setTimeout(function () {
// self.dispatchEvent(
// new CustomEvent(
// ARKitWrapper.COMPUTER_VISION_DATA,
// {
// source: self,
// detail: ev.data
// }
// )
// )
// })
// }
this.lightIntensity = 1000;
/**
* The current projection matrix of the device.
* @type {Float32Array}
* @private
*/
this.projectionMatrix_ = new Float32Array(16);
/**
* The current view matrix of the device.
* @type {Float32Array}
* @private
*/
this.viewMatrix_ = new Float32Array(16);
/**
* The list of planes coming from ARKit.
* @type {Map<number, ARPlane}
* @private
*/
this.planes_ = new Map();
this.anchors_ = new Map();
this._timeOffsets = []
this._timeOffset = 0;
this._timeOffsetComputed = false;
this.timestamp = 0;
this.worldMappingStatus = ARKitWrapper.WEB_AR_WORLDMAPPING_NOT_AVAILABLE;
this._globalCallbacksMap = {} // Used to map a window.arkitCallback method name to an ARKitWrapper.on* method name
// Set up the window.arkitCallback methods that the ARKit bridge depends on
let callbackNames = ['onInit', 'onWatch']
for(let i=0; i < callbackNames.length; i++){
this._generateGlobalCallback(callbackNames[i], i)
}
// default options for initializing ARKit
this._defaultOptions = {
location: true,
camera: true,
objects: true,
light_intensity: true,
computer_vision_data: false
}
this._m90 = mat4.fromZRotation(mat4.create(), 90*MatrixMath.PI_OVER_180);
this._m90neg = mat4.fromZRotation(mat4.create(), -90*MatrixMath.PI_OVER_180);
this._m180 = mat4.fromZRotation(mat4.create(), 180*MatrixMath.PI_OVER_180);
this._mTemp = mat4.create();
// temp storage for CV arraybuffers
//this._ab = []
// Set up some named global methods that the ARKit to JS bridge uses and send out custom events when they are called
let eventCallbacks = [
['arkitStartRecording', ARKitWrapper.RECORD_START_EVENT],
['arkitStopRecording', ARKitWrapper.RECORD_STOP_EVENT],
['arkitDidMoveBackground', ARKitWrapper.DID_MOVE_BACKGROUND_EVENT],
['arkitWillEnterForeground', ARKitWrapper.WILL_ENTER_FOREGROUND_EVENT],
['arkitInterrupted', ARKitWrapper.INTERRUPTED_EVENT],
['arkitInterruptionEnded', ARKitWrapper.INTERRUPTION_ENDED_EVENT],
['arkitShowDebug', ARKitWrapper.SHOW_DEBUG_EVENT],
['arkitWindowResize', ARKitWrapper.WINDOW_RESIZE_EVENT],
['onError', ARKitWrapper.ON_ERROR],
['arTrackingChanged', ARKitWrapper.AR_TRACKING_CHANGED],
['userGrantedComputerVisionData', ARKitWrapper.USER_GRANTED_COMPUTER_VISION_DATA],
['userGrantedWorldSensingData', ARKitWrapper.USER_GRANTED_WORLD_SENSING_DATA]
//,['onComputerVisionData', ARKitWrapper.COMPUTER_VISION_DATA]
]
for(let i=0; i < eventCallbacks.length; i++){
window[eventCallbacks[i][0]] = (detail) => {
detail = detail || null
try {
this.dispatchEvent(
new CustomEvent(
eventCallbacks[i][1],
{
source: this,
detail: detail
}
)
)
} catch(e) {
console.error(eventCallbacks[i][0] + ' callback error', e)
}
}
}
/*
* Computer vision needs massaging
*/
window['onComputerVisionData'] = (detail) => {
this._onComputerVisionData(detail);
}
window['setNativeTime'] = (detail) => {
this._timeOffsets.push (( performance || Date ).now() - detail.nativeTime)
this._timeOffsetComputed = true;
this._timeOffset = 0;
for (var i = 0; i < this._timeOffsets.length; i++) {
this._timeOffset += this._timeOffsets[i];
}
this._timeOffset = this._timeOffset / this._timeOffsets.length;
console.log("Native time: " + detail.nativeTime + ", new timeOffset: " + this._timeOffset)
}
this._adjustARKitTime = function(time) {
// if (!this._timeOffsetComputed && adjust) {
// this._timeOffsetComputed = true;
// this._timeOffset = ( performance || Date ).now() - time;
// }
if (this._timeOffsetComputed) {
return time + this._timeOffset;
} else {
return ( performance || Date ).now()
}
}
/**
* The result of a raycast into the AR world encoded as a transform matrix.
* This structure has a single property - modelMatrix - which encodes the
* translation of the intersection of the hit in the form of a 4x4 matrix.
* @constructor
*/
function VRHit() {
this.modelMatrix = new Float32Array(16);
return this;
};
var self = this;
/**
* Get an iterable of plane objects representing ARKit's current understanding of the world.
* @return {iterator<Object>} The iterable of plane objects.
*/
this.getPlanes = function() {
return Array.from(this.planes_.values());
};
/**
* Get intersection array with planes ARKit detected for the screen coords.
*
* @param {number} x The x coordinate in normalized screen space [0,1].
* @param {number} y The y coordinate in normalized screen space [0,1].
*
* @return {!Array<VRHit>} The array of hits sorted based on distance.
*/
this.hitTestNoAnchor = (function() {
/**
* Cached vec3, mat4, and quat structures needed for the hit testing to
* avoid generating garbage.
* @type {Object}
*/
var hitVars = {
rayStart: vec3.create(),
rayEnd: vec3.create(),
cameraPosition: vec3.create(),
cameraQuaternion: quat.create(),
modelViewMatrix: mat4.create(),
projectionMatrix: mat4.create(),
projViewMatrix: mat4.create(),
worldRayStart: vec3.create(),
worldRayEnd: vec3.create(),
worldRayDir: vec3.create(),
planeMatrix: mat4.create(),
planeExtent: vec3.create(),
planePosition: vec3.create(),
planeCenter: vec3.create(),
planeNormal: vec3.create(),
planeIntersection: vec3.create(),
planeIntersectionLocal: vec3.create(),
planeHit: mat4.create(),
planeQuaternion: quat.create()
};
/**
* Sets the given mat4 from the given float[16] array.
*
* @param {!mat4} m The mat4 to populate with values.
* @param {!Array<number>} a The source array of floats (must be size 16).
*/
var setMat4FromArray = function(m, a) {
mat4.set(
m,
a[0],
a[1],
a[2],
a[3],
a[4],
a[5],
a[6],
a[7],
a[8],
a[9],
a[10],
a[11],
a[12],
a[13],
a[14],
a[15]
);
};
/**
* Tests whether the given ray intersects the given plane.
*
* @param {!vec3} planeNormal The normal of the plane.
* @param {!vec3} planePosition Any point on the plane.
* @param {!vec3} rayOrigin The origin of the ray.
* @param {!vec3} rayDirection The direction of the ray (normalized).
* @return {number} The t-value of the intersection (-1 for none).
*/
var rayIntersectsPlane = (function() {
var rayToPlane = vec3.create();
return function(planeNormal, planePosition, rayOrigin, rayDirection) {
// assuming vectors are all normalized
var denom = vec3.dot(planeNormal, rayDirection);
vec3.subtract(rayToPlane, planePosition, rayOrigin);
return vec3.dot(rayToPlane, planeNormal) / denom;
};
})();
/**
* Sorts based on the distance from the VRHits to the camera.
*
* @param {!VRHit} a The first hit to compare.
* @param {!VRHit} b The second hit item to compare.
* @returns {number} -1 if a is closer than b, otherwise 1.
*/
var sortFunction = function(a, b) {
// Get the matrix of hit a.
setMat4FromArray(hitVars.planeMatrix, a.modelMatrix);
// Get the translation component of a's matrix.
mat4.getTranslation(hitVars.planeIntersection, hitVars.planeMatrix);
// Get the distance from the intersection point to the camera.
var distA = vec3.distance(
hitVars.planeIntersection,
hitVars.cameraPosition
);
// Get the matrix of hit b.
setMat4FromArray(hitVars.planeMatrix, b.modelMatrix);
// Get the translation component of b's matrix.
mat4.getTranslation(hitVars.planeIntersection, hitVars.planeMatrix);
// Get the distance from the intersection point to the camera.
var distB = vec3.distance(
hitVars.planeIntersection,
hitVars.cameraPosition
);
// Return comparison of distance from camera to a and b.
return distA < distB ? -1 : 1;
};
return function(x, y) {
// Coordinates must be in normalized screen space.
if (x < 0 || x > 1 || y < 0 || y > 1) {
throw new Error(
"hitTest - x and y values must be normalized [0,1]!")
;
}
var hits = [];
// If there are no anchors detected, there will be no hits.
var planes = this.getPlanes();
if (!planes || planes.length == 0) {
return hits;
}
// Create a ray in screen space for the hit test ([-1, 1] with y flip).
vec3.set(hitVars.rayStart, 2 * x - 1, 2 * (1 - y) - 1, 0);
vec3.set(hitVars.rayEnd, 2 * x - 1, 2 * (1 - y) - 1, 1);
// Set the projection matrix.
setMat4FromArray(hitVars.projectionMatrix, self.projectionMatrix_);
// Set the model view matrix.
setMat4FromArray(hitVars.modelViewMatrix, self.viewMatrix_);
// Combine the projection and model view matrices.
mat4.multiply(
hitVars.projViewMatrix,
hitVars.projectionMatrix,
hitVars.modelViewMatrix
);
// Invert the combined matrix because we need to go from screen -> world.
mat4.invert(hitVars.projViewMatrix, hitVars.projViewMatrix);
// Transform the screen-space ray start and end to world-space.
vec3.transformMat4(
hitVars.worldRayStart,
hitVars.rayStart,
hitVars.projViewMatrix
);
vec3.transformMat4(
hitVars.worldRayEnd,
hitVars.rayEnd,
hitVars.projViewMatrix
);
// Subtract start from end to get the ray direction and then normalize.
vec3.subtract(
hitVars.worldRayDir,
hitVars.worldRayEnd,
hitVars.worldRayStart
);
vec3.normalize(hitVars.worldRayDir, hitVars.worldRayDir);
// Go through all the anchors and test for intersections with the ray.
for (var i = 0; i < planes.length; i++) {
var plane = planes[i];
// Get the anchor transform.
setMat4FromArray(hitVars.planeMatrix, plane.modelMatrix);
// Get the position of the anchor in world-space.
vec3.set(
hitVars.planeCenter,
plane.center.x,
plane.center.y,
plane.center.z
);
vec3.transformMat4(
hitVars.planePosition,
hitVars.planeCenter,
hitVars.planeMatrix
);
hitVars.planeAlignment = plane.alignment
// Get the plane normal.
if (hitVars.planeAlignment === 0) {
vec3.set(hitVars.planeNormal, 0, 1, 0);
} else {
vec3.set(hitVars.planeNormal, hitVars.planeMatrix[4], hitVars.planeMatrix[5], hitVars.planeMatrix[6]);
}
// Check if the ray intersects the plane.
var t = rayIntersectsPlane(
hitVars.planeNormal,
hitVars.planePosition,
hitVars.worldRayStart,
hitVars.worldRayDir
);
// if t < 0, there is no intersection.
if (t < 0) {
continue;
}
// Calculate the actual intersection point.
vec3.scale(hitVars.planeIntersection, hitVars.worldRayDir, t);
vec3.add(
hitVars.planeIntersection,
hitVars.worldRayStart,
hitVars.planeIntersection
);
// Get the plane extents (extents are in plane local space).
vec3.set(hitVars.planeExtent, plane.extent[0], 0, plane.extent[1]);
/*
///////////////////////////////////////////////
// Test by converting extents to world-space.
// TODO: get this working to avoid matrix inversion in method below.
// Get the rotation component of the anchor transform.
mat4.getRotation(hitVars.planeQuaternion, hitVars.planeMatrix);
// Convert the extent into world space.
vec3.transformQuat(
hitVars.planeExtent, hitVars.planeExtent, hitVars.planeQuaternion);
// Check if intersection is outside of the extent of the anchor.
if (Math.abs(hitVars.planeIntersection[0] - hitVars.planePosition[0]) > hitVars.planeExtent[0] / 2) {
continue;
}
if (Math.abs(hitVars.planeIntersection[2] - hitVars.planePosition[2]) > hitVars.planeExtent[2] / 2) {
continue;
}
////////////////////////////////////////////////
*/
////////////////////////////////////////////////
mat4.getRotation(hitVars.planeQuaternion, hitVars.planeMatrix)
// Test by converting intersection into plane-space.
mat4.invert(hitVars.planeMatrix, hitVars.planeMatrix);
vec3.transformMat4(
hitVars.planeIntersectionLocal,
hitVars.planeIntersection,
hitVars.planeMatrix
);
// Check if intersection is outside of the extent of the anchor.
// Tolerance is added to match the behavior of the native hitTest call.
var tolerance = 0.0075;
if (
Math.abs(hitVars.planeIntersectionLocal[0]) >
hitVars.planeExtent[0] / 2 + tolerance
) {
continue;
}
if (
Math.abs(hitVars.planeIntersectionLocal[2]) >
hitVars.planeExtent[2] / 2 + tolerance
) {
continue;
}
////////////////////////////////////////////////
// The intersection is valid - create a matrix from hit position.
//mat4.fromTranslation(hitVars.planeHit, hitVars.planeIntersection);
mat4.fromRotationTranslation(hitVars.planeHit, hitVars.planeQuaternion, hitVars.planeIntersection);
var hit = new VRHit();
for (var j = 0; j < 16; j++) {
hit.modelMatrix[j] = hitVars.planeHit[j];
}
hit.i = i;
hits.push(hit);
}
// Sort the hits by distance.
hits.sort(sortFunction);
return hits;
};
})();
}
static GetOrCreate(options=null){
if(typeof ARKitWrapper.GLOBAL_INSTANCE === 'undefined'){
ARKitWrapper.GLOBAL_INSTANCE = new ARKitWrapper()
options = (options && typeof(options) == 'object') ? options : {}
let defaultUIOptions = {
browser: true,
points: true,
focus: false,
rec: true,
rec_time: true,
mic: false,
build: false,
plane: true,
warnings: true,
anchors: false,
debug: true,
statistics: false
}
let uiOptions = (typeof(options.ui) == 'object') ? options.ui : {}
options.ui = Object.assign(defaultUIOptions, uiOptions)
ARKitWrapper.GLOBAL_INSTANCE._sendInit(options)
}
return ARKitWrapper.GLOBAL_INSTANCE
}
static HasARKit(){
return typeof window.webkit !== 'undefined'
}
get deviceId(){ return this._deviceId } // The ARKit provided device ID
get isWatching(){ return this._isWatching } // True if ARKit is sending frame data
get isInitialized(){ return this._isInitialized } // True if this instance has received the onInit callback from ARKit
get hasData(){ return this._rawARData !== null } // True if this instance has received data via onWatch
/*
Useful for waiting for or immediately receiving notice of ARKit initialization
*/
waitForInit(){
return new Promise((resolve, reject) => {
if(this._isInitialized){
resolve()
return
}
const callback = () => {
this.removeEventListener(ARKitWrapper.INIT_EVENT, callback, false)
resolve()
}
this.addEventListener(ARKitWrapper.INIT_EVENT, callback, false)
})
}
/*
getData looks into the most recent ARKit data (as received by onWatch) for a key
returns the key's value or null if it doesn't exist or if a key is not specified it returns all data
*/
getData(key=null){
if (key === null){
return this._rawARData
}
if(this._rawARData && typeof this._rawARData[key] !== 'undefined'){
return this._rawARData[key]
}
return null
}
/*
returns
{
uuid: DOMString,
transform: [4x4 column major affine transform]
}
return null if object with `uuid` is not found
*/
getObject(uuid){
if (!this._isInitialized){
return null
}
const objects = this.getKey('objects')
if(objects === null) return null
for(const object of objects){
if(object.uuid === uuid){
return object
}
}
return null
}
/*
Sends a hitTest message to ARKit to get hit testing results
x, y - screen coordinates normalized to 0..1 (0,0 is at top left and 1,1 is at bottom right)
types - bit mask of hit testing types
Returns a Promise that resolves to a (possibly empty) array of hit test data:
[
{
type: 1, // A packed mask of types ARKitWrapper.HIT_TEST_TYPE_*
distance: 1.0216870307922363, // The distance in meters from the camera to the detected anchor or feature point.
world_transform: [float x 16], // The pose of the hit test result relative to the world coordinate system.
local_transform: [float x 16], // The pose of the hit test result relative to the nearest anchor or feature point
// If the `type` is `HIT_TEST_TYPE_ESTIMATED_HORIZONTAL_PLANE`, `HIT_TEST_TYPE_EXISTING_PLANE`, or `HIT_TEST_TYPE_EXISTING_PLANE_USING_EXTENT` (2, 8, or 16) it will also have anchor data:
anchor_center: { x:float, y:float, z:float },
anchor_extent: { x:float, y:float },
uuid: string,
// If the `type` is `HIT_TEST_TYPE_EXISTING_PLANE` or `HIT_TEST_TYPE_EXISTING_PLANE_USING_EXTENT` (8 or 16) it will also have an anchor transform:
anchor_transform: [float x 16]
},
...
]
@see https://developer.apple.com/documentation/arkit/arframe/2875718-hittest
*/
hitTest(x, y, types=ARKitWrapper.HIT_TEST_TYPE_ALL){
return new Promise((resolve, reject) => {
if (!this._isInitialized){
reject(new Error('ARKit is not initialized'));
return;
}
window.webkit.messageHandlers.hitTest.postMessage({
x: x,
y: y,
type: types,
callback: this._createPromiseCallback('hitTest', resolve)
})
})
}
/*
Sends an addAnchor message to ARKit
Returns a promise that returns:
{
uuid - the anchor's uuid,
transform - anchor transformation matrix
}
*/
addAnchor(uid, transform){
return new Promise((resolve, reject) => {
if (!this._isInitialized){
reject(new Error('ARKit is not initialized'));
return;
}
window.webkit.messageHandlers.addAnchor.postMessage({
uuid: uid,
transform: transform,
callback: this._createPromiseCallback('addAnchor', resolve)
})
})
}
removeAnchor(uid) {
window.webkit.messageHandlers.removeAnchors.postMessage([uid])
}
/*
* ask for an image anchor.
*
* Provide a uid for the anchor that will be created.
* Supply the image in an ArrayBuffer, typedArray or ImageData
* width and height are in meters
*/
createImageAnchor(uid, buffer, width, height, physicalWidthInMeters) {
return new Promise((resolve, reject) => {
if (!this._isInitialized){
reject(new Error('ARKit is not initialized'));
return;
}
let b64 = base64.encode(buffer);
window.webkit.messageHandlers.createImageAnchor.postMessage({
uid: uid,
buffer: b64,
imageWidth: width,
imageHeight: height,
physicalWidth: physicalWidthInMeters,
callback: this._createPromiseCallback('createImageAnchor', resolve)
})
})
}
/***
* activateDetectionImage activates an image and waits for the detection
* @param uid The UID of the image to activate, previously created via "createImageAnchor"
* @returns {Promise<any>} a promise that will be resolved when ARKit detects the image, or an error otherwise
*/
activateDetectionImage(uid) {
return new Promise((resolve, reject) => {
if (!this._isInitialized){
reject(new Error('ARKit is not initialized'));
return;
}
window.webkit.messageHandlers.activateDetectionImage.postMessage({
uid: uid,
callback: this._createPromiseCallback('activateDetectionImage', resolve)
})
})
}
/***
* getWorldMap requests a worldmap from the platform
* @returns {Promise<any>} a promise that will be resolved when the worldMap has been retrieved, or an error otherwise
*/
getWorldMap() {
return new Promise((resolve, reject) => {
if (!this._isInitialized){
reject(new Error('ARKit is not initialized'));
return;
}
window.webkit.messageHandlers.getWorldMap.postMessage({
callback: this._createPromiseCallback('getWorldMap', resolve)
})
})
}
/***
* setWorldMap requests a worldmap for the platform be set
* @returns {Promise<any>} a promise that will be resolved when the worldMap has been set, or an error otherwise
*/
setWorldMap(worldMap) {
return new Promise((resolve, reject) => {
if (!this._isInitialized){
reject(new Error('ARKit is not initialized'));
return;
}
window.webkit.messageHandlers.setWorldMap.postMessage({
worldMap: worldMap.worldMap,
callback: this._createPromiseCallback('setWorldMap', resolve)
})
})
}
/*
RACE CONDITION: call stop, then watch: stop does not set isWatching false until it gets a message back from the app,
so watch will return and not issue a watch command. May want to set isWatching false immediately?
*/
/*
If this instance is currently watching, send the stopAR message to ARKit to request that it stop sending data on onWatch
*/
stop(){
return new Promise((resolve, reject) => {
if (!this._isWatching){
resolve();
return;
}
console.log('----STOP');
window.webkit.messageHandlers.stopAR.postMessage({
callback: this._createPromiseCallback('stop', resolve)
})
})
}
/*
If not already watching, send a watchAR message to ARKit to request that it start sending per-frame data to onWatch
options: the options map for ARKit
{
location: boolean,
camera: boolean,
objects: boolean,
light_intensity: boolean,
computer_vision_data: boolean
}
*/
watch(options=null){
if (!this._isInitialized){
return false
}
if(this._isWatching){
return true
}
this._isWatching = true
var newO = Object.assign({}, this._defaultOptions);
if(options != null) {
newO = Object.assign(newO, options)
}
// option to WebXRView is different than the WebXR option
if (newO.videoFrames) {
delete newO.videoFrames
newO.computer_vision_data = true;
}
const data = {
options: newO,
callback: this._globalCallbacksMap.onWatch
}
console.log('----WATCH');
window.webkit.messageHandlers.watchAR.postMessage(data)
return true
}
/*
Sends a setUIOptions message to ARKit to set ui options (show or hide ui elements)
options: {
browser: boolean,
points: boolean,
focus: boolean,
rec: boolean,
rec_time: boolean,
mic: boolean,
build: boolean,
plane: boolean,
warnings: boolean,
anchors: boolean,
debug: boolean,
statistics: boolean
}
*/
setUIOptions(options){
window.webkit.messageHandlers.setUIOptions.postMessage(options)
}
/*
Called during instance creation to send a message to ARKit to initialize and create a device ID
Usually results in ARKit calling back to _onInit with a deviceId
options: {
ui: {
browser: boolean,
points: boolean,
focus: boolean,
rec: boolean,
rec_time: boolean,
mic: boolean,
build: boolean,
plane: boolean,
warnings: boolean,
anchors: boolean,
debug: boolean,
statistics: boolean
}
}
*/
_sendInit(options){
// get device id
console.log('----INIT');
window.webkit.messageHandlers.initAR.postMessage({
options: options,
callback: this._globalCallbacksMap.onInit
})
}
/*
Callback for when ARKit is initialized
deviceId: DOMString with the AR device ID
*/
_onInit(deviceId){
this._deviceId = deviceId
this._isInitialized = true
try {
this.dispatchEvent(new CustomEvent(ARKitWrapper.INIT_EVENT, {
source: this
}))
} catch(e) {
console.error('INIT_EVENT event error', e)
}
}
/*
_onWatch is called from native ARKit on each frame:
data:
{
"timestamp": time value
"light_intensity": value
"camera_view":[4x4 column major affine transform matrix],
"projection_camera":[4x4 projection matrix],
"newObjects": [
{
uuid: DOMString (unique UID),
transform: [4x4 column major affine transform],
plane_center: {x, y, z}, // only on planes
plane_center: {x, y, z} // only on planes, where x/z are used,
}, ...
],
"removeObjects": [
uuid: DOMString (unique UID), ...
]
"objects":[
{
uuid: DOMString (unique UID),
transform: [4x4 column major affine transform]
plane_center: {x, y, z}, // only on planes
plane_center: {x, y, z} // only on planes, where x/z are used,
}, ...
]
}
*/
_onWatch(data){
this._rawARData = data
try {
this.dispatchEvent(new CustomEvent(ARKitWrapper.WATCH_EVENT, {
source: this,
detail: this._rawARData
}))
} catch(e) {
console.error('WATCH_EVENT event error', e)
}
this.timestamp = this._adjustARKitTime(data.timestamp)
this.lightIntensity = data.light_intensity;
this.viewMatrix_ = data.camera_view;
this.projectionMatrix_ = data.projection_camera;
this.worldMappingStatus = data.worldMappingStatus;
if(data.newObjects.length){
for (let i = 0; i < data.newObjects.length; i++) {
const element = data.newObjects[i];
if(element.plane_center){
this.planes_.set(element.uuid, {
id: element.uuid,
center: element.plane_center,
extent: [element.plane_extent.x, element.plane_extent.z],
modelMatrix: element.transform,
alignment: element.plane_alignment
});
}else{
this.anchors_.set(element.uuid, {
id: element.uuid,
modelMatrix: element.transform
});
}
}
}
if(data.removedObjects.length){
for (let i = 0; i < data.removedObjects.length; i++) {
const element = data.removedObjects[i];
if(this.planes_.get(element)){
this.planes_.delete(element);
}else{
this.anchors_.delete(element);
}
}
}
if(data.objects.length){
for (let i = 0; i < data.objects.length; i++) {
const element = data.objects[i];
if(element.plane_center){
var plane = this.planes_.get(element.uuid);
if(!plane){
this.planes_.set(element.uuid, {
id: element.uuid,
center: element.plane_center,
extent: [element.plane_extent.x, element.plane_extent.z],
modelMatrix: element.transform,
alignment: element.plane_alignment
});
} else {
plane.center = element.plane_center;
plane.extent[0] = element.plane_extent.x
plane.extent[1] = element.plane_extent.z
plane.modelMatrix = element.transform;
plane.alignment = element.plane_alignment
}
}else{
var anchor = this.anchors_.get(element.uuid);
if(!anchor){
this.anchors_.set(element.uuid, {
id: element.uuid,
modelMatrix: element.transform
});
}else{
anchor.modelMatrix = element.transform;
}
}
}
}
}
/*
Callback from ARKit for when sending per-frame data to onWatch is stopped
*/
_onStop(){
this._isWatching = false
}
_createPromiseCallback(action, resolve){
const callbackName = this._generateCallbackUID(action);
window[callbackName] = (data) => {
delete window[callbackName]
const wrapperCallbackName = '_on' + action[0].toUpperCase() +
action.slice(1);
if (typeof(this[wrapperCallbackName]) == 'function'){
this[wrapperCallbackName](data);
}
resolve(data)
}
return callbackName;
}
_generateCallbackUID(prefix){
return 'arkitCallback_' + prefix + '_' + new Date().getTime() +
'_' + Math.floor((Math.random() * Number.MAX_SAFE_INTEGER))
}
/*
The ARKit iOS app depends on several callbacks on `window`. This method sets them up.
They end up as window.arkitCallback? where ? is an integer.
You can map window.arkitCallback? to ARKitWrapper instance methods using _globalCallbacksMap
*/
_generateGlobalCallback(callbackName, num){
const name = 'arkitCallback' + num
this._globalCallbacksMap[callbackName] = name
const self = this