UNPKG

bespoke-leapmotion

Version:
1,677 lines (1,391 loc) 283 kB
/*! * bespoke-leapmotion v1.0.0 * * Copyright 2015, Leo Liang * This content is released under the MIT license * http://aleung.mit-license.org/ */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self);var n=o;n=n.bespoke||(n.bespoke={}),n=n.plugins||(n.plugins={}),n.leapmotion=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Leap = _dereq_('leapjs'); module.exports = function() { return function(deck) { var lastGesture = 0, now; new Leap.Controller({enableGestures: true}) .connect() .on('frame', function (frame) { var gesture = frame.gestures[0]; now = new Date().getTime(); // one hand swipe gesture if (frame.gestures.length > 0 && gesture.type === 'swipe' && (now - lastGesture) > 300 ) { if (frame.hands.length === 1) { var x = gesture.direction[0], y = gesture.direction[1], isHorizontal = Math.abs(x) > Math.abs(y); if (isHorizontal) { if (x > 0) { deck.prev(); } else { deck.next(); } lastGesture = now; } } } }); }; }; },{"leapjs":15}],2:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],3:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],4:[function(_dereq_,module,exports){ var Pointable = _dereq_('./pointable'), glMatrix = _dereq_("gl-matrix") , vec3 = glMatrix.vec3 , mat3 = glMatrix.mat3 , mat4 = glMatrix.mat4 , _ = _dereq_('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":18,"gl-matrix":24,"underscore":25}],5:[function(_dereq_,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++; } },{}],6:[function(_dereq_,module,exports){ var chooseProtocol = _dereq_('../protocol').chooseProtocol , EventEmitter = _dereq_('events').EventEmitter , _ = _dereq_('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":19,"events":2,"underscore":25}],7:[function(_dereq_,module,exports){ var BaseConnection = module.exports = _dereq_('./base') , _ = _dereq_('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":6,"underscore":25}],8:[function(_dereq_,module,exports){ var WebSocket = _dereq_('ws') , BaseConnection = _dereq_('./base') , _ = _dereq_('underscore'); var NodeConnection = module.exports = function(opts) { BaseConnection.call(this, opts); var connection = this; this.on('ready', function() { connection.reportFocus(true); }); } _.extend(NodeConnection.prototype, BaseConnection.prototype); NodeConnection.__proto__ = BaseConnection; NodeConnection.prototype.setupSocket = function() { var connection = this; var socket = new WebSocket(this.getUrl()); socket.on('open', function() { connection.handleOpen(); }); socket.on('message', function(m) { connection.handleData(m); }); socket.on('close', function(code, reason) { connection.handleClose(code, reason); }); socket.on('error', function() { connection.startReconnection(); }); return socket; } },{"./base":6,"underscore":25,"ws":26}],9:[function(_dereq_,module,exports){ (function (process){ var Frame = _dereq_('./frame') , Hand = _dereq_('./hand') , Pointable = _dereq_('./pointable') , Finger = _dereq_('./finger') , CircularBuffer = _dereq_("./circular_buffer") , Pipeline = _dereq_("./pipeline") , EventEmitter = _dereq_('events').EventEmitter , gestureListener = _dereq_('./gesture').gestureListener , Dialog = _dereq_('./dialog') , _ = _dereq_('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() ? _dereq_('./connection/browser') : _dereq_('./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); }).call(this,_dereq_("FWaASH")) },{"./circular_buffer":5,"./connection/browser":7,"./connection/node":8,"./dialog":10,"./finger":11,"./frame":12,"./gesture":13,"./hand":14,"./pipeline":17,"./pointable":18,"FWaASH":3,"events":2,"underscore":25}],10:[function(_dereq_,module,exports){ (function (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('m