elation-engine
Version:
WebGL/WebVR engine written in Javascript
1,620 lines (1,355 loc) • 279 kB
JavaScript
/*!
* LeapJS v0.6.4
* http://github.com/leapmotion/leapjs/
*
* Copyright 2013 LeapMotion, Inc. and other contributors
* Released under the Apache-2.0 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 Pointable = require('./pointable'),
glMatrix = require("gl-matrix")
, vec3 = glMatrix.vec3
, mat3 = glMatrix.mat3
, mat4 = glMatrix.mat4
, _ = require('underscore');
var Bone = module.exports = function(finger, data) {
this.finger = finger;
this._center = null, this._matrix = null;
/**
* An integer code for the name of this bone.
*
* * 0 -- metacarpal
* * 1 -- proximal
* * 2 -- medial
* * 3 -- distal
* * 4 -- arm
*
* @member type
* @type {number}
* @memberof Leap.Bone.prototype
*/
this.type = data.type;
/**
* The position of the previous, or base joint of the bone closer to the wrist.
* @type {vector3}
*/
this.prevJoint = data.prevJoint;
/**
* The position of the next joint, or the end of the bone closer to the finger tip.
* @type {vector3}
*/
this.nextJoint = data.nextJoint;
/**
* The estimated width of the tool in millimeters.
*
* The reported width is the average width of the visible portion of the
* tool from the hand to the tip. If the width isn't known,
* then a value of 0 is returned.
*
* Pointable objects representing fingers do not have a width property.
*
* @member width
* @type {number}
* @memberof Leap.Pointable.prototype
*/
this.width = data.width;
var displacement = new Array(3);
vec3.sub(displacement, data.nextJoint, data.prevJoint);
this.length = vec3.length(displacement);
/**
*
* These fully-specify the orientation of the bone.
* See examples/threejs-bones.html for more info
* Three vec3s:
* x (red): The rotation axis of the finger, pointing outwards. (In general, away from the thumb )
* y (green): The "up" vector, orienting the top of the finger
* z (blue): The roll axis of the bone.
*
* Most up vectors will be pointing the same direction, except for the thumb, which is more rightwards.
*
* The thumb has one fewer bones than the fingers, but there are the same number of joints & joint-bases provided
* the first two appear in the same position, but only the second (proximal) rotates.
*
* Normalized.
*/
this.basis = data.basis;
};
Bone.prototype.left = function(){
if (this._left) return this._left;
this._left = mat3.determinant(this.basis[0].concat(this.basis[1]).concat(this.basis[2])) < 0;
return this._left;
};
/**
* The Affine transformation matrix describing the orientation of the bone, in global Leap-space.
* It contains a 3x3 rotation matrix (in the "top left"), and center coordinates in the fourth column.
*
* Unlike the basis, the right and left hands have the same coordinate system.
*
*/
Bone.prototype.matrix = function(){
if (this._matrix) return this._matrix;
var b = this.basis,
t = this._matrix = mat4.create();
// open transform mat4 from rotation mat3
t[0] = b[0][0], t[1] = b[0][1], t[2] = b[0][2];
t[4] = b[1][0], t[5] = b[1][1], t[6] = b[1][2];
t[8] = b[2][0], t[9] = b[2][1], t[10] = b[2][2];
t[3] = this.center()[0];
t[7] = this.center()[1];
t[11] = this.center()[2];
if ( this.left() ) {
// flip the basis to be right-handed
t[0] *= -1;
t[1] *= -1;
t[2] *= -1;
}
return this._matrix;
};
/**
* Helper method to linearly interpolate between the two ends of the bone.
*
* when t = 0, the position of prevJoint will be returned
* when t = 1, the position of nextJoint will be returned
*/
Bone.prototype.lerp = function(out, t){
vec3.lerp(out, this.prevJoint, this.nextJoint, t);
};
/**
*
* The center position of the bone
* Returns a vec3 array.
*
*/
Bone.prototype.center = function(){
if (this._center) return this._center;
var center = vec3.create();
this.lerp(center, 0.5);
this._center = center;
return center;
};
// The negative of the z-basis
Bone.prototype.direction = function(){
return [
this.basis[2][0] * -1,
this.basis[2][1] * -1,
this.basis[2][2] * -1
];
};
},{"./pointable":14,"gl-matrix":23,"underscore":24}],2:[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++;
}
},{}],3:[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,
scheme: this.getScheme(),
port: this.getPort(),
background: false,
optimizeHMD: false,
requestProtocolVersion: BaseConnection.defaultProtocolVersion
});
this.host = this.opts.host;
this.port = this.opts.port;
this.scheme = this.opts.scheme;
this.protocolVersionVerified = false;
this.background = null;
this.optimizeHMD = null;
this.on('ready', function() {
this.enableGestures(this.opts.enableGestures);
this.setBackground(this.opts.background);
this.setOptimizeHMD(this.opts.optimizeHMD);
if (this.opts.optimizeHMD){
console.log("Optimized for head mounted display usage.");
}else {
console.log("Optimized for desktop usage.");
}
});
};
// The latest available:
BaseConnection.defaultProtocolVersion = 6;
BaseConnection.prototype.getUrl = function() {
return this.scheme + "//" + this.host + ":" + this.port + "/v" + this.opts.requestProtocolVersion + ".json";
}
BaseConnection.prototype.getScheme = function(){
return 'ws:'
}
BaseConnection.prototype.getPort = function(){
return 6437
}
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.setOptimizeHMD = function(state) {
this.opts.optimizeHMD = state;
if (this.protocol && this.protocol.sendOptimizeHMD && this.optimizeHMD !== this.opts.optimizeHMD) {
this.optimizeHMD = this.opts.optimizeHMD;
this.protocol.sendOptimizeHMD(this, this.opts.optimizeHMD);
}
}
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;
if(!this.reconnectionTimer){
(this.reconnectionTimer = setInterval(function() { connection.reconnect() }, 500));
}
}
BaseConnection.prototype.stopReconnection = function() {
this.reconnectionTimer = clearInterval(this.reconnectionTimer);
}
// By default, disconnect will prevent auto-reconnection.
// Pass in true to allow the reconnection loop not be interrupted continue
BaseConnection.prototype.disconnect = function(allowReconnect) {
if (!allowReconnect) this.stopReconnection();
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
delete this.optimizeHMD;
delete this.focusedState;
if (this.connected) {
this.connected = false;
this.emit('disconnect');
}
return true;
}
BaseConnection.prototype.reconnect = function() {
if (this.connected) {
this.stopReconnection();
} else {
this.disconnect(true);
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.connected || 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":15,"events":21,"underscore":24}],4:[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.__proto__ = BaseConnection;
BrowserConnection.prototype.useSecure = function(){
return location.protocol === 'https:'
}
BrowserConnection.prototype.getScheme = function(){
return this.useSecure() ? 'wss:' : 'ws:'
}
BrowserConnection.prototype.getPort = function(){
return this.useSecure() ? 6436 : 6437
}
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) };
socket.onerror = function(error) {
// attempt to degrade to ws: after one failed attempt for older Leap Service installations.
if (connection.useSecure() && connection.scheme === 'wss:'){
connection.scheme = 'ws:';
connection.port = 6437;
connection.disconnect();
connection.connect();
}
};
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);
}
// save 100ms when resuming focus
updateFocusState();
this.focusDetectorTimer = setInterval(updateFocusState, 100);
}
BrowserConnection.prototype.stopFocusLoop = function() {
if (!this.focusDetectorTimer) return;
clearTimeout(this.focusDetectorTimer);
delete this.focusDetectorTimer;
}
},{"./base":3,"underscore":24}],5:[function(require,module,exports){
var process=require("__browserify_process");var Frame = require('./frame')
, Hand = require('./hand')
, Pointable = require('./pointable')
, Finger = require('./finger')
, CircularBuffer = require("./circular_buffer")
, Pipeline = require("./pipeline")
, EventEmitter = require('events').EventEmitter
, gestureListener = require('./gesture').gestureListener
, Dialog = require('./dialog')
, _ = 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.
*
* loopWhileDisconnected defaults to true, and maintains a 60FPS frame rate even when Leap Motion is not streaming
* data at that rate (such as no hands in frame). This is important for VR/WebGL apps which rely on rendering for
* regular visual updates, including from other input devices. Flipping this to false should be considered an
* optimization for very specific use-cases.
*
*
*/
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: true,
useAllPlugins: false,
checkVersion: true
});
this.animationFrameRequested = false;
this.onAnimationFrame = function(timestamp) {
if (controller.lastConnectionFrame.valid){
controller.emit('animationFrame', controller.lastConnectionFrame);
}
controller.emit('frameEnd', timestamp);
if (
controller.loopWhileDisconnected &&
( ( controller.connection.focusedState !== false ) // loop while undefined, pre-ready.
|| 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 = [];
this.checkVersion = opts.checkVersion;
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.streamingCount = 0;
this.devices = {};
this.plugins = {};
this._pluginPipelineSteps = {};
this._pluginExtendedMethods = {};
if (opts.useAllPlugins) this.useRegisteredPlugins();
this.setupFrameEvents(opts);
this.setupConnectionEvents();
this.startAnimationLoop(); // immediately when started
}
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.setOptimizeHMD = function(state) {
this.connection.setOptimizeHMD(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.streaming = function() {
return this.streamingCount > 0;
}
Controller.prototype.connected = function() {
return !!this.connection.connected;
}
Controller.prototype.startAnimationLoop = 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) {
if (callback) {
if (typeof callback === 'function'){
this.on(this.frameEventName, callback);
}else{
// callback is actually of the form: {eventName: callback}
this.setupFrameEvents(callback);
}
}
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.startAnimationLoop(); // Only has effect if loopWhileDisconnected: false
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);
this.emitHandEvents(frame);
}
/**
* The controller will emit 'hand' events for every hand on each frame. The hand in question will be passed
* to the event callback.
*
* @param frame
*/
Controller.prototype.emitHandEvents = function(frame){
for (var i = 0; i < frame.hands.length; i++){
this.emit('hand', frame.hands[i]);
}
}
Controller.prototype.setupFrameEvents = function(opts){
if (opts.frame){
this.on('frame', opts.frame);
}
if (opts.hand){
this.on('hand', opts.hand);
}
}
/**
Controller events. The old 'deviceConnected' and 'deviceDisconnected' have been depricated -
use 'deviceStreaming' and 'deviceStopped' instead, except in the case of an unexpected disconnect.
There are 4 pairs of device events recently added/changed:
-deviceAttached/deviceRemoved - called when a device's physical connection to the computer changes
-deviceStreaming/deviceStopped - called when a device is paused or resumed.
-streamingStarted/streamingStopped - called when there is/is no longer at least 1 streaming device.
Always comes after deviceStreaming.
The first of all of the above event pairs is triggered as appropriate upon connection. All of
these events receives an argument with the most recent info about the device that triggered it.
These events will always be fired in the order they are listed here, with reverse ordering for the
matching shutdown call. (ie, deviceStreaming always comes after deviceAttached, and deviceStopped
will come before deviceRemoved).
-deviceConnected/deviceDisconnected - These are considered deprecated and will be removed in
the next revision. In contrast to the other events and in keeping with it's original behavior,
it will only be fired when a device begins streaming AFTER a connection has been established.
It is not paired, and receives no device info. Nearly identical functionality to
streamingStarted/Stopped if you need to port.
*/
Controller.prototype.setupConnectionEvents = function() {
var controller = this;
this.connection.on('frame', function(frame) {
controller.processFrame(frame);
});
// either deviceFrame or animationFrame:
this.on(this.frameEventName, function(frame) {
controller.processFinishedFrame(frame);
});
// here we backfill the 0.5.0 deviceEvents as best possible
// backfill begin streaming events
var backfillStreamingStartedEventsHandler = function(){
if (controller.connection.opts.requestProtocolVersion < 5 && controller.streamingCount == 0){
controller.streamingCount = 1;
var info = {
attached: true,
streaming: true,
type: 'unknown',
id: "Lx00000000000"
};
controller.devices[info.id] = info;
controller.emit('deviceAttached', info);
controller.emit('deviceStreaming', info);
controller.emit('streamingStarted', info);
controller.connection.removeListener('frame', backfillStreamingStartedEventsHandler)
}
}
var backfillStreamingStoppedEvents = function(){
if (controller.streamingCount > 0) {
for (var deviceId in controller.devices){
controller.emit('deviceStopped', controller.devices[deviceId]);
controller.emit('deviceRemoved', controller.devices[deviceId]);
}
// only emit streamingStopped once, with the last device
controller.emit('streamingStopped', controller.devices[deviceId]);
controller.streamingCount = 0;
for (var deviceId in controller.devices){
delete controller.devices[deviceId];
}
}
}
// Delegate connection events
this.connection.on('focus', function() {
if ( controller.loopWhileDisconnected ){
controller.startAnimationLoop();
}
controller.emit('focus');
});
this.connection.on('blur', function() { controller.emit('blur') });
this.connection.on('protocol', function(protocol) {
protocol.on('beforeFrameCreated', function(frameData){
controller.emit('beforeFrameCreated', frameData)
});
protocol.on('afterFrameCreated', function(frame, frameData){
controller.emit('afterFrameCreated', frame, frameData)
});
controller.emit('protocol', protocol);
});
this.connection.on('ready', function() {
if (controller.checkVersion && !controller.inNode){
// show dialog only to web users
controller.checkOutOfDate();
}
controller.emit('ready');
});
this.connection.on('connect', function() {
controller.emit('connect');
controller.connection.removeListener('frame', backfillStreamingStartedEventsHandler)
controller.connection.on('frame', backfillStreamingStartedEventsHandler);
});
this.connection.on('disconnect', function() {
controller.emit('disconnect');
backfillStreamingStoppedEvents();
});
// this does not fire when the controller is manually disconnected
// or for Leap Service v1.2.0+
this.connection.on('deviceConnect', function(evt) {
if (evt.state){
controller.emit('deviceConnected');
controller.connection.removeListener('frame', backfillStreamingStartedEventsHandler)
controller.connection.on('frame', backfillStreamingStartedEventsHandler);
}else{
controller.emit('deviceDisconnected');
backfillStreamingStoppedEvents();
}
});
// Does not fire for Leap Service pre v1.2.0
this.connection.on('deviceEvent', function(evt) {
var info = evt.state,
oldInfo = controller.devices[info.id];
//Grab a list of changed properties in the device info
var changed = {};
for(var property in info) {
//If a property i doesn't exist the cache, or has changed...
if( !oldInfo || !oldInfo.hasOwnProperty(property) || oldInfo[property] != info[property] ) {
changed[property] = true;
}
}
//Update the device list
controller.devices[info.id] = info;
//Fire events based on change list
if(changed.attached) {
controller.emit(info.attached ? 'deviceAttached' : 'deviceRemoved', info);
}
if(!changed.streaming) return;
if(info.streaming) {
controller.streamingCount++;
controller.emit('deviceStreaming', info);
if( controller.streamingCount == 1 ) {
controller.emit('streamingStarted', info);
}
//if attached & streaming both change to true at the same time, that device was streaming
//already when we connected.
if(!changed.attached) {
controller.emit('deviceConnected');
}
}
//Since when devices are attached all fields have changed, don't send events for streaming being false.
else if(!(changed.attached && info.attached)) {
controller.streamingCount--;
controller.emit('deviceStopped', info);
if(controller.streamingCount == 0){
controller.emit('streamingStopped', info);
}
controller.emit('deviceDisconnected');
}
});
this.on('newListener', function(event, listener) {
if( event == 'deviceConnected' || event == 'deviceDisconnected' ) {
console.warn(event + " events are depricated. Consider using 'streamingStarted/streamingStopped' or 'deviceStreaming/deviceStopped' instead");
}
});
};
// Checks if the protocol version is the latest, if if not, shows the dialog.
Controller.prototype.checkOutOfDate = function(){
console.assert(this.connection && this.connection.protocol);
var serviceVersion = this.connection.protocol.serviceVersion;
var protocolVersion = this.connection.protocol.version;
var defaultProtocolVersion = this.connectionType.defaultProtocolVersion;
if (defaultProtocolVersion > protocolVersion){
console.warn("Your Protocol Version is v" + protocolVersion +
", this app was designed for v" + defaultProtocolVersion);
Dialog.warnOutOfDate({
sV: serviceVersion,
pV: protocolVersion
});
return true
}else{
return false
}
};
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]) {
console.warn("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);
};
var setPluginCallbacks = function(pluginName, type, callback){
if ( ['beforeFrameCreated', 'afterFrameCreated'].indexOf(type) != -1 ){
// todo - not able to "unuse" a plugin currently
this.on(type, callback);
}else {
if (!this.pipeline) this.pipeline = new Pipeline(this);
if (!this._pluginPipelineSteps[pluginName]) this._pluginPipelineSteps[pluginName] = [];
this._pluginPipelineSteps[pluginName].push(
this.pipeline.addWrappedStep(type, callback)
);
}
};
var setPluginMethods = function(pluginName, type, hash){
var klass;
if (!this._pluginExtendedMethods[pluginName]) this._pluginExtendedMethods[pluginName] = [];
switch (type) {
case 'frame':
klass = Frame;
break;
case 'hand':
klass = Hand;
break;
case 'pointable':
klass = Pointable;
_.extend(Finger.prototype, hash);
_.extend(Finger.Invalid, hash);
break;
case 'finger':
klass = Finger;
break;
default:
throw pluginName + ' specifies invalid object type "' + type + '" for prototypical extension'
}
_.extend(klass.prototype, hash);
_.extend(klass.Invalid, hash);
this._pluginExtendedMethods[pluginName].push([klass, hash])
}
/*
* 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;
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') {
setPluginCallbacks.call(this, pluginName, key, functionOrHash);
} else {
setPluginMethods.call(this, pluginName, key, 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":2,"./connection/browser":4,"./connection/node":20,"./dialog":6,"./finger":7,"./frame":8,"./gesture":9,"./hand":10,"./pipeline":13,"./pointable":14,"__browserify_process":22,"events":21,"underscore":24}],6:[function(require,module,exports){
var process=require("__browserify_process");var Dialog = module.exports = function(message, options){
this.options = (options || {});
this.message = message;
this.createElement();
};
Dialog.prototype.createElement = function(){
this.element = document.createElement('div');
this.element.className = "leapjs-dialog";
this.element.style.position = "fixed";
this.element.style.top = '8px';
this.element.style.left = 0;
this.element.style.right = 0;
this.element.style.textAlign = 'center';
this.element.style.zIndex = 1000;
var dialog = document.createElement('div');
this.element.appendChild(dialog);
dialog.style.className = "leapjs-dialog";
dialog.style.display = "inline-block";
dialog.style.margin = "auto";
dialog.style.padding = "8px";
dialog.style.color = "#222";
dialog.style.background = "#eee";
dialog.style.borderRadius = "4px";
dialog.style.border = "1px solid #999";
dialog.style.textAlign = "left";
dialog.style.cursor = "pointer";
dialog.style.whiteSpace = "nowrap";
dialog.style.transition = "box-shadow 1s linear";
dialog.innerHTML = this.message;
if (this.options.onclick){
dialog.addEventListener('click', this.options.onclick);
}
if (this.options.onmouseover){
dialog.addEventListener('mouseover', this.options.onmouseover);
}
if (this.options.onmouseout){
dialog.addEventListener('mouseout', this.options.onmouseout);
}
if (this.options.onmousemove){
dialog.addEventListener('mousemove', this.options.onmousemove);
}
};
Dialog.prototype.show = function(){
document.body.appendChild(this.element);
return this;
};
Dialog.prototype.hide = function(){
document.body.removeChild(this.element);
return this;
};
// Shows a DOM dialog box with links to developer.leapmotion.com to upgrade
// This will work whether or not the Leap is plugged in,
// As long as it is called after a call to .connect() and the 'ready' event has fired.
Dialog.warnOutOfDate = function(params){
params || (params = {});
var url = "http://developer.leapmotion.com?";
params.returnTo = window.location.href;
for (var key in params){
url += key + '=' + encodeURIComponent(params[key]) + '&';
}
var dialog,
onclick = function(event){
if (event.target.id != 'leapjs-decline-upgrade'){
var popup = window.open(url,
'_blank',
'height=800,width=1000,location=1,menubar=1,resizable=1,status=1,toolbar=1,scrollbars=1'
);
if (window.focus) {popup.focus()}
}
dialog.hide();
return true;
},
message = "This site requires Leap Motion Tracking V2." +
"<button id='leapjs-accept-upgrade' style='color: #444; transition: box-shadow 100ms linear; cursor: pointer; vertical-align: baseline; margin-left: 16px;'>Upgrade</button>" +
"<button id='leapjs-decline-upgrade' style='color: #444; transition: box-shadow 100ms linear; cursor: pointer; vertical-align: baseline; margin-left: 8px; '>Not Now</button>";
dialog = new Dialog(message, {
onclick: onclick,
onmousemove: function(e){
if (e.target == document.getElementById('leapjs-decline-upgrade')){
document.getElementById('leapjs-decline-upgrade').style.color = '#000';
document.getElementById('leapjs-decline-upgrade').style.boxShadow = '0px 0px 2px #5daa00';
document.getElementById('leapjs-accept-upgrade').style.color = '#444';
document.getElementById('leapjs-accept-upgrade').style.boxShadow = 'none';
}else{
document.getElementById('leapjs-accept-upgrade').style.color = '#000';
document.getElementById('leapjs-accept-upgrade').style.boxShadow = '0px 0px 2px #5daa00';
document.getElementById('leapjs-decline-upgrade').style.color = '#444';
document.getElementById('leapjs-decline-upgrade').style.boxShadow = 'none';
}
},
onmouseout: function(){
document.getElementById('leapjs-decline-upgrade').style.color = '#444';
document.getElementById('leapjs-decline-upgrade').style.boxShadow = 'none';
document.getElementById('leapjs-accept-upgrade').style.color = '#444';
document.getElementById('leapjs-accept-upgrade').style.boxShadow = 'none';
}
}
);
return dialog.show();
};
// Tracks whether we've warned for lack of bones API. This will be shown only for early private-beta members.
Dialog.hasWarnedBones = false;
Dialog.warnBones = function(){
if (this.hasWarnedBones) return;
this.hasWarnedBones = true;
console.warn("Your Leap Service is out of date");
if ( !(typeof(process) !== 'undefined' && process.versions && process.versions.node) ){
this.warnOutOfDate({reason: 'bones'});
}
}
},{"__browserify_process":22}],7:[function(require,module,exports){
var Pointable = require('./pointable'),
Bone = require('./bone')
, Dialog = require('./dialog')
, _ = require('underscore');
/**
* Constructs a Finger object.
*
* An uninitialized finger is considered invalid.
* Get valid Finger objects from a Frame or a Hand object.
*
* @class Finger
* @memberof Leap
* @classdesc
* The Finger class reports the physical characteristics of a finger.
*
* Both fingers and tools are classified as Pointable objects. Use the
* Pointable.tool property to determine whether a Pointable object represents a
* tool or finger. The Leap classifies a detected entity as a tool when it is
* thinner, straighter, and longer than a typical finger.
*
* Note that Finger objects can be invalid, which means that they do not
* contain valid tracking data and do not correspond to a physical entity.
* Invalid Finger objects can be the result of asking for a Finger object
* using an ID from an earlier frame when no Finger objects with that ID
* exist in the current frame. A Finger object created from the Finger
* constructor is also invalid. Test for validity with the Pointable.valid
* property.
*/
var Finger = module.exports = function(data) {
Pointable.call(this, data); // use pointable as super-constructor
/**
* The position of the distal interphalangeal joint of the finger.
* This joint is closest to the tip.
*
* The distal interphalangeal joint is located between the most extreme segment
* of the finger (the distal phalanx) and the middle segment (the medial
* phalanx).
*
* @member dipPosition
* @type {number[]}
* @memberof Leap.Finger.prototype
*/
this.dipPosition = data.dipPosition;
/**
* The position of the proximal interphalangeal joint of the finger. This joint is the middle
* joint of a finger.
*
* The proximal interphalangeal joint is located between the two finger segments
* closest to the hand (the proximal and the medial phalanges). On a thumb,
* which lacks an medial phalanx, this joint index identifies the knuckle joint
* between the proximal phalanx and the metacarpal bone.
*
* @member pipPosition
* @type {number[]}
* @memberof Leap.Finger.prototype
*/
this.pipPosition = data.pipPosition;
/**
* The position of the metacarpopophalangeal joint, or knuckle, of the finger.
*
* The metacarpopophalangeal joint is located at the base of a finger between
* the metacarpal bone and the first phalanx. The common name for this joint is
* the knuckle.
*
* On a thumb, which has one less phalanx than a finger, this joint index
* identifies the thumb joint near the base of the hand, between the carpal
* and metacarpal bones.
*
* @member mcpPosition
* @type {number[]}
* @memberof Leap.Finger.prototype
*/
this.mcpPosition = data.mcpPosition;
/**
* The position of the Carpometacarpal joint
*
* This is at the distal end of the wrist, and has no common name.
*
*/
this.carpPosition = data.carpPosition;
/**
* Whether or not this finger is in an extended posture.
*
* A finger is considered extended if it is extended straight from the hand as if
* pointing. A finger is not extended when it is bent down and curled towards the
* palm.
* @member extended
* @type {Boolean}
* @memberof Leap.Finger.prototype
*/
this.extended = data.extended;
/**
* An integer code for the name of this finger.
*
* * 0 -- thumb
* * 1 -- index finger
* * 2 -- middle finger
* * 3 -- ring finger
* * 4 -- pinky
*
* @member type
* @type {number}
* @memberof Leap.Finger.prototype
*/
this.type = data.type;
this.finger = true;
/**
* The joint positions of this finger as an array in the order base to tip.
*
* @member positions
* @type {array[]}
* @memberof Leap.Finger.prototype
*/
this.positions = [this.carpPosition, this.mcpPosition, this.pipPosition, this.dipPosition, this.tipPosition];
if (data.bases){
this.addBones(data);
} else {
Dialog.warnBones();
}
};
_.extend(Finger.prototype, Pointable.prototype);
Finger.prototype.addBones = function(data){
/**
* Four bones per finger, from wrist outwards:
* metacarpal, proximal, medial, and distal.
*
* See http://en.wikipedia.org/wiki/Interphalangeal_articulations_of_hand
*/
this.metacarpal = new Bone(this, {
type: 0,
width: this.width,
prevJoint: this.carpPosition,
nextJoint: this.mcpPosition,
basis: data.bases[0]
});
this.proximal = new Bone(this, {
type: 1,
width: this.width,
prevJoint: this.mcpPosition,
nextJoint: this.pipPosition,
basis: data.bases[1]
});
this.medial = new Bone(this, {
type: 2,
width: this.width,
prevJoint: this.pipPosition,
nextJoint: this.dipPosition,
basis: data.bases[2]
});
/**
* Note that the `distal.nextJoint` position is slightly different from the `finger.tipPosition`.
* The former is at the very end of the bone, where the latter is the center of a sphere positioned at
* the tip of the finger. The btipPosition "bone tip position" is a few mm closer to the wrist than
* the tipPosition.
* @type {Bone}
*/
this.distal = new Bone(this, {
type: 3,
width: this.width,
prevJoint: this.dipPosition,
nextJoint: data.btipPosition,
basis: data.bases[3]
});
this.bones = [this.metacarpal, this.proximal, this.medial, this.distal];
};
Finger.prototype.toString = function() {
return "Finger [ id:" + this.id + " " + this.length + "mmx | width:" + this.width + "mm | direction:" + this.direction + ' ]';
};
Finger.Invalid = { valid: false };
},{"./bone":1,"./dialog":6,"./pointable":14,"underscore":24}],8:[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")
, Finger = require('./finger')
, _ = 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 = {}