forked from leapmotion/leapjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leap-0.4.3.js
7264 lines (6607 loc) · 217 KB
/
leap-0.4.3.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
/*!
* LeapJS v0.4.3
* http://github.com/leapmotion/leapjs/
*
* Copyright 2013 LeapMotion, Inc. and other contributors
* Released under the BSD-2-Clause license
* http://github.com/leapmotion/leapjs/blob/master/LICENSE.txt
*/
;(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
var CircularBuffer = module.exports = function(size) {
this.pos = 0;
this._buf = [];
this.size = size;
}
CircularBuffer.prototype.get = function(i) {
if (i == undefined) i = 0;
if (i >= this.size) return undefined;
if (i >= this._buf.length) return undefined;
return this._buf[(this.pos - i - 1) % this.size];
}
CircularBuffer.prototype.push = function(o) {
this._buf[this.pos % this.size] = o;
return this.pos++;
}
},{}],2:[function(require,module,exports){
var chooseProtocol = require('../protocol').chooseProtocol
, EventEmitter = require('events').EventEmitter
, _ = require('underscore');
var BaseConnection = module.exports = function(opts) {
this.opts = _.defaults(opts || {}, {
host : '127.0.0.1',
enableGestures: false,
port: 6437,
background: false,
requestProtocolVersion: 4
});
this.host = this.opts.host;
this.port = this.opts.port;
this.protocolVersionVerified = false;
this.on('ready', function() {
this.enableGestures(this.opts.enableGestures);
this.setBackground(this.opts.background);
});
}
BaseConnection.prototype.getUrl = function() {
return "ws://" + this.host + ":" + this.port + "/v" + this.opts.requestProtocolVersion + ".json";
}
BaseConnection.prototype.setBackground = function(state) {
this.opts.background = state;
if (this.protocol && this.protocol.sendBackground && this.background !== this.opts.background) {
this.background = this.opts.background;
this.protocol.sendBackground(this, this.opts.background);
}
}
BaseConnection.prototype.handleOpen = function() {
if (!this.connected) {
this.connected = true;
this.emit('connect');
}
}
BaseConnection.prototype.enableGestures = function(enabled) {
this.gesturesEnabled = enabled ? true : false;
this.send(this.protocol.encode({"enableGestures": this.gesturesEnabled}));
}
BaseConnection.prototype.handleClose = function(code, reason) {
if (!this.connected) return;
this.disconnect();
// 1001 - an active connection is closed
// 1006 - cannot connect
if (code === 1001 && this.opts.requestProtocolVersion > 1) {
if (this.protocolVersionVerified) {
this.protocolVersionVerified = false;
}else{
this.opts.requestProtocolVersion--;
}
}
this.startReconnection();
}
BaseConnection.prototype.startReconnection = function() {
var connection = this;
this.reconnectionTimer = setInterval(function() { connection.reconnect() }, 1000);
}
BaseConnection.prototype.disconnect = function() {
if (!this.socket) return;
this.socket.close();
delete this.socket;
delete this.protocol;
delete this.background; // This is not persisted when reconnecting to the web socket server
if (this.connected) {
this.connected = false;
this.emit('disconnect');
}
return true;
}
BaseConnection.prototype.reconnect = function() {
if (this.connected) {
clearInterval(this.reconnectionTimer);
} else {
this.disconnect();
this.connect();
}
}
BaseConnection.prototype.handleData = function(data) {
var message = JSON.parse(data);
var messageEvent;
if (this.protocol === undefined) {
messageEvent = this.protocol = chooseProtocol(message);
this.protocolVersionVerified = true;
this.emit('ready');
} else {
messageEvent = this.protocol(message);
}
this.emit(messageEvent.type, messageEvent);
}
BaseConnection.prototype.connect = function() {
if (this.socket) return;
this.socket = this.setupSocket();
return true;
}
BaseConnection.prototype.send = function(data) {
this.socket.send(data);
}
BaseConnection.prototype.reportFocus = function(state) {
if (this.focusedState === state) return;
this.focusedState = state;
this.emit(this.focusedState ? 'focus' : 'blur');
if (this.protocol && this.protocol.sendFocused) {
this.protocol.sendFocused(this, this.focusedState);
}
}
_.extend(BaseConnection.prototype, EventEmitter.prototype);
},{"../protocol":12,"events":18,"underscore":21}],3:[function(require,module,exports){
var BaseConnection = module.exports = require('./base')
, _ = require('underscore');
var BrowserConnection = module.exports = function(opts) {
BaseConnection.call(this, opts);
var connection = this;
this.on('ready', function() { connection.startFocusLoop(); })
this.on('disconnect', function() { connection.stopFocusLoop(); })
}
_.extend(BrowserConnection.prototype, BaseConnection.prototype);
BrowserConnection.prototype.setupSocket = function() {
var connection = this;
var socket = new WebSocket(this.getUrl());
socket.onopen = function() { connection.handleOpen(); };
socket.onclose = function(data) { connection.handleClose(data['code'], data['reason']); };
socket.onmessage = function(message) { connection.handleData(message.data) };
return socket;
}
BrowserConnection.prototype.startFocusLoop = function() {
if (this.focusDetectorTimer) return;
var connection = this;
var propertyName = null;
if (typeof document.hidden !== "undefined") {
propertyName = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
propertyName = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
propertyName = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
propertyName = "webkitHidden";
} else {
propertyName = undefined;
}
if (connection.windowVisible === undefined) {
connection.windowVisible = propertyName === undefined ? true : document[propertyName] === false;
}
var focusListener = window.addEventListener('focus', function(e) {
connection.windowVisible = true;
updateFocusState();
});
var blurListener = window.addEventListener('blur', function(e) {
connection.windowVisible = false;
updateFocusState();
});
this.on('disconnect', function() {
window.removeEventListener('focus', focusListener);
window.removeEventListener('blur', blurListener);
});
var updateFocusState = function() {
var isVisible = propertyName === undefined ? true : document[propertyName] === false;
connection.reportFocus(isVisible && connection.windowVisible);
}
this.focusDetectorTimer = setInterval(updateFocusState, 100);
}
BrowserConnection.prototype.stopFocusLoop = function() {
if (!this.focusDetectorTimer) return;
clearTimeout(this.focusDetectorTimer);
delete this.focusDetectorTimer;
}
},{"./base":2,"underscore":21}],4:[function(require,module,exports){
var process=require("__browserify_process");var Frame = require('./frame')
, Hand = require('./hand')
, Pointable = require('./pointable')
, CircularBuffer = require("./circular_buffer")
, Pipeline = require("./pipeline")
, EventEmitter = require('events').EventEmitter
, gestureListener = require('./gesture').gestureListener
, _ = require('underscore');
/**
* Constructs a Controller object.
*
* When creating a Controller object, you may optionally pass in options
* to set the host , set the port, enable gestures, or select the frame event type.
*
* ```javascript
* var controller = new Leap.Controller({
* host: '127.0.0.1',
* port: 6437,
* enableGestures: true,
* frameEventName: 'animationFrame'
* });
* ```
*
* @class Controller
* @memberof Leap
* @classdesc
* The Controller class is your main interface to the Leap Motion Controller.
*
* Create an instance of this Controller class to access frames of tracking data
* and configuration information. Frame data can be polled at any time using the
* [Controller.frame]{@link Leap.Controller#frame}() function. Call frame() or frame(0) to get the most recent
* frame. Set the history parameter to a positive integer to access previous frames.
* A controller stores up to 60 frames in its frame history.
*
* Polling is an appropriate strategy for applications which already have an
* intrinsic update loop, such as a game.
*/
var Controller = module.exports = function(opts) {
var inNode = (typeof(process) !== 'undefined' && process.versions && process.versions.node),
controller = this;
opts = _.defaults(opts || {}, {
inNode: inNode
});
this.inNode = opts.inNode;
opts = _.defaults(opts || {}, {
frameEventName: this.useAnimationLoop() ? 'animationFrame' : 'deviceFrame',
suppressAnimationLoop: !this.useAnimationLoop(),
loopWhileDisconnected: false,
useAllPlugins: false
});
this.animationFrameRequested = false;
this.onAnimationFrame = function() {
controller.emit('animationFrame', controller.lastConnectionFrame);
if (controller.loopWhileDisconnected && (controller.connection.focusedState || controller.connection.opts.background) ){
window.requestAnimationFrame(controller.onAnimationFrame);
}else{
controller.animationFrameRequested = false;
}
}
this.suppressAnimationLoop = opts.suppressAnimationLoop;
this.loopWhileDisconnected = opts.loopWhileDisconnected;
this.frameEventName = opts.frameEventName;
this.useAllPlugins = opts.useAllPlugins;
this.history = new CircularBuffer(200);
this.lastFrame = Frame.Invalid;
this.lastValidFrame = Frame.Invalid;
this.lastConnectionFrame = Frame.Invalid;
this.accumulatedGestures = [];
if (opts.connectionType === undefined) {
this.connectionType = (this.inBrowser() ? require('./connection/browser') : require('./connection/node'));
} else {
this.connectionType = opts.connectionType;
}
this.connection = new this.connectionType(opts);
this.plugins = {};
this._pluginPipelineSteps = {};
this._pluginExtendedMethods = {};
if (opts.useAllPlugins) this.useRegisteredPlugins();
this.setupConnectionEvents();
}
Controller.prototype.gesture = function(type, cb) {
var creator = gestureListener(this, type);
if (cb !== undefined) {
creator.stop(cb);
}
return creator;
}
/*
* @returns the controller
*/
Controller.prototype.setBackground = function(state) {
this.connection.setBackground(state);
return this;
}
Controller.prototype.inBrowser = function() {
return !this.inNode;
}
Controller.prototype.useAnimationLoop = function() {
return this.inBrowser() && !this.inBackgroundPage();
}
Controller.prototype.inBackgroundPage = function(){
// http://developer.chrome.com/extensions/extension#method-getBackgroundPage
return (typeof(chrome) !== "undefined") &&
chrome.extension &&
chrome.extension.getBackgroundPage &&
(chrome.extension.getBackgroundPage() === window)
}
/*
* @returns the controller
*/
Controller.prototype.connect = function() {
this.connection.connect();
return this;
}
Controller.prototype.runAnimationLoop = function(){
if (!this.suppressAnimationLoop && !this.animationFrameRequested) {
this.animationFrameRequested = true;
window.requestAnimationFrame(this.onAnimationFrame);
}
}
/*
* @returns the controller
*/
Controller.prototype.disconnect = function() {
this.connection.disconnect();
return this;
}
/**
* Returns a frame of tracking data from the Leap.
*
* Use the optional history parameter to specify which frame to retrieve.
* Call frame() or frame(0) to access the most recent frame; call frame(1) to
* access the previous frame, and so on. If you use a history value greater
* than the number of stored frames, then the controller returns an invalid frame.
*
* @method frame
* @memberof Leap.Controller.prototype
* @param {number} history The age of the frame to return, counting backwards from
* the most recent frame (0) into the past and up to the maximum age (59).
* @returns {Leap.Frame} The specified frame; or, if no history
* parameter is specified, the newest frame. If a frame is not available at
* the specified history position, an invalid Frame is returned.
*/
Controller.prototype.frame = function(num) {
return this.history.get(num) || Frame.Invalid;
}
Controller.prototype.loop = function(callback) {
switch (callback.length) {
case 1:
this.on(this.frameEventName, callback);
break;
case 2:
var controller = this;
var scheduler = null;
var immediateRunnerCallback = function(frame) {
callback(frame, function() {
if (controller.lastFrame != frame) {
immediateRunnerCallback(controller.lastFrame);
} else {
controller.once(controller.frameEventName, immediateRunnerCallback);
}
});
}
this.once(this.frameEventName, immediateRunnerCallback);
break;
}
return this.connect();
}
Controller.prototype.addStep = function(step) {
if (!this.pipeline) this.pipeline = new Pipeline(this);
this.pipeline.addStep(step);
}
// this is run on every deviceFrame
Controller.prototype.processFrame = function(frame) {
if (frame.gestures) {
this.accumulatedGestures = this.accumulatedGestures.concat(frame.gestures);
}
// lastConnectionFrame is used by the animation loop
this.lastConnectionFrame = frame;
this.runAnimationLoop();
this.emit('deviceFrame', frame);
}
// on a this.deviceEventName (usually 'animationFrame' in browsers), this emits a 'frame'
Controller.prototype.processFinishedFrame = function(frame) {
this.lastFrame = frame;
if (frame.valid) {
this.lastValidFrame = frame;
}
frame.controller = this;
frame.historyIdx = this.history.push(frame);
if (frame.gestures) {
frame.gestures = this.accumulatedGestures;
this.accumulatedGestures = [];
for (var gestureIdx = 0; gestureIdx != frame.gestures.length; gestureIdx++) {
this.emit("gesture", frame.gestures[gestureIdx], frame);
}
}
if (this.pipeline) {
frame = this.pipeline.run(frame);
if (!frame) frame = Frame.Invalid;
}
this.emit('frame', frame);
}
Controller.prototype.setupConnectionEvents = function() {
var controller = this;
this.connection.on('frame', function(frame) {
controller.processFrame(frame);
});
this.on(this.frameEventName, function(frame) {
controller.processFinishedFrame(frame);
});
// Delegate connection events
this.connection.on('disconnect', function() { controller.emit('disconnect'); });
this.connection.on('ready', function() { controller.emit('ready'); });
this.connection.on('connect', function() { controller.emit('connect'); });
this.connection.on('focus', function() { controller.emit('focus'); controller.runAnimationLoop(); });
this.connection.on('blur', function() { controller.emit('blur') });
this.connection.on('protocol', function(protocol) { controller.emit('protocol', protocol); });
this.connection.on('deviceConnect', function(evt) { controller.emit(evt.state ? 'deviceConnected' : 'deviceDisconnected'); });
}
Controller._pluginFactories = {};
/*
* Registers a plugin, making is accessible to controller.use later on.
*
* @member plugin
* @memberof Leap.Controller.prototype
* @param {String} name The name of the plugin (usually camelCase).
* @param {function} factory A factory method which will return an instance of a plugin.
* The factory receives an optional hash of options, passed in via controller.use.
*
* Valid keys for the object include frame, hand, finger, tool, and pointable. The value
* of each key can be either a function or an object. If given a function, that function
* will be called once for every instance of the object, with that instance injected as an
* argument. This allows decoration of objects with additional data:
*
* ```javascript
* Leap.Controller.plugin('testPlugin', function(options){
* return {
* frame: function(frame){
* frame.foo = 'bar';
* }
* }
* });
* ```
*
* When hand is used, the callback is called for every hand in `frame.hands`. Note that
* hand objects are recreated with every new frame, so that data saved on the hand will not
* persist.
*
* ```javascript
* Leap.Controller.plugin('testPlugin', function(){
* return {
* hand: function(hand){
* console.log('testPlugin running on hand ' + hand.id);
* }
* }
* });
* ```
*
* A factory can return an object to add custom functionality to Frames, Hands, or Pointables.
* The methods are added directly to the object's prototype. Finger and Tool cannot be used here, Pointable
* must be used instead.
* This is encouraged for calculations which may not be necessary on every frame.
* Memoization is also encouraged, for cases where the method may be called many times per frame by the application.
*
* ```javascript
* // This plugin allows hand.usefulData() to be called later.
* Leap.Controller.plugin('testPlugin', function(){
* return {
* hand: {
* usefulData: function(){
* console.log('usefulData on hand', this.id);
* // memoize the results on to the hand, preventing repeat work:
* this.x || this.x = someExpensiveCalculation();
* return this.x;
* }
* }
* }
* });
*
* Note that the factory pattern allows encapsulation for every plugin instance.
*
* ```javascript
* Leap.Controller.plugin('testPlugin', function(options){
* options || options = {}
* options.center || options.center = [0,0,0]
*
* privatePrintingMethod = function(){
* console.log('privatePrintingMethod - options', options);
* }
*
* return {
* pointable: {
* publicPrintingMethod: function(){
* privatePrintingMethod();
* }
* }
* }
* });
*
*/
Controller.plugin = function(pluginName, factory) {
if (this._pluginFactories[pluginName]) {
throw "Plugin \"" + pluginName + "\" already registered";
}
return this._pluginFactories[pluginName] = factory;
};
/*
* Returns a list of registered plugins.
* @returns {Array} Plugin Factories.
*/
Controller.plugins = function() {
return _.keys(this._pluginFactories);
};
/*
* Begin using a registered plugin. The plugin's functionality will be added to all frames
* returned by the controller (and/or added to the objects within the frame).
* - The order of plugin execution inside the loop will match the order in which use is called by the application.
* - The plugin be run for both deviceFrames and animationFrames.
*
* If called a second time, the options will be merged with those of the already instantiated plugin.
*
* @method use
* @memberOf Leap.Controller.prototype
* @param pluginName
* @param {Hash} Options to be passed to the plugin's factory.
* @returns the controller
*/
Controller.prototype.use = function(pluginName, options) {
var functionOrHash, pluginFactory, key, pluginInstance, klass;
pluginFactory = (typeof pluginName == 'function') ? pluginName : Controller._pluginFactories[pluginName];
if (!pluginFactory) {
throw 'Leap Plugin ' + pluginName + ' not found.';
}
options || (options = {});
if (this.plugins[pluginName]){
_.extend(this.plugins[pluginName], options)
return this;
}
this.plugins[pluginName] = options;
pluginInstance = pluginFactory.call(this, options);
for (key in pluginInstance) {
functionOrHash = pluginInstance[key];
if (typeof functionOrHash === 'function') {
if (!this.pipeline) this.pipeline = new Pipeline(this);
if (!this._pluginPipelineSteps[pluginName]) this._pluginPipelineSteps[pluginName] = [];
this._pluginPipelineSteps[pluginName].push( this.pipeline.addWrappedStep(key, functionOrHash) );
} else {
if (!this._pluginExtendedMethods[pluginName]) this._pluginExtendedMethods[pluginName] = [];
switch (key) {
case 'frame':
klass = Frame
break;
case 'hand':
klass = Hand
break;
case 'pointable':
klass = Pointable
break;
default:
throw pluginName + ' specifies invalid object type "' + key + '" for prototypical extension'
}
_.extend(klass.prototype, functionOrHash);
_.extend(klass.Invalid, functionOrHash);
this._pluginExtendedMethods[pluginName].push([klass, functionOrHash])
}
}
return this;
};
/*
* Stop using a used plugin. This will remove any of the plugin's pipeline methods (those called on every frame)
* and remove any methods which extend frame-object prototypes.
*
* @method stopUsing
* @memberOf Leap.Controller.prototype
* @param pluginName
* @returns the controller
*/
Controller.prototype.stopUsing = function (pluginName) {
var steps = this._pluginPipelineSteps[pluginName],
extMethodHashes = this._pluginExtendedMethods[pluginName],
i = 0, klass, extMethodHash;
if (!this.plugins[pluginName]) return;
if (steps) {
for (i = 0; i < steps.length; i++) {
this.pipeline.removeStep(steps[i]);
}
}
if (extMethodHashes){
for (i = 0; i < extMethodHashes.length; i++){
klass = extMethodHashes[i][0]
extMethodHash = extMethodHashes[i][1]
for (var methodName in extMethodHash) {
delete klass.prototype[methodName]
delete klass.Invalid[methodName]
}
}
}
delete this.plugins[pluginName]
return this;
}
Controller.prototype.useRegisteredPlugins = function(){
for (var plugin in Controller._pluginFactories){
this.use(plugin);
}
}
_.extend(Controller.prototype, EventEmitter.prototype);
},{"./circular_buffer":1,"./connection/browser":3,"./connection/node":17,"./frame":5,"./gesture":6,"./hand":7,"./pipeline":10,"./pointable":11,"__browserify_process":19,"events":18,"underscore":21}],5:[function(require,module,exports){
var Hand = require("./hand")
, Pointable = require("./pointable")
, createGesture = require("./gesture").createGesture
, glMatrix = require("gl-matrix")
, mat3 = glMatrix.mat3
, vec3 = glMatrix.vec3
, InteractionBox = require("./interaction_box")
, _ = require("underscore");
/**
* Constructs a Frame object.
*
* Frame instances created with this constructor are invalid.
* Get valid Frame objects by calling the
* [Controller.frame]{@link Leap.Controller#frame}() function.
*<C-D-Space>
* @class Frame
* @memberof Leap
* @classdesc
* The Frame class represents a set of hand and finger tracking data detected
* in a single frame.
*
* The Leap detects hands, fingers and tools within the tracking area, reporting
* their positions, orientations and motions in frames at the Leap frame rate.
*
* Access Frame objects using the [Controller.frame]{@link Leap.Controller#frame}() function.
*/
var Frame = module.exports = function(data) {
/**
* Reports whether this Frame instance is valid.
*
* A valid Frame is one generated by the Controller object that contains
* tracking data for all detected entities. An invalid Frame contains no
* actual tracking data, but you can call its functions without risk of a
* undefined object exception. The invalid Frame mechanism makes it more
* convenient to track individual data across the frame history. For example,
* you can invoke:
*
* ```javascript
* var finger = controller.frame(n).finger(fingerID);
* ```
*
* for an arbitrary Frame history value, "n", without first checking whether
* frame(n) returned a null object. (You should still check that the
* returned Finger instance is valid.)
*
* @member valid
* @memberof Leap.Frame.prototype
* @type {Boolean}
*/
this.valid = true;
/**
* A unique ID for this Frame. Consecutive frames processed by the Leap
* have consecutive increasing values.
* @member id
* @memberof Leap.Frame.prototype
* @type {String}
*/
this.id = data.id;
/**
* The frame capture time in microseconds elapsed since the Leap started.
* @member timestamp
* @memberof Leap.Frame.prototype
* @type {number}
*/
this.timestamp = data.timestamp;
/**
* The list of Hand objects detected in this frame, given in arbitrary order.
* The list can be empty if no hands are detected.
*
* @member hands[]
* @memberof Leap.Frame.prototype
* @type {Leap.Hand}
*/
this.hands = [];
this.handsMap = {};
/**
* The list of Pointable objects (fingers and tools) detected in this frame,
* given in arbitrary order. The list can be empty if no fingers or tools are
* detected.
*
* @member pointables[]
* @memberof Leap.Frame.prototype
* @type {Leap.Pointable}
*/
this.pointables = [];
/**
* The list of Tool objects detected in this frame, given in arbitrary order.
* The list can be empty if no tools are detected.
*
* @member tools[]
* @memberof Leap.Frame.prototype
* @type {Leap.Pointable}
*/
this.tools = [];
/**
* The list of Finger objects detected in this frame, given in arbitrary order.
* The list can be empty if no fingers are detected.
* @member fingers[]
* @memberof Leap.Frame.prototype
* @type {Leap.Pointable}
*/
this.fingers = [];
/**
* The InteractionBox associated with the current frame.
*
* @member interactionBox
* @memberof Leap.Frame.prototype
* @type {Leap.InteractionBox}
*/
if (data.interactionBox) {
this.interactionBox = new InteractionBox(data.interactionBox);
}
this.gestures = [];
this.pointablesMap = {};
this._translation = data.t;
this._rotation = _.flatten(data.r);
this._scaleFactor = data.s;
this.data = data;
this.type = 'frame'; // used by event emitting
this.currentFrameRate = data.currentFrameRate;
var handMap = {};
for (var handIdx = 0, handCount = data.hands.length; handIdx != handCount; handIdx++) {
var hand = new Hand(data.hands[handIdx]);
hand.frame = this;
this.hands.push(hand);
this.handsMap[hand.id] = hand;
handMap[hand.id] = handIdx;
}
for (var pointableIdx = 0, pointableCount = data.pointables.length; pointableIdx != pointableCount; pointableIdx++) {
var pointable = new Pointable(data.pointables[pointableIdx]);
pointable.frame = this;
this.pointables.push(pointable);
this.pointablesMap[pointable.id] = pointable;
(pointable.tool ? this.tools : this.fingers).push(pointable);
if (pointable.handId !== undefined && handMap.hasOwnProperty(pointable.handId)) {
var hand = this.hands[handMap[pointable.handId]];
hand.pointables.push(pointable);
(pointable.tool ? hand.tools : hand.fingers).push(pointable);
}
}
if (data.gestures) {
/**
* The list of Gesture objects detected in this frame, given in arbitrary order.
* The list can be empty if no gestures are detected.
*
* Circle and swipe gestures are updated every frame. Tap gestures
* only appear in the list for a single frame.
* @member gestures[]
* @memberof Leap.Frame.prototype
* @type {Leap.Gesture}
*/
for (var gestureIdx = 0, gestureCount = data.gestures.length; gestureIdx != gestureCount; gestureIdx++) {
this.gestures.push(createGesture(data.gestures[gestureIdx]));
}
}
}
/**
* The tool with the specified ID in this frame.
*
* Use the Frame tool() function to retrieve a tool from
* this frame using an ID value obtained from a previous frame.
* This function always returns a Pointable object, but if no tool
* with the specified ID is present, an invalid Pointable object is returned.
*
* Note that ID values persist across frames, but only until tracking of a
* particular object is lost. If tracking of a tool is lost and subsequently
* regained, the new Pointable object representing that tool may have a
* different ID than that representing the tool in an earlier frame.
*
* @method tool
* @memberof Leap.Frame.prototype
* @param {String} id The ID value of a Tool object from a previous frame.
* @returns {Leap.Pointable} The tool with the
* matching ID if one exists in this frame; otherwise, an invalid Pointable object
* is returned.
*/
Frame.prototype.tool = function(id) {
var pointable = this.pointable(id);
return pointable.tool ? pointable : Pointable.Invalid;
}
/**
* The Pointable object with the specified ID in this frame.
*
* Use the Frame pointable() function to retrieve the Pointable object from
* this frame using an ID value obtained from a previous frame.
* This function always returns a Pointable object, but if no finger or tool
* with the specified ID is present, an invalid Pointable object is returned.
*
* Note that ID values persist across frames, but only until tracking of a
* particular object is lost. If tracking of a finger or tool is lost and subsequently
* regained, the new Pointable object representing that finger or tool may have
* a different ID than that representing the finger or tool in an earlier frame.
*
* @method pointable
* @memberof Leap.Frame.prototype
* @param {String} id The ID value of a Pointable object from a previous frame.
* @returns {Leap.Pointable} The Pointable object with
* the matching ID if one exists in this frame;
* otherwise, an invalid Pointable object is returned.
*/
Frame.prototype.pointable = function(id) {
return this.pointablesMap[id] || Pointable.Invalid;
}
/**
* The finger with the specified ID in this frame.
*
* Use the Frame finger() function to retrieve the finger from
* this frame using an ID value obtained from a previous frame.
* This function always returns a Finger object, but if no finger
* with the specified ID is present, an invalid Pointable object is returned.
*
* Note that ID values persist across frames, but only until tracking of a
* particular object is lost. If tracking of a finger is lost and subsequently
* regained, the new Pointable object representing that physical finger may have
* a different ID than that representing the finger in an earlier frame.
*
* @method finger
* @memberof Leap.Frame.prototype
* @param {String} id The ID value of a finger from a previous frame.
* @returns {Leap.Pointable} The finger with the
* matching ID if one exists in this frame; otherwise, an invalid Pointable
* object is returned.
*/
Frame.prototype.finger = function(id) {
var pointable = this.pointable(id);
return !pointable.tool ? pointable : Pointable.Invalid;
}
/**
* The Hand object with the specified ID in this frame.
*
* Use the Frame hand() function to retrieve the Hand object from
* this frame using an ID value obtained from a previous frame.
* This function always returns a Hand object, but if no hand
* with the specified ID is present, an invalid Hand object is returned.
*
* Note that ID values persist across frames, but only until tracking of a
* particular object is lost. If tracking of a hand is lost and subsequently
* regained, the new Hand object representing that physical hand may have
* a different ID than that representing the physical hand in an earlier frame.
*
* @method hand
* @memberof Leap.Frame.prototype
* @param {String} id The ID value of a Hand object from a previous frame.
* @returns {Leap.Hand} The Hand object with the matching
* ID if one exists in this frame; otherwise, an invalid Hand object is returned.
*/
Frame.prototype.hand = function(id) {
return this.handsMap[id] || Hand.Invalid;
}
/**
* The angle of rotation around the rotation axis derived from the overall
* rotational motion between the current frame and the specified frame.
*
* The returned angle is expressed in radians measured clockwise around
* the rotation axis (using the right-hand rule) between the start and end frames.
* The value is always between 0 and pi radians (0 and 180 degrees).
*
* The Leap derives frame rotation from the relative change in position and
* orientation of all objects detected in the field of view.
*
* If either this frame or sinceFrame is an invalid Frame object, then the
* angle of rotation is zero.
*
* @method rotationAngle
* @memberof Leap.Frame.prototype
* @param {Leap.Frame} sinceFrame The starting frame for computing the relative rotation.
* @param {number[]} [axis] The axis to measure rotation around.
* @returns {number} A positive value containing the heuristically determined
* rotational change between the current frame and that specified in the sinceFrame parameter.
*/
Frame.prototype.rotationAngle = function(sinceFrame, axis) {
if (!this.valid || !sinceFrame.valid) return 0.0;
var rot = this.rotationMatrix(sinceFrame);
var cs = (rot[0] + rot[4] + rot[8] - 1.0)*0.5
var angle = Math.acos(cs);
angle = isNaN(angle) ? 0.0 : angle;
if (axis !== undefined) {
var rotAxis = this.rotationAxis(sinceFrame);
angle *= vec3.dot(rotAxis, vec3.normalize(vec3.create(), axis));
}
return angle;
}
/**
* The axis of rotation derived from the overall rotational motion between
* the current frame and the specified frame.
*
* The returned direction vector is normalized.
*
* The Leap derives frame rotation from the relative change in position and
* orientation of all objects detected in the field of view.
*
* If either this frame or sinceFrame is an invalid Frame object, or if no
* rotation is detected between the two frames, a zero vector is returned.
*
* @method rotationAxis
* @memberof Leap.Frame.prototype
* @param {Leap.Frame} sinceFrame The starting frame for computing the relative rotation.
* @returns {number[]} A normalized direction vector representing the axis of the heuristically determined
* rotational change between the current frame and that specified in the sinceFrame parameter.
*/
Frame.prototype.rotationAxis = function(sinceFrame) {
if (!this.valid || !sinceFrame.valid) return vec3.create();
return vec3.normalize(vec3.create(), [
this._rotation[7] - sinceFrame._rotation[5],
this._rotation[2] - sinceFrame._rotation[6],
this._rotation[3] - sinceFrame._rotation[1]
]);
}