-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
artoolkitNFT_ES6.api.js
1069 lines (897 loc) · 35.5 KB
/
artoolkitNFT_ES6.api.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
var scope;
if (typeof window !== 'undefined') {
scope = window;
} else if (typeof global !== 'undefined') {
scope = global;
} else {
scope = self;
}
/**
The ARControllerNFT is the main object for doing AR marker detection with JSARToolKit.
To use an ARControllerNFT, you need to tell it the dimensions to use for the AR processing canvas and
pass it an ARCameraParamNFT to define the camera parameters to use when processing images.
The ARCameraParamNFT defines the lens distortion and aspect ratio of the camera used.
See https://www.artoolworks.com/support/library/Calibrating_your_camera for more information about AR camera parameters and how to make and use them.
If you pass an image as the first argument, the ARControllerNFT uses that as the image to process,
using the dimensions of the image as AR processing canvas width and height. If the first argument
to ARControllerNFT is an image, the second argument is used as the camera param.
The camera parameters argument can be either an ARCameraParamNFT or an URL to a camera definition file.
If the camera argument is an URL, it is loaded into a new ARCameraParamNFT, and the ARControllerNFT dispatches
a 'load' event and calls the onload method if it is defined.
@exports ARControllerNFT
@constructor
@param {number} width The width of the images to process.
@param {number} height The height of the images to process.
@param {ARCameraParamNFT | string} camera The ARCameraParamNFT to use for image processing. If this is a string, the ARControllerNFT treats it as an URL and tries to load it as a ARCameraParamNFT definition file, calling ARControllerNFT#onload on success.
*/
class ARControllerNFT {
constructor(width, height, cameraPara) {
this.id = undefined;
this.listeners = {};
this.width = width;
this.height = height;
this.nftMarkerCount = 0;
this.nftMarkers = {};
this.transform_mat = new Float32Array(16);
this.transformGL_RH = new Float64Array(16);
this.videoWidth = this.width;
this.videoHeight = this.height;
this.videoSize = this.videoWidth * this.videoHeight;
this.framepointer = null;
this.framesize = null;
this.dataHeap = null;
this.videoLuma = null;
this.camera_mat = null;
this.videoLumaPointer = null;
this._bwpointer = undefined;
this._lumaCtx = undefined;
this.version = '1.3.2';
console.info('JsartoolkitNFT ', this.version);
if (typeof cameraPara === 'string') {
this.cameraParam = new ARCameraParamNFT(cameraPara, function () {
this._initialize();
}.bind(this), function (err) {
console.error("ARControllerNFT: Failed to load ARCameraParamNFT", err);
this.onload(err);
}.bind(this));
} else {
this.cameraParam = cameraPara;
this._initialize();
}
}
/**
Destroys the ARControllerNFT instance and frees all associated resources.
After calling dispose, the ARControllerNFT can't be used any longer. Make a new one if you need one.
Calling this avoids leaking Emscripten memory, which may be important if you're using multiple ARControllerNFTs.
*/
dispose() {
// It is possible to call dispose on an ARControllerNFT that was never initialized. But if it was never initialized the id is undefined.
if (this.id > -1) {
artoolkitNFT.teardown(this.id);
}
for (var t in this) {
this[t] = null;
}
}
/**
Detects markers in the given image. The process method dispatches marker detection events during its run.
The marker detection process proceeds by first dispatching a markerNum event that tells you how many
markers were found in the image. Next, a getMarker event is dispatched for each found marker square.
Then, a getNFTMarker event is dispatched for each found NFT marker.
Finally, getMultiMarker is dispatched for every found multimarker, followed by getMultiMarkerSub events
dispatched for each of the markers in the multimarker.
ARControllerNFT.addEventListener('markerNum', function(ev) {
console.log("Detected " + ev.data + " markers.")
});
ARControllerNFT.addEventListener('getMarker', function(ev) {
console.log("Detected marker with ids:", ev.data.marker.id, ev.data.marker.idPatt, ev.data.marker.idMatrix);
console.log("Marker data", ev.data.marker);
console.log("Marker transform matrix:", [].join.call(ev.data.matrix, ', '));
});
ARControllerNFT.addEventListener('getNFTMarker', function(ev) {
// do stuff
});
ARControllerNFT.addEventListener('getMultiMarker', function(ev) {
console.log("Detected multimarker with id:", ev.data.multiMarkerId);
});
ARControllerNFT.addEventListener('getMultiMarkerSub', function(ev) {
console.log("Submarker for " + ev.data.multiMarkerId, ev.data.markerIndex, ev.data.marker);
});
ARControllerNFT.process(image);
If no image is given, defaults to this.image.
If the debugSetup has been called, draws debug markers on the debug canvas.
@param {ImageElement | VideoElement} image The image to process [optional].
*/
process(image) {
var result = this.detectMarker(image);
if (result != 0) {
console.error("detectMarker error: " + result);
}
// get NFT markers
var k, o;
for (k in this.nftMarkers) {
o = this.nftMarkers[k];
o.inPrevious = o.inCurrent;
o.inCurrent = false;
}
// detect NFT markers
var nftMarkerCount = this.nftMarkerCount;
this.detectNFTMarker();
// in ms
var MARKER_LOST_TIME = 200;
for (var i = 0; i < nftMarkerCount; i++) {
var nftMarkerInfo = this.getNFTMarker(i);
var markerType = artoolkitNFT.NFT_MARKER;
if (nftMarkerInfo.found) {
self.markerFound = i;
self.markerFoundTime = Date.now();
var visible = this.trackNFTMarkerId(i);
visible.matrix.set(nftMarkerInfo.pose);
visible.inCurrent = true;
this.transMatToGLMat(visible.matrix, this.transform_mat);
this.transformGL_RH = this.arglCameraViewRHf(this.transform_mat);
this.dispatchEvent({
name: 'getNFTMarker',
target: this,
data: {
index: i,
type: markerType,
marker: nftMarkerInfo,
matrix: this.transform_mat,
matrixGL_RH: this.transformGL_RH
}
});
} else if (self.markerFound === i) {
// for now this marker found/lost events handling is for one marker at a time
if ((Date.now() - self.markerFoundTime) <= MARKER_LOST_TIME) {
// not handling marker lost for less than specified time
return;
}
delete self.markerFound;
this.dispatchEvent({
name: 'lostNFTMarker',
target: this,
data: {
index: i,
type: markerType,
marker: nftMarkerInfo,
matrix: this.transform_mat,
matrixGL_RH: this.transformGL_RH
}
});
}
}
};
/**
Detects the NFT markers in the process() function,
with the given tracked id.
*/
detectNFTMarker() {
artoolkitNFT.detectNFTMarker(this.id);
};
/**
Adds the given NFT marker ID to the index of tracked IDs.
Sets the markerWidth for the pattern marker to markerWidth.
Used by process() to implement continuous tracking,
keeping track of the marker's transformation matrix
and customizable marker widths.
@param {number} id ID of the NFT marker to track.
@param {number} markerWidth The width of the marker to track.
@return {Object} The marker tracking object.
*/
trackNFTMarkerId(id, markerWidth) {
var obj = this.nftMarkers[id];
if (!obj) {
this.nftMarkers[id] = obj = {
inPrevious: false,
inCurrent: false,
matrix: new Float64Array(12),
matrixGL_RH: new Float64Array(12),
markerWidth: markerWidth || this.defaultMarkerWidth
};
}
if (markerWidth) {
obj.markerWidth = markerWidth;
}
return obj;
};
/**
Add an event listener on this ARControllerNFT for the named event, calling the callback function
whenever that event is dispatched.
Possible events are:
* getNFTMarker - dispatched whenever process() finds a NFT marker
* load - dispatched when the ARControllerNFT is ready to use (useful if passing in a camera URL in the constructor)
@param {string} name Name of the event to listen to.
@param {function} callback Callback function to call when an event with the given name is dispatched.
*/
addEventListener(name, callback) {
if (!this.listeners[name]) {
this.listeners[name] = [];
}
this.listeners[name].push(callback);
};
/**
Remove an event listener from the named event.
@param {string} name Name of the event to stop listening to.
@param {function} callback Callback function to remove from the listeners of the named event.
*/
removeEventListener(name, callback) {
if (this.listeners[name]) {
var index = this.listeners[name].indexOf(callback);
if (index > -1) {
this.listeners[name].splice(index, 1);
}
}
};
/**
Dispatches the given event to all registered listeners on event.name.
@param {Object} event Event to dispatch.
*/
dispatchEvent(event) {
var listeners = this.listeners[event.name];
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].call(this, event);
}
}
};
/**
Sets up a debug canvas for the AR detection. Draws a red marker on top of each detected square in the image.
The debug canvas is added to document.body.
*/
debugSetup() {
this.setDebugMode(true);
this._bwpointer = this.getProcessingImage();
};
async loadNFTMarkerNew(markerURLs, onSuccess, onError) {
//var self = this;
let nft = await artoolkitNFT.addNFTMarkerNew(this.id, markerURLs, function (ids) {
self.nftMarkerCount += ids.length;
onSuccess(ids);
}, onError);
return nft;
};
/**
Loads an NFT marker from the given URL prefix and calls the onSuccess callback with the UID of the marker.
ARControllerNFT.loadNFTMarker(markerURL, onSuccess, onError);
@param {string} markerURLs - List of the URL prefix of the NFT markers to load.
@param {function} onSuccess - The success callback. Called with the id of the loaded marker on a successful load.
@param {function} onError - The error callback. Called with the encountered error if the load fails.
*/
loadNFTMarkers(markerURLs, onSuccess, onError) {
var self = this;
artoolkitNFT.addNFTMarkers(this.id, markerURLs, function (ids) {
self.nftMarkerCount += ids.length;
onSuccess(ids);
}, onError);
};
loadNFTMarker(markerURL, onSuccess, onError) {
if (markerURL) {
this.loadNFTMarkers([markerURL], function (ids) {
onSuccess(ids[0]);
}, onError);
} else {
if (onError) {
onError("Marker URL needs to be defined and not equal empty string!");
}
else {
console.error("Marker URL needs to be defined and not equal empty string!");
}
}
};
/**
Converts the given 3x4 marker transformation matrix in the 12-element transMat array
into a 4x4 WebGL matrix and writes the result into the 16-element glMat array.
If scale parameter is given, scales the transform of the glMat by the scale parameter.
@param {Float64Array} transMat The 3x4 marker transformation matrix.
@param {Float64Array} glMat The 4x4 GL transformation matrix.
@param {number} scale The scale for the transform.
*/
transMatToGLMat(transMat, glMat, scale) {
if (glMat == undefined) {
glMat = new Float64Array(16);
}
glMat[0 + 0 * 4] = transMat[0]; // R1C1
glMat[0 + 1 * 4] = transMat[1]; // R1C2
glMat[0 + 2 * 4] = transMat[2];
glMat[0 + 3 * 4] = transMat[3];
glMat[1 + 0 * 4] = transMat[4]; // R2
glMat[1 + 1 * 4] = transMat[5];
glMat[1 + 2 * 4] = transMat[6];
glMat[1 + 3 * 4] = transMat[7];
glMat[2 + 0 * 4] = transMat[8]; // R3
glMat[2 + 1 * 4] = transMat[9];
glMat[2 + 2 * 4] = transMat[10];
glMat[2 + 3 * 4] = transMat[11];
glMat[3 + 0 * 4] = 0.0;
glMat[3 + 1 * 4] = 0.0;
glMat[3 + 2 * 4] = 0.0;
glMat[3 + 3 * 4] = 1.0;
if (scale != undefined && scale !== 0.0) {
glMat[12] *= scale;
glMat[13] *= scale;
glMat[14] *= scale;
}
return glMat;
};
/**
Converts the given 4x4 openGL matrix in the 16-element transMat array
into a 4x4 OpenGL Right-Hand-View matrix and writes the result into the 16-element glMat array.
If scale parameter is given, scales the transform of the glMat by the scale parameter.
@param {Float64Array} glMatrix The 4x4 marker transformation matrix.
@param {Float64Array} [glRhMatrix] The 4x4 GL right hand transformation matrix.
@param {number} [scale] The scale for the transform.
*/
arglCameraViewRHf(glMatrix, glRhMatrix, scale) {
var m_modelview;
if (glRhMatrix == undefined)
m_modelview = new Float64Array(16);
else
m_modelview = glRhMatrix;
// x
m_modelview[0] = glMatrix[0];
m_modelview[4] = glMatrix[4];
m_modelview[8] = glMatrix[8];
m_modelview[12] = glMatrix[12];
// y
m_modelview[1] = -glMatrix[1];
m_modelview[5] = -glMatrix[5];
m_modelview[9] = -glMatrix[9];
m_modelview[13] = -glMatrix[13];
// z
m_modelview[2] = -glMatrix[2];
m_modelview[6] = -glMatrix[6];
m_modelview[10] = -glMatrix[10];
m_modelview[14] = -glMatrix[14];
// 0 0 0 1
m_modelview[3] = 0;
m_modelview[7] = 0;
m_modelview[11] = 0;
m_modelview[15] = 1;
if (scale != undefined && scale !== 0.0) {
m_modelview[12] *= scale;
m_modelview[13] *= scale;
m_modelview[14] *= scale;
}
glRhMatrix = m_modelview;
return glRhMatrix;
};
/**
This is the core ARToolKit marker detection function. It calls through to a set of
internal functions to perform the key marker detection steps of binarization and
labelling, contour extraction, and template matching and/or matrix code extraction.
Typically, the resulting set of detected markers is retrieved by calling arGetMarkerNum
to get the number of markers detected and arGetMarker to get an array of ARMarkerInfo
structures with information on each detected marker, followed by a step in which
detected markers are possibly examined for some measure of goodness of match (e.g. by
examining the match confidence value) and pose extraction.
@param {image} Image to be processed to detect markers.
@return {number} 0 if the function proceeded without error, or a value less than 0 in case of error.
A result of 0 does not however, imply any markers were detected.
*/
detectMarker(image) {
if (this._copyImageToHeap(image)) {
return artoolkitNFT.detectMarker(this.id);
}
return -99;
};
/**
Get the NFT marker info struct for the given NFT marker index in detected markers.
The returned object is the global artoolkit.NFTMarkerInfo object and will be overwritten
by subsequent calls.
Returns undefined if no marker was found.
A markerIndex of -1 is used to access the global custom marker.
@param {number} markerIndex The index of the NFT marker to query.
@returns {Object} The NFTmarkerInfo struct.
*/
getNFTMarker(markerIndex) {
if (0 === artoolkitNFT.getNFTMarker(this.id, markerIndex)) {
return artoolkitNFT.NFTMarkerInfo;
}
};
/**
* Get the NFT data (id, dpi, width and height) of the NFT marker.
* @returns {Object} nft object (id, dpi, width, height)
*/
getNFTData(index) {
return artoolkitNFT.getNFTData(this.id, index);
};
/**
Returns the 16-element WebGL transformation matrix used by ARControllerNFT.process to
pass marker WebGL matrices to event listeners.
Unique to each ARControllerNFT.
@return {Float64Array} The 16-element WebGL transformation matrix used by the ARControllerNFT.
*/
getTransformationMatrix() {
return this.transform_mat;
};
/**
* Returns the projection matrix computed from camera parameters for the ARControllerNFT.
*
* @return {Float64Array} The 16-element WebGL camera matrix for the ARControllerNFT camera parameters.
*/
getCameraMatrix() {
return this.camera_mat;
};
/* Setter / Getter Proxies */
/**
* Enables or disables debug mode in the tracker. When enabled, a black and white debug
* image is generated during marker detection. The debug image is useful for visualising
* the binarization process and choosing a threshold value.
* @param {boolean} mode true to enable debug mode, false to disable debug mode
* @see getDebugMode()
*/
setDebugMode(mode) {
return artoolkitNFT.setDebugMode(this.id, mode);
};
/**
* Returns whether debug mode is currently enabled.
* @return {boolean} true when debug mode is enabled, false when debug mode is disabled
* @see setDebugMode()
*/
getDebugMode() {
return artoolkitNFT.getDebugMode(this.id);
};
/**
Returns the Emscripten HEAP offset to the debug processing image used by ARToolKit.
@return {number} HEAP offset to the debug processing image.
*/
getProcessingImage() {
return artoolkitNFT.getProcessingImage(this.id);
};
/**
Sets the logging level to use by ARToolKit.
@param {number} mode type for the log level.
*/
setLogLevel(mode) {
return artoolkitNFT.setLogLevel(mode);
};
/**
Gets the logging level used by ARToolKit.
@return {number} return the log level in use.
*/
getLogLevel() {
return artoolkitNFT.getLogLevel();
};
/**
Sets the value of the near plane of the camera.
@param {number} value the value of the near plane
@return {number} 0 (void)
*/
setProjectionNearPlane(value) {
return artoolkitNFT.setProjectionNearPlane(this.id, value);
};
/**
Gets the value of the near plane of the camera with the give id.
@return {number} the value of the near plane.
*/
getProjectionNearPlane() {
return artoolkitNFT.getProjectionNearPlane(this.id);
};
/**
Sets the value of the far plane of the camera.
@param {number} value the value of the far plane
@return {number} 0 (void)
*/
setProjectionFarPlane(value) {
return artoolkitNFT.setProjectionFarPlane(this.id, value);
};
/**
Gets the value of the far plane of the camera with the give id.
@return {number} the value of the far plane.
*/
getProjectionFarPlane() {
return artoolkitNFT.getProjectionFarPlane(this.id);
};
/**
Set the labeling threshold mode (auto/manual).
@param {number} mode An integer specifying the mode. One of:
AR_LABELING_THRESH_MODE_MANUAL,
AR_LABELING_THRESH_MODE_AUTO_MEDIAN,
AR_LABELING_THRESH_MODE_AUTO_OTSU,
AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE,
AR_LABELING_THRESH_MODE_AUTO_BRACKETING
*/
setThresholdMode(mode) {
return artoolkitNFT.setThresholdMode(this.id, mode);
};
/**
* Gets the current threshold mode used for image binarization.
* @return {number} The current threshold mode
* @see getVideoThresholdMode()
*/
getThresholdMode() {
return artoolkitNFT.getThresholdMode(this.id);
};
/**
Set the labeling threshhold.
This function forces sets the threshold value.
The default value is AR_DEFAULT_LABELING_THRESH which is 100.
The current threshold mode is not affected by this call.
Typically, this function is used when labeling threshold mode
is AR_LABELING_THRESH_MODE_MANUAL.
The threshold value is not relevant if threshold mode is
AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE.
Background: The labeling threshold is the value which
the AR library uses to differentiate between black and white
portions of an ARToolKit marker. Since the actual brightness,
contrast, and gamma of incoming images can vary signficantly
between different cameras and lighting conditions, this
value typically needs to be adjusted dynamically to a
suitable midpoint between the observed values for black
and white portions of the markers in the image.
@param {number} threshold An integer in the range [0,255] (inclusive).
*/
setThreshold(threshold) {
return artoolkitNFT.setThreshold(this.id, threshold);
};
/**
Get the current labeling threshold.
This function queries the current labeling threshold. For,
AR_LABELING_THRESH_MODE_AUTO_MEDIAN, AR_LABELING_THRESH_MODE_AUTO_OTSU,
and AR_LABELING_THRESH_MODE_AUTO_BRACKETING
the threshold value is only valid until the next auto-update.
The current threshold mode is not affected by this call.
The threshold value is not relevant if threshold mode is
AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE.
@return {number} The current threshold value.
*/
getThreshold() {
return artoolkitNFT.getThreshold(this.id);
};
/**
Set the image processing mode.
When the image processing mode is AR_IMAGE_PROC_FRAME_IMAGE,
ARToolKit processes all pixels in each incoming image
to locate markers. When the mode is AR_IMAGE_PROC_FIELD_IMAGE,
ARToolKit processes pixels in only every second pixel row and
column. This is useful both for handling images from interlaced
video sources (where alternate lines are assembled from alternate
fields and thus have one field time-difference, resulting in a
"comb" effect) such as Digital Video cameras.
The effective reduction by 75% in the pixels processed also
has utility in accelerating tracking by effectively reducing
the image size to one quarter size, at the cost of pose accuraccy.
@param {number} mode
Options for this field are:
AR_IMAGE_PROC_FRAME_IMAGE
AR_IMAGE_PROC_FIELD_IMAGE
The default mode is AR_IMAGE_PROC_FRAME_IMAGE.
*/
setImageProcMode(mode) {
return artoolkitNFT.setImageProcMode(this.id, mode);
};
/**
Get the image processing mode.
See arSetImageProcMode() for a complete description.
@return {number} The current image processing mode.
*/
getImageProcMode() {
return artoolkitNFT.getImageProcMode(this.id);
};
// private methods
/**
This function init the ARControllerNFT with the necessary parmeters and variables.
Don't call directly this but instead instantiate a new ARControllerNFT.
@return {number} 0 (void)
*/
_initialize() {
this.id = artoolkitNFT.setup(this.width, this.height, this.cameraParam.id);
this._initNFT();
var params = artoolkitNFT.frameMalloc;
this.framepointer = params.framepointer;
this.framesize = params.framesize;
this.videoLumaPointer = params.videoLumaPointer;
this.dataHeap = new Uint8Array(Module.HEAPU8.buffer, this.framepointer, this.framesize);
this.videoLuma = new Uint8Array(Module.HEAPU8.buffer, this.videoLumaPointer, this.framesize / 4);
this.camera_mat = new Float64Array(Module.HEAPU8.buffer, params.camera, 16);
this.setProjectionNearPlane(0.1);
this.setProjectionFarPlane(1000);
setTimeout(function () {
if (this.onload) {
this.onload();
}
this.dispatchEvent({
name: 'load',
target: this
});
}.bind(this), 1);
};
/**
Init the necessary kpm handle for NFT and the settings for the CPU.
@return {number} 0 (void)
*/
_initNFT() {
artoolkitNFT.setupAR2(this.id);
};
/**
Copy the Image data to the HEAP for the debugSetup function.
@return {number} 0 (void)
*/
_copyImageToHeap(image) {
if (!image) {
console.error("Error: no provided imageData to ARControllerNFT");
return;
}
if (image.data) {
var imageData = image;
}
var data = imageData.data; // this is of type Uint8ClampedArray: The Uint8ClampedArray typed array represents an array of 8-bit unsigned integers clamped to 0-255 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray)
//Here we have access to the unmodified video image. We now need to add the videoLuma chanel to be able to serve the underlying ARTK API
if (this.videoLuma) {
var q = 0;
//Create luma from video data assuming Pixelformat AR_PIXEL_FORMAT_RGBA (ARToolKitJS.cpp L: 43)
for (var p = 0; p < this.videoSize; p++) {
var r = data[q + 0], g = data[q + 1], b = data[q + 2];
// videoLuma[p] = (r+r+b+g+g+g)/6; // https://stackoverflow.com/a/596241/5843642
this.videoLuma[p] = (r + r + r + b + g + g + g + g) >> 3;
q += 4;
}
}
if (this.dataHeap) {
this.dataHeap.set(data);
return true;
}
return false;
};
}
// static
/**
ARCameraParamNFT is used for loading AR camera parameters for use with ARControllerNFT.
Use by passing in an URL and a callback function.
var camera = new ARCameraParamNFT('Data/camera_para.dat', function() {
console.log('loaded camera', this.id);
},
function(err) {
console.log('failed to load camera', err);
});
@exports ARCameraParamNFT
@constructor
@param {string} src URL to load camera parameters from.
@param {Function} onload Onload callback to be called on successful parameter loading.
@param {Function} onerror Error callback to called when things don't work out.
*/
class ARCameraParamNFT {
constructor(src, onload, onerror) {
this.id = -1;
this._src = '';
this.complete = false;
if (!onload) {
this.onload = function () { console.log('Successfully loaded'); };
console.warn("onload callback should be defined");
} else {
this.onload = onload;
}
if (!onerror) {
this.onerror = function (err) { console.error("Error: " + err) };
console.warn("onerror callback should be defined");
} else {
this.onerror = onerror;
}
if (src) {
this.load(src);
}
else {
console.warn("No camera parameter file defined! It should be defined in constructor or in ARCameraParamNFT.load(url)");
}
};
/**
Loads the given URL as camera parameters definition file into this ARCameraParamNFT.
Can only be called on an unloaded ARCameraParamNFT instance.
@param {string} src URL to load.
*/
load(src) {
if (this._src !== '') {
throw ("ARCameraParamNFT: Trying to load camera parameters twice.");
}
this._src = src;
if (src) {
artoolkitNFT.loadCamera(src, function (id) {
this.id = id;
this.complete = true;
this.onload();
}.bind(this), function (err) {
this.onerror(err);
}.bind(this));
}
};
set src(src) {
this.load(src);
}
get src() {
return this._src;
}
/**
Destroys the camera parameter and frees associated Emscripten resources.
*/
dispose() {
if (this.id !== -1) {
artoolkitNFT.deleteCamera(this.id);
}
this.id = -1;
this._src = '';
this.complete = false;
};
}
// ARToolKit exported JS API
//
var artoolkitNFT = {
UNKNOWN_MARKER: -1,
NFT_MARKER: 0, // 0,
loadCamera: loadCamera,
addNFTMarker: addNFTMarker,
addNFTMarkers: addNFTMarkers
};
var FUNCTIONS = [
'setup',
'teardown',
'setupAR2',
'setLogLevel',
'getLogLevel',
'setDebugMode',
'getDebugMode',
'getProcessingImage',
'detectMarker',
'detectNFTMarker',
'getNFTMarker',
'getNFTData',
'setProjectionNearPlane',
'getProjectionNearPlane',
'setProjectionFarPlane',
'getProjectionFarPlane',
'setThresholdMode',
'getThresholdMode',
'setThreshold',
'getThreshold',
'setImageProcMode',
'getImageProcMode',
];
function runWhenLoaded() {
FUNCTIONS.forEach(function (n) {
artoolkitNFT[n] = Module[n];
});
for (var m in Module) {
if (m.match(/^AR/))
artoolkitNFT[m] = Module[m];
}
}
var marker_count = 0;
function addNFTMarker(arId, url, callback, onError) {
var mId = marker_count++;
var prefix = '/markerNFT_' + mId;
var filename1 = prefix + '.fset';
var filename2 = prefix + '.iset';
var filename3 = prefix + '.fset3';
ajax(url + '.fset', filename1, function () {
ajax(url + '.iset', filename2, function () {
ajax(url + '.fset3', filename3, function () {
var nftMarker = Module._addNFTMarker(arId, prefix);
if (callback) callback(nftMarker);
}, function (errorNumber) { if (onError) onError(errorNumber); });
}, function (errorNumber) { if (onError) onError(errorNumber); });
}, function (errorNumber) { if (onError) onError(errorNumber); });
}
function addNFTMarkers(arId, urls, callback, onError) {
var prefixes = [];
var pending = urls.length * 3;
var onSuccess = (filename) => {
pending -= 1;
if (pending === 0) {
const vec = new Module.StringList();
const markerIds = [];
for (let i = 0; i < prefixes.length; i++) {
vec.push_back(prefixes[i]);
}
var ret = Module._addNFTMarkers(arId, vec);
for (let i = 0; i < ret.size(); i++) {
markerIds.push(ret.get(i));
}
console.log("add nft marker ids: ", markerIds);
if (callback) callback(markerIds);
}
}
var onError = (filename, errorNumber) => {
console.log("failed to load: ", filename);
onError(errorNumber);
}
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
var prefix = '/markerNFT_' + marker_count;
prefixes.push(prefix);
var filename1 = prefix + '.fset';
var filename2 = prefix + '.iset';
var filename3 = prefix + '.fset3';
ajax(url + '.fset', filename1, onSuccess.bind(filename1), onError.bind(filename1));
ajax(url + '.iset', filename2, onSuccess.bind(filename2), onError.bind(filename2));
ajax(url + '.fset3', filename3, onSuccess.bind(filename3), onError.bind(filename3));
marker_count += 1;
}
}
function bytesToString(array) {
return String.fromCharCode.apply(String, array);
}
var camera_count = 0;
function loadCamera(url, callback, errorCallback) {
var filename = '/camera_param_' + camera_count++;
var writeCallback = function (errorCode) {
if (!Module._loadCamera) {
if (callback) callback(id); setTimeout(writeCallback, 10);
} else {
var id = Module._loadCamera(filename);
if (callback) callback(id);
}
};
if (typeof url === 'object') { // Maybe it's a byte array
writeByteArrayToFS(filename, url, writeCallback);
} else if (url.indexOf("\n") > -1) { // Or a string with the camera param
writeStringToFS(filename, url, writeCallback);
} else {
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not OK');
}
return response.blob();
})
.then(blob => {
blob.arrayBuffer().then(buff => {
let buffer = new Uint8Array(buff)