From a3629ba4be2750f70287ccb6aeadd6e4ebded2c2 Mon Sep 17 00:00:00 2001 From: Peter Dave Hello Date: Fri, 31 Oct 2014 20:27:33 +0800 Subject: [PATCH] add cannon.js v0.6.1 --- ajax/libs/cannon.js/0.6.1/cannon.js | 11689 ++++++++++++++++++++++ ajax/libs/cannon.js/0.6.1/cannon.min.js | 27 + ajax/libs/cannon.js/package.json | 2 +- 3 files changed, 11717 insertions(+), 1 deletion(-) create mode 100644 ajax/libs/cannon.js/0.6.1/cannon.js create mode 100644 ajax/libs/cannon.js/0.6.1/cannon.min.js diff --git a/ajax/libs/cannon.js/0.6.1/cannon.js b/ajax/libs/cannon.js/0.6.1/cannon.js new file mode 100644 index 000000000..4640474cc --- /dev/null +++ b/ajax/libs/cannon.js/0.6.1/cannon.js @@ -0,0 +1,11689 @@ +/* + * Copyright (c) 2014 cannon.js Authors + * + * 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(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&false)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.CANNON=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 (http://steffe.se)", + "keywords": [ + "cannon.js", + "cannon", + "physics", + "engine", + "3d" + ], + "main": "./build/cannon.js", + "engines": { + "node": "*" + }, + "repository": { + "type": "git", + "url": "https://github.com/schteppe/cannon.js.git" + }, + "bugs": { + "url": "https://github.com/schteppe/cannon.js/issues" + }, + "licenses": [ + { + "type": "MIT" + } + ], + "devDependencies": { + "jshint": "latest", + "uglify-js": "latest", + "nodeunit": "^0.9.0", + "grunt": "~0.4.0", + "grunt-contrib-jshint": "~0.1.1", + "grunt-contrib-nodeunit": "^0.4.1", + "grunt-contrib-concat": "~0.1.3", + "grunt-contrib-uglify": "^0.5.1", + "grunt-browserify": "^2.1.4", + "grunt-contrib-yuidoc": "^0.5.2", + "browserify": "*" + }, + "dependencies": {} +} + +},{}],2:[function(_dereq_,module,exports){ +// Export classes +module.exports = { + version : _dereq_('../package.json').version, + + ArrayCollisionMatrix : _dereq_('./collision/ArrayCollisionMatrix'), + Body : _dereq_('./objects/Body'), + Box : _dereq_('./shapes/Box'), + Broadphase : _dereq_('./collision/Broadphase'), + Constraint : _dereq_('./constraints/Constraint'), + ContactEquation : _dereq_('./equations/ContactEquation'), + Narrowphase : _dereq_('./world/Narrowphase'), + ContactMaterial : _dereq_('./material/ContactMaterial'), + ConvexPolyhedron : _dereq_('./shapes/ConvexPolyhedron'), + Cylinder : _dereq_('./shapes/Cylinder'), + DistanceConstraint : _dereq_('./constraints/DistanceConstraint'), + Equation : _dereq_('./equations/Equation'), + EventTarget : _dereq_('./utils/EventTarget'), + FrictionEquation : _dereq_('./equations/FrictionEquation'), + GSSolver : _dereq_('./solver/GSSolver'), + GridBroadphase : _dereq_('./collision/GridBroadphase'), + Heightfield : _dereq_('./shapes/Heightfield'), + HingeConstraint : _dereq_('./constraints/HingeConstraint'), + Mat3 : _dereq_('./math/Mat3'), + Material : _dereq_('./material/Material'), + NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'), + ObjectCollisionMatrix : _dereq_('./collision/ObjectCollisionMatrix'), + Pool : _dereq_('./utils/Pool'), + Particle : _dereq_('./shapes/Particle'), + Plane : _dereq_('./shapes/Plane'), + PointToPointConstraint : _dereq_('./constraints/PointToPointConstraint'), + Quaternion : _dereq_('./math/Quaternion'), + Ray : _dereq_('./collision/Ray'), + RaycastVehicle : _dereq_('./objects/RaycastVehicle'), + RaycastResult : _dereq_('./collision/RaycastResult'), + RigidVehicle : _dereq_('./objects/RigidVehicle'), + RotationalEquation : _dereq_('./equations/RotationalEquation'), + RotationalMotorEquation : _dereq_('./equations/RotationalMotorEquation'), + SAPBroadphase : _dereq_('./collision/SAPBroadphase'), + SPHSystem : _dereq_('./objects/SPHSystem'), + Shape : _dereq_('./shapes/Shape'), + Solver : _dereq_('./solver/Solver'), + Sphere : _dereq_('./shapes/Sphere'), + SplitSolver : _dereq_('./solver/SplitSolver'), + Spring : _dereq_('./objects/Spring'), + Vec3 : _dereq_('./math/Vec3'), + Vec3Pool : _dereq_('./utils/Vec3Pool'), + World : _dereq_('./world/World'), +}; + +},{"../package.json":1,"./collision/ArrayCollisionMatrix":4,"./collision/Broadphase":5,"./collision/GridBroadphase":6,"./collision/NaiveBroadphase":7,"./collision/ObjectCollisionMatrix":8,"./collision/Ray":9,"./collision/RaycastResult":10,"./collision/SAPBroadphase":11,"./constraints/Constraint":12,"./constraints/DistanceConstraint":13,"./constraints/HingeConstraint":14,"./constraints/PointToPointConstraint":15,"./equations/ContactEquation":16,"./equations/Equation":17,"./equations/FrictionEquation":18,"./equations/RotationalEquation":19,"./equations/RotationalMotorEquation":20,"./material/ContactMaterial":21,"./material/Material":22,"./math/Mat3":24,"./math/Quaternion":25,"./math/Vec3":27,"./objects/Body":28,"./objects/RaycastVehicle":29,"./objects/RigidVehicle":30,"./objects/SPHSystem":31,"./objects/Spring":32,"./shapes/Box":34,"./shapes/ConvexPolyhedron":35,"./shapes/Cylinder":36,"./shapes/Heightfield":37,"./shapes/Particle":38,"./shapes/Plane":39,"./shapes/Shape":40,"./shapes/Sphere":41,"./solver/GSSolver":42,"./solver/Solver":43,"./solver/SplitSolver":44,"./utils/EventTarget":45,"./utils/Pool":46,"./utils/Vec3Pool":49,"./world/Narrowphase":50,"./world/World":51}],3:[function(_dereq_,module,exports){ +var Vec3 = _dereq_('../math/Vec3'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = AABB; + +/** + * Axis aligned bounding box class. + * @class AABB + * @constructor + * @param {Object} [options] + * @param {Array} [options.upperBound] + * @param {Array} [options.lowerBound] + */ +function AABB(options){ + options = options || {}; + + /** + * The lower bound of the bounding box. + * @property lowerBound + * @type {Array} + */ + this.lowerBound = new Vec3(); + if(options.lowerBound){ + this.lowerBound.copy(options.lowerBound); + } + + /** + * The upper bound of the bounding box. + * @property upperBound + * @type {Array} + */ + this.upperBound = new Vec3(); + if(options.upperBound){ + this.upperBound.copy(options.upperBound); + } +} + +var tmp = new Vec3(); + +/** + * Set the AABB bounds from a set of points. + * @method setFromPoints + * @param {Array} points An array of Vec3's. + * @param {Vec3} position + * @param {Quaternion} quaternion + * @param {number} skinSize + */ +AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){ + var l = this.lowerBound, + u = this.upperBound, + q = quaternion; + + // Set to the first point + l.copy(points[0]); + if(q){ + q.vmult(l, l); + } + u.copy(l); + + for(var i = 1; i u.x){ u.x = p.x; } + if(p.x < l.x){ l.x = p.x; } + if(p.y > u.y){ u.y = p.y; } + if(p.y < l.y){ l.y = p.y; } + if(p.z > u.z){ u.z = p.z; } + if(p.z < l.z){ l.z = p.z; } + } + + // Add offset + if (position) { + position.vadd(l, l); + position.vadd(u, u); + } + + if(skinSize){ + l.x -= skinSize; + l.y -= skinSize; + l.z -= skinSize; + u.x += skinSize; + u.y += skinSize; + u.z += skinSize; + } +}; + +/** + * Copy bounds from an AABB to this AABB + * @method copy + * @param {AABB} aabb Source to copy from + */ +AABB.prototype.copy = function(aabb){ + this.lowerBound.copy(aabb.lowerBound); + this.upperBound.copy(aabb.upperBound); +}; + +/** + * Extend this AABB so that it covers the given AABB too. + * @method extend + * @param {AABB} aabb + */ +AABB.prototype.extend = function(aabb){ + // Extend lower bound + var l = aabb.lowerBound.x; + if(this.lowerBound.x > l){ + this.lowerBound.x = l; + } + + // Upper + var u = aabb.upperBound.x; + if(this.upperBound.x < u){ + this.upperBound.x = u; + } + + // Extend lower bound + var l = aabb.lowerBound.y; + if(this.lowerBound.y > l){ + this.lowerBound.y = l; + } + + // Upper + var u = aabb.upperBound.y; + if(this.upperBound.y < u){ + this.upperBound.y = u; + } + + // Extend lower bound + var l = aabb.lowerBound.z; + if(this.lowerBound.z > l){ + this.lowerBound.z = l; + } + + // Upper + var u = aabb.upperBound.z; + if(this.upperBound.z < u){ + this.upperBound.z = u; + } +}; + +/** + * Returns true if the given AABB overlaps this AABB. + * @method overlaps + * @param {AABB} aabb + * @return {Boolean} + */ +AABB.prototype.overlaps = function(aabb){ + var l1 = this.lowerBound, + u1 = this.upperBound, + l2 = aabb.lowerBound, + u2 = aabb.upperBound; + + // l2 u2 + // |---------| + // |--------| + // l1 u1 + + return ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x)) && + ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y)) && + ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z)); +}; + +},{"../math/Vec3":27,"../utils/Utils":48}],4:[function(_dereq_,module,exports){ +module.exports = ArrayCollisionMatrix; + +/** + * Collision "matrix". It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step + * @class ArrayCollisionMatrix + * @constructor + */ +function ArrayCollisionMatrix() { + + /** + * The matrix storage + * @property matrix + * @type {Array} + */ + this.matrix = []; +} + +/** + * Get an element + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +ArrayCollisionMatrix.prototype.get = function(i, j) { + i = i.index; + j = j.index; + if (j > i) { + var temp = j; + j = i; + i = temp; + } + return this.matrix[(i*(i + 1)>>1) + j-1]; +}; + +/** + * Set an element + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +ArrayCollisionMatrix.prototype.set = function(i, j, value) { + i = i.index; + j = j.index; + if (j > i) { + var temp = j; + j = i; + i = temp; + } + this.matrix[(i*(i + 1)>>1) + j-1] = value ? 1 : 0; +}; + +/** + * Sets all elements to zero + * @method reset + */ +ArrayCollisionMatrix.prototype.reset = function() { + for (var i=0, l=this.matrix.length; i!==l; i++) { + this.matrix[i]=0; + } +}; + +/** + * Sets the max number of objects + * @method setNumObjects + * @param {Number} n + */ +ArrayCollisionMatrix.prototype.setNumObjects = function(n) { + this.matrix.length = n*(n-1)>>1; +}; + +},{}],5:[function(_dereq_,module,exports){ +var Body = _dereq_('../objects/Body'); +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var Shape = _dereq_('../shapes/Shape'); +var Plane = _dereq_('../shapes/Plane'); + +module.exports = Broadphase; + +/** + * Base class for broadphase implementations + * @class Broadphase + * @constructor + * @author schteppe + */ +function Broadphase(){ + /** + * The world to search for collisions in. + * @property world + * @type {World} + */ + this.world = null; + + /** + * If set to true, the broadphase uses bounding boxes for intersection test, else it uses bounding spheres. + * @property useBoundingBoxes + * @type {Boolean} + */ + this.useBoundingBoxes = false; + + /** + * Set to true if the objects in the world moved. + * @property {Boolean} dirty + */ + this.dirty = true; +} + +/** + * Get the collision pairs from the world + * @method collisionPairs + * @param {World} world The world to search in + * @param {Array} p1 Empty array to be filled with body objects + * @param {Array} p2 Empty array to be filled with body objects + */ +Broadphase.prototype.collisionPairs = function(world,p1,p2){ + throw new Error("collisionPairs not implemented for this BroadPhase class!"); +}; + +/** + * Check if a body pair needs to be intersection tested at all. + * @method needBroadphaseCollision + * @param {Body} bodyA + * @param {Body} bodyB + * @return {bool} + */ +var Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC = Body.STATIC | Body.KINEMATIC; +Broadphase.prototype.needBroadphaseCollision = function(bodyA,bodyB){ + + // Check collision filter masks + if( (bodyA.collisionFilterGroup & bodyB.collisionFilterMask)===0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask)===0){ + return false; + } + + // Check types + if(((bodyA.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyA.sleepState === Body.SLEEPING) && + ((bodyB.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyB.sleepState === Body.SLEEPING)) { + // Both bodies are static, kinematic or sleeping. Skip. + return false; + } + + return true; +}; + +/** + * Check if the bounding volumes of two bodies intersect. + * @method intersectionTest + * @param {Body} bodyA + * @param {Body} bodyB + * @param {array} pairs1 + * @param {array} pairs2 + */ +Broadphase.prototype.intersectionTest = function(bodyA, bodyB, pairs1, pairs2){ + if(this.useBoundingBoxes){ + this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2); + } else { + this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2); + } +}; + +/** + * Check if the bounding spheres of two bodies are intersecting. + * @method doBoundingSphereBroadphase + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Array} pairs1 bodyA is appended to this array if intersection + * @param {Array} pairs2 bodyB is appended to this array if intersection + */ +var Broadphase_collisionPairs_r = new Vec3(), // Temp objects + Broadphase_collisionPairs_normal = new Vec3(), + Broadphase_collisionPairs_quat = new Quaternion(), + Broadphase_collisionPairs_relpos = new Vec3(); +Broadphase.prototype.doBoundingSphereBroadphase = function(bodyA,bodyB,pairs1,pairs2){ + var r = Broadphase_collisionPairs_r; + bodyB.position.vsub(bodyA.position,r); + var boundingRadiusSum2 = Math.pow(bodyA.boundingRadius + bodyB.boundingRadius, 2); + var norm2 = r.norm2(); + if(norm2 < boundingRadiusSum2){ + pairs1.push(bodyA); + pairs2.push(bodyB); + } +}; + +/** + * Check if the bounding boxes of two bodies are intersecting. + * @method doBoundingBoxBroadphase + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Array} pairs1 + * @param {Array} pairs2 + */ +Broadphase.prototype.doBoundingBoxBroadphase = function(bodyA,bodyB,pairs1,pairs2){ + if(bodyA.aabbNeedsUpdate){ + bodyA.computeAABB(); + } + if(bodyB.aabbNeedsUpdate){ + bodyB.computeAABB(); + } + + // Check AABB / AABB + if(bodyA.aabb.overlaps(bodyB.aabb)){ + pairs1.push(bodyA); + pairs2.push(bodyB); + } +}; + +/** + * Removes duplicate pairs from the pair arrays. + * @method makePairsUnique + * @param {Array} pairs1 + * @param {Array} pairs2 + */ +var Broadphase_makePairsUnique_temp = { keys:[] }, + Broadphase_makePairsUnique_p1 = [], + Broadphase_makePairsUnique_p2 = []; +Broadphase.prototype.makePairsUnique = function(pairs1,pairs2){ + var t = Broadphase_makePairsUnique_temp, + p1 = Broadphase_makePairsUnique_p1, + p2 = Broadphase_makePairsUnique_p2, + N = pairs1.length; + + for(var i=0; i!==N; i++){ + p1[i] = pairs1[i]; + p2[i] = pairs2[i]; + } + + pairs1.length = 0; + pairs2.length = 0; + + for(var i=0; i!==N; i++){ + var id1 = p1[i].id, + id2 = p2[i].id; + var key = id1 < id2 ? id1+","+id2 : id2+","+id1; + t[key] = i; + t.keys.push(key); + } + + for(var i=0; i!==t.keys.length; i++){ + var key = t.keys.pop(), + pairIndex = t[key]; + pairs1.push(p1[pairIndex]); + pairs2.push(p2[pairIndex]); + delete t[key]; + } +}; + +/** + * To be implemented by subcasses + * @method setWorld + * @param {World} world + */ +Broadphase.prototype.setWorld = function(world){ +}; + +/** + * Check if the bounding spheres of two bodies overlap. + * @method boundingSphereCheck + * @param {Body} bodyA + * @param {Body} bodyB + * @return {boolean} + */ +var bsc_dist = new Vec3(); +Broadphase.boundingSphereCheck = function(bodyA,bodyB){ + var dist = bsc_dist; + bodyA.position.vsub(bodyB.position,dist); + return Math.pow(bodyA.shape.boundingSphereRadius + bodyB.shape.boundingSphereRadius,2) > dist.norm2(); +}; + +/** + * Returns all the bodies within the AABB. + * @method aabbQuery + * @param {World} world + * @param {AABB} aabb + * @return {array} + */ +Broadphase.prototype.aabbQuery = function(world, aabb){ + console.warn('.aabbQuery is not implemented in this Broadphase subclass.'); + return []; +}; +},{"../math/Quaternion":25,"../math/Vec3":27,"../objects/Body":28,"../shapes/Plane":39,"../shapes/Shape":40}],6:[function(_dereq_,module,exports){ +module.exports = GridBroadphase; + +var Broadphase = _dereq_('./Broadphase'); +var Vec3 = _dereq_('../math/Vec3'); +var Shape = _dereq_('../shapes/Shape'); + +/** + * Axis aligned uniform grid broadphase. + * @class GridBroadphase + * @constructor + * @extends Broadphase + * @todo Needs support for more than just planes and spheres. + * @param {Vec3} aabbMin + * @param {Vec3} aabbMax + * @param {Number} nx Number of boxes along x + * @param {Number} ny Number of boxes along y + * @param {Number} nz Number of boxes along z + */ +function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){ + Broadphase.apply(this); + this.nx = nx || 10; + this.ny = ny || 10; + this.nz = nz || 10; + this.aabbMin = aabbMin || new Vec3(100,100,100); + this.aabbMax = aabbMax || new Vec3(-100,-100,-100); + var nbins = this.nx * this.ny * this.nz; + if (nbins <= 0) { + throw "GridBroadphase: Each dimension's n must be >0"; + } + this.bins = []; + this.binLengths = []; //Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow + this.bins.length = nbins; + this.binLengths.length = nbins; + for (var i=0;i= nx) { xoff0 = nx - 1; } + if (yoff0 < 0) { yoff0 = 0; } else if (yoff0 >= ny) { yoff0 = ny - 1; } + if (zoff0 < 0) { zoff0 = 0; } else if (zoff0 >= nz) { zoff0 = nz - 1; } + if (xoff1 < 0) { xoff1 = 0; } else if (xoff1 >= nx) { xoff1 = nx - 1; } + if (yoff1 < 0) { yoff1 = 0; } else if (yoff1 >= ny) { yoff1 = ny - 1; } + if (zoff1 < 0) { zoff1 = 0; } else if (zoff1 >= nz) { zoff1 = nz - 1; } + + xoff0 *= xstep; + yoff0 *= ystep; + zoff0 *= zstep; + xoff1 *= xstep; + yoff1 *= ystep; + zoff1 *= zstep; + + for (var xoff = xoff0; xoff <= xoff1; xoff += xstep) { + for (var yoff = yoff0; yoff <= yoff1; yoff += ystep) { + for (var zoff = zoff0; zoff <= zoff1; zoff += zstep) { + var idx = xoff+yoff+zoff; + bins[idx][binLengths[idx]++] = bi; + } + } + } + } + + // Put all bodies into the bins + for(var i=0; i!==N; i++){ + var bi = bodies[i]; + var si = bi.shape; + + switch(si.type){ + case SPHERE: + // Put in bin + // check if overlap with other bins + var x = bi.position.x, + y = bi.position.y, + z = bi.position.z; + var r = si.radius; + + addBoxToBins(x-r, y-r, z-r, x+r, y+r, z+r, bi); + break; + + case PLANE: + if(si.worldNormalNeedsUpdate){ + si.computeWorldNormal(bi.quaternion); + } + var planeNormal = si.worldNormal; + + //Relative position from origin of plane object to the first bin + //Incremented as we iterate through the bins + var xreset = xmin + binsizeX*0.5 - bi.position.x, + yreset = ymin + binsizeY*0.5 - bi.position.y, + zreset = zmin + binsizeZ*0.5 - bi.position.z; + + var d = GridBroadphase_collisionPairs_d; + d.set(xreset, yreset, zreset); + + for (var xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) { + for (var yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) { + for (var zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) { + if (d.dot(planeNormal) < binRadius) { + var idx = xoff + yoff + zoff; + bins[idx][binLengths[idx]++] = bi; + } + } + } + } + break; + + default: + if (bi.aabbNeedsUpdate) { + bi.computeAABB(); + } + + addBoxToBins( + bi.aabb.lowerBound.x, + bi.aabb.lowerBound.y, + bi.aabb.lowerBound.z, + bi.aabb.upperBound.x, + bi.aabb.upperBound.y, + bi.aabb.upperBound.z, + bi); + break; + } + } + + // Check each bin + for(var i=0; i!==Nbins; i++){ + var binLength = binLengths[i]; + //Skip bins with no potential collisions + if (binLength > 1) { + var bin = bins[i]; + + // Do N^2 broadphase inside + for(var xi=0; xi!==binLength; xi++){ + var bi = bin[xi]; + for(var yi=0; yi!==xi; yi++){ + var bj = bin[yi]; + if(this.needBroadphaseCollision(bi,bj)){ + this.intersectionTest(bi,bj,pairs1,pairs2); + } + } + } + } + } + +// for (var zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) { +// console.log("layer "+zi); +// for (var yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) { +// var row = ''; +// for (var xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) { +// var idx = xoff + yoff + zoff; +// row += ' ' + binLengths[idx]; +// } +// console.log(row); +// } +// } + + this.makePairsUnique(pairs1,pairs2); +}; + +},{"../math/Vec3":27,"../shapes/Shape":40,"./Broadphase":5}],7:[function(_dereq_,module,exports){ +module.exports = NaiveBroadphase; + +var Broadphase = _dereq_('./Broadphase'); +var AABB = _dereq_('./AABB'); + +/** + * Naive broadphase implementation, used in lack of better ones. + * @class NaiveBroadphase + * @constructor + * @description The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 (which is bad) + * @extends Broadphase + */ +function NaiveBroadphase(){ + Broadphase.apply(this); +} +NaiveBroadphase.prototype = new Broadphase(); +NaiveBroadphase.prototype.constructor = NaiveBroadphase; + +/** + * Get all the collision pairs in the physics world + * @method collisionPairs + * @param {World} world + * @param {Array} pairs1 + * @param {Array} pairs2 + */ +NaiveBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){ + var bodies = world.bodies, + n = bodies.length, + i,j,bi,bj; + + // Naive N^2 ftw! + for(i=0; i!==n; i++){ + for(j=0; j!==i; j++){ + + bi = bodies[i]; + bj = bodies[j]; + + if(!this.needBroadphaseCollision(bi,bj)){ + continue; + } + + this.intersectionTest(bi,bj,pairs1,pairs2); + } + } +}; + +var tmpAABB = new AABB(); + +/** + * Returns all the bodies within an AABB. + * @method aabbQuery + * @param {World} world + * @param {AABB} aabb + * @param {array} result An array to store resulting bodies in. + * @return {array} + */ +NaiveBroadphase.prototype.aabbQuery = function(world, aabb, result){ + result = result || []; + + for(var i = 0; i < world.bodies.length; i++){ + var b = world.bodies[i]; + + if(b.aabbNeedsUpdate){ + b.computeAABB(); + } + + // Ugly hack until RigidBody gets aabb + if(b.aabb.overlaps(aabb)){ + result.push(b); + } + } + + return result; +}; +},{"./AABB":3,"./Broadphase":5}],8:[function(_dereq_,module,exports){ +module.exports = ObjectCollisionMatrix; + +/** + * Records what objects are colliding with each other + * @class ObjectCollisionMatrix + * @constructor + */ +function ObjectCollisionMatrix() { + + /** + * The matrix storage + * @property matrix + * @type {Object} + */ + this.matrix = {}; +} + +/** + * @method get + * @param {Number} i + * @param {Number} j + * @return {Number} + */ +ObjectCollisionMatrix.prototype.get = function(i, j) { + i = i.id; + j = j.id; + if (j > i) { + var temp = j; + j = i; + i = temp; + } + return i+'-'+j in this.matrix; +}; + +/** + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +ObjectCollisionMatrix.prototype.set = function(i, j, value) { + i = i.id; + j = j.id; + if (j > i) { + var temp = j; + j = i; + i = temp; + } + if (value) { + this.matrix[i+'-'+j] = true; + } + else { + delete this.matrix[i+'-'+j]; + } +}; + +/** + * Empty the matrix + * @method reset + */ +ObjectCollisionMatrix.prototype.reset = function() { + this.matrix = {}; +}; + +/** + * Set max number of objects + * @method setNumObjects + * @param {Number} n + */ +ObjectCollisionMatrix.prototype.setNumObjects = function(n) { +}; + +},{}],9:[function(_dereq_,module,exports){ +module.exports = Ray; + +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var Transform = _dereq_('../math/Transform'); +var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron'); +var Box = _dereq_('../shapes/Box'); +var RaycastResult = _dereq_('../collision/RaycastResult'); +var Shape = _dereq_('../shapes/Shape'); +var AABB = _dereq_('../collision/AABB'); + +/** + * A line in 3D space that intersects bodies and return points. + * @class Ray + * @constructor + * @param {Vec3} from + * @param {Vec3} to + */ +function Ray(from, to){ + /** + * @property {Vec3} from + */ + this.from = from ? from.clone() : new Vec3(); + + /** + * @property {Vec3} to + */ + this.to = to ? to.clone() : new Vec3(); + + this._direction = new Vec3(); + + /** + * The precision of the ray. Used when checking parallelity etc. + * @property {Number} precision + */ + this.precision = 0.0001; + + /** + * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes. + * @property {Boolean} checkCollisionResponse + */ + this.checkCollisionResponse = true; +} +Ray.prototype.constructor = Ray; + +var v1 = new Vec3(), + v2 = new Vec3(); + +/* + * As per "Barycentric Technique" as named here http://www.blackpawn.com/texts/pointinpoly/default.html But without the division + */ +function pointInTriangle(p, a, b, c) { + c.vsub(a,v0); + b.vsub(a,v1); + p.vsub(a,v2); + + var dot00 = v0.dot( v0 ); + var dot01 = v0.dot( v1 ); + var dot02 = v0.dot( v2 ); + var dot11 = v1.dot( v1 ); + var dot12 = v1.dot( v2 ); + + var u,v; + + return ( (u = dot11 * dot02 - dot01 * dot12) >= 0 ) && + ( (v = dot00 * dot12 - dot01 * dot02) >= 0 ) && + ( u + v < ( dot00 * dot11 - dot01 * dot01 ) ); +} + +/** + * Shoot a ray at a body, get back information about the hit. + * @method intersectBody + * @private + * @param {Body} body + * @param {RaycastResult} result + * @param {Vec3} [direction] + */ +Ray.prototype.intersectBody = function (body, result, direction) { + var checkCollisionResponse = this.checkCollisionResponse; + + if(checkCollisionResponse && !body.collisionResponse){ + return result; + } + + if(!direction){ + this._updateDirection(); + direction = this._direction; + } + + var xi = new Vec3(); + var qi = new Quaternion(); + for (var i = 0; i < body.shapes.length; i++) { + var shape = body.shapes[i]; + + if(checkCollisionResponse && !shape.collisionResponse){ + continue; // Skip + } + + body.quaternion.mult(body.shapeOrientations[i], qi); + body.quaternion.vmult(body.shapeOffsets[i], xi); + xi.vadd(body.position, xi); + + this.intersectShape( + shape, + qi, + xi, + body, + direction, + result + ); + } + + return result; +}; + +/** + * @method intersectBodies + * @param {Array} bodies An array of Body objects. + * @param {RaycastResult} result + */ +Ray.prototype.intersectBodies = function (bodies, result) { + this._updateDirection(); + var direction = this._direction; + + if(result instanceof RaycastResult){ + result.reset(); + } + + for ( var i = 0, l = bodies.length; i < l; i ++ ) { + this.intersectBody(bodies[i], result, direction); + } +}; + +Ray.prototype._updateDirection = function(){ + this.to.vsub(this.from, this._direction); + this._direction.normalize(); +}; + +/** + * @method intersectShape + * @private + * @param {Shape} shape + * @param {Quaternion} quat + * @param {Vec3} position + * @param {Body} body + * @param {Vec3} direction + * @param {RaycastResult} result + */ +Ray.prototype.intersectShape = function(shape, quat, position, body, direction, result){ + var from = this.from; + + // Checking boundingSphere + var distance = distanceFromIntersection(from, direction, position); + if ( distance > shape.boundingSphereRadius ) { + return result; + } + + this[shape.type](shape, quat, position, body, direction, result); + + return result; +}; + +var vector = new Vec3(); +var normal = new Vec3(); +var intersectPoint = new Vec3(); + +var a = new Vec3(); +var b = new Vec3(); +var c = new Vec3(); +var d = new Vec3(); + +var tmpRaycastResult = new RaycastResult(); + +/** + * @method intersectBox + * @private + * @param {Shape} shape + * @param {Quaternion} quat + * @param {Vec3} position + * @param {Body} body + * @param {Vec3} direction + * @param {RaycastResult} result + */ +Ray.prototype.intersectBox = function(shape, quat, position, body, direction, result){ + return this.intersectConvex(shape.convexPolyhedronRepresentation, quat, position, body, direction, result); +}; +Ray.prototype[Shape.types.BOX] = Ray.prototype.intersectBox; + +/** + * @method intersectPlane + * @private + * @param {Shape} shape + * @param {Quaternion} quat + * @param {Vec3} position + * @param {Body} body + * @param {Vec3} direction + * @param {RaycastResult} result + */ +Ray.prototype.intersectPlane = function(shape, quat, position, body, direction, result){ + var from = this.from; + var to = this.to; + + // Get plane normal + var worldNormal = new Vec3(0, 0, 1); + quat.vmult(worldNormal, worldNormal); + + var len = new Vec3(); + from.vsub(position, len); + var planeToFrom = len.dot(worldNormal); + to.vsub(position, len); + var planeToTo = len.dot(worldNormal); + + if(planeToFrom * planeToTo > 0){ + // "from" and "to" are on the same side of the plane... bail out + return result; + } + + if(from.distanceTo(to) < planeToFrom){ + return result; + } + + var n_dot_dir = worldNormal.dot(direction); + + if (Math.abs(n_dot_dir) < this.precision) { + // No intersection + return result; + } + + var planePointToFrom = new Vec3(); + var dir_scaled_with_t = new Vec3(); + var hitPointWorld = new Vec3(); + + from.vsub(position, planePointToFrom); + var t = -worldNormal.dot(planePointToFrom) / n_dot_dir; + direction.scale(t, dir_scaled_with_t); + from.vadd(dir_scaled_with_t, hitPointWorld); + + if(this.reportIntersection(worldNormal, hitPointWorld, shape, body, result)){ + return result; + } + + return result; +}; +Ray.prototype[Shape.types.PLANE] = Ray.prototype.intersectPlane; + +/** + * Get the AABB of the ray. + * @method getAABB + * @param {AABB} aabb + */ +Ray.prototype.getAABB = function(result){ + var to = this.to; + var from = this.from; + result.lowerBound.x = Math.min(to.x, from.x); + result.lowerBound.y = Math.min(to.y, from.y); + result.lowerBound.z = Math.min(to.z, from.z); + result.upperBound.x = Math.max(to.x, from.x); + result.upperBound.y = Math.max(to.y, from.y); + result.upperBound.z = Math.max(to.z, from.z); +}; + +var intersectConvexOptions = { + faceList: [0] +}; + +/** + * @method intersectHeightfield + * @private + * @param {Shape} shape + * @param {Quaternion} quat + * @param {Vec3} position + * @param {Body} body + * @param {Vec3} direction + * @param {RaycastResult} result + */ +Ray.prototype.intersectHeightfield = function(shape, quat, position, body, direction, result){ + var data = shape.data, + w = shape.elementSize, + worldPillarOffset = new Vec3(); + + // Convert the ray to local heightfield coordinates + var localRay = new Ray(this.from, this.to); + Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from); + Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to); + + // Get the index of the data points to test against + var index = []; + var iMinX = null; + var iMinY = null; + var iMaxX = null; + var iMaxY = null; + + var inside = shape.getIndexOfPosition(localRay.from.x, localRay.from.y, index, false); + if(inside){ + iMinX = index[0]; + iMinY = index[1]; + iMaxX = index[0]; + iMaxY = index[1]; + } + inside = shape.getIndexOfPosition(localRay.to.x, localRay.to.y, index, false); + if(inside){ + if (iMinX === null || index[0] < iMinX) { iMinX = index[0]; } + if (iMaxX === null || index[0] > iMaxX) { iMaxX = index[0]; } + if (iMinY === null || index[1] < iMinY) { iMinY = index[1]; } + if (iMaxY === null || index[1] > iMaxY) { iMaxY = index[1]; } + } + + if(iMinX === null){ + return result; + } + + var minMax = []; + shape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax); + var min = minMax[0]; + var max = minMax[1]; + + // // Bail out if the ray can't touch the bounding box + // // TODO + // var aabb = new AABB(); + // this.getAABB(aabb); + // if(aabb.intersects()){ + // return; + // } + + for(var i = iMinX; i <= iMaxX; i++){ + for(var j = iMinY; j <= iMaxY; j++){ + + // Lower triangle + shape.getConvexTrianglePillar(i, j, false); + Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset); + this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, direction, result, intersectConvexOptions); + + // Upper triangle + shape.getConvexTrianglePillar(i, j, true); + Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset); + this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, direction, result, intersectConvexOptions); + } + } + + return result; +}; +Ray.prototype[Shape.types.HEIGHTFIELD] = Ray.prototype.intersectHeightfield; + +/** + * @method intersectSphere + * @private + * @param {Shape} shape + * @param {Quaternion} quat + * @param {Vec3} position + * @param {Body} body + * @param {Vec3} direction + * @param {RaycastResult} result + */ +Ray.prototype.intersectSphere = function(shape, quat, position, body, direction, result){ + var from = this.from, + to = this.to, + r = shape.radius; + + var a = Math.pow(to.x - from.x, 2) + Math.pow(to.y - from.y, 2) + Math.pow(to.z - from.z, 2); + var b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z)); + var c = Math.pow(from.x - position.x, 2) + Math.pow(from.y - position.y, 2) + Math.pow(from.z - position.z, 2) - Math.pow(r, 2); + + var delta = Math.pow(b, 2) - 4 * a * c; + + if(delta < 0){ + // No intersection + return result; + + } else if(delta === 0){ + // single intersection point + var intersectionPoint = new Vec3(); + from.lerp(to, delta, intersectionPoint); + + var normal = new Vec3(); + intersectionPoint.vsub(position, normal); + normal.normalize(); + + if(this.reportIntersection(normal, intersectionPoint, shape, body, result)){ + return result; + } + } else { + var d1 = (- b - Math.sqrt(delta)) / (2 * a); + var d2 = (- b + Math.sqrt(delta)) / (2 * a); + + var intersectionPoint = new Vec3(); + from.lerp(to, d1, intersectionPoint); + var normal = new Vec3(); + intersectionPoint.vsub(position, normal); + normal.normalize(); + if(this.reportIntersection(normal, intersectionPoint, shape, body, result)){ + return result; + } + + from.lerp(to, d2, intersectionPoint); + var normal = new Vec3(); + intersectionPoint.vsub(position, normal); + normal.normalize(); + if(this.reportIntersection(normal, intersectionPoint, shape, body, result)){ + return result; + } + } + + return result; +}; +Ray.prototype[Shape.types.SPHERE] = Ray.prototype.intersectSphere; + + +var intersectConvex_normal = new Vec3(); +var intersectConvex_minDistNormal = new Vec3(); +var intersectConvex_minDistIntersect = new Vec3(); +var intersectConvex_vector = new Vec3(); + +/** + * @method intersectConvex + * @private + * @param {Shape} shape + * @param {Quaternion} quat + * @param {Vec3} position + * @param {Body} body + * @param {Vec3} direction + * @param {RaycastResult} result + * @param {object} [options] + * @param {array} [options.faceList] + */ +Ray.prototype.intersectConvex = function intersectConvex(shape, quat, position, body, direction, result, options){ + var minDistNormal = intersectConvex_minDistNormal; + var normal = intersectConvex_normal; + var vector = intersectConvex_vector; + var minDistIntersect = intersectConvex_minDistIntersect; + var faceList = (options && options.faceList) || null; + + // Checking faces + var faces = shape.faces, + vertices = shape.vertices, + normals = shape.faceNormals; + + var from = this.from; + var to = this.to; + var fromToDistance = from.distanceTo(to); + + var reportClosest = result instanceof RaycastResult; + var minDist = -1; + var Nfaces = faceList ? faceList.length : faces.length; + + for (var j = 0; j < Nfaces; j++) { + var fi = faceList ? faceList[j] : j; + + var face = faces[fi]; + var faceNormal = normals[fi]; + var q = quat; + var x = position; + + // determine if ray intersects the plane of the face + // note: this works regardless of the direction of the face normal + + // Get plane point in world coordinates... + vector.copy(vertices[face[0]]); + q.vmult(vector,vector); + vector.vadd(x,vector); + + // ...but make it relative to the ray from. We'll fix this later. + vector.vsub(from,vector); + + // Get plane normal + q.vmult(faceNormal,normal); + + // If this dot product is negative, we have something interesting + var dot = direction.dot(normal); + + // Bail out if ray and plane are parallel + if ( Math.abs( dot ) < this.precision ){ + continue; + } + + // calc distance to plane + var scalar = normal.dot(vector) / dot; + + // if negative distance, then plane is behind ray + if (scalar < 0){ + continue; + } + + if (dot < 0) { + + // Intersection point is from + direction * scalar + direction.mult(scalar,intersectPoint); + intersectPoint.vadd(from,intersectPoint); + + // a is the point we compare points b and c with. + a.copy(vertices[face[0]]); + q.vmult(a,a); + x.vadd(a,a); + + for(var i = 1; i < face.length - 1; i++){ + // Transform 3 vertices to world coords + b.copy(vertices[face[i]]); + c.copy(vertices[face[i+1]]); + q.vmult(b,b); + q.vmult(c,c); + x.vadd(b,b); + x.vadd(c,c); + + var distance = intersectPoint.distanceTo(from); + + if(!pointInTriangle(intersectPoint, a, b, c) || distance > fromToDistance){ + continue; + } + + if(minDist === -1 || distance < minDist){ + minDist = distance; + minDistNormal.copy(normal); + minDistIntersect.copy(intersectPoint); + } + } + } + } + + if(minDist !== -1 && this.reportIntersection(minDistNormal, minDistIntersect, shape, body, result)){ + return result; + } + + return result; +}; + +Ray.prototype[Shape.types.CONVEXPOLYHEDRON] = Ray.prototype.intersectConvex; + +/** + * @method reportIntersection + * @private + * @param {Vec3} normal + * @param {Vec3} hitPointWorld + * @param {Shape} shape + * @param {Body} body + * @param {RaycastResult} result + * @return {boolean} True if the intersections should continue + */ +Ray.prototype.reportIntersection = function(normal, hitPointWorld, shape, body, result){ + var from = this.from; + var to = this.to; + var distance = from.distanceTo(hitPointWorld); + + if(!(result instanceof RaycastResult)){ + // Got a callback + tmpRaycastResult.set( + from, + to, + normal, + hitPointWorld, + shape, + body, + distance + ); + tmpRaycastResult.hasHit = true; + result(tmpRaycastResult); + + return true; + + } else { + + // Store if closer than current cloest + if(distance < result.distance || !result.hasHit){ + result.hasHit = true; + result.set( + from, + to, + normal, + hitPointWorld, + shape, + body, + distance + ); + } + + return false; + } +}; + +var v0 = new Vec3(), + intersect = new Vec3(); +function distanceFromIntersection(from, direction, position) { + + // v0 is vector from from to position + position.vsub(from,v0); + var dot = v0.dot( direction ); + + // intersect = direction*dot + from + direction.mult(dot,intersect); + intersect.vadd(from,intersect); + + var distance = position.distanceTo(intersect); + + return distance; +} + + +},{"../collision/AABB":3,"../collision/RaycastResult":10,"../math/Quaternion":25,"../math/Transform":26,"../math/Vec3":27,"../shapes/Box":34,"../shapes/ConvexPolyhedron":35,"../shapes/Shape":40}],10:[function(_dereq_,module,exports){ +var Vec3 = _dereq_('../math/Vec3'); + +module.exports = RaycastResult; + +/** + * Storage for Ray casting data. + * @class RaycastResult + * @constructor + */ +function RaycastResult(){ + + /** + * @property {Vec3} rayFromWorld + */ + this.rayFromWorld = new Vec3(); + + /** + * @property {Vec3} rayToWorld + */ + this.rayToWorld = new Vec3(); + + /** + * @property {Vec3} hitNormalWorld + */ + this.hitNormalWorld = new Vec3(); + + /** + * @property {Vec3} hitPointWorld + */ + this.hitPointWorld = new Vec3(); + + /** + * @property {boolean} hasHit + */ + this.hasHit = false; + + /** + * The hit shape, or null. + * @property {Shape} shape + */ + this.shape = null; + + /** + * The hit body, or null. + * @property {Body} body + */ + this.body = null; + + /** + * Distance to the hit. Will be set to -1 if there was no hit. + * @property {number} distance + */ + this.distance = -1; +} + +/** + * Reset all result data. + * @method reset + */ +RaycastResult.prototype.reset = function () { + this.rayFromWorld.setZero(); + this.rayToWorld.setZero(); + this.hitNormalWorld.setZero(); + this.hitPointWorld.setZero(); + this.hasHit = false; + this.shape = null; + this.body = null; + this.distance = -1; +}; + +/** + * @method set + * @param {Vec3} rayFromWorld + * @param {Vec3} rayToWorld + * @param {Vec3} hitNormalWorld + * @param {Vec3} hitPointWorld + * @param {Shape} shape + * @param {Body} body + * @param {number} distance + */ +RaycastResult.prototype.set = function( + rayFromWorld, + rayToWorld, + hitNormalWorld, + hitPointWorld, + shape, + body, + distance +){ + this.rayFromWorld.copy(rayFromWorld); + this.rayToWorld.copy(rayToWorld); + this.hitNormalWorld.copy(hitNormalWorld); + this.hitPointWorld.copy(hitPointWorld); + this.shape = shape; + this.body = body; + this.distance = distance; +}; +},{"../math/Vec3":27}],11:[function(_dereq_,module,exports){ +var Shape = _dereq_('../shapes/Shape'); +var Broadphase = _dereq_('../collision/Broadphase'); + +module.exports = SAPBroadphase; + +/** + * Sweep and prune broadphase along one axis. + * + * @class SAPBroadphase + * @constructor + * @param {World} [world] + * @extends Broadphase + */ +function SAPBroadphase(world){ + Broadphase.apply(this); + + /** + * List of bodies currently in the broadphase. + * @property axisList + * @type {Array} + */ + this.axisList = []; + + /** + * The world to search in. + * @property world + * @type {World} + */ + this.world = null; + + /** + * Axis to sort the bodies along. Set to 0 for x axis, and 1 for y axis. For best performance, choose an axis that the bodies are spread out more on. + * @property axisIndex + * @type {Number} + */ + this.axisIndex = 0; + + var axisList = this.axisList; + + this._addBodyHandler = function(e){ + axisList.push(e.body); + }; + + this._removeBodyHandler = function(e){ + var idx = axisList.indexOf(e.body); + if(idx !== -1){ + axisList.splice(idx,1); + } + }; + + if(world){ + this.setWorld(world); + } +} +SAPBroadphase.prototype = new Broadphase(); + +/** + * Change the world + * @method setWorld + * @param {World} world + */ +SAPBroadphase.prototype.setWorld = function(world){ + // Clear the old axis array + this.axisList.length = 0; + + // Add all bodies from the new world + for(var i=0; i=0;j--) { + if(a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x){ + break; + } + a[j+1] = a[j]; + } + a[j+1] = v; + } + return a; +}; + +/** + * @static + * @method insertionSortY + * @param {Array} a + * @return {Array} + */ +SAPBroadphase.insertionSortY = function(a) { + for(var i=1,l=a.length;i=0;j--) { + if(a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y){ + break; + } + a[j+1] = a[j]; + } + a[j+1] = v; + } + return a; +}; + +/** + * @static + * @method insertionSortZ + * @param {Array} a + * @return {Array} + */ +SAPBroadphase.insertionSortZ = function(a) { + for(var i=1,l=a.length;i=0;j--) { + if(a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z){ + break; + } + a[j+1] = a[j]; + } + a[j+1] = v; + } + return a; +}; + +/** + * Collect all collision pairs + * @method collisionPairs + * @param {World} world + * @param {Array} p1 + * @param {Array} p2 + */ +SAPBroadphase.prototype.collisionPairs = function(world,p1,p2){ + var bodies = this.axisList, + N = bodies.length, + axisIndex = this.axisIndex, + i, j; + + if(this.dirty){ + this.sortList(); + this.dirty = false; + } + + // Look through the list + for(i=0; i !== N; i++){ + var bi = bodies[i]; + + for(j=i+1; j < N; j++){ + var bj = bodies[j]; + + if(!this.needBroadphaseCollision(bi,bj)){ + continue; + } + + if(!SAPBroadphase.checkBounds(bi,bj,axisIndex)){ + break; + } + + this.intersectionTest(bi,bj,p1,p2); + } + } +}; + +SAPBroadphase.prototype.sortList = function(){ + var axisList = this.axisList; + var axisIndex = this.axisIndex; + var N = axisList.length; + + // Update AABBs + for(var i = 0; i!==N; i++){ + var bi = axisList[i]; + if(bi.aabbNeedsUpdate){ + bi.computeAABB(); + } + } + + // Sort the list + if(axisIndex === 0){ + SAPBroadphase.insertionSortX(axisList); + } else if(axisIndex === 1){ + SAPBroadphase.insertionSortY(axisList); + } else if(axisIndex === 2){ + SAPBroadphase.insertionSortZ(axisList); + } +}; + +/** + * Check if the bounds of two bodies overlap, along the given SAP axis. + * @static + * @method checkBounds + * @param {Body} bi + * @param {Body} bj + * @param {Number} axisIndex + * @return {Boolean} + */ +SAPBroadphase.checkBounds = function(bi, bj, axisIndex){ + var axis; + if(axisIndex === 0){ axis = 'x'; } + if(axisIndex === 1){ axis = 'y'; } + if(axisIndex === 2){ axis = 'z'; } + + var biPos = bi.position[axis], + ri = bi.boundingRadius, + bjPos = bj.position[axis], + rj = bj.boundingRadius, + boundA1 = biPos - ri, + boundA2 = biPos + ri, + boundB1 = bjPos - rj, + boundB2 = bjPos + rj; + + return boundB1 < boundA2; +}; + +/** + * Computes the variance of the body positions and estimates the best + * axis to use. Will automatically set property .axisIndex. + * @method autoDetectAxis + */ +SAPBroadphase.prototype.autoDetectAxis = function(){ + var sumX=0, + sumX2=0, + sumY=0, + sumY2=0, + sumZ=0, + sumZ2=0, + bodies = this.axisList, + N = bodies.length, + invN=1/N; + + for(var i=0; i!==N; i++){ + var b = bodies[i]; + + var centerX = b.position.x; + sumX += centerX; + sumX2 += centerX*centerX; + + var centerY = b.position.y; + sumY += centerY; + sumY2 += centerY*centerY; + + var centerZ = b.position.z; + sumZ += centerZ; + sumZ2 += centerZ*centerZ; + } + + var varianceX = sumX2 - sumX*sumX*invN, + varianceY = sumY2 - sumY*sumY*invN, + varianceZ = sumZ2 - sumZ*sumZ*invN; + + if(varianceX > varianceY){ + if(varianceX > varianceZ){ + this.axisIndex = 0; + } else{ + this.axisIndex = 2; + } + } else if(varianceY > varianceZ){ + this.axisIndex = 1; + } else{ + this.axisIndex = 2; + } +}; + +/** + * Returns all the bodies within an AABB. + * @method aabbQuery + * @param {World} world + * @param {AABB} aabb + * @param {array} result An array to store resulting bodies in. + * @return {array} + */ +SAPBroadphase.prototype.aabbQuery = function(world, aabb, result){ + result = result || []; + + if(this.dirty){ + this.sortList(); + this.dirty = false; + } + + var axisIndex = this.axisIndex, axis = 'x'; + if(axisIndex === 1){ axis = 'y'; } + if(axisIndex === 2){ axis = 'z'; } + + var axisList = this.axisList; + var lower = aabb.lowerBound[axis]; + var upper = aabb.upperBound[axis]; + for(var i = 0; i < axisList.length; i++){ + var b = axisList[i]; + + if(b.aabbNeedsUpdate){ + b.computeAABB(); + } + + if(b.aabb.overlaps(aabb)){ + result.push(b); + } + } + + return result; +}; +},{"../collision/Broadphase":5,"../shapes/Shape":40}],12:[function(_dereq_,module,exports){ +module.exports = Constraint; + +var Utils = _dereq_('../utils/Utils'); + +/** + * Constraint base class + * @class Constraint + * @author schteppe + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {object} [options] + * @param {boolean} [options.collideConnected=true] + * @param {boolean} [options.wakeUpBodies=true] + */ +function Constraint(bodyA, bodyB, options){ + options = Utils.defaults(options,{ + collideConnected : true, + wakeUpBodies : true, + }); + + /** + * Equations to be solved in this constraint + * @property equations + * @type {Array} + */ + this.equations = []; + + /** + * @property {Body} bodyA + */ + this.bodyA = bodyA; + + /** + * @property {Body} bodyB + */ + this.bodyB = bodyB; + + /** + * @property {Number} id + */ + this.id = Constraint.idCounter++; + + /** + * Set to true if you want the bodies to collide when they are connected. + * @property collideConnected + * @type {boolean} + */ + this.collideConnected = options.collideConnected; + + if(options.wakeUpBodies){ + if(bodyA){ + bodyA.wakeUp(); + } + if(bodyB){ + bodyB.wakeUp(); + } + } +} + +/** + * @method update + */ +Constraint.prototype.update = function(){ + throw new Error("method update() not implmemented in this Constraint subclass!"); +}; + +Constraint.idCounter = 0; + +},{"../utils/Utils":48}],13:[function(_dereq_,module,exports){ +module.exports = DistanceConstraint; + +var Constraint = _dereq_('./Constraint'); +var ContactEquation = _dereq_('../equations/ContactEquation'); + +/** + * Constrains two bodies to be at a constant distance from each other. + * @class DistanceConstraint + * @constructor + * @author schteppe + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Number} distance + * @param {Number} maxForce + * @extends Constraint + */ +function DistanceConstraint(bodyA,bodyB,distance,maxForce){ + Constraint.call(this,bodyA,bodyB); + + if(typeof(maxForce)==="undefined" ) { + maxForce = 1e6; + } + + // Equations to be fed to the solver + var eqs = this.equations = [ + new ContactEquation(bodyA,bodyB), // Just in the normal direction + ]; + + var normal = eqs[0]; + + normal.minForce = -maxForce; + normal.maxForce = maxForce; + + // Update + this.update = function(){ + bodyB.position.vsub(bodyA.position,normal.ni); + normal.ni.normalize(); + /*bodyA.quaternion.vmult(pivotA,normal.ri); + bodyB.quaternion.vmult(pivotB,normal.rj);*/ + normal.ni.mult( distance*0.5,normal.ri); + normal.ni.mult( -distance*0.5,normal.rj); + }; +} +DistanceConstraint.prototype = new Constraint(); + +},{"../equations/ContactEquation":16,"./Constraint":12}],14:[function(_dereq_,module,exports){ +module.exports = HingeConstraint; + +var Constraint = _dereq_('./Constraint'); +var RotationalEquation = _dereq_('../equations/RotationalEquation'); +var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation'); +var ContactEquation = _dereq_('../equations/ContactEquation'); +var Vec3 = _dereq_('../math/Vec3'); + +/** + * Hinge constraint. Tries to keep the local body axes equal. + * @class HingeConstraint + * @constructor + * @author schteppe + * @param {RigidBody} bodyA + * @param {RigidBody} bodyB + * @param {object} [options] + * @param {Vec3} [options.pivotA] A point defined locally in bodyA. This defines the offset of axisA. + * @param {Vec3} [options.axisA] an axis that bodyA can rotate around. + * @param {Vec3} [options.pivotB] + * @param {Vec3} [options.axisB] + * @param {Number} [options.maxForce=1e6] + * @extends Constraint + */ +function HingeConstraint(bodyA, bodyB, options){ // bodyA, pivotA, axisA, bodyB, pivotB, axisB, maxForce + Constraint.call(this, bodyA, bodyB, options); + + var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6; + + // TODO: use a clever default setup... how? + var pivotA = this.pivotA = typeof(options.pivotA) !== 'undefined' ? options.pivotA.clone() : new Vec3(); + var pivotB = this.pivotB = typeof(options.pivotB) !== 'undefined' ? options.pivotB.clone() : new Vec3(); + var axisA = this.axisA = typeof(options.axisA) !== 'undefined' ? options.axisA.clone() : new Vec3(1,0,0); + var axisB = this.axisB = typeof(options.axisB) !== 'undefined' ? options.axisB.clone() : new Vec3(1,0,0); + + var that = this; + + // Equations to be fed to the solver + var eqs = this.equations = [ + new RotationalEquation(bodyA,bodyB), // rotational1 + new RotationalEquation(bodyA,bodyB), // rotational2 + new ContactEquation(bodyA,bodyB), // p2pNormal + new ContactEquation(bodyA,bodyB), // p2pTangent1 + new ContactEquation(bodyA,bodyB), // p2pTangent2 + ]; + + var r1 = this.getRotationalEquation1(); + var r2 = this.getRotationalEquation2(); + var normal = this.getPointToPointEquation1(); + var t1 = this.getPointToPointEquation2(); + var t2 = this.getPointToPointEquation3(); + var motor; // not activated by default + + t1.minForce = t2.minForce = normal.minForce = -maxForce; + t1.maxForce = t2.maxForce = normal.maxForce = maxForce; + + var unitPivotA = pivotA.unit(); + var unitPivotB = pivotB.unit(); + + var axisA_x_pivotA = this.axisA_x_pivotA = new Vec3(); + var axisA_x_axisA_x_pivotA = this.axisA_x_axisA_x_pivotA = new Vec3(); + var axisB_x_pivotB = this.axisB_x_pivotB = new Vec3(); + axisA.cross(unitPivotA,axisA_x_pivotA); + if(axisA_x_pivotA.norm2() < 0.001){ // pivotA is along the same line as axisA + unitPivotA.tangents(axisA_x_pivotA,axisA_x_pivotA); + } + axisA.cross(axisA_x_pivotA,axisA_x_axisA_x_pivotA); + axisB.cross(unitPivotB,axisB_x_pivotB); + if(axisB_x_pivotB.norm2() < 0.001){ // pivotB is along the same line as axisB + axisB.tangents(axisB_x_pivotB,axisB_x_pivotB); + } + + axisA_x_pivotA.normalize(); + axisB_x_pivotB.normalize(); + + // Motor stuff + this.motorEnabled = false; + this.motorTargetVelocity = 0; + this.motorMinForce = -maxForce; + this.motorMaxForce = maxForce; + this.motorEquation = new RotationalMotorEquation(bodyA,bodyB,maxForce); +} +HingeConstraint.prototype = new Constraint(); + +/** + * @method enableMotor + */ +HingeConstraint.prototype.enableMotor = function(){ + if(!this.motorEnabled){ + this.equations.push(this.motorEquation); + this.motorEnabled = true; + } +}; + +/** + * @method disableMotor + */ +HingeConstraint.prototype.disableMotor = function(){ + if(this.motorEnabled){ + this.motorEnabled = false; + this.equations.pop(); + } +}; + +HingeConstraint.prototype.update = function(){ + var bodyA = this.bodyA, + bodyB = this.bodyB, + eqs = this.equations, + motor = this.motorEquation, + r1 = eqs[0], + r2 = eqs[1], + normal = eqs[2], + t1 = eqs[3], + t2 = eqs[4]; + var axisA_x_pivotA = this.axisA_x_pivotA; + var axisA = this.axisA; + var axisB = this.axisB; + var pivotA = this.pivotA; + var pivotB = this.pivotB; + var axisA_x_axisA_x_pivotA = this.axisA_x_axisA_x_pivotA; + var axisB_x_pivotB = this.axisB_x_pivotB; + + // Update world positions of pivots + /* + bodyB.position.vsub(bodyA.position,normal.ni); + normal.ni.normalize(); + */ + normal.ni.set(1,0,0); + t1.ni.set(0,1,0); + t2.ni.set(0,0,1); + bodyA.quaternion.vmult(this.pivotA,normal.ri); + bodyB.quaternion.vmult(this.pivotB,normal.rj); + + //normal.ni.tangents(t1.ni,t2.ni); + t1.ri.copy(normal.ri); + t1.rj.copy(normal.rj); + t2.ri.copy(normal.ri); + t2.rj.copy(normal.rj); + + axisA.cross(pivotA, axisA_x_pivotA); + if(axisA_x_pivotA.norm2() < 0.001){ // pivotA is along the same line as axisA + pivotA.tangents(axisA_x_pivotA, axisA_x_pivotA); + } + axisA.cross(axisA_x_pivotA, axisA_x_axisA_x_pivotA); + axisB.cross(pivotB, axisB_x_pivotB); + if(axisB_x_pivotB.norm2() < 0.001){ // pivotB is along the same line as axisB + axisB.tangents(axisB_x_pivotB,axisB_x_pivotB); + } + + axisA_x_pivotA.normalize(); + axisB_x_pivotB.normalize(); + + // update rotational constraints + bodyA.quaternion.vmult(axisA_x_pivotA, r1.ni); + bodyB.quaternion.vmult(axisB, r1.nj); + bodyA.quaternion.vmult(axisA_x_axisA_x_pivotA, r2.ni); + bodyB.quaternion.vmult(axisB, r2.nj); + + if(this.motorEnabled){ + bodyA.quaternion.vmult(this.axisA, motor.axisA); + bodyB.quaternion.vmult(this.axisB, motor.axisB); + motor.targetVelocity = this.motorTargetVelocity; + motor.maxForce = this.motorMaxForce; + motor.minForce = this.motorMinForce; + } +}; + +HingeConstraint.prototype.getRotationalEquation1 = function(){ return this.equations[0]; }; +HingeConstraint.prototype.getRotationalEquation2 = function(){ return this.equations[1]; }; +HingeConstraint.prototype.getPointToPointEquation1 = function(){ return this.equations[2]; }; +HingeConstraint.prototype.getPointToPointEquation2 = function(){ return this.equations[3]; }; +HingeConstraint.prototype.getPointToPointEquation3 = function(){ return this.equations[4]; }; + +},{"../equations/ContactEquation":16,"../equations/RotationalEquation":19,"../equations/RotationalMotorEquation":20,"../math/Vec3":27,"./Constraint":12}],15:[function(_dereq_,module,exports){ +module.exports = PointToPointConstraint; + +var Constraint = _dereq_('./Constraint'); +var ContactEquation = _dereq_('../equations/ContactEquation'); + +/** + * Connects two bodies at given offset points. + * @class PointToPointConstraint + * @extends Constraint + * @constructor + * @param {Body} bodyA + * @param {Vec3} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to. + * @param {Body} bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get sort of a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point. + * @param {Vec3} pivotB See pivotA. + * @param {Number} maxForce The maximum force that should be applied to constrain the bodies. + * + * @example + * var bodyA = new Body({ mass: 1 }); + * var bodyB = new Body({ mass: 1 }); + * bodyA.position.set(-1, 0, 0); + * bodyB.position.set(1, 0, 0); + * bodyA.addShape(shapeA); + * bodyB.addShape(shapeB); + * world.addBody(bodyA); + * world.addBody(bodyB); + * var localPivotA = new Vec3(1, 0, 0); + * var localPivotB = new Vec3(-1, 0, 0); + * var constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB); + * world.addConstraint(constraint); + */ +function PointToPointConstraint(bodyA,pivotA,bodyB,pivotB,maxForce){ + Constraint.call(this,bodyA,bodyB); + + // Equations to be fed to the solver + var eqs = this.equations = [ + new ContactEquation(bodyA,bodyB), // Normal + new ContactEquation(bodyA,bodyB), // Tangent2 + new ContactEquation(bodyA,bodyB), // Tangent2 + ]; + + var normal = eqs[0]; + var t1 = eqs[1]; + var t2 = eqs[2]; + + t1.minForce = t2.minForce = normal.minForce = -maxForce; + t1.maxForce = t2.maxForce = normal.maxForce = maxForce; + + // Update + this.update = function(){ + bodyB.position.vsub(bodyA.position,normal.ni); + normal.ni.normalize(); + bodyA.quaternion.vmult(pivotA,normal.ri); + bodyB.quaternion.vmult(pivotB,normal.rj); + + normal.ni.tangents(t1.ni,t2.ni); + t1.ri.copy(normal.ri); + t1.rj.copy(normal.rj); + t2.ri.copy(normal.ri); + t2.rj.copy(normal.rj); + }; +} +PointToPointConstraint.prototype = new Constraint(); + +},{"../equations/ContactEquation":16,"./Constraint":12}],16:[function(_dereq_,module,exports){ +module.exports = ContactEquation; + +var Equation = _dereq_('./Equation'); +var Vec3 = _dereq_('../math/Vec3'); +var Mat3 = _dereq_('../math/Mat3'); + +/** + * Contact/non-penetration constraint equation + * @class ContactEquation + * @constructor + * @author schteppe + * @param {Body} bj + * @param {Body} bi + * @extends Equation + */ +function ContactEquation(bi,bj){ + Equation.call(this,bi,bj,0,1e6); + + /** + * @property restitution + * @type {Number} + */ + this.restitution = 0.0; // "bounciness": u1 = -e*u0 + + /** + * World-oriented vector that goes from the center of bi to the contact point. + * @property {Vec3} ri + */ + this.ri = new Vec3(); + + /** + * World-oriented vector that starts in body j position and goes to the contact point. + * @property {Vec3} rj + */ + this.rj = new Vec3(); + + this.penetrationVec = new Vec3(); + + /** + * Contact normal, pointing out of body i. + * @property {Vec3} ni + */ + this.ni = new Vec3(); + + this.rixn = new Vec3(); + this.rjxn = new Vec3(); + + this.invIi = new Mat3(); + this.invIj = new Mat3(); + + // Cache + this.biInvInertiaTimesRixn = new Vec3(); + this.bjInvInertiaTimesRjxn = new Vec3(); +} + +ContactEquation.prototype = new Equation(); +ContactEquation.prototype.constructor = ContactEquation; + +var ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors +var ContactEquation_computeB_temp2 = new Vec3(); +var ContactEquation_computeB_zero = new Vec3(); +ContactEquation.prototype.computeB = function(h){ + var a = this.a, + b = this.b, + bi = this.bi, + bj = this.bj, + ri = this.ri, + rj = this.rj, + rixn = this.rixn, + rjxn = this.rjxn, + + zero = ContactEquation_computeB_zero, + + vi = bi.velocity, + wi = bi.angularVelocity ? bi.angularVelocity : zero, + fi = bi.force, + taui = bi.torque ? bi.torque : zero, + + vj = bj.velocity, + wj = bj.angularVelocity ? bj.angularVelocity : zero, + fj = bj.force, + tauj = bj.torque ? bj.torque : zero, + + penetrationVec = this.penetrationVec, + invMassi = bi.invMass, + invMassj = bj.invMass, + + invIi = this.invIi, + invIj = this.invIj, + + GA = this.jacobianElementA, + GB = this.jacobianElementB, + + n = this.ni; + + // Caluclate cross products + ri.cross(n,rixn); + rj.cross(n,rjxn); + + // g = xj+rj -(xi+ri) + // G = [ -ni -rixn ni rjxn ] + n.negate(GA.spatial); + rixn.negate(GA.rotational); + GB.spatial.copy(n); + GB.rotational.copy(rjxn); + + // Calculate the penetration vector + var penetrationVec = this.penetrationVec; + penetrationVec.set(0,0,0); + penetrationVec.vadd(bj.position,penetrationVec); + penetrationVec.vadd(rj,penetrationVec); + penetrationVec.vsub(bi.position,penetrationVec); + penetrationVec.vsub(ri,penetrationVec); + + var g = n.dot(penetrationVec); + + var invIi_vmult_taui = ContactEquation_computeB_temp1; + var invIj_vmult_tauj = ContactEquation_computeB_temp2; + if(bi.invInertiaWorld){ + bi.invInertiaWorld.vmult(taui,invIi_vmult_taui); + } else { + invIi_vmult_taui.set(0,0,0); + } + if(bj.invInertiaWorld){ + bj.invInertiaWorld.vmult(tauj,invIj_vmult_tauj); + } else { + invIj_vmult_tauj.set(0,0,0); + } + + // Compute iteration + var ePlusOne = this.restitution+1; + var GW = ePlusOne*vj.dot(n) - ePlusOne*vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn); + var GiMf = this.computeGiMf();//fj.dot(n)*invMassj - fi.dot(n)*invMassi + rjxn.dot(invIj_vmult_tauj) - rixn.dot(invIi_vmult_taui); + + var B = - g * a - GW * b - h*GiMf; + + return B; +}; + +// Compute C = GMG+eps in the SPOOK equation +/* +var computeC_temp1 = new Vec3(); +var computeC_temp2 = new Vec3(); +ContactEquation.prototype.computeC = function(){ + var bi = this.bi; + var bj = this.bj; + var rixn = this.rixn; + var rjxn = this.rjxn; + var invMassi = bi.invMass; + var invMassj = bj.invMass; + + var C = invMassi + invMassj + this.eps; + + var invIi = this.invIi; + var invIj = this.invIj; + + // Compute rxn * I * rxn for each body + if(bi.invInertiaWorld) bi.invInertiaWorld.vmult(rixn, this.biInvInertiaTimesRixn); + if(bj.invInertiaWorld) bj.invInertiaWorld.vmult(rjxn, this.bjInvInertiaTimesRjxn); + + C += this.biInvInertiaTimesRixn.dot(rixn); + C += this.bjInvInertiaTimesRjxn.dot(rjxn); + + return C; +}; + +var computeGWlambda_ulambda = new Vec3(); +ContactEquation.prototype.computeGWlambda = function(){ + var bi = this.bi; + var bj = this.bj; + var ulambda = computeGWlambda_ulambda; + + var GWlambda = 0.0; + + bj.vlambda.vsub(bi.vlambda, ulambda); + GWlambda += ulambda.dot(this.ni); + + // Angular + if(bi.wlambda){ + GWlambda -= bi.wlambda.dot(this.rixn); + } + if(bj.wlambda){ + GWlambda += bj.wlambda.dot(this.rjxn); + } + + return GWlambda; +}; + +var ContactEquation_addToWlambda_temp1 = new Vec3(); +var ContactEquation_addToWlambda_temp2 = new Vec3(); +ContactEquation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bi, + bj = this.bj, + rixn = this.rixn, + rjxn = this.rjxn, + invMassi = bi.invMass, + invMassj = bj.invMass, + n = this.ni, + temp1 = ContactEquation_addToWlambda_temp1, + temp2 = ContactEquation_addToWlambda_temp2; + + + // Add to linear velocity + n.mult(invMassi * deltalambda, temp2); + bi.vlambda.vsub(temp2,bi.vlambda); + n.mult(invMassj * deltalambda, temp2); + bj.vlambda.vadd(temp2,bj.vlambda); + + // Add to angular velocity + if(bi.wlambda !== undefined){ + this.biInvInertiaTimesRixn.mult(deltalambda,temp1); + + bi.wlambda.vsub(temp1,bi.wlambda); + } + if(bj.wlambda !== undefined){ + this.bjInvInertiaTimesRjxn.mult(deltalambda,temp1); + bj.wlambda.vadd(temp1,bj.wlambda); + } +}; +*/ + +},{"../math/Mat3":24,"../math/Vec3":27,"./Equation":17}],17:[function(_dereq_,module,exports){ +module.exports = Equation; + +var JacobianElement = _dereq_('../math/JacobianElement'), + Vec3 = _dereq_('../math/Vec3'); + +/** + * Equation base class + * @class Equation + * @constructor + * @author schteppe + * @param {Body} bi + * @param {Body} bj + * @param {Number} minForce Minimum (read: negative max) force to be applied by the constraint. + * @param {Number} maxForce Maximum (read: positive max) force to be applied by the constraint. + */ +function Equation(bi,bj,minForce,maxForce){ + this.id = -1; + + /** + * @property {number} minForce + */ + this.minForce = typeof(minForce)==="undefined" ? -1e6 : minForce; + + /** + * @property {number} maxForce + */ + this.maxForce = typeof(maxForce)==="undefined" ? 1e6 : maxForce; + + /** + * @property bi + * @type {Body} + */ + this.bi = bi; + + /** + * @property bj + * @type {Body} + */ + this.bj = bj; + + /** + * SPOOK parameter + * @property {number} a + */ + this.a = 0.0; + + /** + * SPOOK parameter + * @property {number} b + */ + this.b = 0.0; + + /** + * SPOOK parameter + * @property {number} eps + */ + this.eps = 0.0; + + /** + * @property {JacobianElement} jacobianElementA + */ + this.jacobianElementA = new JacobianElement(); + + /** + * @property {JacobianElement} jacobianElementA + */ + this.jacobianElementB = new JacobianElement(); + + // Set typical spook params + this.setSpookParams(1e7,4,1/60); + + this.enabled = true; +} +Equation.prototype.constructor = Equation; + +/** + * Recalculates a,b,eps. + * @method setSpookParams + */ +Equation.prototype.setSpookParams = function(stiffness,relaxation,timeStep){ + var d = relaxation, + k = stiffness, + h = timeStep; + this.a = 4.0 / (h * (1 + 4 * d)); + this.b = (4.0 * d) / (1 + 4 * d); + this.eps = 4.0 / (h * h * k * (1 + 4 * d)); +}; + +/** + * Computes the RHS of the SPOOK equation + * @method computeB + * @return {Number} + */ +Equation.prototype.computeB = function(a,b,h){ + var GW = this.computeGW(), + Gq = this.computeGq(), + GiMf = this.computeGiMf(); + return - Gq * a - GW * b - GiMf*h; +}; + +/** + * Computes G*q, where q are the generalized body coordinates + * @method computeGq + * @return {Number} + */ +Equation.prototype.computeGq = function(){ + var GA = this.jacobianElementA, + GB = this.jacobianElementB, + bi = this.bi, + bj = this.bj, + xi = bi.position, + xj = bj.position; + return GA.spatial.dot(xi) + GB.spatial.dot(xj); +}; + +var zero = new Vec3(); + +/** + * Computes G*W, where W are the body velocities + * @method computeGW + * @return {Number} + */ +Equation.prototype.computeGW = function(){ + var GA = this.jacobianElementA, + GB = this.jacobianElementB, + bi = this.bi, + bj = this.bj, + vi = bi.velocity, + vj = bj.velocity, + wi = bi.angularVelocity || zero, + wj = bj.angularVelocity || zero; + return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj); +}; + + +/** + * Computes G*Wlambda, where W are the body velocities + * @method computeGWlambda + * @return {Number} + */ +Equation.prototype.computeGWlambda = function(){ + var GA = this.jacobianElementA, + GB = this.jacobianElementB, + bi = this.bi, + bj = this.bj, + vi = bi.vlambda, + vj = bj.vlambda, + wi = bi.wlambda || zero, + wj = bj.wlambda || zero; + return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj); +}; + +/** + * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. + * @method computeGiMf + * @return {Number} + */ +var iMfi = new Vec3(), + iMfj = new Vec3(), + invIi_vmult_taui = new Vec3(), + invIj_vmult_tauj = new Vec3(); +Equation.prototype.computeGiMf = function(){ + var GA = this.jacobianElementA, + GB = this.jacobianElementB, + bi = this.bi, + bj = this.bj, + fi = bi.force, + ti = bi.torque, + fj = bj.force, + tj = bj.torque, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve; + + if(bi.invInertiaWorldSolve){ bi.invInertiaWorldSolve.vmult(ti,invIi_vmult_taui); } + else { invIi_vmult_taui.set(0,0,0); } + if(bj.invInertiaWorldSolve){ bj.invInertiaWorldSolve.vmult(tj,invIj_vmult_tauj); } + else { invIj_vmult_tauj.set(0,0,0); } + + fi.mult(invMassi,iMfi); + fj.mult(invMassj,iMfj); + + return GA.multiplyVectors(iMfi,invIi_vmult_taui) + GB.multiplyVectors(iMfj,invIj_vmult_tauj); +}; + +/** + * Computes G*inv(M)*G' + * @method computeGiMGt + * @return {Number} + */ +var tmp = new Vec3(); +Equation.prototype.computeGiMGt = function(){ + var GA = this.jacobianElementA, + GB = this.jacobianElementB, + bi = this.bi, + bj = this.bj, + invMassi = bi.invMassSolve, + invMassj = bj.invMassSolve, + invIi = bi.invInertiaWorldSolve, + invIj = bj.invInertiaWorldSolve, + result = invMassi + invMassj; + + if(invIi){ + invIi.vmult(GA.rotational,tmp); + result += tmp.dot(GA.rotational); + } + + if(invIj){ + invIj.vmult(GB.rotational,tmp); + result += tmp.dot(GB.rotational); + } + + return result; +}; + +var addToWlambda_temp = new Vec3(), + addToWlambda_Gi = new Vec3(), + addToWlambda_Gj = new Vec3(), + addToWlambda_ri = new Vec3(), + addToWlambda_rj = new Vec3(), + addToWlambda_Mdiag = new Vec3(); + +/** + * Add constraint velocity to the bodies. + * @method addToWlambda + * @param {Number} deltalambda + */ +Equation.prototype.addToWlambda = function(deltalambda){ + var GA = this.jacobianElementA, + GB = this.jacobianElementB, + bi = this.bi, + bj = this.bj, + temp = addToWlambda_temp; + + // Add to linear velocity + // v_lambda += inv(M) * delta_lamba * G + GA.spatial.mult(bi.invMassSolve * deltalambda,temp); + bi.vlambda.vadd(temp, bi.vlambda); + + GB.spatial.mult(bj.invMassSolve * deltalambda,temp); + bj.vlambda.vadd(temp, bj.vlambda); + + // Add to angular velocity + if(bi.invInertiaWorldSolve){ + bi.invInertiaWorldSolve.vmult(GA.rotational,temp); + temp.mult(deltalambda,temp); + bi.wlambda.vadd(temp,bi.wlambda); + } + + if(bj.invInertiaWorldSolve){ + bj.invInertiaWorldSolve.vmult(GB.rotational,temp); + temp.mult(deltalambda,temp); + bj.wlambda.vadd(temp,bj.wlambda); + } +}; + +/** + * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps + * @method computeInvC + * @param {Number} eps + * @return {Number} + */ +Equation.prototype.computeC = function(){ + return this.computeGiMGt() + this.eps; +}; + +},{"../math/JacobianElement":23,"../math/Vec3":27}],18:[function(_dereq_,module,exports){ +module.exports = FrictionEquation; + +var Equation = _dereq_('./Equation'); +var Vec3 = _dereq_('../math/Vec3'); +var Mat3 = _dereq_('../math/Mat3'); + +/** + * Constrains the slipping in a contact along a tangent + * @class FrictionEquation + * @constructor + * @author schteppe + * @param {Body} bi + * @param {Body} bj + * @param {Number} slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g + * @extends Equation + */ +function FrictionEquation(bi,bj,slipForce){ + Equation.call(this,bi,bj,-slipForce,slipForce); + this.ri = new Vec3(); + this.rj = new Vec3(); + this.t = new Vec3(); // tangent + + + // The following is just cache + this.rixt = new Vec3(); + this.rjxt = new Vec3(); + this.wixri = new Vec3(); + this.wjxrj = new Vec3(); + + this.invIi = new Mat3(); + this.invIj = new Mat3(); + + this.relVel = new Vec3(); + this.relForce = new Vec3(); + + this.biInvInertiaTimesRixt = new Vec3(); + this.bjInvInertiaTimesRjxt = new Vec3(); +} + +FrictionEquation.prototype = new Equation(); +FrictionEquation.prototype.constructor = FrictionEquation; + +var FrictionEquation_computeB_temp1 = new Vec3(); +var FrictionEquation_computeB_temp2 = new Vec3(); +var FrictionEquation_computeB_zero = new Vec3(); +FrictionEquation.prototype.computeB = function(h){ + var a = this.a, + b = this.b, + bi = this.bi, + bj = this.bj, + ri = this.ri, + rj = this.rj, + rixt = this.rixt, + rjxt = this.rjxt, + wixri = this.wixri, + wjxrj = this.wjxrj, + zero = FrictionEquation_computeB_zero; + + var vi = bi.velocity, + wi = bi.angularVelocity ? bi.angularVelocity : zero, + fi = bi.force, + taui = bi.torque ? bi.torque : zero, + + vj = bj.velocity, + wj = bj.angularVelocity ? bj.angularVelocity : zero, + fj = bj.force, + tauj = bj.torque ? bj.torque : zero, + + relVel = this.relVel, + relForce = this.relForce, + invMassi = bi.invMass, + invMassj = bj.invMass, + + invIi = this.invIi, + invIj = this.invIj, + + t = this.t, + + invIi_vmult_taui = FrictionEquation_computeB_temp1, + invIj_vmult_tauj = FrictionEquation_computeB_temp2; + + // Caluclate cross products + ri.cross(t,rixt); + rj.cross(t,rjxt); + + wi.cross(ri,wixri); + wj.cross(rj,wjxrj); + + // G = [-t -rixt t rjxt] + // And remember, this is a pure velocity constraint, g is always zero! + var GA = this.jacobianElementA, + GB = this.jacobianElementB; + t.negate(GA.spatial); + rixt.negate(GA.rotational); + GB.spatial.copy(t); + GB.rotational.copy(rjxt); + + if(bi.invInertiaWorld){ bi.invInertiaWorld.vmult(taui,invIi_vmult_taui); } + else { invIi_vmult_taui.set(0,0,0); } + if(bj.invInertiaWorld){ bj.invInertiaWorld.vmult(tauj,invIj_vmult_tauj); } + else { invIj_vmult_tauj.set(0,0,0); } + + var GW = this.computeGW();//vj.dot(t) - vi.dot(t) + wjxrj.dot(t) - wixri.dot(t), // eq. 40 + var GiMf = this.computeGiMf();//fj.dot(t)*invMassj - fi.dot(t)*invMassi + rjxt.dot(invIj_vmult_tauj) - rixt.dot(invIi_vmult_taui); + + // we do only want to constrain velocity, so g=0 + var B = - GW * b - h*GiMf; + + return B; +}; + +/* +// Compute C = G * Minv * G + eps +//var FEcomputeC_temp1 = new Vec3(); +//var FEcomputeC_temp2 = new Vec3(); +FrictionEquation.prototype.computeC = function(){ + var bi = this.bi, + bj = this.bj, + rixt = this.rixt, + rjxt = this.rjxt, + invMassi = bi.invMass, + invMassj = bj.invMass, + C = invMassi + invMassj + this.eps, + invIi = this.invIi, + invIj = this.invIj; + + // Compute rxt * I * rxt for each body + if(bi.invInertiaWorld) bi.invInertiaWorld.vmult(rixt,this.biInvInertiaTimesRixt); + if(bj.invInertiaWorld) bj.invInertiaWorld.vmult(rjxt,this.bjInvInertiaTimesRjxt); + C += this.biInvInertiaTimesRixt.dot(rixt); + C += this.bjInvInertiaTimesRjxt.dot(rjxt); + + return C; +}; + +var FrictionEquation_computeGWlambda_ulambda = new Vec3(); +FrictionEquation.prototype.computeGWlambda = function(){ + var bi = this.bi; + var bj = this.bj; + + var GWlambda = 0.0; + var ulambda = FrictionEquation_computeGWlambda_ulambda; + bj.vlambda.vsub(bi.vlambda,ulambda); + GWlambda += ulambda.dot(this.t); + + // Angular + if(bi.wlambda){ + GWlambda -= bi.wlambda.dot(this.rixt); + } + if(bj.wlambda){ + GWlambda += bj.wlambda.dot(this.rjxt); + } + + return GWlambda; +}; + +var FrictionEquation_addToWlambda_tmp = new Vec3(); +FrictionEquation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bi, + bj = this.bj, + rixt = this.rixt, + rjxt = this.rjxt, + invMassi = bi.invMass, + invMassj = bj.invMass, + t = this.t, + tmp = FrictionEquation_addToWlambda_tmp, + wi = bi.wlambda, + wj = bj.wlambda; + + // Add to linear velocity + t.mult(invMassi * deltalambda, tmp); + bi.vlambda.vsub(tmp,bi.vlambda); + + t.mult(invMassj * deltalambda, tmp); + bj.vlambda.vadd(tmp,bj.vlambda); + + // Add to angular velocity + if(wi){ + this.biInvInertiaTimesRixt.mult(deltalambda,tmp); + wi.vsub(tmp,wi); + } + if(wj){ + this.bjInvInertiaTimesRjxt.mult(deltalambda,tmp); + wj.vadd(tmp,wj); + } +}; +*/ + +},{"../math/Mat3":24,"../math/Vec3":27,"./Equation":17}],19:[function(_dereq_,module,exports){ +module.exports = RotationalEquation; + +var Vec3 = _dereq_('../math/Vec3'); +var Mat3 = _dereq_('../math/Mat3'); +var Equation = _dereq_('./Equation'); + +/** + * Rotational constraint. Works to keep the local vectors orthogonal to each other. + * @class RotationalEquation + * @constructor + * @author schteppe + * @param {RigidBody} bj + * @param {Vec3} localVectorInBodyA + * @param {RigidBody} bi + * @param {Vec3} localVectorInBodyB + * @extends Equation + */ +function RotationalEquation(bodyA, bodyB){ + Equation.call(this,bodyA,bodyB,-1e6,1e6); + this.ni = new Vec3(); // World oriented localVectorInBodyA + this.nj = new Vec3(); // ...and B + + this.nixnj = new Vec3(); + this.njxni = new Vec3(); + + this.invIi = new Mat3(); + this.invIj = new Mat3(); + + this.relVel = new Vec3(); + this.relForce = new Vec3(); +} + +RotationalEquation.prototype = new Equation(); +RotationalEquation.prototype.constructor = RotationalEquation; + +var zero = new Vec3(); + +RotationalEquation.prototype.computeB = function(h){ + var a = this.a, + b = this.b, + bi = this.bi, + bj = this.bj, + + ni = this.ni, + nj = this.nj, + + nixnj = this.nixnj, + njxni = this.njxni, + + vi = bi.velocity, + wi = bi.angularVelocity ? bi.angularVelocity : zero, + fi = bi.force, + taui = bi.torque ? bi.torque : zero, + + vj = bj.velocity, + wj = bj.angularVelocity ? bj.angularVelocity : zero, + fj = bj.force, + tauj = bj.torque ? bj.torque : zero, + + invMassi = bi.invMass, + invMassj = bj.invMass, + + GA = this.jacobianElementA, + GB = this.jacobianElementB, + + invIi = this.invIi, + invIj = this.invIj; + + // Caluclate cross products + ni.cross(nj,nixnj); + nj.cross(ni,njxni); + + // g = ni * nj + // gdot = (nj x ni) * wi + (ni x nj) * wj + // G = [0 njxni 0 nixnj] + // W = [vi wi vj wj] + GA.rotational.copy(njxni); + GB.rotational.copy(nixnj); + + var g = -ni.dot(nj), + GW = this.computeGW(),//njxni.dot(wi) + nixnj.dot(wj), + GiMf = this.computeGiMf();//njxni.dot(invIi.vmult(taui)) + nixnj.dot(invIj.vmult(tauj)); + + var B = - g * a - GW * b - h*GiMf; + + return B; +}; + +/* +// Compute C = GMG+eps +RotationalEquation.prototype.computeC = function(){ + var bi = this.bi; + var bj = this.bj; + var nixnj = this.nixnj; + var njxni = this.njxni; + var invMassi = bi.invMass; + var invMassj = bj.invMass; + + var C = this.eps; + + + C += bi.invInertiaWorld.vmult(njxni).dot(njxni); + C += bj.invInertiaWorld.vmult(nixnj).dot(nixnj); + + return C; +}; + +var computeGWlambda_ulambda = new Vec3(); +RotationalEquation.prototype.computeGWlambda = function(){ + var bi = this.bi; + var bj = this.bj; + var ulambda = computeGWlambda_ulambda; + + var GWlambda = 0.0; + //bj.vlambda.vsub(bi.vlambda, ulambda); + //GWlambda += ulambda.dot(this.ni); + + // Angular + if(bi.wlambda){ + GWlambda += bi.wlambda.dot(this.njxni); + } + if(bj.wlambda){ + GWlambda += bj.wlambda.dot(this.nixnj); + } + + //console.log("GWlambda:",GWlambda); + + return GWlambda; +}; + +RotationalEquation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bi; + var bj = this.bj; + var nixnj = this.nixnj; + var njxni = this.njxni; + var invMassi = bi.invMass; + var invMassj = bj.invMass; + + // Add to linear velocity + //bi.vlambda.vsub(n.mult(invMassi * deltalambda),bi.vlambda); + //bj.vlambda.vadd(n.mult(invMassj * deltalambda),bj.vlambda); + + // Add to angular velocity + if(bi.wlambda){ + var I = bi.invInertiaWorld; + bi.wlambda.vsub(I.vmult(nixnj).mult(deltalambda),bi.wlambda); + } + if(bj.wlambda){ + var I = bj.invInertiaWorld; + bj.wlambda.vadd(I.vmult(nixnj).mult(deltalambda),bj.wlambda); + } +}; +*/ + +},{"../math/Mat3":24,"../math/Vec3":27,"./Equation":17}],20:[function(_dereq_,module,exports){ +module.exports = RotationalMotorEquation; + +var Vec3 = _dereq_('../math/Vec3'); +var Mat3 = _dereq_('../math/Mat3'); +var Equation = _dereq_('./Equation'); + +/** + * Rotational motor constraint. Works to keep the relative angular velocity of the bodies to a given value + * @class RotationalMotorEquation + * @constructor + * @author schteppe + * @param {RigidBody} bodyA + * @param {RigidBody} bodyB + * @param {Number} maxForce + * @extends Equation + */ +function RotationalMotorEquation(bodyA, bodyB, maxForce){ + maxForce = maxForce || 1e6; + Equation.call(this,bodyA,bodyB,-maxForce,maxForce); + this.axisA = new Vec3(); // World oriented rotational axis + this.axisB = new Vec3(); // World oriented rotational axis + + this.invIi = new Mat3(); + this.invIj = new Mat3(); + + /** + * Motor velocity + * @property {Number} targetVelocity + */ + this.targetVelocity = 0; +} + +RotationalMotorEquation.prototype = new Equation(); +RotationalMotorEquation.prototype.constructor = RotationalMotorEquation; + +var zero = new Vec3(); + +RotationalMotorEquation.prototype.computeB = function(h){ + var a = this.a, + b = this.b, + bi = this.bi, + bj = this.bj, + + axisA = this.axisA, + axisB = this.axisB, + + vi = bi.velocity, + wi = bi.angularVelocity ? bi.angularVelocity : zero, + fi = bi.force, + taui = bi.torque ? bi.torque : zero, + + vj = bj.velocity, + wj = bj.angularVelocity ? bj.angularVelocity : zero, + fj = bj.force, + tauj = bj.torque ? bj.torque : zero, + + GA = this.jacobianElementA, + GB = this.jacobianElementB, + + invMassi = bi.invMass, + invMassj = bj.invMass; + + // g = 0 + // gdot = axisA * wi - axisB * wj + // G = [0 axisA 0 -axisB] + // W = [vi wi vj wj] + + GA.rotational.copy(axisA); + axisB.negate(GB.rotational); + + var GW = this.computeGW() - this.targetVelocity, + GiMf = this.computeGiMf();//axis.dot(invIi.vmult(taui)) + axis.dot(invIj.vmult(tauj)); + + var B = - GW * b - h*GiMf; + + return B; +}; + +/* +// Compute C = GMG+eps +RotationalMotorEquation.prototype.computeC = function(){ + var bi = this.bi; + var bj = this.bj; + var axisA = this.axisA; + var axisB = this.axisB; + var invMassi = bi.invMass; + var invMassj = bj.invMass; + + var C = this.eps; + + C += bi.invInertiaWorld.vmult(axisA).dot(axisB); + C += bj.invInertiaWorld.vmult(axisB).dot(axisB); + + return C; +}; + +var computeGWlambda_ulambda = new Vec3(); +RotationalMotorEquation.prototype.computeGWlambda = function(){ + var bi = this.bi; + var bj = this.bj; + var ulambda = computeGWlambda_ulambda; + var axisA = this.axisA; + var axisB = this.axisB; + + var GWlambda = 0.0; + //bj.vlambda.vsub(bi.vlambda, ulambda); + //GWlambda += ulambda.dot(this.ni); + + // Angular + if(bi.wlambda){ + GWlambda += bi.wlambda.dot(axisA); + } + if(bj.wlambda){ + GWlambda += bj.wlambda.dot(axisB); + } + + //console.log("GWlambda:",GWlambda); + + return GWlambda; +}; + +RotationalMotorEquation.prototype.addToWlambda = function(deltalambda){ + var bi = this.bi; + var bj = this.bj; + var axisA = this.axisA; + var axisB = this.axisB; + var invMassi = bi.invMass; + var invMassj = bj.invMass; + + // Add to linear velocity + //bi.vlambda.vsub(n.mult(invMassi * deltalambda),bi.vlambda); + //bj.vlambda.vadd(n.mult(invMassj * deltalambda),bj.vlambda); + + // Add to angular velocity + if(bi.wlambda){ + var I = bi.invInertiaWorld; + bi.wlambda.vsub(I.vmult(axisA).mult(deltalambda),bi.wlambda); + } + if(bj.wlambda){ + var I = bj.invInertiaWorld; + bj.wlambda.vadd(I.vmult(axisB).mult(deltalambda),bj.wlambda); + } +}; +*/ + +},{"../math/Mat3":24,"../math/Vec3":27,"./Equation":17}],21:[function(_dereq_,module,exports){ +var Utils = _dereq_('../utils/Utils'); + +module.exports = ContactMaterial; + +/** + * Defines what happens when two materials meet. + * @class ContactMaterial + * @constructor + * @param {Material} m1 + * @param {Material} m2 + * @param {object} [options] + * @param {Number} [options.friction=0.3] + * @param {Number} [options.restitution=0.3] + * @param {number} [options.contactEquationStiffness=1e7] + * @param {number} [options.contactEquationRelaxation=3] + * @param {number} [options.frictionEquationStiffness=1e7] + * @param {Number} [options.frictionEquationRelaxation=3] + */ +function ContactMaterial(m1, m2, options){ + options = Utils.defaults(options, { + friction: 0.3, + restitution: 0.3, + contactEquationStiffness: 1e7, + contactEquationRelaxation: 3, + frictionEquationStiffness: 1e7, + frictionEquationRelaxation: 3 + }); + + /** + * Identifier of this material + * @property {Number} id + */ + this.id = ContactMaterial.idCounter++; + + /** + * Participating materials + * @property {Array} materials + * @todo Should be .materialA and .materialB instead + */ + this.materials = [m1, m2]; + + /** + * Friction coefficient + * @property {Number} friction + */ + this.friction = options.friction; + + /** + * Restitution coefficient + * @property {Number} restitution + */ + this.restitution = options.restitution; + + /** + * Stiffness of the produced contact equations + * @property {Number} contactEquationStiffness + */ + this.contactEquationStiffness = options.contactEquationStiffness; + + /** + * Relaxation time of the produced contact equations + * @property {Number} contactEquationRelaxation + */ + this.contactEquationRelaxation = options.contactEquationRelaxation; + + /** + * Stiffness of the produced friction equations + * @property {Number} frictionEquationStiffness + */ + this.frictionEquationStiffness = options.frictionEquationStiffness; + + /** + * Relaxation time of the produced friction equations + * @property {Number} frictionEquationRelaxation + */ + this.frictionEquationRelaxation = options.frictionEquationRelaxation; +} + +ContactMaterial.idCounter = 0; + +},{"../utils/Utils":48}],22:[function(_dereq_,module,exports){ +module.exports = Material; + +/** + * Defines a physics material. + * @class Material + * @constructor + * @param {String} name + * @author schteppe + */ +function Material(name){ + /** + * @property name + * @type {String} + */ + this.name = name; + + /** + * material id. + * @property id + */ + this.id = Material.idCounter++; +} + +Material.idCounter = 0; + +},{}],23:[function(_dereq_,module,exports){ +module.exports = JacobianElement; + +var Vec3 = _dereq_('./Vec3'); + +/** + * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom. + * @class JacobianElement + * @constructor + */ +function JacobianElement(){ + + /** + * @property {Vec3} spatial + */ + this.spatial = new Vec3(); + + /** + * @property {Vec3} rotational + */ + this.rotational = new Vec3(); +} + +/** + * Multiply with other JacobianElement + * @method multiplyElement + * @param {JacobianElement} element + * @return {Number} + */ +JacobianElement.prototype.multiplyElement = function(element){ + return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational); +}; + +/** + * Multiply with two vectors + * @method multiplyVectors + * @param {Vec3} spatial + * @param {Vec3} rotational + * @return {Number} + */ +JacobianElement.prototype.multiplyVectors = function(spatial,rotational){ + return spatial.dot(this.spatial) + rotational.dot(this.rotational); +}; + +},{"./Vec3":27}],24:[function(_dereq_,module,exports){ +module.exports = Mat3; + +var Vec3 = _dereq_('./Vec3'); + +/** + * A 3x3 matrix. + * @class Mat3 + * @constructor + * @param array elements Array of nine elements. Optional. + * @author schteppe / http://github.com/schteppe + */ +function Mat3(elements){ + /** + * A vector of length 9, containing all matrix elements + * @property {Array} elements + */ + if(elements){ + this.elements = elements; + } else { + this.elements = [0,0,0,0,0,0,0,0,0]; + } +} + +/** + * Sets the matrix to identity + * @method identity + * @todo Should perhaps be renamed to setIdentity() to be more clear. + * @todo Create another function that immediately creates an identity matrix eg. eye() + */ +Mat3.prototype.identity = function(){ + this.elements[0] = 1; + this.elements[1] = 0; + this.elements[2] = 0; + + this.elements[3] = 0; + this.elements[4] = 1; + this.elements[5] = 0; + + this.elements[6] = 0; + this.elements[7] = 0; + this.elements[8] = 1; +}; + +/** + * Set all elements to zero + * @method setZero + */ +Mat3.prototype.setZero = function(){ + var e = this.elements; + e[0] = 0; + e[1] = 0; + e[2] = 0; + e[3] = 0; + e[4] = 0; + e[5] = 0; + e[6] = 0; + e[7] = 0; + e[8] = 0; +}; + +/** + * Sets the matrix diagonal elements from a Vec3 + * @method setTrace + */ +Mat3.prototype.setTrace = function(vec3){ + var e = this.elements; + e[0] = vec3.x; + e[4] = vec3.y; + e[8] = vec3.z; +}; + +/** + * Sets the matrix diagonal elements from a Vec3 + * @method setTrace + */ +Mat3.prototype.getTrace = function(target){ + var target = target || new Vec3(); + var e = this.elements; + target.x = e[0]; + target.y = e[4]; + target.z = e[8]; +}; + +/** + * Matrix-Vector multiplication + * @method vmult + * @param {Vec3} v The vector to multiply with + * @param {Vec3} target Optional, target to save the result in. + */ +Mat3.prototype.vmult = function(v,target){ + target = target || new Vec3(); + + var e = this.elements, + x = v.x, + y = v.y, + z = v.z; + target.x = e[0]*x + e[1]*y + e[2]*z; + target.y = e[3]*x + e[4]*y + e[5]*z; + target.z = e[6]*x + e[7]*y + e[8]*z; + + return target; +}; + +/** + * Matrix-scalar multiplication + * @method smult + * @param {Number} s + */ +Mat3.prototype.smult = function(s){ + for(var i=0; i1 acos and sqrt will produce errors, this cant happen if quaternion is normalised + var angle = 2 * Math.acos(this.w); + var s = Math.sqrt(1-this.w*this.w); // assuming quaternion normalised then w is less than 1, so term always positive. + if (s < 0.001) { // test to avoid divide by zero, s is always positive due to sqrt + // if s close to zero then direction of axis not important + targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0; + targetAxis.y = this.y; + targetAxis.z = this.z; + } else { + targetAxis.x = this.x / s; // normalise axis + targetAxis.y = this.y / s; + targetAxis.z = this.z / s; + } + return [targetAxis,angle]; +}; + +var sfv_t1 = new Vec3(), + sfv_t2 = new Vec3(); + +/** + * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v. + * @method setFromVectors + * @param {Vec3} u + * @param {Vec3} v + */ +Quaternion.prototype.setFromVectors = function(u,v){ + if(u.isAntiparallelTo(v)){ + var t1 = sfv_t1; + var t2 = sfv_t2; + + u.tangents(t1,t2); + this.setFromAxisAngle(t1,Math.PI); + } else { + var a = u.cross(v); + this.x = a.x; + this.y = a.y; + this.z = a.z; + this.w = Math.sqrt(Math.pow(u.norm(),2) * Math.pow(v.norm(),2)) + u.dot(v); + this.normalize(); + } +}; + +/** + * Quaternion multiplication + * @method mult + * @param {Quaternion} q + * @param {Quaternion} target Optional. + * @return {Quaternion} + */ +var Quaternion_mult_va = new Vec3(); +var Quaternion_mult_vb = new Vec3(); +var Quaternion_mult_vaxvb = new Vec3(); +Quaternion.prototype.mult = function(q,target){ + target = target || new Quaternion(); + var w = this.w, + va = Quaternion_mult_va, + vb = Quaternion_mult_vb, + vaxvb = Quaternion_mult_vaxvb; + + va.set(this.x,this.y,this.z); + vb.set(q.x,q.y,q.z); + target.w = w*q.w - va.dot(vb); + va.cross(vb,vaxvb); + + target.x = w * vb.x + q.w*va.x + vaxvb.x; + target.y = w * vb.y + q.w*va.y + vaxvb.y; + target.z = w * vb.z + q.w*va.z + vaxvb.z; + + return target; +}; + +/** + * Get the inverse quaternion rotation. + * @method inverse + * @param {Quaternion} target + * @return {Quaternion} + */ +Quaternion.prototype.inverse = function(target){ + var x = this.x, y = this.y, z = this.z, w = this.w; + target = target || new Quaternion(); + + this.conjugate(target); + var inorm2 = 1/(x*x + y*y + z*z + w*w); + target.x *= inorm2; + target.y *= inorm2; + target.z *= inorm2; + target.w *= inorm2; + + return target; +}; + +/** + * Get the quaternion conjugate + * @method conjugate + * @param {Quaternion} target + * @return {Quaternion} + */ +Quaternion.prototype.conjugate = function(target){ + target = target || new Quaternion(); + + target.x = -this.x; + target.y = -this.y; + target.z = -this.z; + target.w = this.w; + + return target; +}; + +/** + * Normalize the quaternion. Note that this changes the values of the quaternion. + * @method normalize + */ +Quaternion.prototype.normalize = function(){ + var l = Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w); + if ( l === 0 ) { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; + } else { + l = 1 / l; + this.x *= l; + this.y *= l; + this.z *= l; + this.w *= l; + } +}; + +/** + * Approximation of quaternion normalization. Works best when quat is already almost-normalized. + * @method normalizeFast + * @see http://jsperf.com/fast-quaternion-normalization + * @author unphased, https://github.com/unphased + */ +Quaternion.prototype.normalizeFast = function () { + var f = (3.0-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2.0; + if ( f === 0 ) { + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; + } else { + this.x *= f; + this.y *= f; + this.z *= f; + this.w *= f; + } +}; + +/** + * Multiply the quaternion by a vector + * @method vmult + * @param {Vec3} v + * @param {Vec3} target Optional + * @return {Vec3} + */ +Quaternion.prototype.vmult = function(v,target){ + target = target || new Vec3(); + + var x = v.x, + y = v.y, + z = v.z; + + var qx = this.x, + qy = this.y, + qz = this.z, + qw = this.w; + + // q*v + var ix = qw * x + qy * z - qz * y, + iy = qw * y + qz * x - qx * z, + iz = qw * z + qx * y - qy * x, + iw = -qx * x - qy * y - qz * z; + + target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; + target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; + target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; + + return target; +}; + +/** + * Copies value of source to this quaternion. + * @method copy + * @param {Quaternion} source + * @return {Quaternion} this + */ +Quaternion.prototype.copy = function(source){ + this.x = source.x; + this.y = source.y; + this.z = source.z; + this.w = source.w; + return this; +}; + +/** + * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: http://www.euclideanspace.com/maths/standards/index.htm + * @method toEuler + * @param {Vec3} target + * @param string order Three-character string e.g. "YZX", which also is default. + */ +Quaternion.prototype.toEuler = function(target,order){ + order = order || "YZX"; + + var heading, attitude, bank; + var x = this.x, y = this.y, z = this.z, w = this.w; + + switch(order){ + case "YZX": + var test = x*y + z*w; + if (test > 0.499) { // singularity at north pole + heading = 2 * Math.atan2(x,w); + attitude = Math.PI/2; + bank = 0; + } + if (test < -0.499) { // singularity at south pole + heading = -2 * Math.atan2(x,w); + attitude = - Math.PI/2; + bank = 0; + } + if(isNaN(heading)){ + var sqx = x*x; + var sqy = y*y; + var sqz = z*z; + heading = Math.atan2(2*y*w - 2*x*z , 1 - 2*sqy - 2*sqz); // Heading + attitude = Math.asin(2*test); // attitude + bank = Math.atan2(2*x*w - 2*y*z , 1 - 2*sqx - 2*sqz); // bank + } + break; + default: + throw new Error("Euler order "+order+" not supported yet."); + } + + target.y = heading; + target.z = attitude; + target.x = bank; +}; + +/** + * See http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m + * @method setFromEuler + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @param {String} order The order to apply angles: 'XYZ' or 'YXZ' or any other combination + */ +Quaternion.prototype.setFromEuler = function ( x, y, z, order ) { + order = order || "XYZ"; + + var c1 = Math.cos( x / 2 ); + var c2 = Math.cos( y / 2 ); + var c3 = Math.cos( z / 2 ); + var s1 = Math.sin( x / 2 ); + var s2 = Math.sin( y / 2 ); + var s3 = Math.sin( z / 2 ); + + if ( order === 'XYZ' ) { + + this.x = s1 * c2 * c3 + c1 * s2 * s3; + this.y = c1 * s2 * c3 - s1 * c2 * s3; + this.z = c1 * c2 * s3 + s1 * s2 * c3; + this.w = c1 * c2 * c3 - s1 * s2 * s3; + + } else if ( order === 'YXZ' ) { + + this.x = s1 * c2 * c3 + c1 * s2 * s3; + this.y = c1 * s2 * c3 - s1 * c2 * s3; + this.z = c1 * c2 * s3 - s1 * s2 * c3; + this.w = c1 * c2 * c3 + s1 * s2 * s3; + + } else if ( order === 'ZXY' ) { + + this.x = s1 * c2 * c3 - c1 * s2 * s3; + this.y = c1 * s2 * c3 + s1 * c2 * s3; + this.z = c1 * c2 * s3 + s1 * s2 * c3; + this.w = c1 * c2 * c3 - s1 * s2 * s3; + + } else if ( order === 'ZYX' ) { + + this.x = s1 * c2 * c3 - c1 * s2 * s3; + this.y = c1 * s2 * c3 + s1 * c2 * s3; + this.z = c1 * c2 * s3 - s1 * s2 * c3; + this.w = c1 * c2 * c3 + s1 * s2 * s3; + + } else if ( order === 'YZX' ) { + + this.x = s1 * c2 * c3 + c1 * s2 * s3; + this.y = c1 * s2 * c3 + s1 * c2 * s3; + this.z = c1 * c2 * s3 - s1 * s2 * c3; + this.w = c1 * c2 * c3 - s1 * s2 * s3; + + } else if ( order === 'XZY' ) { + + this.x = s1 * c2 * c3 - c1 * s2 * s3; + this.y = c1 * s2 * c3 - s1 * c2 * s3; + this.z = c1 * c2 * s3 + s1 * s2 * c3; + this.w = c1 * c2 * c3 + s1 * s2 * s3; + + } + + return this; + +}; + +Quaternion.prototype.clone = function(){ + return new Quaternion(this.x, this.y, this.z, this.w); +}; +},{"./Vec3":27}],26:[function(_dereq_,module,exports){ +var Vec3 = _dereq_('./Vec3'); +var Quaternion = _dereq_('./Quaternion'); + +module.exports = Transform; + +/** + * @class Transform + * @constructor + */ +function Transform() { + /** + * @property {Vec3} position + */ + this.position = new Vec3(); + + /** + * @property {Quaternion} quaternion + */ + this.quaternion = new Quaternion(); +} + +var tmpQuat = new Quaternion(); + +/** + * @static + * @method pointToLocaFrame + * @param {Vec3} position + * @param {Quaternion} quaternion + * @param {Vec3} worldPoint + * @param {Vec3} result + */ +Transform.pointToLocalFrame = function(position, quaternion, worldPoint, result){ + var result = result || new Vec3(); + worldPoint.vsub(position, result); + quaternion.conjugate(tmpQuat); + tmpQuat.vmult(result, result); + return result; +}; + +/** + * @static + * @method pointToWorldFrame + * @param {Vec3} position + * @param {Vec3} quaternion + * @param {Vec3} localPoint + * @param {Vec3} result + */ +Transform.pointToWorldFrame = function(position, quaternion, localPoint, result){ + var result = result || new Vec3(); + quaternion.vmult(localPoint, result); + result.vadd(position, result); + return result; +}; + +Transform.prototype.vectorToWorldFrame = function(localVector, result){ + var result = result || new Vec3(); + this.quaternion.vmult(localVector, result); + return result; +}; + +Transform.vectorToLocalFrame = function(position, quaternion, worldVector, result){ + var result = result || new Vec3(); + quaternion.w *= -1; + quaternion.vmult(worldVector, result); + quaternion.w *= -1; + return result; +}; + +},{"./Quaternion":25,"./Vec3":27}],27:[function(_dereq_,module,exports){ +module.exports = Vec3; + +var Mat3 = _dereq_('./Mat3'); + +/** + * 3-dimensional vector + * @class Vec3 + * @constructor + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @author schteppe + * @example + * var v = new Vec3(1, 2, 3); + * console.log('x=' + v.x); // x=1 + */ +function Vec3(x,y,z){ + /** + * @property x + * @type {Number} + */ + this.x = x||0.0; + + /** + * @property y + * @type {Number} + */ + this.y = y||0.0; + + /** + * @property z + * @type {Number} + */ + this.z = z||0.0; +} + +Vec3.ZERO = new Vec3(0, 0, 0); + +/** + * Vector cross product + * @method cross + * @param {Vec3} v + * @param {Vec3} target Optional. Target to save in. + * @return {Vec3} + */ +Vec3.prototype.cross = function(v,target){ + var vx=v.x, vy=v.y, vz=v.z, x=this.x, y=this.y, z=this.z; + target = target || new Vec3(); + + target.x = (y * vz) - (z * vy); + target.y = (z * vx) - (x * vz); + target.z = (x * vy) - (y * vx); + + return target; +}; + +/** + * Set the vectors' 3 elements + * @method set + * @param {Number} x + * @param {Number} y + * @param {Number} z + * @return Vec3 + */ +Vec3.prototype.set = function(x,y,z){ + this.x = x; + this.y = y; + this.z = z; + return this; +}; + +/** + * Set all components of the vector to zero. + * @method setZero + */ +Vec3.prototype.setZero = function(){ + this.x = this.y = this.z = 0; +}; + +/** + * Vector addition + * @method vadd + * @param {Vec3} v + * @param {Vec3} target Optional. + * @return {Vec3} + */ +Vec3.prototype.vadd = function(v,target){ + if(target){ + target.x = v.x + this.x; + target.y = v.y + this.y; + target.z = v.z + this.z; + } else { + return new Vec3(this.x + v.x, + this.y + v.y, + this.z + v.z); + } +}; + +/** + * Vector subtraction + * @method vsub + * @param {Vec3} v + * @param {Vec3} target Optional. Target to save in. + * @return {Vec3} + */ +Vec3.prototype.vsub = function(v,target){ + if(target){ + target.x = this.x - v.x; + target.y = this.y - v.y; + target.z = this.z - v.z; + } else { + return new Vec3(this.x-v.x, + this.y-v.y, + this.z-v.z); + } +}; + +/** + * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c + * @method crossmat + * @see http://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf + * @return {Mat3} + */ +Vec3.prototype.crossmat = function(){ + return new Mat3([ 0, -this.z, this.y, + this.z, 0, -this.x, + -this.y, this.x, 0]); +}; + +/** + * Normalize the vector. Note that this changes the values in the vector. + * @method normalize + * @return {Number} Returns the norm of the vector + */ +Vec3.prototype.normalize = function(){ + var x=this.x, y=this.y, z=this.z; + var n = Math.sqrt(x*x + y*y + z*z); + if(n>0.0){ + var invN = 1/n; + this.x *= invN; + this.y *= invN; + this.z *= invN; + } else { + // Make something up + this.x = 0; + this.y = 0; + this.z = 0; + } + return n; +}; + +/** + * Get the version of this vector that is of length 1. + * @method unit + * @param {Vec3} target Optional target to save in + * @return {Vec3} Returns the unit vector + */ +Vec3.prototype.unit = function(target){ + target = target || new Vec3(); + var x=this.x, y=this.y, z=this.z; + var ninv = Math.sqrt(x*x + y*y + z*z); + if(ninv>0.0){ + ninv = 1.0/ninv; + target.x = x * ninv; + target.y = y * ninv; + target.z = z * ninv; + } else { + target.x = 1; + target.y = 0; + target.z = 0; + } + return target; +}; + +/** + * Get the 2-norm (length) of the vector + * @method norm + * @return {Number} + */ +Vec3.prototype.norm = function(){ + var x=this.x, y=this.y, z=this.z; + return Math.sqrt(x*x + y*y + z*z); +}; + +/** + * Get the squared length of the vector + * @method norm2 + * @return {Number} + */ +Vec3.prototype.norm2 = function(){ + return this.dot(this); +}; + +/** + * Get distance from this point to another point + * @method distanceTo + * @param {Vec3} p + * @return {Number} + */ +Vec3.prototype.distanceTo = function(p){ + var x=this.x, y=this.y, z=this.z; + var px=p.x, py=p.y, pz=p.z; + return Math.sqrt((px-x)*(px-x)+ + (py-y)*(py-y)+ + (pz-z)*(pz-z)); +}; + +/** + * Multiply the vector with a scalar + * @deprecated Use .scale instead + * @method mult + * @param {Number} scalar + * @param {Vec3} target + * @return {Vec3} + */ +Vec3.prototype.mult = function(scalar,target){ + target = target || new Vec3(); + var x = this.x, + y = this.y, + z = this.z; + target.x = scalar * x; + target.y = scalar * y; + target.z = scalar * z; + return target; +}; + +/** + * Multiply the vector with a scalar. + * @method scale + * @param {Number} scalar + * @param {Vec3} target + * @return {Vec3} + */ +Vec3.prototype.scale = Vec3.prototype.mult; + +/** + * Calculate dot product + * @method dot + * @param {Vec3} v + * @return {Number} + */ +Vec3.prototype.dot = function(v){ + return this.x * v.x + this.y * v.y + this.z * v.z; +}; + +/** + * @method isZero + * @return bool + */ +Vec3.prototype.isZero = function(){ + return this.x===0 && this.y===0 && this.z===0; +}; + +/** + * Make the vector point in the opposite direction. + * @method negate + * @param {Vec3} target Optional target to save in + * @return {Vec3} + */ +Vec3.prototype.negate = function(target){ + target = target || new Vec3(); + target.x = -this.x; + target.y = -this.y; + target.z = -this.z; + return target; +}; + +/** + * Compute two artificial tangents to the vector + * @method tangents + * @param {Vec3} t1 Vector object to save the first tangent in + * @param {Vec3} t2 Vector object to save the second tangent in + */ +var Vec3_tangents_n = new Vec3(); +var Vec3_tangents_randVec = new Vec3(); +Vec3.prototype.tangents = function(t1,t2){ + var norm = this.norm(); + if(norm>0.0){ + var n = Vec3_tangents_n; + var inorm = 1/norm; + n.set(this.x*inorm,this.y*inorm,this.z*inorm); + var randVec = Vec3_tangents_randVec; + if(Math.abs(n.x) < 0.9){ + randVec.set(1,0,0); + n.cross(randVec,t1); + } else { + randVec.set(0,1,0); + n.cross(randVec,t1); + } + n.cross(t1,t2); + } else { + // The normal length is zero, make something up + t1.set(1,0,0).normalize(); + t2.set(0,1,0).normalize(); + } +}; + +/** + * Converts to a more readable format + * @method toString + * @return string + */ +Vec3.prototype.toString = function(){ + return this.x+","+this.y+","+this.z; +}; + +/** + * Converts to an array + * @method toArray + * @return Array + */ +Vec3.prototype.toArray = function(){ + return [this.x, this.y, this.z]; +}; + +/** + * Copies value of source to this vector. + * @method copy + * @param {Vec3} source + * @return {Vec3} this + */ +Vec3.prototype.copy = function(source){ + this.x = source.x; + this.y = source.y; + this.z = source.z; + return this; +}; + + +/** + * Do a linear interpolation between two vectors + * @method lerp + * @param {Vec3} v + * @param {Number} t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them. + * @param {Vec3} target + */ +Vec3.prototype.lerp = function(v,t,target){ + var x=this.x, y=this.y, z=this.z; + target.x = x + (v.x-x)*t; + target.y = y + (v.y-y)*t; + target.z = z + (v.z-z)*t; +}; + +/** + * Check if a vector equals is almost equal to another one. + * @method almostEquals + * @param {Vec3} v + * @param {Number} precision + * @return bool + */ +Vec3.prototype.almostEquals = function(v,precision){ + if(precision===undefined){ + precision = 1e-6; + } + if( Math.abs(this.x-v.x)>precision || + Math.abs(this.y-v.y)>precision || + Math.abs(this.z-v.z)>precision){ + return false; + } + return true; +}; + +/** + * Check if a vector is almost zero + * @method almostZero + * @param {Number} precision + */ +Vec3.prototype.almostZero = function(precision){ + if(precision===undefined){ + precision = 1e-6; + } + if( Math.abs(this.x)>precision || + Math.abs(this.y)>precision || + Math.abs(this.z)>precision){ + return false; + } + return true; +}; + +var antip_neg = new Vec3(); + +/** + * Check if the vector is anti-parallel to another vector. + * @method isAntiparallelTo + * @param {Vec3} v + * @param {Number} precision Set to zero for exact comparisons + * @return {Boolean} + */ +Vec3.prototype.isAntiparallelTo = function(v,precision){ + this.negate(antip_neg); + return antip_neg.almostEquals(v,precision); +}; + +/** + * Clone the vector + * @method clone + * @return {Vec3} + */ +Vec3.prototype.clone = function(){ + return new Vec3(this.x, this.y, this.z); +}; +},{"./Mat3":24}],28:[function(_dereq_,module,exports){ +module.exports = Body; + +var EventTarget = _dereq_('../utils/EventTarget'); +var Shape = _dereq_('../shapes/Shape'); +var Vec3 = _dereq_('../math/Vec3'); +var Mat3 = _dereq_('../math/Mat3'); +var Quaternion = _dereq_('../math/Quaternion'); +var Material = _dereq_('../material/Material'); +var AABB = _dereq_('../collision/AABB'); +var Box = _dereq_('../shapes/Box'); + +/** + * Base class for all body types. + * @class Body + * @constructor + * @extends EventTarget + * @param {object} [options] + * @param {Vec3} [options.position] + * @param {Vec3} [options.velocity] + * @param {Vec3} [options.angularVelocity] + * @param {Quaternion} [options.quaternion] + * @param {number} [options.mass] + * @param {number} [options.type] + * @param {number} [options.linearDamping] + * @example + * var body = new Body({ + * mass: 1 + * }); + * var shape = new Sphere(1); + * body.addShape(shape); + * world.add(body); + */ +function Body(options){ + options = options || {}; + + EventTarget.apply(this); + + this.id = Body.idCounter++; + + /** + * Reference to the world the body is living in + * @property world + * @type {World} + */ + this.world = null; + + /** + * Callback function that is used BEFORE stepping the system. Use it to apply forces, for example. Inside the function, "this" will refer to this Body object. + * @property preStep + * @type {Function} + * @deprecated Use World events instead + */ + this.preStep = null; + + /** + * Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object. + * @property postStep + * @type {Function} + * @deprecated Use World events instead + */ + this.postStep = null; + + this.vlambda = new Vec3(); + + /** + * @property {Number} collisionFilterGroup + */ + this.collisionFilterGroup = 1; + + /** + * @property {Number} collisionFilterMask + */ + this.collisionFilterMask = 1; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. + * @property {Number} collisionResponse + */ + this.collisionResponse = true; + + /** + * @property position + * @type {Vec3} + */ + this.position = new Vec3(); + + if(options.position){ + this.position.copy(options.position); + } + + /** + * @property {Vec3} previousPosition + */ + this.previousPosition = new Vec3(); + + /** + * Initial position of the body + * @property initPosition + * @type {Vec3} + */ + this.initPosition = new Vec3(); + + /** + * @property velocity + * @type {Vec3} + */ + this.velocity = new Vec3(); + + if(options.velocity){ + this.velocity.copy(options.velocity); + } + + /** + * @property initVelocity + * @type {Vec3} + */ + this.initVelocity = new Vec3(); + + /** + * Linear force on the body + * @property force + * @type {Vec3} + */ + this.force = new Vec3(); + + var mass = typeof(options.mass) === 'number' ? options.mass : 0; + + /** + * @property mass + * @type {Number} + */ + this.mass = mass; + + /** + * @property invMass + * @type {Number} + */ + this.invMass = mass > 0 ? 1.0 / mass : 0; + + /** + * @property material + * @type {Material} + */ + this.material = options.material || null; + + /** + * @property linearDamping + * @type {Number} + */ + this.linearDamping = typeof(options.linearDamping) === 'number' ? options.linearDamping : 0.01; + + /** + * One of: Body.DYNAMIC, Body.STATIC and Body.KINEMATIC. + * @property type + * @type {Number} + */ + this.type = (mass <= 0.0 ? Body.STATIC : Body.DYNAMIC); + if(typeof(options.type) === typeof(Body.STATIC)){ + this.type = options.type; + } + + /** + * If true, the body will automatically fall to sleep. + * @property allowSleep + * @type {Boolean} + */ + this.allowSleep = true; + + /** + * Current sleep state. + * @property sleepState + * @type {Number} + */ + this.sleepState = 0; + + /** + * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy. + * @property sleepSpeedLimit + * @type {Number} + */ + this.sleepSpeedLimit = 0.1; + + /** + * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping. + * @property sleepTimeLimit + * @type {Number} + */ + this.sleepTimeLimit = 1; + + this.timeLastSleepy = 0; + + this._wakeUpAfterNarrowphase = false; + + + /** + * Rotational force on the body, around center of mass + * @property {Vec3} torque + */ + this.torque = new Vec3(); + + /** + * Orientation of the body + * @property quaternion + * @type {Quaternion} + */ + this.quaternion = new Quaternion(); + + if(options.quaternion){ + this.quaternion.copy(options.quaternion); + } + + /** + * @property initQuaternion + * @type {Quaternion} + */ + this.initQuaternion = new Quaternion(); + + /** + * @property angularVelocity + * @type {Vec3} + */ + this.angularVelocity = new Vec3(); + + if(options.angularVelocity){ + this.angularVelocity.copy(options.angularVelocity); + } + + /** + * @property initAngularVelocity + * @type {Vec3} + */ + this.initAngularVelocity = new Vec3(); + + this.interpolatedPosition = new Vec3(); + this.interpolatedQuaternion = new Quaternion(); + + /** + * @property shapes + * @type {array} + */ + this.shapes = []; + + /** + * @property shapeOffsets + * @type {array} + */ + this.shapeOffsets = []; + + /** + * @property shapeOrientations + * @type {array} + */ + this.shapeOrientations = []; + + /** + * @property inertia + * @type {Vec3} + */ + this.inertia = new Vec3(); + + /** + * @property {Vec3} invInertia + */ + this.invInertia = new Vec3(); + + /** + * @property {Mat3} invInertiaWorld + */ + this.invInertiaWorld = new Mat3(); + + this.invMassSolve = 0; + + /** + * @property {Vec3} invInertiaSolve + */ + this.invInertiaSolve = new Vec3(); + + /** + * @property {Mat3} invInertiaWorldSolve + */ + this.invInertiaWorldSolve = new Mat3(); + + /** + * Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() after changing this. + * @property {Boolean} fixedRotation + */ + this.fixedRotation = false; + + /** + * @property {Number} angularDamping + */ + this.angularDamping = 0.01; // Perhaps default should be zero here? + + /** + * @property aabb + * @type {Vec3} + */ + this.aabb = new AABB(); + + /** + * Indicates if the AABB needs to be updated before use. + * @property aabbNeedsUpdate + * @type {Boolean} + */ + this.aabbNeedsUpdate = true; + + this.wlambda = new Vec3(); + + this.updateMassProperties(); +} +Body.prototype = new EventTarget(); +Body.prototype.constructor = Body; + +/** + * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass. + * @static + * @property DYNAMIC + * @type {Number} + */ +Body.DYNAMIC = 1; + +/** + * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies. + * @static + * @property STATIC + * @type {Number} + */ +Body.STATIC = 2; + +/** + * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies. + * @static + * @property KINEMATIC + * @type {Number} + */ +Body.KINEMATIC = 4; + + + +/** + * @static + * @property AWAKE + * @type {number} + */ +Body.AWAKE = 0; + +/** + * @static + * @property SLEEPY + * @type {number} + */ +Body.SLEEPY = 1; + +/** + * @static + * @property SLEEPING + * @type {number} + */ +Body.SLEEPING = 2; + +Body.idCounter = 0; + +/** + * Wake the body up. + * @method wakeUp + */ +Body.prototype.wakeUp = function(){ + var s = this.sleepState; + this.sleepState = 0; + if(s === Body.SLEEPING){ + this.dispatchEvent({type:"wakeup"}); + } +}; + +/** + * Force body sleep + * @method sleep + */ +Body.prototype.sleep = function(){ + this.sleepState = Body.SLEEPING; + this.velocity.set(0,0,0); + this.angularVelocity.set(0,0,0); +}; + +Body.sleepyEvent = { + type: "sleepy" +}; + +Body.sleepEvent = { + type: "sleep" +}; + +/** + * Called every timestep to update internal sleep timer and change sleep state if needed. + * @method sleepTick + * @param {Number} time The world time in seconds + */ +Body.prototype.sleepTick = function(time){ + if(this.allowSleep){ + var sleepState = this.sleepState; + var speedSquared = this.velocity.norm2() + this.angularVelocity.norm2(); + var speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); + if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){ + this.sleepState = Body.SLEEPY; // Sleepy + this.timeLastSleepy = time; + this.dispatchEvent(Body.sleepyEvent); + } else if(sleepState===Body.SLEEPY && speedSquared > speedLimitSquared){ + this.wakeUp(); // Wake up + } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){ + this.sleep(); // Sleeping + this.dispatchEvent(Body.sleepEvent); + } + } +}; + +/** + * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass". + * @method updateSolveMassProperties + */ +Body.prototype.updateSolveMassProperties = function(){ + if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){ + this.invMassSolve = 0; + this.invInertiaSolve.setZero(); + this.invInertiaWorldSolve.setZero(); + } else { + this.invMassSolve = this.invMass; + this.invInertiaSolve.copy(this.invInertia); + this.invInertiaWorldSolve.copy(this.invInertiaWorld); + } +}; + +/** + * Convert a world point to local body frame. + * @method pointToLocalFrame + * @param {Vec3} worldPoint + * @param {Vec3} result + * @return {Vec3} + */ +Body.prototype.pointToLocalFrame = function(worldPoint,result){ + var result = result || new Vec3(); + worldPoint.vsub(this.position,result); + this.quaternion.conjugate().vmult(result,result); + return result; +}; + +/** + * Convert a local body point to world frame. + * @method pointToWorldFrame + * @param {Vec3} localPoint + * @param {Vec3} result + * @return {Vec3} + */ +Body.prototype.pointToWorldFrame = function(localPoint,result){ + var result = result || new Vec3(); + this.quaternion.vmult(localPoint,result); + result.vadd(this.position,result); + return result; +}; + +/** + * Convert a local body point to world frame. + * @method vectorToWorldFrame + * @param {Vec3} localVector + * @param {Vec3} result + * @return {Vec3} + */ +Body.prototype.vectorToWorldFrame = function(localVector, result){ + var result = result || new Vec3(); + this.quaternion.vmult(localVector, result); + return result; +}; + +var tmpVec = new Vec3(); +var tmpQuat = new Quaternion(); + + +Body.prototype.addShape = function(shape, _offset, _orientation){ + var offset = new Vec3(); + var orientation = new Quaternion(); + + if(_offset){ + offset.copy(_offset); + } + if(_orientation){ + orientation.copy(_orientation); + } + + this.shapes.push(shape); + this.shapeOffsets.push(offset); + this.shapeOrientations.push(orientation); + this.updateMassProperties(); + this.updateBoundingRadius(); + + this.aabbNeedsUpdate = true; +}; + +/** + * Update the bounding radius of the body. Should be done if any of the shapes are changed. + * @method updateBoundingRadius + */ +Body.prototype.updateBoundingRadius = function(){ + var shapes = this.shapes, + shapeOffsets = this.shapeOffsets, + N = shapes.length, + radius = 0; + + for(var i=0; i!==N; i++){ + var shape = shapes[i]; + shape.updateBoundingSphereRadius(); + var offset = shapeOffsets[i].norm(), + r = shape.boundingSphereRadius; + if(offset + r > radius){ + radius = offset + r; + } + } + + this.boundingRadius = radius; +}; + +var computeAABB_shapeAABB = new AABB(); + +/** + * Updates the .aabb + * @method computeAABB + * @todo rename to updateAABB() + */ +Body.prototype.computeAABB = function(){ + var shapes = this.shapes, + shapeOffsets = this.shapeOffsets, + shapeOrientations = this.shapeOrientations, + N = shapes.length, + offset = tmpVec, + orientation = tmpQuat, + bodyQuat = this.quaternion, + aabb = this.aabb, + shapeAABB = computeAABB_shapeAABB; + + for(var i=0; i!==N; i++){ + var shape = shapes[i]; + + // Get shape world quaternion + shapeOrientations[i].mult(bodyQuat, orientation); + + // Get shape world position + orientation.vmult(shapeOffsets[i], offset); + offset.vadd(this.position, offset); + + // vec2.rotate(offset, shapeOffsets[i], bodyAngle); + // vec2.add(offset, offset, this.position); + + // Get shape AABB + shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound); + + if(i === 0){ + aabb.copy(shapeAABB); + } else { + aabb.extend(shapeAABB); + } + } + + this.aabbNeedsUpdate = false; +}; + +var uiw_m1 = new Mat3(), + uiw_m2 = new Mat3(), + uiw_m3 = new Mat3(); + +/** + * Update .inertiaWorld and .invInertiaWorld + * @method updateInertiaWorld + */ +Body.prototype.updateInertiaWorld = function(force){ + var I = this.invInertia; + if (I.x === I.y && I.y === I.z && !force) { + // If inertia M = s*I, where I is identity and s a scalar, then + // R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M + // where R is the rotation matrix. + // In other words, we don't have to transform the inertia if all + // inertia diagonal entries are equal. + } else { + var m1 = uiw_m1, + m2 = uiw_m2, + m3 = uiw_m3; + m1.setRotationFromQuaternion(this.quaternion); + m1.transpose(m2); + m1.scale(I,m1); + m1.mmult(m2,this.invInertiaWorld); + //m3.getTrace(this.invInertiaWorld); + } + + /* + this.quaternion.vmult(this.inertia,this.inertiaWorld); + this.quaternion.vmult(this.invInertia,this.invInertiaWorld); + */ +}; + +/** + * Apply force to a world point. This could for example be a point on the Body surface. Applying force this way will add to Body.force and Body.torque. + * @method applyForce + * @param {Vec3} force The amount of force to add. + * @param {Vec3} worldPoint A world point to apply the force on. + */ +var Body_applyForce_r = new Vec3(); +var Body_applyForce_rotForce = new Vec3(); +Body.prototype.applyForce = function(force,worldPoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute point position relative to the body center + var r = Body_applyForce_r; + worldPoint.vsub(this.position,r); + + // Compute produced rotational force + var rotForce = Body_applyForce_rotForce; + r.cross(force,rotForce); + + // Add linear force + this.force.vadd(force,this.force); + + // Add rotational force + this.torque.vadd(rotForce,this.torque); +}; + +/** + * Apply impulse to a world point. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity. + * @method applyImpulse + * @param {Vec3} impulse The amount of impulse to add. + * @param {Vec3} worldPoint A world point to apply the force on. + */ +var Body_applyImpulse_r = new Vec3(); +var Body_applyImpulse_velo = new Vec3(); +var Body_applyImpulse_rotVelo = new Vec3(); +Body.prototype.applyImpulse = function(impulse, worldPoint){ + if(this.type !== Body.DYNAMIC){ + return; + } + + // Compute point position relative to the body center + var r = Body_applyImpulse_r; + worldPoint.vsub(this.position,r); + + // Compute produced central impulse velocity + var velo = Body_applyImpulse_velo; + velo.copy(impulse); + velo.mult(this.invMass,velo); + + // Add linear impulse + this.velocity.vadd(velo, this.velocity); + + // Compute produced rotational impulse velocity + var rotVelo = Body_applyImpulse_rotVelo; + r.cross(impulse,rotVelo); + + /* + rotVelo.x *= this.invInertia.x; + rotVelo.y *= this.invInertia.y; + rotVelo.z *= this.invInertia.z; + */ + this.invInertiaWorld.vmult(rotVelo,rotVelo); + + // Add rotational Impulse + this.angularVelocity.vadd(rotVelo, this.angularVelocity); +}; + +/** + * Should be called whenever you change the body mass. + * @method updateMassProperties + */ +/*Body.prototype.updateMassProperties = function(){ + this.invMass = this.mass>0 ? 1.0/this.mass : 0; + this.shape.calculateLocalInertia(this.mass, this.inertia); + var I = this.inertia; + var fixed = this.fixedRotation; + this.invInertia.set( + I.x > 0 && !fixed ? 1.0 / I.x : 0, + I.y > 0 && !fixed ? 1.0 / I.y : 0, + I.z > 0 && !fixed ? 1.0 / I.z : 0 + ); + this.updateInertiaWorld(true); +}; +*/ + +Body.prototype.updateMassProperties = function(){ + var target = new Vec3(); + + // TODO: check if only 1 shape at origin, use shape inertia in that case + + this.invMass = this.mass > 0 ? 1.0 / this.mass : 0; + var I = this.inertia; + var fixed = this.fixedRotation; + + // Approximate with AABB + this.computeAABB(); + Box.calculateInertia(new Vec3( + (this.aabb.upperBound.x-this.aabb.lowerBound.x) / 2, + (this.aabb.upperBound.y-this.aabb.lowerBound.y) / 2, + (this.aabb.upperBound.z-this.aabb.lowerBound.z) / 2 + ), this.mass, I); + + this.invInertia.set( + I.x > 0 && !fixed ? 1.0 / I.x : 0, + I.y > 0 && !fixed ? 1.0 / I.y : 0, + I.z > 0 && !fixed ? 1.0 / I.z : 0 + ); + this.updateInertiaWorld(true); +}; + +/** + * Get world velocity of a point in the body. + * @method getVelocityAtWorldPoint + * @param {Vec3} worldPoint + * @param {Vec3} result + * @return {Vec3} The result vector. + */ +Body.prototype.getVelocityAtWorldPoint = function(worldPoint, result){ + var r = new Vec3(); + worldPoint.vsub(this.position, r); + this.angularVelocity.cross(r, result); + this.velocity.vadd(result, result); + return result; +}; + +},{"../collision/AABB":3,"../material/Material":22,"../math/Mat3":24,"../math/Quaternion":25,"../math/Vec3":27,"../shapes/Box":34,"../shapes/Shape":40,"../utils/EventTarget":45}],29:[function(_dereq_,module,exports){ +var Body = _dereq_('./Body'); +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var RaycastResult = _dereq_('../collision/RaycastResult'); +var Ray = _dereq_('../collision/Ray'); +var WheelInfo = _dereq_('../objects/WheelInfo'); + +module.exports = RaycastVehicle; + +/** + * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces. + * @class RaycastVehicle + * @constructor + * @param {object} [options] + * @param {Body} [options.chassisBody] The car chassis body. + * @param {integer} [options.indexRightAxis] Axis to use for right. x=0, y=1, z=2 + * @param {integer} [options.indexLeftAxis] + * @param {integer} [options.indexUpAxis] + */ +function RaycastVehicle(options){ + + /** + * @property {Body} chassisBody + */ + this.chassisBody = options.chassisBody; + + /** + * An array of WheelInfo objects. + * @property {array} wheelInfos + */ + this.wheelInfos = []; + + /** + * Will be set to true if the car is sliding. + * @property {boolean} sliding + */ + this.sliding = false; + + /** + * @property {World} world + */ + this.world = null; + + /** + * Index of the right axis, 0=x, 1=y, 2=z + * @property {integer} indexRightAxis + * @default 1 + */ + this.indexRightAxis = typeof(options.indexRightAxis) !== 'undefined' ? options.indexRightAxis : 1; + + /** + * Index of the forward axis, 0=x, 1=y, 2=z + * @property {integer} indexForwardAxis + * @default 0 + */ + this.indexForwardAxis = typeof(options.indexForwardAxis) !== 'undefined' ? options.indexForwardAxis : 0; + + /** + * Index of the up axis, 0=x, 1=y, 2=z + * @property {integer} indexUpAxis + * @default 2 + */ + this.indexUpAxis = typeof(options.indexUpAxis) !== 'undefined' ? options.indexUpAxis : 2; +} + +var tmpVec1 = new Vec3(); +var tmpVec2 = new Vec3(); +var tmpVec3 = new Vec3(); +var tmpVec4 = new Vec3(); +var tmpVec5 = new Vec3(); +var tmpVec6 = new Vec3(); +var tmpRay = new Ray(); + +/** + * Add a wheel. For information about the options, see WheelInfo. + * @method addWheel + * @param {object} [options] + */ +RaycastVehicle.prototype.addWheel = function(options){ + options = options || {}; + + var info = new WheelInfo(options); + var index = this.wheelInfos.length; + this.wheelInfos.push(info); + + return index; +}; + +/** + * Set the steering value of a wheel. + * @method setSteeringValue + * @param {number} value + * @param {integer} wheelIndex + */ +RaycastVehicle.prototype.setSteeringValue = function(value, wheelIndex){ + var wheel = this.wheelInfos[wheelIndex]; + wheel.steering = value; +}; + +var torque = new Vec3(); + +/** + * Set the wheel force to apply on one of the wheels each time step + * @method applyEngineForce + * @param {number} value + * @param {integer} wheelIndex + */ +RaycastVehicle.prototype.applyEngineForce = function(value, wheelIndex){ + this.wheelInfos[wheelIndex].engineForce = value; +}; + +/** + * Set the braking force of a wheel + * @method setBrake + * @param {number} brake + * @param {integer} wheelIndex + */ +RaycastVehicle.prototype.setBrake = function(brake, wheelIndex){ + this.wheelInfos[wheelIndex].brake = brake; +}; + +/** + * Add the vehicle including its constraints to the world. + * @method addToWorld + * @param {World} world + */ +RaycastVehicle.prototype.addToWorld = function(world){ + var constraints = this.constraints; + world.add(this.chassisBody); + var that = this; + world.addEventListener('preStep', function(){ + that.updateVehicle(world.dt); + }); + this.world = world; +}; + +/** + * Get one of the wheel axles, world-oriented. + * @private + * @method getVehicleAxisWorld + * @param {integer} axisIndex + * @param {Vec3} result + */ +RaycastVehicle.prototype.getVehicleAxisWorld = function(axisIndex, result){ + result.set( + axisIndex === 0 ? 1 : 0, + axisIndex === 1 ? 1 : 0, + axisIndex === 2 ? 1 : 0 + ); + this.chassisBody.vectorToWorldFrame(result, result); +}; + +RaycastVehicle.prototype.updateVehicle = function(timeStep){ + var wheelInfos = this.wheelInfos; + var numWheels = wheelInfos.length; + var chassisBody = this.chassisBody; + + for (var i = 0; i < numWheels; i++) { + this.updateWheelTransform(i, false); + } + + this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.norm(); + + var forwardWorld = new Vec3(); + this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld); + + if (forwardWorld.dot(chassisBody.velocity) < 0){ + this.currentVehicleSpeedKmHour *= -1; + } + + // simulate suspension + for (var i = 0; i < numWheels; i++) { + this.castRay(wheelInfos[i]); + } + + this.updateSuspension(timeStep); + + var impulse = new Vec3(); + var relpos = new Vec3(); + for (var i = 0; i < numWheels; i++) { + //apply suspension force + var wheel = wheelInfos[i]; + var suspensionForce = wheel.suspensionForce; + if (suspensionForce > wheel.maxSuspensionForce) { + suspensionForce = wheel.maxSuspensionForce; + } + wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse); + + wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos); + chassisBody.applyImpulse(impulse, wheel.raycastResult.hitPointWorld/*relpos*/); + } + + this.updateFriction(timeStep); + + var hitNormalWorldScaledWithProj = new Vec3(); + var fwd = new Vec3(); + var vel = new Vec3(); + for (i = 0; i < numWheels; i++) { + var wheel = wheelInfos[i]; + //var relpos = new Vec3(); + //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos); + chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel); + + // Hack to get the rotation in the correct direction + var m = 1; + switch(this.indexUpAxis){ + case 1: + m = -1; + break; + } + + if (wheel.isInContact) { + + this.getVehicleAxisWorld(this.indexForwardAxis, fwd); + var proj = fwd.dot(wheel.raycastResult.hitNormalWorld); + wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj); + + fwd.vsub(hitNormalWorldScaledWithProj, fwd); + + var proj2 = fwd.dot(vel); + wheel.deltaRotation = m * proj2 * timeStep / wheel.radius; + } + + if((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed){ + // Apply custom rotation when accelerating and sliding + wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep; + } + + // Lock wheels + if(Math.abs(wheel.brake) > Math.abs(wheel.engineForce)){ + wheel.deltaRotation = 0; + } + + wheel.rotation += wheel.deltaRotation; // Use the old value + wheel.deltaRotation *= 0.99; // damping of rotation when not in contact + } +}; + +RaycastVehicle.prototype.updateSuspension = function(deltaTime) { + var chassisBody = this.chassisBody; + var chassisMass = chassisBody.mass; + var wheelInfos = this.wheelInfos; + var numWheels = wheelInfos.length; + + for (var w_it = 0; w_it < numWheels; w_it++){ + var wheel = wheelInfos[w_it]; + + if (wheel.isInContact){ + var force; + + // Spring + var susp_length = wheel.suspensionRestLength; + var current_length = wheel.suspensionLength; + var length_diff = (susp_length - current_length); + + force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension; + + // Damper + var projected_rel_vel = wheel.suspensionRelativeVelocity; + var susp_damping; + if (projected_rel_vel < 0) { + susp_damping = wheel.dampingCompression; + } else { + susp_damping = wheel.dampingRelaxation; + } + force -= susp_damping * projected_rel_vel; + + wheel.suspensionForce = force * chassisMass; + if (wheel.suspensionForce < 0) { + wheel.suspensionForce = 0; + } + } else { + wheel.suspensionForce = 0; + } + } +}; + +/** + * Remove the vehicle including its constraints from the world. + * @method removeFromWorld + * @param {World} world + */ +RaycastVehicle.prototype.removeFromWorld = function(world){ + var constraints = this.constraints; + world.remove(this.chassisBody); + world.removeEventListener('preStep', this.updateVehicle); + this.world = null; +}; + +var castRay_rayvector = new Vec3(); +var castRay_target = new Vec3(); +RaycastVehicle.prototype.castRay = function(wheel) { + var rayvector = castRay_rayvector; + var target = castRay_target; + + this.updateWheelTransformWorld(wheel); + var chassisBody = this.chassisBody; + + var depth = -1; + + var raylen = wheel.suspensionRestLength + wheel.radius; + + wheel.directionWorld.scale(raylen, rayvector); + var source = wheel.chassisConnectionPointWorld; + source.vadd(rayvector, target); + var raycastResult = wheel.raycastResult; + + var param = 0; + + raycastResult.reset(); + // Turn off ray collision with the chassis temporarily + var oldState = chassisBody.collisionResponse; + chassisBody.collisionResponse = false; + + // Cast ray against world + this.world.rayTest(source, target, raycastResult); + chassisBody.collisionResponse = oldState; + + var object = raycastResult.body; + + wheel.raycastResult.groundObject = 0; + + if (object) { + depth = raycastResult.distance; + wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld; + wheel.isInContact = true; + + var hitDistance = raycastResult.distance; + wheel.suspensionLength = hitDistance - wheel.radius; + + // clamp on max suspension travel + var minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel; + var maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel; + if (wheel.suspensionLength < minSuspensionLength) { + wheel.suspensionLength = minSuspensionLength; + } + if (wheel.suspensionLength > maxSuspensionLength) { + wheel.suspensionLength = maxSuspensionLength; + wheel.raycastResult.reset(); + } + + var denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld); + + var chassis_velocity_at_contactPoint = new Vec3(); + chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint); + + var projVel = wheel.raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint ); + + if (denominator >= -0.1) { + wheel.suspensionRelativeVelocity = 0; + wheel.clippedInvContactDotSuspension = 1 / 0.1; + } else { + var inv = -1 / denominator; + wheel.suspensionRelativeVelocity = projVel * inv; + wheel.clippedInvContactDotSuspension = inv; + } + + } else { + + //put wheel info as in rest position + wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel; + wheel.suspensionRelativeVelocity = 0.0; + wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld); + wheel.clippedInvContactDotSuspension = 1.0; + } + + return depth; +}; + +RaycastVehicle.prototype.updateWheelTransformWorld = function(wheel){ + wheel.isInContact = false; + var chassisBody = this.chassisBody; + chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld); + chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld); + chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld); +}; + +RaycastVehicle.prototype.updateWheelTransform = function(wheelIndex){ + var up = tmpVec4; + var right = tmpVec5; + var fwd = tmpVec6; + + var wheel = this.wheelInfos[wheelIndex]; + this.updateWheelTransformWorld(wheel); + + wheel.directionLocal.scale(-1, up); + right.copy(wheel.axleLocal); + up.cross(right, fwd); + fwd.normalize(); + right.normalize(); + + // Rotate around steering over the wheelAxle + var steering = wheel.steering; + var steeringOrn = new Quaternion(); + steeringOrn.setFromAxisAngle(up, steering); + + var rotatingOrn = new Quaternion(); + rotatingOrn.setFromAxisAngle(right, wheel.rotation); + + // World rotation of the wheel + var q = wheel.worldTransform.quaternion; + this.chassisBody.quaternion.mult(steeringOrn, q); + q.mult(rotatingOrn, q); + + q.normalize(); + + // world position of the wheel + var p = wheel.worldTransform.position; + p.copy(wheel.directionWorld); + p.scale(wheel.suspensionLength, p); + p.vadd(wheel.chassisConnectionPointWorld, p); +}; + +var directions = [ + new Vec3(1, 0, 0), + new Vec3(0, 1, 0), + new Vec3(0, 0, 1) +]; + +/** + * Get the world transform of one of the wheels + * @method getWheelTransformWorld + * @param {integer} wheelIndex + * @return {Transform} + */ +RaycastVehicle.prototype.getWheelTransformWorld = function(wheelIndex) { + return this.wheelInfos[wheelIndex].worldTransform; +}; + + +var updateFriction_surfNormalWS_scaled_proj = new Vec3(); +var updateFriction_axle = []; +var updateFriction_forwardWS = []; +var sideFrictionStiffness2 = 1; +RaycastVehicle.prototype.updateFriction = function(timeStep) { + var surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj; + + //calculate the impulse, so that the wheels don't move sidewards + var wheelInfos = this.wheelInfos; + var numWheels = wheelInfos.length; + var chassisBody = this.chassisBody; + var forwardWS = updateFriction_forwardWS; + var axle = updateFriction_axle; + + var numWheelsOnGround = 0; + + for (var i = 0; i < numWheels; i++) { + var wheel = wheelInfos[i]; + + var groundObject = wheel.raycastResult.body; + if (groundObject){ + numWheelsOnGround++; + } + + wheel.sideImpulse = 0; + wheel.forwardImpulse = 0; + if(!forwardWS[i]){ + forwardWS[i] = new Vec3(); + } + if(!axle[i]){ + axle[i] = new Vec3(); + } + } + + for (var i = 0; i < numWheels; i++){ + var wheel = wheelInfos[i]; + + var groundObject = wheel.raycastResult.body; + + if (groundObject) { + var axlei = axle[i]; + var wheelTrans = this.getWheelTransformWorld(i); + + // Get world axle + wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei); + + var surfNormalWS = wheel.raycastResult.hitNormalWorld; + var proj = axlei.dot(surfNormalWS); + surfNormalWS.scale(proj, surfNormalWS_scaled_proj); + axlei.vsub(surfNormalWS_scaled_proj, axlei); + axlei.normalize(); + + surfNormalWS.cross(axlei, forwardWS[i]); + forwardWS[i].normalize(); + + wheel.sideImpulse = resolveSingleBilateral( + chassisBody, + wheel.raycastResult.hitPointWorld, + groundObject, + wheel.raycastResult.hitPointWorld, + axlei + ); + + wheel.sideImpulse *= sideFrictionStiffness2; + } + } + + var sideFactor = 1; + var fwdFactor = 0.5; + + this.sliding = false; + for (var i = 0; i < numWheels; i++) { + var wheel = wheelInfos[i]; + var groundObject = wheel.raycastResult.body; + + var rollingFriction = 0; + + wheel.slipInfo = 1; + if (groundObject) { + var defaultRollingFrictionImpulse = 0; + var maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse; + + // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse); + // rollingFriction = calcRollingFriction(contactPt); + rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse); + + rollingFriction += wheel.engineForce * timeStep; + + // rollingFriction = 0; + var factor = maxImpulse / rollingFriction; + wheel.slipInfo *= factor; + } + + //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break) + + wheel.forwardImpulse = 0; + wheel.skidInfo = 1; + + if (groundObject) { + wheel.skidInfo = 1; + + var maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip; + var maximpSide = maximp; + + var maximpSquared = maximp * maximpSide; + + wheel.forwardImpulse = rollingFriction;//wheelInfo.engineForce* timeStep; + + var x = wheel.forwardImpulse * fwdFactor; + var y = wheel.sideImpulse * sideFactor; + + var impulseSquared = x * x + y * y; + + wheel.sliding = false; + if (impulseSquared > maximpSquared) { + this.sliding = true; + wheel.sliding = true; + + var factor = maximp / Math.sqrt(impulseSquared); + + wheel.skidInfo *= factor; + } + } + } + + if (this.sliding) { + for (var i = 0; i < numWheels; i++) { + var wheel = wheelInfos[i]; + if (wheel.sideImpulse !== 0) { + if (wheel.skidInfo < 1){ + wheel.forwardImpulse *= wheel.skidInfo; + wheel.sideImpulse *= wheel.skidInfo; + } + } + } + } + + // apply the impulses + for (var i = 0; i < numWheels; i++) { + var wheel = wheelInfos[i]; + + var rel_pos = new Vec3(); + //wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos); + // cannons applyimpulse is using world coord for the position + rel_pos.copy(wheel.raycastResult.hitPointWorld); + + if (wheel.forwardImpulse !== 0) { + var impulse = new Vec3(); + forwardWS[i].scale(wheel.forwardImpulse, impulse); + chassisBody.applyImpulse(impulse, rel_pos); + } + + if (wheel.sideImpulse !== 0){ + var groundObject = wheel.raycastResult.body; + + var rel_pos2 = new Vec3(); + //wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2); + rel_pos2.copy(wheel.raycastResult.hitPointWorld); + var sideImp = new Vec3(); + axle[i].scale(wheel.sideImpulse, sideImp); + + // Scale the relative position in the up direction with rollInfluence. + // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over). + chassisBody.pointToLocalFrame(rel_pos, rel_pos); + rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence; + chassisBody.pointToWorldFrame(rel_pos, rel_pos); + chassisBody.applyImpulse(sideImp, rel_pos); + + //apply friction impulse on the ground + sideImp.scale(-1, sideImp); + groundObject.applyImpulse(sideImp, rel_pos2); + } + } +}; + +var calcRollingFriction_vel1 = new Vec3(); +var calcRollingFriction_vel2 = new Vec3(); +var calcRollingFriction_vel = new Vec3(); + +function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) { + var j1 = 0; + var contactPosWorld = frictionPosWorld; + + // var rel_pos1 = new Vec3(); + // var rel_pos2 = new Vec3(); + var vel1 = calcRollingFriction_vel1; + var vel2 = calcRollingFriction_vel2; + var vel = calcRollingFriction_vel; + // contactPosWorld.vsub(body0.position, rel_pos1); + // contactPosWorld.vsub(body1.position, rel_pos2); + + body0.getVelocityAtWorldPoint(contactPosWorld, vel1); + body1.getVelocityAtWorldPoint(contactPosWorld, vel2); + vel1.vsub(vel2, vel); + + var vrel = frictionDirectionWorld.dot(vel); + + var denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld); + var denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld); + var relaxation = 1; + var jacDiagABInv = relaxation / (denom0 + denom1); + + // calculate j that moves us to zero relative velocity + j1 = -vrel * jacDiagABInv; + + if (maxImpulse < j1) { + j1 = maxImpulse; + } + if (j1 < -maxImpulse) { + j1 = -maxImpulse; + } + + return j1; +} + +var computeImpulseDenominator_r0 = new Vec3(); +var computeImpulseDenominator_c0 = new Vec3(); +var computeImpulseDenominator_vec = new Vec3(); +var computeImpulseDenominator_m = new Vec3(); +function computeImpulseDenominator(body, pos, normal) { + var r0 = computeImpulseDenominator_r0; + var c0 = computeImpulseDenominator_c0; + var vec = computeImpulseDenominator_vec; + var m = computeImpulseDenominator_m; + + pos.vsub(body.position, r0); + r0.cross(normal, c0); + body.invInertiaWorld.vmult(c0, m); + m.cross(r0, vec); + + return body.invMass + normal.dot(vec); +} + + +var resolveSingleBilateral_vel1 = new Vec3(); +var resolveSingleBilateral_vel2 = new Vec3(); +var resolveSingleBilateral_vel = new Vec3(); + +//bilateral constraint between two dynamic objects +function resolveSingleBilateral(body1, pos1, body2, pos2, normal, impulse){ + var normalLenSqr = normal.norm2(); + if (normalLenSqr > 1.1){ + return 0; // no impulse + } + // var rel_pos1 = new Vec3(); + // var rel_pos2 = new Vec3(); + // pos1.vsub(body1.position, rel_pos1); + // pos2.vsub(body2.position, rel_pos2); + + var vel1 = resolveSingleBilateral_vel1; + var vel2 = resolveSingleBilateral_vel2; + var vel = resolveSingleBilateral_vel; + body1.getVelocityAtWorldPoint(pos1, vel1); + body2.getVelocityAtWorldPoint(pos2, vel2); + + vel1.vsub(vel2, vel); + + var rel_vel = normal.dot(vel); + + var contactDamping = 0.2; + var massTerm = 1 / (body1.invMass + body2.invMass); + var impulse = - contactDamping * rel_vel * massTerm; + + return impulse; +} +},{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":25,"../math/Vec3":27,"../objects/WheelInfo":33,"./Body":28}],30:[function(_dereq_,module,exports){ +var Body = _dereq_('./Body'); +var Sphere = _dereq_('../shapes/Sphere'); +var Box = _dereq_('../shapes/Box'); +var Vec3 = _dereq_('../math/Vec3'); +var HingeConstraint = _dereq_('../constraints/HingeConstraint'); + +module.exports = RigidVehicle; + +/** + * Simple vehicle helper class with spherical rigid body wheels. + * @class RigidVehicle + * @constructor + * @param {object} [options.chassisBody] + */ +function RigidVehicle(options){ + this.wheelBodies = []; + + /** + * @property coordinateSystem + * @type {Vec3} + */ + this.coordinateSystem = typeof(options.coordinateSystem)==='undefined' ? new Vec3(1, 2, 3) : options.coordinateSystem.clone(); + + /** + * @property {Body} chassisBody + */ + this.chassisBody = options.chassisBody; + + if(!this.chassisBody){ + // No chassis body given. Create it! + var chassisShape = new Box(new Vec3(5, 2, 0.5)); + this.chassisBody = new Body(1, chassisShape); + } + + /** + * @property constraints + * @type {Array} + */ + this.constraints = []; + + this.wheelAxes = []; + this.wheelForces = []; +} + +/** + * Add a wheel + * @method addWheel + * @param {object} options + * @param {object} [options.isFrontWheel] + * @param {Vec3} [options.position] Position of the wheel, locally in the chassis body. + * @param {Vec3} [options.direction] Slide direction of the wheel along the suspension. + * @param {Vec3} [options.axis] Axis of rotation of the wheel, locally defined in the chassis. + * @param {Body} [options.body] The wheel body. + */ +RigidVehicle.prototype.addWheel = function(options){ + options = options || {}; + var wheelBody = options.body; + if(!wheelBody){ + wheelBody = new Body(1, new Sphere(1.2)); + } + this.wheelBodies.push(wheelBody); + this.wheelForces.push(0); + + // Position constrain wheels + var zero = new Vec3(); + var position = typeof(options.position) !== 'undefined' ? options.position.clone() : new Vec3(); + + // Set position locally to the chassis + var worldPosition = new Vec3(); + this.chassisBody.pointToWorldFrame(position, worldPosition); + wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z); + + // Constrain wheel + var axis = typeof(options.axis) !== 'undefined' ? options.axis.clone() : new Vec3(0, 1, 0); + this.wheelAxes.push(axis); + + var hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, { + pivotA: position, + axisA: axis, + pivotB: Vec3.ZERO, + axisB: axis, + collideConnected: false + }); + this.constraints.push(hingeConstraint); + + return this.wheelBodies.length - 1; +}; + +/** + * Set the steering value of a wheel. + * @method setSteeringValue + * @param {number} value + * @param {integer} wheelIndex + * @todo check coordinateSystem + */ +RigidVehicle.prototype.setSteeringValue = function(value, wheelIndex){ + // Set angle of the hinge axis + var axis = this.wheelAxes[wheelIndex]; + + var c = Math.cos(value), + s = Math.sin(value), + x = axis.x, + y = axis.y; + this.constraints[wheelIndex].axisA.set( + c*x -s*y, + s*x +c*y, + 0 + ); +}; + +/** + * Set the target rotational speed of the hinge constraint. + * @method setMotorSpeed + * @param {number} value + * @param {integer} wheelIndex + */ +RigidVehicle.prototype.setMotorSpeed = function(value, wheelIndex){ + var hingeConstraint = this.constraints[wheelIndex]; + hingeConstraint.enableMotor(); + hingeConstraint.motorTargetVelocity = value; +}; + +/** + * Set the target rotational speed of the hinge constraint. + * @method disableMotor + * @param {number} value + * @param {integer} wheelIndex + */ +RigidVehicle.prototype.disableMotor = function(wheelIndex){ + var hingeConstraint = this.constraints[wheelIndex]; + hingeConstraint.disableMotor(); +}; + +var torque = new Vec3(); + +/** + * Set the wheel force to apply on one of the wheels each time step + * @method setWheelForce + * @param {number} value + * @param {integer} wheelIndex + */ +RigidVehicle.prototype.setWheelForce = function(value, wheelIndex){ + this.wheelForces[wheelIndex] = value; +}; + +/** + * Apply a torque on one of the wheels. + * @method applyWheelForce + * @param {number} value + * @param {integer} wheelIndex + */ +RigidVehicle.prototype.applyWheelForce = function(value, wheelIndex){ + var axis = this.wheelAxes[wheelIndex]; + var wheelBody = this.wheelBodies[wheelIndex]; + var bodyTorque = wheelBody.torque; + + axis.scale(value, torque); + wheelBody.vectorToWorldFrame(torque, torque); + bodyTorque.vadd(torque, bodyTorque); +}; + +/** + * Add the vehicle including its constraints to the world. + * @method addToWorld + * @param {World} world + */ +RigidVehicle.prototype.addToWorld = function(world){ + var constraints = this.constraints; + var bodies = this.wheelBodies.concat([this.chassisBody]); + + for (var i = 0; i < bodies.length; i++) { + world.add(bodies[i]); + } + + for (var i = 0; i < constraints.length; i++) { + world.addConstraint(constraints[i]); + } + + world.addEventListener('preStep', this._update.bind(this)); +}; + +RigidVehicle.prototype._update = function(){ + var wheelForces = this.wheelForces; + for (var i = 0; i < wheelForces.length; i++) { + this.applyWheelForce(wheelForces[i], i); + } +}; + +/** + * Remove the vehicle including its constraints from the world. + * @method removeFromWorld + * @param {World} world + */ +RigidVehicle.prototype.removeFromWorld = function(world){ + var constraints = this.constraints; + var bodies = this.wheelBodies.concat([this.chassisBody]); + + for (var i = 0; i < bodies.length; i++) { + world.remove(bodies[i]); + } + + for (var i = 0; i < constraints.length; i++) { + world.removeConstraint(constraints[i]); + } +}; + +var worldAxis = new Vec3(); + +/** + * Get current rotational velocity of a wheel + * @method getWheelSpeed + * @param {integer} wheelIndex + */ +RigidVehicle.prototype.getWheelSpeed = function(wheelIndex){ + var axis = this.wheelAxes[wheelIndex]; + var wheelBody = this.wheelBodies[wheelIndex]; + var w = wheelBody.angularVelocity; + this.chassisBody.vectorToWorldFrame(axis, worldAxis); + return w.dot(worldAxis); +}; + +},{"../constraints/HingeConstraint":14,"../math/Vec3":27,"../shapes/Box":34,"../shapes/Sphere":41,"./Body":28}],31:[function(_dereq_,module,exports){ +module.exports = SPHSystem; + +var Shape = _dereq_('../shapes/Shape'); +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var Particle = _dereq_('../shapes/Particle'); +var Body = _dereq_('../objects/Body'); +var Material = _dereq_('../material/Material'); + +/** + * Smoothed-particle hydrodynamics system + * @class SPHSystem + * @constructor + */ +function SPHSystem(){ + this.particles = []; + this.density = 1; // kg/m3 + this.smoothingRadius = 1; // Adjust so there are about 15-20 neighbor particles within this radius + this.speedOfSound = 1; + this.viscosity = 0.01; + this.eps = 0.000001; + + // Stuff Computed per particle + this.pressures = []; + this.densities = []; + this.neighbors = []; +} + +SPHSystem.prototype.add = function(particle){ + this.particles.push(particle); + if(this.neighbors.length < this.particles.length){ + this.neighbors.push([]); + } +}; + +SPHSystem.prototype.remove = function(particle){ + var idx = this.particles.indexOf(particle); + if(idx !== -1){ + this.particles.splice(idx,1); + if(this.neighbors.length > this.particles.length){ + this.neighbors.pop(); + } + } +}; + +/** + * Get neighbors within smoothing volume, save in the array neighbors + * @method getNeighbors + * @param {Body} particle + * @param {Array} neighbors + */ +var SPHSystem_getNeighbors_dist = new Vec3(); +SPHSystem.prototype.getNeighbors = function(particle,neighbors){ + var N = this.particles.length, + id = particle.id, + R2 = this.smoothingRadius * this.smoothingRadius, + dist = SPHSystem_getNeighbors_dist; + for(var i=0; i!==N; i++){ + var p = this.particles[i]; + p.position.vsub(particle.position,dist); + if(id!==p.id && dist.norm2() < R2){ + neighbors.push(p); + } + } +}; + +// Temp vectors for calculation +var SPHSystem_update_dist = new Vec3(), + SPHSystem_update_a_pressure = new Vec3(), + SPHSystem_update_a_visc = new Vec3(), + SPHSystem_update_gradW = new Vec3(), + SPHSystem_update_r_vec = new Vec3(), + SPHSystem_update_u = new Vec3(); // Relative velocity +SPHSystem.prototype.update = function(){ + var N = this.particles.length, + dist = SPHSystem_update_dist, + cs = this.speedOfSound, + eps = this.eps; + + for(var i=0; i!==N; i++){ + var p = this.particles[i]; // Current particle + var neighbors = this.neighbors[i]; + + // Get neighbors + neighbors.length = 0; + this.getNeighbors(p,neighbors); + neighbors.push(this.particles[i]); // Add current too + var numNeighbors = neighbors.length; + + // Accumulate density for the particle + var sum = 0.0; + for(var j=0; j!==numNeighbors; j++){ + + //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z()); + p.position.vsub(neighbors[j].position, dist); + var len = dist.norm(); + + var weight = this.w(len); + sum += neighbors[j].mass * weight; + } + + // Save + this.densities[i] = sum; + this.pressures[i] = cs * cs * (this.densities[i] - this.density); + } + + // Add forces + + // Sum to these accelerations + var a_pressure= SPHSystem_update_a_pressure; + var a_visc = SPHSystem_update_a_visc; + var gradW = SPHSystem_update_gradW; + var r_vec = SPHSystem_update_r_vec; + var u = SPHSystem_update_u; + + for(var i=0; i!==N; i++){ + + var particle = this.particles[i]; + + a_pressure.set(0,0,0); + a_visc.set(0,0,0); + + // Init vars + var Pij; + var nabla; + var Vij; + + // Sum up for all other neighbors + var neighbors = this.neighbors[i]; + var numNeighbors = neighbors.length; + + //printf("Neighbors: "); + for(var j=0; j!==numNeighbors; j++){ + + var neighbor = neighbors[j]; + //printf("%d ",nj); + + // Get r once for all.. + particle.position.vsub(neighbor.position,r_vec); + var r = r_vec.norm(); + + // Pressure contribution + Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i]*this.densities[i] + eps) + this.pressures[j] / (this.densities[j]*this.densities[j] + eps)); + this.gradw(r_vec, gradW); + // Add to pressure acceleration + gradW.mult(Pij , gradW); + a_pressure.vadd(gradW, a_pressure); + + // Viscosity contribution + neighbor.velocity.vsub(particle.velocity, u); + u.mult( 1.0 / (0.0001+this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass , u ); + nabla = this.nablaw(r); + u.mult(nabla,u); + // Add to viscosity acceleration + a_visc.vadd( u, a_visc ); + } + + // Calculate force + a_visc.mult(particle.mass, a_visc); + a_pressure.mult(particle.mass, a_pressure); + + // Add force to particles + particle.force.vadd(a_visc, particle.force); + particle.force.vadd(a_pressure, particle.force); + } +}; + +// Calculate the weight using the W(r) weightfunction +SPHSystem.prototype.w = function(r){ + // 315 + var h = this.smoothingRadius; + return 315.0/(64.0*Math.PI*Math.pow(h,9)) * Math.pow(h*h-r*r,3); +}; + +// calculate gradient of the weight function +SPHSystem.prototype.gradw = function(rVec,resultVec){ + var r = rVec.norm(), + h = this.smoothingRadius; + rVec.mult(945.0/(32.0*Math.PI*Math.pow(h,9)) * Math.pow((h*h-r*r),2) , resultVec); +}; + +// Calculate nabla(W) +SPHSystem.prototype.nablaw = function(r){ + var h = this.smoothingRadius; + var nabla = 945.0/(32.0*Math.PI*Math.pow(h,9)) * (h*h-r*r)*(7*r*r - 3*h*h); + return nabla; +}; + +},{"../material/Material":22,"../math/Quaternion":25,"../math/Vec3":27,"../objects/Body":28,"../shapes/Particle":38,"../shapes/Shape":40}],32:[function(_dereq_,module,exports){ +var Vec3 = _dereq_('../math/Vec3'); + +module.exports = Spring; + +/** + * A spring, connecting two bodies. + * + * @class Spring + * @constructor + * @param {Body} bodyA + * @param {Body} bodyB + * @param {Object} [options] + * @param {number} [options.restLength] A number > 0. Default: 1 + * @param {number} [options.stiffness] A number >= 0. Default: 100 + * @param {number} [options.damping] A number >= 0. Default: 1 + * @param {Vec3} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. + * @param {Vec3} [options.worldAnchorB] + * @param {Vec3} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. + * @param {Vec3} [options.localAnchorB] + */ +function Spring(bodyA,bodyB,options){ + options = options || {}; + + /** + * Rest length of the spring. + * @property restLength + * @type {number} + */ + this.restLength = typeof(options.restLength) === "number" ? options.restLength : 1; + + /** + * Stiffness of the spring. + * @property stiffness + * @type {number} + */ + this.stiffness = options.stiffness || 100; + + /** + * Damping of the spring. + * @property damping + * @type {number} + */ + this.damping = options.damping || 1; + + /** + * First connected body. + * @property bodyA + * @type {Body} + */ + this.bodyA = bodyA; + + /** + * Second connected body. + * @property bodyB + * @type {Body} + */ + this.bodyB = bodyB; + + /** + * Anchor for bodyA in local bodyA coordinates. + * @property localAnchorA + * @type {Vec3} + */ + this.localAnchorA = new Vec3(); + + /** + * Anchor for bodyB in local bodyB coordinates. + * @property localAnchorB + * @type {Vec3} + */ + this.localAnchorB = new Vec3(); + + if(options.localAnchorA){ + this.localAnchorA.copy(options.localAnchorA); + } + if(options.localAnchorB){ + this.localAnchorB.copy(options.localAnchorB); + } + if(options.worldAnchorA){ + this.setWorldAnchorA(options.worldAnchorA); + } + if(options.worldAnchorB){ + this.setWorldAnchorB(options.worldAnchorB); + } +} + +/** + * Set the anchor point on body A, using world coordinates. + * @method setWorldAnchorA + * @param {Vec3} worldAnchorA + */ +Spring.prototype.setWorldAnchorA = function(worldAnchorA){ + this.bodyA.pointToLocalFrame(worldAnchorA,this.localAnchorA); +}; + +/** + * Set the anchor point on body B, using world coordinates. + * @method setWorldAnchorB + * @param {Vec3} worldAnchorB + */ +Spring.prototype.setWorldAnchorB = function(worldAnchorB){ + this.bodyB.pointToLocalFrame(worldAnchorB,this.localAnchorB); +}; + +/** + * Get the anchor point on body A, in world coordinates. + * @method getWorldAnchorA + * @param {Vec3} result The vector to store the result in. + */ +Spring.prototype.getWorldAnchorA = function(result){ + this.bodyA.pointToWorldFrame(this.localAnchorA,result); +}; + +/** + * Get the anchor point on body B, in world coordinates. + * @method getWorldAnchorB + * @param {Vec3} result The vector to store the result in. + */ +Spring.prototype.getWorldAnchorB = function(result){ + this.bodyB.pointToWorldFrame(this.localAnchorB,result); +}; + +var applyForce_r = new Vec3(), + applyForce_r_unit = new Vec3(), + applyForce_u = new Vec3(), + applyForce_f = new Vec3(), + applyForce_worldAnchorA = new Vec3(), + applyForce_worldAnchorB = new Vec3(), + applyForce_ri = new Vec3(), + applyForce_rj = new Vec3(), + applyForce_ri_x_f = new Vec3(), + applyForce_rj_x_f = new Vec3(), + applyForce_tmp = new Vec3(); + +/** + * Apply the spring force to the connected bodies. + * @method applyForce + */ +Spring.prototype.applyForce = function(){ + var k = this.stiffness, + d = this.damping, + l = this.restLength, + bodyA = this.bodyA, + bodyB = this.bodyB, + r = applyForce_r, + r_unit = applyForce_r_unit, + u = applyForce_u, + f = applyForce_f, + tmp = applyForce_tmp; + + var worldAnchorA = applyForce_worldAnchorA, + worldAnchorB = applyForce_worldAnchorB, + ri = applyForce_ri, + rj = applyForce_rj, + ri_x_f = applyForce_ri_x_f, + rj_x_f = applyForce_rj_x_f; + + // Get world anchors + this.getWorldAnchorA(worldAnchorA); + this.getWorldAnchorB(worldAnchorB); + + // Get offset points + worldAnchorA.vsub(bodyA.position,ri); + worldAnchorB.vsub(bodyB.position,rj); + + // Compute distance vector between world anchor points + worldAnchorB.vsub(worldAnchorA,r); + var rlen = r.norm(); + r_unit.copy(r); + r_unit.normalize(); + + // Compute relative velocity of the anchor points, u + bodyB.velocity.vsub(bodyA.velocity,u); + // Add rotational velocity + + bodyB.angularVelocity.cross(rj,tmp); + u.vadd(tmp,u); + bodyA.angularVelocity.cross(ri,tmp); + u.vsub(tmp,u); + + // F = - k * ( x - L ) - D * ( u ) + r_unit.mult(-k*(rlen-l) - d*u.dot(r_unit), f); + + // Add forces to bodies + bodyA.force.vsub(f,bodyA.force); + bodyB.force.vadd(f,bodyB.force); + + // Angular force + ri.cross(f,ri_x_f); + rj.cross(f,rj_x_f); + bodyA.torque.vsub(ri_x_f,bodyA.torque); + bodyB.torque.vadd(rj_x_f,bodyB.torque); +}; + +},{"../math/Vec3":27}],33:[function(_dereq_,module,exports){ +var Vec3 = _dereq_('../math/Vec3'); +var Transform = _dereq_('../math/Transform'); +var RaycastResult = _dereq_('../collision/RaycastResult'); +var Utils = _dereq_('../utils/Utils'); + +module.exports = WheelInfo; + +/** + * @class WheelInfo + * @constructor + * @param {Object} [options] + * + * @param {Vec3} [options.chassisConnectionPointLocal] + * @param {Vec3} [options.chassisConnectionPointWorld] + * @param {Vec3} [options.directionLocal] + * @param {Vec3} [options.directionWorld] + * @param {Vec3} [options.axleLocal] + * @param {Vec3} [options.axleWorld] + * @param {number} [options.suspensionRestLength=1] + * @param {number} [options.suspensionMaxLength=2] + * @param {number} [options.radius=1] + * @param {number} [options.suspensionStiffness=100] + * @param {number} [options.dampingCompression=10] + * @param {number} [options.dampingRelaxation=10] + * @param {number} [options.frictionSlip=10000] + * @param {number} [options.steering=0] + * @param {number} [options.rotation=0] + * @param {number} [options.deltaRotation=0] + * @param {number} [options.rollInfluence=0.01] + * @param {number} [options.maxSuspensionForce] + * @param {number} [options.isFrontWheel=true] + * @param {number} [options.clippedInvContactDotSuspension=1] + * @param {number} [options.suspensionRelativeVelocity=0] + * @param {number} [options.suspensionForce=0] + * @param {number} [options.skidInfo=0] + * @param {number} [options.suspensionLength=0] + * @param {number} [options.maxSuspensionTravel=1] + * @param {number} [options.useCustomSlidingRotationalSpeed=false] + * @param {number} [options.customSlidingRotationalSpeed=-0.1] + */ +function WheelInfo(options){ + options = Utils.defaults(options, { + chassisConnectionPointLocal: new Vec3(), + chassisConnectionPointWorld: new Vec3(), + directionLocal: new Vec3(), + directionWorld: new Vec3(), + axleLocal: new Vec3(), + axleWorld: new Vec3(), + suspensionRestLength: 1, + suspensionMaxLength: 2, + radius: 1, + suspensionStiffness: 100, + dampingCompression: 10, + dampingRelaxation: 10, + frictionSlip: 10000, + steering: 0, + rotation: 0, + deltaRotation: 0, + rollInfluence: 0.01, + maxSuspensionForce: Number.MAX_VALUE, + isFrontWheel: true, + clippedInvContactDotSuspension: 1, + suspensionRelativeVelocity: 0, + suspensionForce: 0, + skidInfo: 0, + suspensionLength: 0, + maxSuspensionTravel: 1, + useCustomSlidingRotationalSpeed: false, + customSlidingRotationalSpeed: -0.1 + }); + + /** + * Max travel distance of the suspension, in meters. + * @property {number} maxSuspensionTravel + */ + this.maxSuspensionTravel = options.maxSuspensionTravel; + + /** + * Speed to apply to the wheel rotation when the wheel is sliding. + * @property {number} customSlidingRotationalSpeed + */ + this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed; + + /** + * If the customSlidingRotationalSpeed should be used. + * @property {Boolean} useCustomSlidingRotationalSpeed + */ + this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed; + + /** + * @property {Boolean} sliding + */ + this.sliding = false; + + /** + * Connection point, defined locally in the chassis body frame. + * @property {Vec3} chassisConnectionPointLocal + */ + this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone(); + + /** + * @property {Vec3} chassisConnectionPointWorld + */ + this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone(); + + /** + * @property {Vec3} directionLocal + */ + this.directionLocal = options.directionLocal.clone(); + + /** + * @property {Vec3} directionWorld + */ + this.directionWorld = options.directionWorld.clone(); + + /** + * @property {Vec3} axleLocal + */ + this.axleLocal = options.axleLocal.clone(); + + /** + * @property {Vec3} axleWorld + */ + this.axleWorld = options.axleWorld.clone(); + + /** + * @property {number} suspensionRestLength + */ + this.suspensionRestLength = options.suspensionRestLength; + + /** + * @property {number} suspensionMaxLength + */ + this.suspensionMaxLength = options.suspensionMaxLength; + + /** + * @property {number} radius + */ + this.radius = options.radius; + + /** + * @property {number} suspensionStiffness + */ + this.suspensionStiffness = options.suspensionStiffness; + + /** + * @property {number} dampingCompression + */ + this.dampingCompression = options.dampingCompression; + + /** + * @property {number} dampingRelaxation + */ + this.dampingRelaxation = options.dampingRelaxation; + + /** + * @property {number} frictionSlip + */ + this.frictionSlip = options.frictionSlip; + + /** + * @property {number} steering + */ + this.steering = 0; + + /** + * Rotation value, in radians. + * @property {number} rotation + */ + this.rotation = 0; + + /** + * @property {number} deltaRotation + */ + this.deltaRotation = 0; + + /** + * @property {number} rollInfluence + */ + this.rollInfluence = options.rollInfluence; + + /** + * @property {number} maxSuspensionForce + */ + this.maxSuspensionForce = options.maxSuspensionForce; + + /** + * @property {number} engineForce + */ + this.engineForce = 0; + + /** + * @property {number} brake + */ + this.brake = 0; + + /** + * @property {number} isFrontWheel + */ + this.isFrontWheel = options.isFrontWheel; + + /** + * @property {number} clippedInvContactDotSuspension + */ + this.clippedInvContactDotSuspension = 1; + + /** + * @property {number} suspensionRelativeVelocity + */ + this.suspensionRelativeVelocity = 0; + + /** + * @property {number} suspensionForce + */ + this.suspensionForce = 0; + + /** + * @property {number} skidInfo + */ + this.skidInfo = 0; + + /** + * @property {number} suspensionLength + */ + this.suspensionLength = 0; + + /** + * @property {number} sideImpulse + */ + this.sideImpulse = 0; + + /** + * @property {number} forwardImpulse + */ + this.forwardImpulse = 0; + + /** + * The result from raycasting + * @property {RaycastResult} raycastResult + */ + this.raycastResult = new RaycastResult(); + + /** + * Wheel world transform + * @property {Transform} worldTransform + */ + this.worldTransform = new Transform(); + + /** + * @property {boolean} isInContact + */ + this.isInContact = false; +} + +var chassis_velocity_at_contactPoint = new Vec3(); +var relpos = new Vec3(); +var chassis_velocity_at_contactPoint = new Vec3(); +WheelInfo.prototype.updateWheel = function(chassis){ + var raycastResult = this.raycastResult; + + if (this.isInContact){ + var project= raycastResult.hitNormalWorld.dot(raycastResult.directionWorld); + raycastResult.hitPointWorld.vsub(chassis.position, relpos); + chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint); + var projVel = raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint ); + if (project >= -0.1) { + this.suspensionRelativeVelocity = 0.0; + this.clippedInvContactDotSuspension = 1.0 / 0.1; + } else { + var inv = -1 / project; + this.suspensionRelativeVelocity = projVel * inv; + this.clippedInvContactDotSuspension = inv; + } + + } else { + // Not in contact : position wheel in a nice (rest length) position + raycastResult.suspensionLength = this.suspensionRestLength; + this.suspensionRelativeVelocity = 0.0; + raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld); + this.clippedInvContactDotSuspension = 1.0; + } +}; +},{"../collision/RaycastResult":10,"../math/Transform":26,"../math/Vec3":27,"../utils/Utils":48}],34:[function(_dereq_,module,exports){ +module.exports = Box; + +var Shape = _dereq_('./Shape'); +var Vec3 = _dereq_('../math/Vec3'); +var ConvexPolyhedron = _dereq_('./ConvexPolyhedron'); + +/** + * A 3d box shape. + * @class Box + * @constructor + * @param {Vec3} halfExtents + * @author schteppe + * @extends Shape + */ +function Box(halfExtents){ + Shape.call(this); + + this.type = Shape.types.BOX; + + /** + * @property halfExtents + * @type {Vec3} + */ + this.halfExtents = halfExtents; + + /** + * Used by the contact generator to make contacts with other convex polyhedra for example + * @property convexPolyhedronRepresentation + * @type {ConvexPolyhedron} + */ + this.convexPolyhedronRepresentation = null; + + this.updateConvexPolyhedronRepresentation(); + this.updateBoundingSphereRadius(); +} +Box.prototype = new Shape(); +Box.prototype.constructor = Box; + +/** + * Updates the local convex polyhedron representation used for some collisions. + * @method updateConvexPolyhedronRepresentation + */ +Box.prototype.updateConvexPolyhedronRepresentation = function(){ + var sx = this.halfExtents.x; + var sy = this.halfExtents.y; + var sz = this.halfExtents.z; + var V = Vec3; + + var h = new ConvexPolyhedron([new V(-sx,-sy,-sz), + new V( sx,-sy,-sz), + new V( sx, sy,-sz), + new V(-sx, sy,-sz), + new V(-sx,-sy, sz), + new V( sx,-sy, sz), + new V( sx, sy, sz), + new V(-sx, sy, sz)], + [[3,2,1,0], // -z + [4,5,6,7], // +z + [5,4,0,1], // -y + [2,3,7,6], // +y + [0,4,7,3], // -x + [1,2,6,5], // +x + ], + [new V( 0, 0,-1), + new V( 0, 0, 1), + new V( 0,-1, 0), + new V( 0, 1, 0), + new V(-1, 0, 0), + new V( 1, 0, 0)]); + this.convexPolyhedronRepresentation = h; +}; + +/** + * @method calculateLocalInertia + * @param {Number} mass + * @param {Vec3} target + * @return {Vec3} + */ +Box.prototype.calculateLocalInertia = function(mass,target){ + target = target || new Vec3(); + Box.calculateInertia(this.halfExtents, mass, target); + return target; +}; + +Box.calculateInertia = function(halfExtents,mass,target){ + var e = halfExtents; + target.x = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.z*2*e.z ); + target.y = 1.0 / 12.0 * mass * ( 2*e.x*2*e.x + 2*e.z*2*e.z ); + target.z = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.x*2*e.x ); +}; + +/** + * Get the box 6 side normals + * @method getSideNormals + * @param {Boolean} includeNegative If true, this function returns 6 vectors. If false, it only returns 3 (but you get 6 by reversing those 3) + * @param {Quaternion} quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame. + * @return {array} + */ +Box.prototype.getSideNormals = function(sixTargetVectors,quat){ + var sides = sixTargetVectors; + var ex = this.halfExtents; + sides[0].set( ex.x, 0, 0); + sides[1].set( 0, ex.y, 0); + sides[2].set( 0, 0, ex.z); + sides[3].set( -ex.x, 0, 0); + sides[4].set( 0, -ex.y, 0); + sides[5].set( 0, 0, -ex.z); + + if(quat!==undefined){ + for(var i=0; i!==sides.length; i++){ + quat.vmult(sides[i],sides[i]); + } + } + + return sides; +}; + +Box.prototype.volume = function(){ + return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z; +}; + +Box.prototype.updateBoundingSphereRadius = function(){ + this.boundingSphereRadius = this.halfExtents.norm(); +}; + +var worldCornerTempPos = new Vec3(); +var worldCornerTempNeg = new Vec3(); +Box.prototype.forEachWorldCorner = function(pos,quat,callback){ + + var e = this.halfExtents; + var corners = [[ e.x, e.y, e.z], + [ -e.x, e.y, e.z], + [ -e.x, -e.y, e.z], + [ -e.x, -e.y, -e.z], + [ e.x, -e.y, -e.z], + [ e.x, e.y, -e.z], + [ -e.x, e.y, -e.z], + [ e.x, -e.y, e.z]]; + for(var i=0; i max.x){ + max.x = x; + } + if(y > max.y){ + max.y = y; + } + if(z > max.z){ + max.z = z; + } + + if(x < min.x){ + min.x = x; + } + if(y < min.y){ + min.y = y; + } + if(z < min.z){ + min.z = z; + } + } + + // Get each axis max + // min.set(Infinity,Infinity,Infinity); + // max.set(-Infinity,-Infinity,-Infinity); + // this.forEachWorldCorner(pos,quat,function(x,y,z){ + // if(x > max.x){ + // max.x = x; + // } + // if(y > max.y){ + // max.y = y; + // } + // if(z > max.z){ + // max.z = z; + // } + + // if(x < min.x){ + // min.x = x; + // } + // if(y < min.y){ + // min.y = y; + // } + // if(z < min.z){ + // min.z = z; + // } + // }); +}; + +},{"../math/Vec3":27,"./ConvexPolyhedron":35,"./Shape":40}],35:[function(_dereq_,module,exports){ +module.exports = ConvexPolyhedron; + +var Shape = _dereq_('./Shape'); +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var Transform = _dereq_('../math/Transform'); + +/** + * A set of polygons describing a convex shape. + * @class ConvexPolyhedron + * @constructor + * @extends Shape + * @description The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained + * in the same 3D plane), instead these should be merged into one polygon. + * + * @param {array} points An array of Vec3's + * @param {array} faces Array of integer arrays, describing which vertices that is included in each face. + * + * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f) + * @author schteppe / https://github.com/schteppe + * @see http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/ + * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp + * + * @todo Move the clipping functions to ContactGenerator? + * @todo Automatically merge coplanar polygons in constructor. + */ +function ConvexPolyhedron(points, faces) { + var that = this; + Shape.call(this); + this.type = Shape.types.CONVEXPOLYHEDRON; + + /** + * Array of Vec3 + * @property vertices + * @type {Array} + */ + this.vertices = points||[]; + + this.worldVertices = []; // World transformed version of .vertices + this.worldVerticesNeedsUpdate = true; + + /** + * Array of integer arrays, indicating which vertices each face consists of + * @property faces + * @type {Array} + */ + this.faces = faces||[]; + + /** + * Array of Vec3 + * @property faceNormals + * @type {Array} + */ + this.faceNormals = []; + this.computeNormals(); + + this.worldFaceNormalsNeedsUpdate = true; + this.worldFaceNormals = []; // World transformed version of .faceNormals + + /** + * Array of Vec3 + * @property uniqueEdges + * @type {Array} + */ + this.uniqueEdges = []; + + this.computeEdges(); + this.updateBoundingSphereRadius(); +} +ConvexPolyhedron.prototype = new Shape(); +ConvexPolyhedron.prototype.constructor = ConvexPolyhedron; + +/** + * Computes uniqueEdges + * @method computeEdges + */ +ConvexPolyhedron.prototype.computeEdges = function(){ + var faces = this.faces; + var vertices = this.vertices; + var nv = vertices.length; + var edges = this.uniqueEdges; + + edges.length = 0; + + for(var pi=0; pi dmax){ + dmax = d; + closestFaceB = face; + } + } + var worldVertsB1 = []; + var polyB = hullB.faces[closestFaceB]; + var numVertices = polyB.length; + for(var e0=0; e0=0){ + this.clipFaceAgainstHull(separatingNormal, + posA, + quatA, + worldVertsB1, + minDist, + maxDist, + result); + } +}; + +/** + * Find the separating axis between this hull and another + * @method findSeparatingAxis + * @param {ConvexPolyhedron} hullB + * @param {Vec3} posA + * @param {Quaternion} quatA + * @param {Vec3} posB + * @param {Quaternion} quatB + * @param {Vec3} target The target vector to save the axis in + * @return {bool} Returns false if a separation is found, else true + */ +var fsa_faceANormalWS3 = new Vec3(), + fsa_Worldnormal1 = new Vec3(), + fsa_deltaC = new Vec3(), + fsa_worldEdge0 = new Vec3(), + fsa_worldEdge1 = new Vec3(), + fsa_Cross = new Vec3(); +ConvexPolyhedron.prototype.findSeparatingAxis = function(hullB,posA,quatA,posB,quatB,target, faceListA, faceListB){ + var faceANormalWS3 = fsa_faceANormalWS3, + Worldnormal1 = fsa_Worldnormal1, + deltaC = fsa_deltaC, + worldEdge0 = fsa_worldEdge0, + worldEdge1 = fsa_worldEdge1, + Cross = fsa_Cross; + + var dmin = Infinity; + var hullA = this; + var curPlaneTests=0; + var numFacesA = faceListA ? faceListA.length : hullA.faces.length; + + // Test normals from hullA + for(var i=0; i0.0){ + target.negate(target); + } + return true; +}; + +/** + * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one. + * @method testSepAxis + * @param {Vec3} axis + * @param {ConvexPolyhedron} hullB + * @param {Vec3} posA + * @param {Quaternion} quatA + * @param {Vec3} posB + * @param {Quaternion} quatB + * @return {float} The overlap depth, or FALSE if no penetration. + */ +ConvexPolyhedron.prototype.testSepAxis = function(axis, hullB, posA, quatA, posB, quatB){ + var maxminA=[], maxminB=[], hullA=this; + ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA); + ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB); + var maxA = maxminA[0]; + var minA = maxminA[1]; + var maxB = maxminB[0]; + var minB = maxminB[1]; + if(maxA= 0, so output intersection + var newv = new Vec3(); + firstVertex.lerp(lastVertex, + n_dot_first / (n_dot_first - n_dot_last), + newv); + outVertices.push(newv); + } + } else { + if(n_dot_last<0){ + // Start >= 0, end < 0 so output intersection and end + var newv = new Vec3(); + firstVertex.lerp(lastVertex, + n_dot_first / (n_dot_first - n_dot_last), + newv); + outVertices.push(newv); + outVertices.push(lastVertex); + } + } + firstVertex = lastVertex; + n_dot_first = n_dot_last; + } + return outVertices; +}; + +// Updates .worldVertices and sets .worldVerticesNeedsUpdate to false. +ConvexPolyhedron.prototype.computeWorldVertices = function(position,quat){ + var N = this.vertices.length; + while(this.worldVertices.length < N){ + this.worldVertices.push( new Vec3() ); + } + + var verts = this.vertices, + worldVerts = this.worldVertices; + for(var i=0; i!==N; i++){ + quat.vmult( verts[i] , worldVerts[i] ); + position.vadd( worldVerts[i] , worldVerts[i] ); + } + + this.worldVerticesNeedsUpdate = false; +}; + +var computeLocalAABB_worldVert = new Vec3(); +ConvexPolyhedron.prototype.computeLocalAABB = function(aabbmin,aabbmax){ + var n = this.vertices.length, + vertices = this.vertices, + worldVert = computeLocalAABB_worldVert; + + aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + + for(var i=0; i aabbmax.x){ + aabbmax.x = v.x; + } + if (v.y < aabbmin.y){ + aabbmin.y = v.y; + } else if(v.y > aabbmax.y){ + aabbmax.y = v.y; + } + if (v.z < aabbmin.z){ + aabbmin.z = v.z; + } else if(v.z > aabbmax.z){ + aabbmax.z = v.z; + } + } +}; + +/** + * Updates .worldVertices and sets .worldVerticesNeedsUpdate to false. + * @method computeWorldFaceNormals + * @param {Quaternion} quat + */ +ConvexPolyhedron.prototype.computeWorldFaceNormals = function(quat){ + var N = this.faceNormals.length; + while(this.worldFaceNormals.length < N){ + this.worldFaceNormals.push( new Vec3() ); + } + + var normals = this.faceNormals, + worldNormals = this.worldFaceNormals; + for(var i=0; i!==N; i++){ + quat.vmult( normals[i] , worldNormals[i] ); + } + + this.worldFaceNormalsNeedsUpdate = false; +}; + +/** + * @method updateBoundingSphereRadius + */ +ConvexPolyhedron.prototype.updateBoundingSphereRadius = function(){ + // Assume points are distributed with local (0,0,0) as center + var max2 = 0; + var verts = this.vertices; + for(var i=0, N=verts.length; i!==N; i++) { + var norm2 = verts[i].norm2(); + if(norm2 > max2){ + max2 = norm2; + } + } + this.boundingSphereRadius = Math.sqrt(max2); +}; + +var tempWorldVertex = new Vec3(); + +/** + * @method calculateWorldAABB + * @param {Vec3} pos + * @param {Quaternion} quat + * @param {Vec3} min + * @param {Vec3} max + */ +ConvexPolyhedron.prototype.calculateWorldAABB = function(pos,quat,min,max){ + var n = this.vertices.length, verts = this.vertices; + var minx,miny,minz,maxx,maxy,maxz; + for(var i=0; i maxx || maxx===undefined){ + maxx = v.x; + } + + if (v.y < miny || miny===undefined){ + miny = v.y; + } else if(v.y > maxy || maxy===undefined){ + maxy = v.y; + } + + if (v.z < minz || minz===undefined){ + minz = v.z; + } else if(v.z > maxz || maxz===undefined){ + maxz = v.z; + } + } + min.set(minx,miny,minz); + max.set(maxx,maxy,maxz); +}; + +/** + * Get approximate convex volume + * @method volume + * @return {Number} + */ +ConvexPolyhedron.prototype.volume = function(){ + return 4.0 * Math.PI * this.boundingSphereRadius / 3.0; +}; + +/** + * Get an average of all the vertices positions + * @method getAveragePointLocal + * @param {Vec3} target + * @return {Vec3} + */ +ConvexPolyhedron.prototype.getAveragePointLocal = function(target){ + target = target || new Vec3(); + var n = this.vertices.length, + verts = this.vertices; + for(var i=0; i0) || (r1>0 && r2<0)){ + return false; // Encountered some other sign. Exit. + } else { + } + } + + // If we got here, all dot products were of the same sign. + return positiveResult ? 1 : -1; +}; + +/** + * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis. Results are saved in the array maxmin. + * @static + * @method project + * @param {ConvexPolyhedron} hull + * @param {Vec3} axis + * @param {Vec3} pos + * @param {Quaternion} quat + * @param {array} result result[0] and result[1] will be set to maximum and minimum, respectively. + */ +var project_worldVertex = new Vec3(); +var project_localAxis = new Vec3(); +var project_localOrigin = new Vec3(); +ConvexPolyhedron.project = function(hull, axis, pos, quat, result){ + var n = hull.vertices.length, + worldVertex = project_worldVertex, + localAxis = project_localAxis, + max = 0, + min = 0, + localOrigin = project_localOrigin, + vs = hull.vertices; + + localOrigin.setZero(); + + // Transform the axis to local + Transform.vectorToLocalFrame(pos, quat, axis, localAxis); + Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin); + var add = localOrigin.dot(localAxis); + + min = max = vs[0].dot(localAxis); + + for(var i = 1; i < n; i++){ + var val = vs[i].dot(localAxis); + + if(val > max){ + max = val; + } + + if(val < min){ + min = val; + } + } + + min -= add; + max -= add; + + if(min > max){ + // Inconsistent - swap + var temp = min; + min = max; + max = temp; + } + // Output + result[0] = max; + result[1] = min; +}; + +},{"../math/Quaternion":25,"../math/Transform":26,"../math/Vec3":27,"./Shape":40}],36:[function(_dereq_,module,exports){ +module.exports = Cylinder; + +var Shape = _dereq_('./Shape'); +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var ConvexPolyhedron = _dereq_('./ConvexPolyhedron'); + +/** + * @class Cylinder + * @constructor + * @extends ConvexPolyhedron + * @author schteppe / https://github.com/schteppe + * @param {Number} radiusTop + * @param {Number} radiusBottom + * @param {Number} height + * @param {Number} numSegments The number of segments to build the cylinder out of + */ +function Cylinder( radiusTop, radiusBottom, height , numSegments ) { + var N = numSegments, + verts = [], + normals = [], + faces = [], + bottomface = [], + topface = [], + cos = Math.cos, + sin = Math.sin; + + // First bottom point + verts.push(new Vec3(radiusBottom*cos(0), + radiusBottom*sin(0), + -height*0.5)); + bottomface.push(0); + + // First top point + verts.push(new Vec3(radiusTop*cos(0), + radiusTop*sin(0), + height*0.5)); + topface.push(1); + + for(var i=0; i { convex: ..., offset: ... } + // for example: + // _cachedPillars["0_2_1"] + this._cachedPillars = {}; +} +Heightfield.prototype = new Shape(); + +/** + * Call whenever you change the data array. + * @method update + */ +Heightfield.prototype.update = function(){ + this._cachedPillars = {}; +}; + +/** + * @method updateMinValue + * Update the .minValue property + */ +Heightfield.prototype.updateMinValue = function(){ + var data = this.data; + var minValue = data[0][0]; + for(var i=0; i !== data.length; i++){ + for(var j=0; j !== data[i].length; j++){ + var v = data[i][j]; + if(v < minValue){ + minValue = v; + } + } + } + this.minValue = minValue; +}; + +/** + * Update the .maxValue property + * @method updateMaxValue + */ +Heightfield.prototype.updateMaxValue = function(){ + var data = this.data; + var maxValue = data[0][0]; + for(var i=0; i !== data.length; i++){ + for(var j=0; j !== data[i].length; j++){ + var v = data[i][j]; + if(v > maxValue){ + maxValue = v; + } + } + } + this.maxValue = maxValue; +}; + +/** + * Set the height value at an index. Don't forget to update maxValue and minValue after you're done. + * @method setHeightValueAtIndex + * @param {integer} xi + * @param {integer} yi + * @param {number} value + */ +Heightfield.prototype.setHeightValueAtIndex = function(xi, yi, value){ + var data = this.data; + data[xi][yi] = value; + + // Invalidate cache + this.clearCachedConvexTrianglePillar(xi, yi, false); + if(xi > 0){ + this.clearCachedConvexTrianglePillar(xi - 1, yi, true); + this.clearCachedConvexTrianglePillar(xi - 1, yi, false); + } + if(yi > 0){ + this.clearCachedConvexTrianglePillar(xi, yi - 1, true); + this.clearCachedConvexTrianglePillar(xi, yi - 1, false); + } + if(yi > 0 && xi > 0){ + this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true); + } +}; + +/** + * Get max/min in a rectangle in the matrix data + * @method getRectMinMax + * @param {integer} iMinX + * @param {integer} iMinY + * @param {integer} iMaxX + * @param {integer} iMaxY + * @param {array} [result] An array to store the results in. + * @return {array} The result array, if it was passed in. Minimum will be at position 0 and max at 1. + */ +Heightfield.prototype.getRectMinMax = function (iMinX, iMinY, iMaxX, iMaxY, result) { + result = result || []; + + // Get max and min of the data + var data = this.data, + max = this.minValue; // Set first value + for(var i = iMinX; i < iMaxX; i++){ + for(var j = iMinY; j < iMaxY; j++){ + var height = data[i][j]; + if(height > max){ + max = height; + } + } + } + + result[0] = this.minValue; + result[1] = max; +}; + +/** + * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1. + * @method getIndexOfPosition + * @param {number} x + * @param {number} y + * @param {array} result Two-element array + * @param {boolean} clamp If the position should be clamped to the heightfield edge. + * @return {boolean} + */ +Heightfield.prototype.getIndexOfPosition = function (x, y, result, clamp) { + + // Get the index of the data points to test against + var w = this.elementSize; + var data = this.data; + var xi = Math.floor(x / w); + var yi = Math.floor(y / w); + + result[0] = xi; + result[1] = yi; + + if(clamp){ + // Clamp index to edges + if(xi < 0){ xi = 0; } + if(yi < 0){ yi = 0; } + if(xi >= data.length - 1){ xi = data.length - 1; } + if(yi >= data[0].length - 1){ yi = data[0].length - 1; } + } + + // Bail out if we are out of the terrain + if(xi < 0 || yi < 0 || xi >= data.length-1 || yi >= data[0].length-1){ + return false; + } + + return true; +}; + +Heightfield.prototype.getHeightAt = function(x, y, edgeClamp){ + var idx = []; + this.getIndexOfPosition(x, y, idx, edgeClamp); + + // TODO: do it better + var minmax = []; + this.getRectMinMax(idx[0], idx[1] + 1, idx[0], idx[1] + 1, minmax); + + return (minmax[0] + minmax[1]) / 2; // average +}; + +Heightfield.prototype.getCacheConvexTrianglePillarKey = function(xi, yi, getUpperTriangle){ + return xi + '_' + yi + '_' + (getUpperTriangle ? 1 : 0); +}; + +Heightfield.prototype.getCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){ + return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)]; +}; + +Heightfield.prototype.setCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle, convex, offset){ + this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = { + convex: convex, + offset: offset + }; +}; + +Heightfield.prototype.clearCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){ + delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)]; +}; + +/** + * Get a triangle in the terrain in the form of a triangular convex shape. + * @method getConvexTrianglePillar + * @param {integer} i + * @param {integer} j + * @param {boolean} getUpperTriangle + */ +Heightfield.prototype.getConvexTrianglePillar = function(xi, yi, getUpperTriangle){ + var result = this.pillarConvex; + var offsetResult = this.pillarOffset; + + if(this.cacheEnabled){ + var data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle); + if(data){ + this.pillarConvex = data.convex; + this.pillarOffset = data.offset; + return; + } + + result = new ConvexPolyhedron(); + offsetResult = new Vec3(); + + this.pillarConvex = result; + this.pillarOffset = offsetResult; + } + + var data = this.data; + var elementSize = this.elementSize; + var faces = result.faces; + + // Reuse verts if possible + result.vertices.length = 6; + for (var i = 0; i < 6; i++) { + if(!result.vertices[i]){ + result.vertices[i] = new Vec3(); + } + } + + // Reuse faces if possible + faces.length = 5; + for (var i = 0; i < 5; i++) { + if(!faces[i]){ + faces[i] = []; + } + } + + var verts = result.vertices; + + var h = (Math.min( + data[xi][yi], + data[xi+1][yi], + data[xi][yi+1], + data[xi+1][yi+1] + ) - this.minValue ) / 2 + this.minValue; + + if (!getUpperTriangle) { + + // Center of the triangle pillar - all polygons are given relative to this one + offsetResult.set( + (xi + 0.25) * elementSize, // sort of center of a triangle + (yi + 0.25) * elementSize, + h // vertical center + ); + + // Top triangle verts + verts[0].set( + -0.25 * elementSize, + -0.25 * elementSize, + data[xi][yi] - h + ); + verts[1].set( + 0.75 * elementSize, + -0.25 * elementSize, + data[xi + 1][yi] - h + ); + verts[2].set( + -0.25 * elementSize, + 0.75 * elementSize, + data[xi][yi + 1] - h + ); + + // bottom triangle verts + verts[3].set( + -0.25 * elementSize, + -0.25 * elementSize, + -h-1 + ); + verts[4].set( + 0.75 * elementSize, + -0.25 * elementSize, + -h-1 + ); + verts[5].set( + -0.25 * elementSize, + 0.75 * elementSize, + -h-1 + ); + + // top triangle + faces[0][0] = 0; + faces[0][1] = 1; + faces[0][2] = 2; + + // bottom triangle + faces[1][0] = 5; + faces[1][1] = 4; + faces[1][2] = 3; + + // -x facing quad + faces[2][0] = 0; + faces[2][1] = 2; + faces[2][2] = 5; + faces[2][3] = 3; + + // -y facing quad + faces[3][0] = 1; + faces[3][1] = 0; + faces[3][2] = 3; + faces[3][3] = 4; + + // +xy facing quad + faces[4][0] = 4; + faces[4][1] = 5; + faces[4][2] = 2; + faces[4][3] = 1; + + + } else { + + // Center of the triangle pillar - all polygons are given relative to this one + offsetResult.set( + (xi + 0.75) * elementSize, // sort of center of a triangle + (yi + 0.75) * elementSize, + h // vertical center + ); + + // Top triangle verts + verts[0].set( + 0.25 * elementSize, + 0.25 * elementSize, + data[xi + 1][yi + 1] - h + ); + verts[1].set( + -0.75 * elementSize, + 0.25 * elementSize, + data[xi][yi + 1] - h + ); + verts[2].set( + 0.25 * elementSize, + -0.75 * elementSize, + data[xi + 1][yi] - h + ); + + // bottom triangle verts + verts[3].set( + 0.25 * elementSize, + 0.25 * elementSize, + - h-1 + ); + verts[4].set( + -0.75 * elementSize, + 0.25 * elementSize, + - h-1 + ); + verts[5].set( + 0.25 * elementSize, + -0.75 * elementSize, + - h-1 + ); + + // Top triangle + faces[0][0] = 0; + faces[0][1] = 1; + faces[0][2] = 2; + + // bottom triangle + faces[1][0] = 5; + faces[1][1] = 4; + faces[1][2] = 3; + + // +x facing quad + faces[2][0] = 2; + faces[2][1] = 5; + faces[2][2] = 3; + faces[2][3] = 0; + + // +y facing quad + faces[3][0] = 3; + faces[3][1] = 4; + faces[3][2] = 1; + faces[3][3] = 0; + + // -xy facing quad + faces[4][0] = 1; + faces[4][1] = 4; + faces[4][2] = 5; + faces[4][3] = 2; + } + + result.computeNormals(); + result.computeEdges(); + result.updateBoundingSphereRadius(); + + this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult); +}; + +Heightfield.prototype.calculateLocalInertia = function(mass, target){ + target = target || new Vec3(); + target.set(0, 0, 0); + return target; +}; + +Heightfield.prototype.volume = function(){ + return Number.MAX_VALUE; // The terrain is infinite +}; + +Heightfield.prototype.calculateWorldAABB = function(pos, quat, min, max){ + // TODO: do it properly + min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); +}; + +Heightfield.prototype.updateBoundingSphereRadius = function(){ + // Use the bounding box of the min/max values + var data = this.data, + s = this.elementSize; + this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).norm(); +}; +},{"../math/Vec3":27,"../utils/Utils":48,"./ConvexPolyhedron":35,"./Shape":40}],38:[function(_dereq_,module,exports){ +module.exports = Particle; + +var Shape = _dereq_('./Shape'); +var Vec3 = _dereq_('../math/Vec3'); + +/** + * Particle shape. + * @class Particle + * @constructor + * @author schteppe + * @extends Shape + */ +function Particle(){ + Shape.call(this); + + this.type = Shape.types.PARTICLE; +} +Particle.prototype = new Shape(); +Particle.prototype.constructor = Particle; + +/** + * @method calculateLocalInertia + * @param {Number} mass + * @param {Vec3} target + * @return {Vec3} + */ +Particle.prototype.calculateLocalInertia = function(mass,target){ + target = target || new Vec3(); + target.set(0, 0, 0); + return target; +}; + +Particle.prototype.volume = function(){ + return 0; +}; + +Particle.prototype.updateBoundingSphereRadius = function(){ + this.boundingSphereRadius = 0; +}; + +Particle.prototype.calculateWorldAABB = function(pos,quat,min,max){ + // Get each axis max + min.copy(pos); + max.copy(pos); +}; + +},{"../math/Vec3":27,"./Shape":40}],39:[function(_dereq_,module,exports){ +module.exports = Plane; + +var Shape = _dereq_('./Shape'); +var Vec3 = _dereq_('../math/Vec3'); + +/** + * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a RigidBody and rotate that body. See the demos. + * @class Plane + * @constructor + * @extends Shape + * @author schteppe + */ +function Plane(){ + Shape.call(this); + this.type = Shape.types.PLANE; + + // World oriented normal + this.worldNormal = new Vec3(); + this.worldNormalNeedsUpdate = true; + + this.boundingSphereRadius = Number.MAX_VALUE; +} +Plane.prototype = new Shape(); +Plane.prototype.constructor = Plane; + +Plane.prototype.computeWorldNormal = function(quat){ + var n = this.worldNormal; + n.set(0,0,1); + quat.vmult(n,n); + this.worldNormalNeedsUpdate = false; +}; + +Plane.prototype.calculateLocalInertia = function(mass,target){ + target = target || new Vec3(); + return target; +}; + +Plane.prototype.volume = function(){ + return Number.MAX_VALUE; // The plane is infinite... +}; + +var tempNormal = new Vec3(); +Plane.prototype.calculateWorldAABB = function(pos, quat, min, max){ + // The plane AABB is infinite, except if the normal is pointing along any axis + tempNormal.set(0,0,1); // Default plane normal is z + quat.vmult(tempNormal,tempNormal); + var maxVal = Number.MAX_VALUE; + min.set(-maxVal, -maxVal, -maxVal); + max.set(maxVal, maxVal, maxVal); + + if(tempNormal.x === 1){ max.x = pos.x; } + if(tempNormal.y === 1){ max.y = pos.y; } + if(tempNormal.z === 1){ max.z = pos.z; } + + if(tempNormal.x === -1){ min.x = pos.x; } + if(tempNormal.y === -1){ min.y = pos.y; } + if(tempNormal.z === -1){ min.z = pos.z; } +}; + +Plane.prototype.updateBoundingSphereRadius = function(){ + this.boundingSphereRadius = Number.MAX_VALUE; +}; +},{"../math/Vec3":27,"./Shape":40}],40:[function(_dereq_,module,exports){ +module.exports = Shape; + +var Shape = _dereq_('./Shape'); +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var Material = _dereq_('../material/Material'); + +/** + * Base class for shapes + * @class Shape + * @constructor + * @author schteppe + * @todo Should have a mechanism for caching bounding sphere radius instead of calculating it each time + */ +function Shape(){ + + /** + * The type of this shape. Must be set to an int > 0 by subclasses. + * @property type + * @type {Number} + * @see Shape.types + */ + this.type = 0; + + /** + * The local bounding sphere radius of this shape. + * @property {Number} boundingSphereRadius + */ + this.boundingSphereRadius = 0; + + /** + * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. + * @property {boolean} collisionResponse + */ + this.collisionResponse = true; +} +Shape.prototype.constructor = Shape; + +/** + * Computes the bounding sphere radius. The result is stored in the property .boundingSphereRadius + * @method updateBoundingSphereRadius + * @return {Number} + */ +Shape.prototype.updateBoundingSphereRadius = function(){ + throw "computeBoundingSphereRadius() not implemented for shape type "+this.type; +}; + +/** + * Get the volume of this shape + * @method volume + * @return {Number} + */ +Shape.prototype.volume = function(){ + throw "volume() not implemented for shape type "+this.type; +}; + +/** + * Calculates the inertia in the local frame for this shape. + * @method calculateLocalInertia + * @return {Vec3} + * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia + */ +Shape.prototype.calculateLocalInertia = function(mass,target){ + throw "calculateLocalInertia() not implemented for shape type "+this.type; +}; + +/** + * The available shape types. + * @static + * @property types + * @type {Object} + */ +Shape.types = { + SPHERE:1, + PLANE:2, + BOX:4, + COMPOUND:8, + CONVEXPOLYHEDRON:16, + HEIGHTFIELD:32, + PARTICLE:64, + CYLINDER:128 +}; + + +},{"../material/Material":22,"../math/Quaternion":25,"../math/Vec3":27,"./Shape":40}],41:[function(_dereq_,module,exports){ +module.exports = Sphere; + +var Shape = _dereq_('./Shape'); +var Vec3 = _dereq_('../math/Vec3'); + +/** + * Spherical shape + * @class Sphere + * @constructor + * @extends Shape + * @param {Number} radius + * @author schteppe / http://github.com/schteppe + */ +function Sphere(radius){ + Shape.call(this); + + /** + * @property {Number} radius + */ + this.radius = radius!==undefined ? Number(radius) : 1.0; + this.type = Shape.types.SPHERE; + + this.updateBoundingSphereRadius(); +} +Sphere.prototype = new Shape(); +Sphere.prototype.constructor = Sphere; + +Sphere.prototype.calculateLocalInertia = function(mass,target){ + target = target || new Vec3(); + var I = 2.0*mass*this.radius*this.radius/5.0; + target.x = I; + target.y = I; + target.z = I; + return target; +}; + +Sphere.prototype.volume = function(){ + return 4.0 * Math.PI * this.radius / 3.0; +}; + +Sphere.prototype.updateBoundingSphereRadius = function(){ + this.boundingSphereRadius = this.radius; +}; + +Sphere.prototype.calculateWorldAABB = function(pos,quat,min,max){ + var r = this.radius; + var axes = ['x','y','z']; + for(var i=0; i c.maxForce){ + deltalambda = c.maxForce - lambdaj; + } + lambda[j] += deltalambda; + + deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda) + + c.addToWlambda(deltalambda); + } + + // If the total error is small enough - stop iterate + if(deltalambdaTot*deltalambdaTot < tolSquared){ + break; + } + } + + // Add result to velocity + for(var i=0; i!==Nbodies; i++){ + var b=bodies[i], + v=b.velocity, + w=b.angularVelocity; + v.vadd(b.vlambda, v); + if(w){ + w.vadd(b.wlambda, w); + } + } + } + + return iter; +}; + +},{"../math/Quaternion":25,"../math/Vec3":27,"./Solver":43}],43:[function(_dereq_,module,exports){ +module.exports = Solver; + +/** + * Constraint equation solver base class. + * @class Solver + * @constructor + * @author schteppe / https://github.com/schteppe + */ +function Solver(){ + /** + * All equations to be solved + * @property {Array} equations + */ + this.equations = []; +} + +/** + * Should be implemented in subclasses! + * @method solve + * @param {Number} dt + * @param {World} world + */ +Solver.prototype.solve = function(dt,world){ + // Should return the number of iterations done! + return 0; +}; + +/** + * Add an equation + * @method addEquation + * @param {Equation} eq + */ +Solver.prototype.addEquation = function(eq){ + if (eq.enabled) { + this.equations.push(eq); + } +}; + +/** + * Remove an equation + * @method removeEquation + * @param {Equation} eq + */ +Solver.prototype.removeEquation = function(eq){ + var eqs = this.equations; + var i = eqs.indexOf(eq); + if(i !== -1){ + eqs.splice(i,1); + } +}; + +/** + * Add all equations + * @method removeAllEquations + */ +Solver.prototype.removeAllEquations = function(){ + this.equations.length = 0; +}; + + +},{}],44:[function(_dereq_,module,exports){ +module.exports = SplitSolver; + +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var Solver = _dereq_('./Solver'); +var Body = _dereq_('../objects/Body'); + +/** + * Splits the equations into islands and solves them independently. Can improve performance. + * @class SplitSolver + * @constructor + * @extends Solver + * @param {Solver} subsolver + */ +function SplitSolver(subsolver){ + Solver.call(this); + this.subsolver = subsolver; +} +SplitSolver.prototype = new Solver(); + +// Returns the number of subsystems +var SplitSolver_solve_nodes = []; // All allocated node objects +var SplitSolver_solve_eqs = []; // Temp array +var SplitSolver_solve_bds = []; // Temp array +var SplitSolver_solve_dummyWorld = {bodies:null}; // Temp object + +/** + * Solve the subsystems + * @method solve + * @param {Number} dt + * @param {World} world + */ +SplitSolver.prototype.solve = function(dt,world){ + var nodes=SplitSolver_solve_nodes, + bodies=world.bodies, + equations=this.equations, + Neq=equations.length, + Nbodies=bodies.length, + subsolver=this.subsolver; + // Create needed nodes, reuse if possible + if(nodes.length>Nbodies){ + nodes.length = Nbodies; + } + while(nodes.length j) { + // swap + var temp = j; + j = i; + i = temp; + } + return this.data[i+'-'+j]; +}; + +/** + * @method set + * @param {Number} i + * @param {Number} j + * @param {Number} value + */ +TupleDictionary.prototype.set = function(i, j, value) { + if (i > j) { + var temp = j; + j = i; + i = temp; + } + var key = i+'-'+j; + + // Check if key already exists + if(!this.get(i,j)){ + this.data.keys.push(key); + } + + this.data[key] = value; +}; + +/** + * @method reset + */ +TupleDictionary.prototype.reset = function() { + var data = this.data, + keys = data.keys; + while(keys.length > 0){ + var key = keys.pop(); + delete data[key]; + } +}; + +},{}],48:[function(_dereq_,module,exports){ +function Utils(){} + +module.exports = Utils; + +/** + * Extend an options object with default values. + * @static + * @method defaults + * @param {object} options The options object. May be falsy: in this case, a new object is created and returned. + * @param {object} defaults An object containing default values. + * @return {object} The modified options object. + */ +Utils.defaults = function(options, defaults){ + options = options || {}; + + for(var key in defaults){ + if(!(key in options)){ + options[key] = defaults[key]; + } + } + + return options; +}; + +},{}],49:[function(_dereq_,module,exports){ +module.exports = Vec3Pool; + +var Vec3 = _dereq_('../math/Vec3'); +var Pool = _dereq_('./Pool'); + +/** + * @class Vec3Pool + * @constructor + * @extends Pool + */ +function Vec3Pool(){ + Pool.call(this); + this.type = Vec3; +} +Vec3Pool.prototype = new Pool(); + +/** + * Construct a vector + * @method constructObject + * @return {Vec3} + */ +Vec3Pool.prototype.constructObject = function(){ + return new Vec3(); +}; + +},{"../math/Vec3":27,"./Pool":46}],50:[function(_dereq_,module,exports){ +module.exports = Narrowphase; + +var Shape = _dereq_('../shapes/Shape'); +var Vec3 = _dereq_('../math/Vec3'); +var Transform = _dereq_('../math/Transform'); +var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron'); +var Quaternion = _dereq_('../math/Quaternion'); +var Solver = _dereq_('../solver/Solver'); +var Vec3Pool = _dereq_('../utils/Vec3Pool'); +var ContactEquation = _dereq_('../equations/ContactEquation'); + +/** + * Helper class for the World. Generates ContactEquations. + * @class Narrowphase + * @constructor + * @todo Sphere-ConvexPolyhedron contacts + * @todo Contact reduction + * @todo should move methods to prototype + */ +function Narrowphase(){ + + /** + * Internal storage of pooled contact points. + * @property {Array} contactPointPool + */ + this.contactPointPool = []; + + /** + * Pooled vectors. + * @property {Vec3Pool} v3pool + */ + this.v3pool = new Vec3Pool(); +} + +/** + * Make a contact object, by using the internal pool or creating a new one. + * @method makeResult + * @return {ContactEquation} + */ +Narrowphase.prototype.makeResult = function(bi, bj, si, sj, rsi, rsj){ + var c; + if(this.contactPointPool.length){ + c = this.contactPointPool.pop(); + c.bi = bi; + c.bj = bj; + } else { + c = new ContactEquation(bi, bj); + } + + c.enabled = true; + c.si = rsi || si; + c.sj = rsj || sj; + + return c; +}; + +var tmpVec1 = new Vec3(); +var tmpVec2 = new Vec3(); +var tmpQuat1 = new Quaternion(); +var tmpQuat2 = new Quaternion(); + +/** + * Generate all contacts between a list of body pairs + * @method getContacts + * @param {array} p1 Array of body indices + * @param {array} p2 Array of body indices + * @param {World} world + * @param {array} result Array to store generated contacts + * @param {array} oldcontacts Optional. Array of reusable contact objects + */ +Narrowphase.prototype.getContacts = function(p1,p2,world,result,oldcontacts){ + // Save old contact objects + this.contactPointPool = oldcontacts; + + var qi = tmpQuat1; + var qj = tmpQuat2; + var xi = tmpVec1; + var xj = tmpVec2; + + for(var k=0, N=p1.length; k!==N; k++){ + + // Get current collision bodies + var bi = p1[k], + bj = p2[k]; + + for (var i = 0; i < bi.shapes.length; i++) { + bi.quaternion.mult(bi.shapeOrientations[i], qi); + bi.quaternion.vmult(bi.shapeOffsets[i], xi); + xi.vadd(bi.position, xi); + var si = bi.shapes[i]; + + for (var j = 0; j < bj.shapes.length; j++) { + + // Compute world transform of shapes + bj.quaternion.mult(bj.shapeOrientations[j], qj); + bj.quaternion.vmult(bj.shapeOffsets[j], xj); + xj.vadd(bj.position, xj); + var sj = bj.shapes[j]; + + if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){ + continue; + } + + // Get contacts + var resolver = this[si.type | sj.type]; + if(resolver){ + if (si.type < sj.type) { + resolver.call(this, result, si,sj,xi,xj,qi,qj,bi,bj,si,sj); + } else { + resolver.call(this, result, sj,si,xj,xi,qj,qi,bj,bi,si,sj); + } + } + } + } + } +}; + +var numWarnings = 0; +var maxWarnings = 10; + +function warn(msg){ + if(numWarnings > maxWarnings){ + return; + } + + numWarnings++; + + console.warn(msg); +} + +Narrowphase.prototype[Shape.types.BOX | Shape.types.BOX] = +Narrowphase.prototype.boxBox = function(result,si,sj,xi,xj,qi,qj,bi,bj){ + this.convexConvex(result,si.convexPolyhedronRepresentation,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj,si,sj); +}; + +Narrowphase.prototype[Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON] = +Narrowphase.prototype.boxConvex = function(result,si,sj,xi,xj,qi,qj,bi,bj){ + this.convexConvex(result,si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj); +}; + +Narrowphase.prototype[Shape.types.BOX | Shape.types.PARTICLE] = +Narrowphase.prototype.boxParticle = function(result,si,sj,xi,xj,qi,qj,bi,bj){ + this.convexParticle(result,si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj); +}; + +/** + * @method sphereSphere + * @param {Array} result + * @param {Shape} si + * @param {Shape} sj + * @param {Vec3} xi + * @param {Vec3} xj + * @param {Quaternion} qi + * @param {Quaternion} qj + * @param {Body} bi + * @param {Body} bj + */ +Narrowphase.prototype[Shape.types.SPHERE] = +Narrowphase.prototype.sphereSphere = function(result,si,sj,xi,xj,qi,qj,bi,bj){ + // We will have only one contact in this case + var r = this.makeResult(bi,bj,si,sj); + + // Contact normal + bj.position.vsub(xi, r.ni); + r.ni.normalize(); + + // Contact point locations + r.ri.copy(r.ni); + r.rj.copy(r.ni); + r.ri.mult(si.radius, r.ri); + r.rj.mult(-sj.radius, r.rj); + result.push(r); +}; + +var point_on_plane_to_sphere = new Vec3(); +var plane_to_sphere_ortho = new Vec3(); + +/** + * @method spherePlane + * @param {Array} result + * @param {Shape} si + * @param {Shape} sj + * @param {Vec3} xi + * @param {Vec3} xj + * @param {Quaternion} qi + * @param {Quaternion} qj + * @param {Body} bi + * @param {Body} bj + */ +Narrowphase.prototype[Shape.types.SPHERE | Shape.types.PLANE] = +Narrowphase.prototype.spherePlane = function(result,si,sj,xi,xj,qi,qj,bi,bj){ + // We will have one contact in this case + var r = this.makeResult(bi,bj,si,sj); + + // Contact normal + r.ni.set(0,0,1); + qj.vmult(r.ni, r.ni); + r.ni.negate(r.ni); // body i is the sphere, flip normal + r.ni.normalize(); // Needed? + + // Vector from sphere center to contact point + r.ni.mult(si.radius, r.ri); + + // Project down sphere on plane + xi.vsub(xj, point_on_plane_to_sphere); + r.ni.mult(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho); + point_on_plane_to_sphere.vsub(plane_to_sphere_ortho,r.rj); // The sphere position projected to plane + + if(plane_to_sphere_ortho.norm2() <= si.radius * si.radius){ + result.push(r); + + // Make it relative to the body + var ri = r.ri; + var rj = r.rj; + ri.vadd(xi, ri); + ri.vsub(bi.position, ri); + rj.vadd(xj, rj); + rj.vsub(bj.position, rj); + } +}; + +// See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html +var pointInPolygon_edge = new Vec3(); +var pointInPolygon_edge_x_normal = new Vec3(); +var pointInPolygon_vtp = new Vec3(); +function pointInPolygon(verts, normal, p){ + var positiveResult = null; + var N = verts.length; + for(var i=0; i!==N; i++){ + var v = verts[i]; + + // Get edge to the next vertex + var edge = pointInPolygon_edge; + verts[(i+1) % (N)].vsub(v,edge); + + // Get cross product between polygon normal and the edge + var edge_x_normal = pointInPolygon_edge_x_normal; + //var edge_x_normal = new Vec3(); + edge.cross(normal,edge_x_normal); + + // Get vector between point and current vertex + var vertex_to_p = pointInPolygon_vtp; + p.vsub(v,vertex_to_p); + + // This dot product determines which side of the edge the point is + var r = edge_x_normal.dot(vertex_to_p); + + // If all such dot products have same sign, we are inside the polygon. + if(positiveResult===null || (r>0 && positiveResult===true) || (r<=0 && positiveResult===false)){ + if(positiveResult===null){ + positiveResult = r>0; + } + continue; + } else { + return false; // Encountered some other sign. Exit. + } + } + + // If we got here, all dot products were of the same sign. + return true; +} + +var box_to_sphere = new Vec3(); +var sphereBox_ns = new Vec3(); +var sphereBox_ns1 = new Vec3(); +var sphereBox_ns2 = new Vec3(); +var sphereBox_sides = [new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3()]; +var sphereBox_sphere_to_corner = new Vec3(); +var sphereBox_side_ns = new Vec3(); +var sphereBox_side_ns1 = new Vec3(); +var sphereBox_side_ns2 = new Vec3(); + +/** + * @method sphereBox + * @param {Array} result + * @param {Shape} si + * @param {Shape} sj + * @param {Vec3} xi + * @param {Vec3} xj + * @param {Quaternion} qi + * @param {Quaternion} qj + * @param {Body} bi + * @param {Body} bj + */ +Narrowphase.prototype[Shape.types.SPHERE | Shape.types.BOX] = +Narrowphase.prototype.sphereBox = function(result,si,sj,xi,xj,qi,qj,bi,bj){ + var v3pool = this.v3pool; + + // we refer to the box as body j + var sides = sphereBox_sides; + xi.vsub(xj,box_to_sphere); + sj.getSideNormals(sides,qj); + var R = si.radius; + var penetrating_sides = []; + + // Check side (plane) intersections + var found = false; + + // Store the resulting side penetration info + var side_ns = sphereBox_side_ns; + var side_ns1 = sphereBox_side_ns1; + var side_ns2 = sphereBox_side_ns2; + var side_h = null; + var side_penetrations = 0; + var side_dot1 = 0; + var side_dot2 = 0; + var side_distance = null; + for(var idx=0,nsides=sides.length; idx!==nsides && found===false; idx++){ + // Get the plane side normal (ns) + var ns = sphereBox_ns; + ns.copy(sides[idx]); + + var h = ns.norm(); + ns.normalize(); + + // The normal/distance dot product tells which side of the plane we are + var dot = box_to_sphere.dot(ns); + + if(dot0){ + // Intersects plane. Now check the other two dimensions + var ns1 = sphereBox_ns1; + var ns2 = sphereBox_ns2; + ns1.copy(sides[(idx+1)%3]); + ns2.copy(sides[(idx+2)%3]); + var h1 = ns1.norm(); + var h2 = ns2.norm(); + ns1.normalize(); + ns2.normalize(); + var dot1 = box_to_sphere.dot(ns1); + var dot2 = box_to_sphere.dot(ns2); + if(dot1

-h1 && dot2

-h2){ + var dist = Math.abs(dot-h-R); + if(side_distance===null || dist < side_distance){ + side_distance = dist; + side_dot1 = dot1; + side_dot2 = dot2; + side_h = h; + side_ns.copy(ns); + side_ns1.copy(ns1); + side_ns2.copy(ns2); + side_penetrations++; + } + } + } + } + if(side_penetrations){ + found = true; + var r = this.makeResult(bi,bj,si,sj); + side_ns.mult(-R,r.ri); // Sphere r + r.ni.copy(side_ns); + r.ni.negate(r.ni); // Normal should be out of sphere + side_ns.mult(side_h,side_ns); + side_ns1.mult(side_dot1,side_ns1); + side_ns.vadd(side_ns1,side_ns); + side_ns2.mult(side_dot2,side_ns2); + side_ns.vadd(side_ns2,r.rj); + + // Make relative to bodies + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); + + result.push(r); + } + + // Check corners + var rj = v3pool.get(); + var sphere_to_corner = sphereBox_sphere_to_corner; + for(var j=0; j!==2 && !found; j++){ + for(var k=0; k!==2 && !found; k++){ + for(var l=0; l!==2 && !found; l++){ + rj.set(0,0,0); + if(j){ + rj.vadd(sides[0],rj); + } else { + rj.vsub(sides[0],rj); + } + if(k){ + rj.vadd(sides[1],rj); + } else { + rj.vsub(sides[1],rj); + } + if(l){ + rj.vadd(sides[2],rj); + } else { + rj.vsub(sides[2],rj); + } + + // World position of corner + xj.vadd(rj,sphere_to_corner); + sphere_to_corner.vsub(xi,sphere_to_corner); + + if(sphere_to_corner.norm2() < R*R){ + found = true; + var r = this.makeResult(bi,bj,si,sj); + r.ri.copy(sphere_to_corner); + r.ri.normalize(); + r.ni.copy(r.ri); + r.ri.mult(R,r.ri); + r.rj.copy(rj); + + // Make relative to bodies + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); + + result.push(r); + } + } + } + } + v3pool.release(rj); + rj = null; + + // Check edges + var edgeTangent = v3pool.get(); + var edgeCenter = v3pool.get(); + var r = v3pool.get(); // r = edge center to sphere center + var orthogonal = v3pool.get(); + var dist = v3pool.get(); + var Nsides = sides.length; + for(var j=0; j!==Nsides && !found; j++){ + for(var k=0; k!==Nsides && !found; k++){ + if(j%3 !== k%3){ + // Get edge tangent + sides[k].cross(sides[j],edgeTangent); + edgeTangent.normalize(); + sides[j].vadd(sides[k], edgeCenter); + r.copy(xi); + r.vsub(edgeCenter,r); + r.vsub(xj,r); + var orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction + edgeTangent.mult(orthonorm,orthogonal); // Vector from edge center to sphere center in the tangent direction + + // Find the third side orthogonal to this one + var l = 0; + while(l===j%3 || l===k%3){ + l++; + } + + // vec from edge center to sphere projected to the plane orthogonal to the edge tangent + dist.copy(xi); + dist.vsub(orthogonal,dist); + dist.vsub(edgeCenter,dist); + dist.vsub(xj,dist); + + // Distances in tangent direction and distance in the plane orthogonal to it + var tdist = Math.abs(orthonorm); + var ndist = dist.norm(); + + if(tdist < sides[l].norm() && ndist si.boundingSphereRadius + sj.boundingSphereRadius){ + // return; + // } + + // Check corners + for(var i=0; i!==verts.length; i++){ + var v = verts[i]; + + // World position of corner + var worldCorner = sphereConvex_worldCorner; + qj.vmult(v,worldCorner); + xj.vadd(worldCorner,worldCorner); + var sphere_to_corner = sphereConvex_sphereToCorner; + worldCorner.vsub(xi, sphere_to_corner); + if(sphere_to_corner.norm2() < R * R){ + found = true; + var r = this.makeResult(bi,bj,si,sj); + r.ri.copy(sphere_to_corner); + r.ri.normalize(); + r.ni.copy(r.ri); + r.ri.mult(R,r.ri); + worldCorner.vsub(xj,r.rj); + + // Should be relative to the body. + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); + + // Should be relative to the body. + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); + + result.push(r); + return; + } + } + + // Check side (plane) intersections + var found = false; + for(var i=0, nfaces=faces.length; i!==nfaces && found===false; i++){ + var normal = normals[i]; + var face = faces[i]; + + // Get world-transformed normal of the face + var worldNormal = sphereConvex_worldNormal; + qj.vmult(normal,worldNormal); + + // Get a world vertex from the face + var worldPoint = sphereConvex_worldPoint; + qj.vmult(verts[face[0]],worldPoint); + worldPoint.vadd(xj,worldPoint); + + // Get a point on the sphere, closest to the face normal + var worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane; + worldNormal.mult(-R, worldSpherePointClosestToPlane); + xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane); + + // Vector from a face point to the closest point on the sphere + var penetrationVec = sphereConvex_penetrationVec; + worldSpherePointClosestToPlane.vsub(worldPoint,penetrationVec); + + // The penetration. Negative value means overlap. + var penetration = penetrationVec.dot(worldNormal); + + var worldPointToSphere = sphereConvex_sphereToWorldPoint; + xi.vsub(worldPoint, worldPointToSphere); + + if(penetration < 0 && worldPointToSphere.dot(worldNormal)>0){ + // Intersects plane. Now check if the sphere is inside the face polygon + var faceVerts = []; // Face vertices, in world coords + for(var j=0, Nverts=face.length; j!==Nverts; j++){ + var worldVertex = v3pool.get(); + qj.vmult(verts[face[j]], worldVertex); + xj.vadd(worldVertex,worldVertex); + faceVerts.push(worldVertex); + } + + if(pointInPolygon(faceVerts,worldNormal,xi)){ // Is the sphere center in the face polygon? + found = true; + var r = this.makeResult(bi,bj,si,sj); + + worldNormal.mult(-R, r.ri); // Contact offset, from sphere center to contact + worldNormal.negate(r.ni); // Normal pointing out of sphere + + var penetrationVec2 = v3pool.get(); + worldNormal.mult(-penetration, penetrationVec2); + var penetrationSpherePoint = v3pool.get(); + worldNormal.mult(-R, penetrationSpherePoint); + + //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj); + xi.vsub(xj,r.rj); + r.rj.vadd(penetrationSpherePoint,r.rj); + r.rj.vadd(penetrationVec2 , r.rj); + + // Should be relative to the body. + r.rj.vadd(xj, r.rj); + r.rj.vsub(bj.position, r.rj); + + // Should be relative to the body. + r.ri.vadd(xi, r.ri); + r.ri.vsub(bi.position, r.ri); + + v3pool.release(penetrationVec2); + v3pool.release(penetrationSpherePoint); + + result.push(r); + + // Release world vertices + for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){ + v3pool.release(faceVerts[j]); + } + + return; // We only expect *one* face contact + } else { + // Edge? + for(var j=0; j!==face.length; j++){ + + // Get two world transformed vertices + var v1 = v3pool.get(); + var v2 = v3pool.get(); + qj.vmult(verts[face[(j+1)%face.length]], v1); + qj.vmult(verts[face[(j+2)%face.length]], v2); + xj.vadd(v1, v1); + xj.vadd(v2, v2); + + // Construct edge vector + var edge = sphereConvex_edge; + v2.vsub(v1,edge); + + // Construct the same vector, but normalized + var edgeUnit = sphereConvex_edgeUnit; + edge.unit(edgeUnit); + + // p is xi projected onto the edge + var p = v3pool.get(); + var v1_to_xi = v3pool.get(); + xi.vsub(v1, v1_to_xi); + var dot = v1_to_xi.dot(edgeUnit); + edgeUnit.mult(dot, p); + p.vadd(v1, p); + + // Compute a vector from p to the center of the sphere + var xi_to_p = v3pool.get(); + p.vsub(xi, xi_to_p); + + // Collision if the edge-sphere distance is less than the radius + // AND if p is in between v1 and v2 + if(dot > 0 && dot*dot si.boundingSphereRadius + sj.boundingSphereRadius){ + return; + } + + if(si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){ + var res = []; + var q = convexConvex_q; + si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res); + for(var j = 0; j !== res.length; j++){ + var r = this.makeResult(bi,bj,si,sj,rsi,rsj), + ri = r.ri, + rj = r.rj; + sepAxis.negate(r.ni); + res[j].normal.negate(q); + q.mult(res[j].depth, q); + res[j].point.vadd(q, ri); + rj.copy(res[j].point); + + // Contact points are in world coordinates. Transform back to relative + ri.vsub(xi,ri); + rj.vsub(xj,rj); + + // Make relative to bodies + ri.vadd(xi, ri); + ri.vsub(bi.position, ri); + rj.vadd(xj, rj); + rj.vsub(bj.position, rj); + + result.push(r); + } + } +}; + +var particlePlane_normal = new Vec3(); +var particlePlane_relpos = new Vec3(); +var particlePlane_projected = new Vec3(); + +/** + * @method particlePlane + * @param {Array} result + * @param {Shape} si + * @param {Shape} sj + * @param {Vec3} xi + * @param {Vec3} xj + * @param {Quaternion} qi + * @param {Quaternion} qj + * @param {Body} bi + * @param {Body} bj + */ +Narrowphase.prototype[Shape.types.PLANE | Shape.types.PARTICLE] = +Narrowphase.prototype.planeParticle = function(result,sj,si,xj,xi,qj,qi,bj,bi){ + var normal = particlePlane_normal; + normal.set(0,0,1); + bj.quaternion.vmult(normal,normal); // Turn normal according to plane orientation + var relpos = particlePlane_relpos; + xi.vsub(bj.position,relpos); + var dot = normal.dot(relpos); + if(dot <= 0.0){ + var r = this.makeResult(bi,bj,si,sj); + r.ni.copy(normal); // Contact normal is the plane normal + r.ni.negate(r.ni); + r.ri.set(0,0,0); // Center of particle + + // Get particle position projected on plane + var projected = particlePlane_projected; + normal.mult(normal.dot(xi),projected); + xi.vsub(projected,projected); + //projected.vadd(bj.position,projected); + + // rj is now the projected world position minus plane position + r.rj.copy(projected); + result.push(r); + } +}; + +var particleSphere_normal = new Vec3(); + +/** + * @method particleSphere + * @param {Array} result + * @param {Shape} si + * @param {Shape} sj + * @param {Vec3} xi + * @param {Vec3} xj + * @param {Quaternion} qi + * @param {Quaternion} qj + * @param {Body} bi + * @param {Body} bj + */ +Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.SPHERE] = +Narrowphase.prototype.sphereParticle = function(result,sj,si,xj,xi,qj,qi,bj,bi){ + // The normal is the unit vector from sphere center to particle center + var normal = particleSphere_normal; + normal.set(0,0,1); + xi.vsub(xj,normal); + var lengthSquared = normal.norm2(); + + if(lengthSquared <= sj.radius * sj.radius){ + var r = this.makeResult(bi,bj,si,sj); + normal.normalize(); + r.rj.copy(normal); + r.rj.mult(sj.radius,r.rj); + r.ni.copy(normal); // Contact normal + r.ni.negate(r.ni); + r.ri.set(0,0,0); // Center of particle + result.push(r); + } +}; + +// WIP +var cqj = new Quaternion(); +var convexParticle_local = new Vec3(); +var convexParticle_normal = new Vec3(); +var convexParticle_penetratedFaceNormal = new Vec3(); +var convexParticle_vertexToParticle = new Vec3(); +var convexParticle_worldPenetrationVec = new Vec3(); + +/** + * @method convexParticle + * @param {Array} result + * @param {Shape} si + * @param {Shape} sj + * @param {Vec3} xi + * @param {Vec3} xj + * @param {Quaternion} qi + * @param {Quaternion} qj + * @param {Body} bi + * @param {Body} bj + */ +Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON] = +Narrowphase.prototype.convexParticle = function(result,sj,si,xj,xi,qj,qi,bj,bi){ + var penetratedFaceIndex = -1; + var penetratedFaceNormal = convexParticle_penetratedFaceNormal; + var worldPenetrationVec = convexParticle_worldPenetrationVec; + var minPenetration = null; + var numDetectedFaces = 0; + + // Convert particle position xi to local coords in the convex + var local = convexParticle_local; + local.copy(xi); + local.vsub(xj,local); // Convert position to relative the convex origin + qj.conjugate(cqj); + cqj.vmult(local,local); + + if(sj.pointIsInside(local)){ + + if(sj.worldVerticesNeedsUpdate){ + sj.computeWorldVertices(xj,qj); + } + if(sj.worldFaceNormalsNeedsUpdate){ + sj.computeWorldFaceNormals(qj); + } + + // For each world polygon in the polyhedra + for(var i=0,nfaces=sj.faces.length; i!==nfaces; i++){ + + // Construct world face vertices + var verts = [ sj.worldVertices[ sj.faces[i][0] ] ]; + var normal = sj.worldFaceNormals[i]; + + // Check how much the particle penetrates the polygon plane. + xi.vsub(verts[0],convexParticle_vertexToParticle); + var penetration = -normal.dot(convexParticle_vertexToParticle); + if(minPenetration===null || Math.abs(penetration) data.length || iMaxY > data[0].length){ + return; + } + + // Clamp index to edges + if(iMinX < 0){ iMinX = 0; } + if(iMaxX < 0){ iMaxX = 0; } + if(iMinY < 0){ iMinY = 0; } + if(iMaxY < 0){ iMaxY = 0; } + if(iMinX >= data.length){ iMinX = data.length - 1; } + if(iMaxX >= data.length){ iMaxX = data.length - 1; } + if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; } + if(iMinY >= data[0].length){ iMinY = data[0].length - 1; } + + var minMax = []; + hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax); + var min = minMax[0]; + var max = minMax[1]; + + // Bail out if we're cant touch the bounding height box + if(localConvexPos.z - radius > max || localConvexPos.z + radius < min){ + return; + } + + for(var i = iMinX; i < iMaxX; i++){ + for(var j = iMinY; j < iMaxY; j++){ + + // Lower triangle + hfShape.getConvexTrianglePillar(i, j, false); + Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset); + if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) { + this.convexConvex(result, convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null); + } + + // Upper triangle + hfShape.getConvexTrianglePillar(i, j, true); + Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset); + if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) { + this.convexConvex(result, convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null); + } + } + } +}; + + + + +var sphereHeightfield_tmp1 = new Vec3(); +var sphereHeightfield_tmp2 = new Vec3(); + +/** + * @method sphereHeightfield + */ +Narrowphase.prototype[Shape.types.SPHERE | Shape.types.HEIGHTFIELD] = +Narrowphase.prototype.sphereHeightfield = function ( + result, + sphereShape, + hfShape, + spherePos, + hfPos, + sphereQuat, + hfQuat, + sphereBody, + hfBody +){ + var data = hfShape.data, + radius = sphereShape.radius, + w = hfShape.elementSize, + worldPillarOffset = sphereHeightfield_tmp2; + + // Get sphere position to heightfield local! + var localSpherePos = sphereHeightfield_tmp1; + Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos); + + // Get the index of the data points to test against + var iMinX = Math.floor((localSpherePos.x - radius) / w) - 1, + iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1, + iMinY = Math.floor((localSpherePos.y - radius) / w) - 1, + iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1; + + // Bail out if we are out of the terrain + if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMaxY > data[0].length){ + return; + } + + // Clamp index to edges + if(iMinX < 0){ iMinX = 0; } + if(iMaxX < 0){ iMaxX = 0; } + if(iMinY < 0){ iMinY = 0; } + if(iMaxY < 0){ iMaxY = 0; } + if(iMinX >= data.length){ iMinX = data.length - 1; } + if(iMaxX >= data.length){ iMaxX = data.length - 1; } + if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; } + if(iMinY >= data[0].length){ iMinY = data[0].length - 1; } + + var minMax = []; + hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax); + var min = minMax[0]; + var max = minMax[1]; + + // Bail out if we're cant touch the bounding height box + if(localSpherePos.z - radius > max || localSpherePos.z + radius < min){ + return; + } + + for(var i = iMinX; i < iMaxX; i++){ + for(var j = iMinY; j < iMaxY; j++){ + + var numContactsBefore = result.length; + + // Lower triangle + hfShape.getConvexTrianglePillar(i, j, false); + Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset); + if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) { + this.sphereConvex(result, sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody); + } + + // Upper triangle + hfShape.getConvexTrianglePillar(i, j, true); + Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset); + if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) { + this.sphereConvex(result, sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody); + } + + var numContacts = result.length - numContactsBefore; + + if(numContacts > 2){ + return; + } + /* + // Skip all but 1 + for (var k = 0; k < numContacts - 1; k++) { + result.pop(); + } + */ + } + } +}; +},{"../equations/ContactEquation":16,"../math/Quaternion":25,"../math/Transform":26,"../math/Vec3":27,"../shapes/ConvexPolyhedron":35,"../shapes/Shape":40,"../solver/Solver":43,"../utils/Vec3Pool":49}],51:[function(_dereq_,module,exports){ +/* global performance */ + +module.exports = World; + +var Shape = _dereq_('../shapes/Shape'); +var Vec3 = _dereq_('../math/Vec3'); +var Quaternion = _dereq_('../math/Quaternion'); +var GSSolver = _dereq_('../solver/GSSolver'); +var Vec3Pool = _dereq_('../utils/Vec3Pool'); +var ContactEquation = _dereq_('../equations/ContactEquation'); +var FrictionEquation = _dereq_('../equations/FrictionEquation'); +var Narrowphase = _dereq_('./Narrowphase'); +var EventTarget = _dereq_('../utils/EventTarget'); +var ArrayCollisionMatrix = _dereq_('../collision/ArrayCollisionMatrix'); +var Material = _dereq_('../material/Material'); +var ContactMaterial = _dereq_('../material/ContactMaterial'); +var Body = _dereq_('../objects/Body'); +var TupleDictionary = _dereq_('../utils/TupleDictionary'); +var RaycastResult = _dereq_('../collision/RaycastResult'); +var AABB = _dereq_('../collision/AABB'); +var Ray = _dereq_('../collision/Ray'); +var NaiveBroadphase = _dereq_('../collision/NaiveBroadphase'); + +/** + * The physics world + * @class World + * @constructor + * @extends EventTarget + */ +function World(){ + EventTarget.apply(this); + + /** + * Last used timestep. Is set to -1 if not available. + * @property {Number} dt + */ + this.dt = -1; + + /** + * Makes bodies go to sleep when they've been inactive + * @property allowSleep + * @type {Boolean} + */ + this.allowSleep = false; + + /** + * All the current contacts (instances of ContactEquation) in the world. + * @property contacts + * @type {Array} + */ + this.contacts = []; + this.frictionEquations = []; + + /** + * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong). + * @property quatNormalizeSkip + * @type {Number} + */ + this.quatNormalizeSkip = 0; + + /** + * Set to true to use fast quaternion normalization. It is often enough accurate to use. If bodies tend to explode, set to false. + * @property quatNormalizeFast + * @type {Boolean} + * @see Quaternion.normalizeFast + * @see Quaternion.normalize + */ + this.quatNormalizeFast = false; + + /** + * The wall-clock time since simulation start + * @property time + * @type {Number} + */ + this.time = 0.0; + + /** + * Number of timesteps taken since start + * @property stepnumber + * @type {Number} + */ + this.stepnumber = 0; + + /// Default and last timestep sizes + this.default_dt = 1/60; + + this.nextId = 0; + /** + * @property gravity + * @type {Vec3} + */ + this.gravity = new Vec3(); + + /** + * @property broadphase + * @type {Broadphase} + */ + this.broadphase = new NaiveBroadphase(); + + /** + * @property bodies + * @type {Array} + */ + this.bodies = []; + + /** + * @property solver + * @type {Solver} + */ + this.solver = new GSSolver(); + + /** + * @property constraints + * @type {Array} + */ + this.constraints = []; + + /** + * @property narrowphase + * @type {Narrowphase} + */ + this.narrowphase = new Narrowphase(); + + /** + * @property {ArrayCollisionMatrix} collisionMatrix + * @type {ArrayCollisionMatrix} + */ + this.collisionMatrix = new ArrayCollisionMatrix(); + + /** + * CollisionMatrix from the previous step. + * @property {ArrayCollisionMatrix} collisionMatrixPrevious + * @type {ArrayCollisionMatrix} + */ + this.collisionMatrixPrevious = new ArrayCollisionMatrix(); + + /** + * All added materials + * @property materials + * @type {Array} + */ + this.materials = []; + + /** + * @property contactmaterials + * @type {Array} + */ + this.contactmaterials = []; + + /** + * Used to look up a ContactMaterial given two instances of Material. + * @property {TupleDictionary} contactMaterialTable + */ + this.contactMaterialTable = new TupleDictionary(); + + this.defaultMaterial = new Material("default"); + + /** + * This contact material is used if no suitable contactmaterial is found for a contact. + * @property defaultContactMaterial + * @type {ContactMaterial} + */ + this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, { friction: 0.3, restitution: 0.0 }); + + /** + * @property doProfiling + * @type {Boolean} + */ + this.doProfiling = false; + + /** + * @property profile + * @type {Object} + */ + this.profile = { + solve:0, + makeContactConstraints:0, + broadphase:0, + integrate:0, + narrowphase:0, + }; + + /** + * @property subystems + * @type {Array} + */ + this.subsystems = []; + + this.addBodyEvent = { + type:"addBody", + body : null, + }; + + this.removeBodyEvent = { + type:"removeBody", + body : null, + }; +} +World.prototype = new EventTarget(); + +// Temp stuff +var tmpAABB1 = new AABB(); +var tmpArray1 = []; +var tmpRay = new Ray(); + +/** + * Get the contact material between materials m1 and m2 + * @method getContactMaterial + * @param {Material} m1 + * @param {Material} m2 + * @return {Contactmaterial} The contact material if it was found. + */ +World.prototype.getContactMaterial = function(m1,m2){ + return this.contactMaterialTable.get(m1.id,m2.id); //this.contactmaterials[this.mats2cmat[i+j*this.materials.length]]; +}; + +/** + * Get number of objects in the world. + * @method numObjects + * @return {Number} + * @deprecated + */ +World.prototype.numObjects = function(){ + return this.bodies.length; +}; + +/** + * Store old collision state info + * @method collisionMatrixTick + */ +World.prototype.collisionMatrixTick = function(){ + var temp = this.collisionMatrixPrevious; + this.collisionMatrixPrevious = this.collisionMatrix; + this.collisionMatrix = temp; + this.collisionMatrix.reset(); +}; + +/** + * Add a rigid body to the simulation. + * @method add + * @param {Body} body + * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case. + * @todo Adding an array of bodies should be possible. This would save some loops too + * @deprecated Use .addBody instead + */ +World.prototype.add = World.prototype.addBody = function(body){ + if(this.bodies.indexOf(body) !== -1){ + return; + } + body.index = this.bodies.length; + this.bodies.push(body); + body.world = this; + body.initPosition.copy(body.position); + body.initVelocity.copy(body.velocity); + body.timeLastSleepy = this.time; + if(body instanceof Body){ + body.initAngularVelocity.copy(body.angularVelocity); + body.initQuaternion.copy(body.quaternion); + } + this.collisionMatrix.setNumObjects(this.bodies.length); + this.addBodyEvent.body = body; + this.dispatchEvent(this.addBodyEvent); +}; + +/** + * Add a constraint to the simulation. + * @method addConstraint + * @param {Constraint} c + */ +World.prototype.addConstraint = function(c){ + this.constraints.push(c); +}; + +/** + * Removes a constraint + * @method removeConstraint + * @param {Constraint} c + */ +World.prototype.removeConstraint = function(c){ + var idx = this.constraints.indexOf(c); + if(idx!==-1){ + this.constraints.splice(idx,1); + } +}; + +/** + * Raycast test + * @method rayTest + * @param {Vec3} from + * @param {Vec3} to + * @param {Function|RaycastResult} result + */ +World.prototype.rayTest = function(from, to, result){ + // result = result || new RaycastResult(); + + tmpRay.from.copy(from); + tmpRay.to.copy(to); + tmpRay.getAABB(tmpAABB1); + + tmpArray1.length = 0; + this.broadphase.aabbQuery(this, tmpAABB1, tmpArray1); + + tmpRay.intersectBodies(tmpArray1, result); +}; + +/** + * Remove a rigid body from the simulation. + * @method remove + * @param {Body} body + * @todo Rename to .removeBody + */ +World.prototype.remove = function(body){ + body.world = null; + var n = this.bodies.length-1, + bodies = this.bodies, + idx = bodies.indexOf(body); + if(idx !== -1){ + bodies.splice(idx, 1); // Todo: should use a garbage free method + + // Recompute index + for(var i=0; i!==bodies.length; i++){ + bodies[i].index = i; + } + + this.collisionMatrix.setNumObjects(n); + this.removeBodyEvent.body = body; + this.dispatchEvent(this.removeBodyEvent); + } +}; + +/** + * Adds a material to the World. + * @method addMaterial + * @param {Material} m + * @todo Necessary? + */ +World.prototype.addMaterial = function(m){ + this.materials.push(m); +}; + +/** + * Adds a contact material to the World + * @method addContactMaterial + * @param {ContactMaterial} cmat + */ +World.prototype.addContactMaterial = function(cmat) { + + // Add contact material + this.contactmaterials.push(cmat); + + // Add current contact material to the material table + this.contactMaterialTable.set(cmat.materials[0].id,cmat.materials[1].id,cmat); +}; + +// performance.now() +if(typeof performance === 'undefined'){ + performance = {}; +} +if(!performance.now){ + var nowOffset = Date.now(); + if (performance.timing && performance.timing.navigationStart){ + nowOffset = performance.timing.navigationStart; + } + performance.now = function(){ + return Date.now() - nowOffset; + }; +} + +var step_tmp1 = new Vec3(); + +/** + * Step the physics world forward in time. + * + * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take. + * + * @method step + * @param {Number} dt The fixed time step size to use. + * @param {Number} [timeSinceLastCalled] The time elapsed since the function was last called. + * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call. + * + * @example + * // fixed timestepping without interpolation + * world.step(1/60); + * + * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World + */ +World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps){ + maxSubSteps = maxSubSteps || 10; + timeSinceLastCalled = timeSinceLastCalled || 0; + + if(timeSinceLastCalled === 0){ // Fixed, simple stepping + + this.internalStep(dt); + + // Increment time + this.time += dt; + + } else { + + // Compute the number of fixed steps we should have taken since the last step + var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt); + internalSteps = Math.min(internalSteps,maxSubSteps); + + // Do some fixed steps to catch up + var t0 = performance.now(); + for(var i=0; i!==internalSteps; i++){ + this.internalStep(dt); + if(performance.now() - t0 > dt * 1000){ + // We are slower than real-time. Better bail out. + break; + } + } + + // Increment internal clock + this.time += timeSinceLastCalled; + + // Compute "Left over" time step + var h = this.time % dt; + var h_div_dt = h / dt; + var interpvelo = step_tmp1; + var bodies = this.bodies; + + for(var j=0; j !== bodies.length; j++){ + var b = bodies[j]; + if(b.type !== Body.STATIC && b.sleepState !== Body.SLEEPING){ + + // Interpolate + b.position.vsub(b.previousPosition, interpvelo); + interpvelo.scale(h_div_dt, interpvelo); + b.position.vadd(interpvelo, b.interpolatedPosition); + + // TODO: interpolate quaternion + // b.interpolatedAngle = b.angle + (b.angle - b.previousAngle) * h_div_dt; + + } else { + + // For static bodies, just copy. Who else will do it? + b.interpolatedPosition.copy(b.position); + b.interpolatedQuaternion.copy(b.quaternion); + } + } + } +}; + +/** + * Step the simulation + * @method step + * @param {Number} dt + */ +var World_step_postStepEvent = {type:"postStep"}, // Reusable event objects to save memory + World_step_preStepEvent = {type:"preStep"}, + World_step_collideEvent = {type:"collide", body:null, contact:null }, + World_step_oldContacts = [], // Pools for unused objects + World_step_frictionEquationPool = [], + World_step_p1 = [], // Reusable arrays for collision pairs + World_step_p2 = [], + World_step_gvec = new Vec3(), // Temporary vectors and quats + World_step_vi = new Vec3(), + World_step_vj = new Vec3(), + World_step_wi = new Vec3(), + World_step_wj = new Vec3(), + World_step_t1 = new Vec3(), + World_step_t2 = new Vec3(), + World_step_rixn = new Vec3(), + World_step_rjxn = new Vec3(), + World_step_step_q = new Quaternion(), + World_step_step_w = new Quaternion(), + World_step_step_wq = new Quaternion(), + invI_tau_dt = new Vec3(); +World.prototype.internalStep = function(dt){ + this.dt = dt; + + var world = this, + that = this, + contacts = this.contacts, + p1 = World_step_p1, + p2 = World_step_p2, + N = this.numObjects(), + bodies = this.bodies, + solver = this.solver, + gravity = this.gravity, + doProfiling = this.doProfiling, + profile = this.profile, + DYNAMIC = Body.DYNAMIC, + profilingStart, + constraints = this.constraints, + frictionEquationPool = World_step_frictionEquationPool, + gnorm = gravity.norm(), + gx = gravity.x, + gy = gravity.y, + gz = gravity.z, + i=0; + + if(doProfiling){ + profilingStart = performance.now(); + } + + // Add gravity to all objects + for(i=0; i!==N; i++){ + var bi = bodies[i]; + if(bi.type & DYNAMIC){ // Only for dynamic bodies + var f = bi.force, m = bi.mass; + f.x += m*gx; + f.y += m*gy; + f.z += m*gz; + } + } + + // Update subsystems + for(var i=0, Nsubsystems=this.subsystems.length; i!==Nsubsystems; i++){ + this.subsystems[i].update(); + } + + // Collision detection + if(doProfiling){ profilingStart = performance.now(); } + p1.length = 0; // Clean up pair arrays from last step + p2.length = 0; + this.broadphase.collisionPairs(this,p1,p2); + if(doProfiling){ profile.broadphase = performance.now() - profilingStart; } + + // Remove constrained pairs with collideConnected == false + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + var c = constraints[i]; + if(!c.collideConnected){ + for(var j = p1.length-1; j>=0; j-=1){ + if( (c.bodyA === p1[j] && c.bodyB === p2[j]) || + (c.bodyB === p1[j] && c.bodyA === p2[j])){ + p1.splice(j, 1); + p2.splice(j, 1); + } + } + } + } + + this.collisionMatrixTick(); + + // Generate contacts + if(doProfiling){ profilingStart = performance.now(); } + var oldcontacts = World_step_oldContacts; + var NoldContacts = contacts.length; + + for(i=0; i!==NoldContacts; i++){ + oldcontacts.push(contacts[i]); + } + contacts.length = 0; + + this.narrowphase.getContacts(p1,p2, + this, + contacts, + oldcontacts // To be reused + ); + if(doProfiling){ + profile.narrowphase = performance.now() - profilingStart; + } + + // Loop over all collisions + if(doProfiling){ + profilingStart = performance.now(); + } + var ncontacts = contacts.length; + + // Transfer FrictionEquation from current list to the pool for reuse + var NoldFrictionEquations = this.frictionEquations.length; + for(i=0; i!==NoldFrictionEquations; i++){ + frictionEquationPool.push(this.frictionEquations[i]); + } + this.frictionEquations.length = 0; + + for(var k=0; k!==ncontacts; k++){ + + // Current contact + var c = contacts[k]; + + // Get current collision indeces + var bi = c.bi, + bj = c.bj, + si = c.si, + sj = c.sj; + + // Resolve indices + var i = bodies.indexOf(bi), j = bodies.indexOf(bj); + + // Get collision properties + var cm; + if(bi.material && bj.material){ + cm = this.getContactMaterial(bi.material,bj.material) || this.defaultContactMaterial; + } else { + cm = this.defaultContactMaterial; + } + var mu = cm.friction; + + // g = ( xj + rj - xi - ri ) .dot ( ni ) + var gvec = World_step_gvec; + gvec.set(bj.position.x + c.rj.x - bi.position.x - c.ri.x, + bj.position.y + c.rj.y - bi.position.y - c.ri.y, + bj.position.z + c.rj.z - bi.position.z - c.ri.z); + var g = gvec.dot(c.ni); // Gap, negative if penetration + + // Action if penetration + if(g < 0.0){ + + c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse; + + c.restitution = cm.restitution; + c.penetration = g; + c.setSpookParams(cm.contactEquationStiffness, + cm.contactEquationRelaxation, + dt); + + solver.addEquation(c); + + // Add friction constraint equation + if(mu > 0){ + + // Create 2 tangent equations + var mug = mu*gnorm; + var reducedMass = (bi.invMass + bj.invMass); + if(reducedMass > 0){ + reducedMass = 1/reducedMass; + } + var pool = frictionEquationPool; + var c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass); + var c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass); + this.frictionEquations.push(c1); + this.frictionEquations.push(c2); + + c1.bi = c2.bi = bi; + c1.bj = c2.bj = bj; + c1.minForce = c2.minForce = -mug*reducedMass; + c1.maxForce = c2.maxForce = mug*reducedMass; + + // Copy over the relative vectors + c1.ri.copy(c.ri); + c1.rj.copy(c.rj); + c2.ri.copy(c.ri); + c2.rj.copy(c.rj); + + // Construct tangents + c.ni.tangents(c1.t, c2.t); + + // Set spook params + c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt); + c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt); + + c1.enabled = c2.enabled = c.enabled; + + // Add equations to solver + solver.addEquation(c1); + solver.addEquation(c2); + } + + if( bi.allowSleep && + bi.type === Body.DYNAMIC && + bi.sleepState === Body.SLEEPING && + bj.sleepState === Body.AWAKE && + bj.type !== Body.STATIC + ){ + var speedSquaredB = bj.velocity.norm2() + bj.angularVelocity.norm2(); + var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); + if(speedSquaredB >= speedLimitSquaredB*2){ + bi._wakeUpAfterNarrowphase = true; + } + } + + if( bj.allowSleep && + bj.type === Body.DYNAMIC && + bj.sleepState === Body.SLEEPING && + bi.sleepState === Body.AWAKE && + bi.type !== Body.STATIC + ){ + var speedSquaredA = bi.velocity.norm2() + bi.angularVelocity.norm2(); + var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2); + if(speedSquaredA >= speedLimitSquaredA*2){ + bj._wakeUpAfterNarrowphase = true; + } + } + + // Now we know that i and j are in contact. Set collision matrix state + this.collisionMatrix.set(bi, bj, true); + + if (this.collisionMatrix.get(bi, bj) !== this.collisionMatrixPrevious.get(bi, bj)) { + // First contact! + // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached. + World_step_collideEvent.body = bj; + World_step_collideEvent.contact = c; + bi.dispatchEvent(World_step_collideEvent); + + World_step_collideEvent.body = bi; + bj.dispatchEvent(World_step_collideEvent); + + /* + bi.wakeUp(); + bj.wakeUp(); + */ + } + } + } + if(doProfiling){ + profile.makeContactConstraints = performance.now() - profilingStart; + profilingStart = performance.now(); + } + + // Wake up bodies + for(i=0; i!==N; i++){ + var bi = bodies[i]; + if(bi._wakeUpAfterNarrowphase){ + bi.wakeUp(); + bi._wakeUpAfterNarrowphase = false; + } + } + + // Add user-added constraints + var Nconstraints = constraints.length; + for(i=0; i!==Nconstraints; i++){ + var c = constraints[i]; + c.update(); + for(var j=0, Neq=c.equations.length; j!==Neq; j++){ + var eq = c.equations[j]; + solver.addEquation(eq); + } + } + + // Solve the constrained system + solver.solve(dt,this); + + if(doProfiling){ + profile.solve = performance.now() - profilingStart; + } + + // Remove all contacts from solver + solver.removeAllEquations(); + + // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details + var pow = Math.pow; + for(i=0; i!==N; i++){ + var bi = bodies[i]; + if(bi.type & DYNAMIC){ // Only for dynamic bodies + var ld = pow(1.0 - bi.linearDamping,dt); + var v = bi.velocity; + v.mult(ld,v); + var av = bi.angularVelocity; + if(av){ + var ad = pow(1.0 - bi.angularDamping,dt); + av.mult(ad,av); + } + } + } + + this.dispatchEvent(World_step_preStepEvent); + + // Invoke pre-step callbacks + for(i=0; i!==N; i++){ + var bi = bodies[i]; + if(bi.preStep){ + bi.preStep.call(bi); + } + } + + // Leap frog + // vnew = v + h*f/m + // xnew = x + h*vnew + if(doProfiling){ + profilingStart = performance.now(); + } + var q = World_step_step_q; + var w = World_step_step_w; + var wq = World_step_step_wq; + var stepnumber = this.stepnumber; + var DYNAMIC_OR_KINEMATIC = Body.DYNAMIC | Body.KINEMATIC; + var quatNormalize = stepnumber % (this.quatNormalizeSkip+1) === 0; + var quatNormalizeFast = this.quatNormalizeFast; + var half_dt = dt * 0.5; + var PLANE = Shape.types.PLANE, + CONVEX = Shape.types.CONVEXPOLYHEDRON; + + for(i=0; i!==N; i++){ + var b = bodies[i], + s = b.shape, + force = b.force, + tau = b.torque; + if((b.type & DYNAMIC_OR_KINEMATIC) && b.sleepState !== Body.SLEEPING){ // Only for dynamic + var velo = b.velocity, + angularVelo = b.angularVelocity, + pos = b.position, + quat = b.quaternion, + invMass = b.invMass, + invInertia = b.invInertiaWorld; + + velo.x += force.x * invMass * dt; + velo.y += force.y * invMass * dt; + velo.z += force.z * invMass * dt; + + if(b.angularVelocity){ + invInertia.vmult(tau,invI_tau_dt); + invI_tau_dt.mult(dt,invI_tau_dt); + invI_tau_dt.vadd(angularVelo,angularVelo); + //console.log(invI_tau_dt); + /* + angularVelo.x += tau.x * invInertia.x * dt; + angularVelo.y += tau.y * invInertia.y * dt; + angularVelo.z += tau.z * invInertia.z * dt; + */ + } + + // Use new velocity - leap frog + pos.x += velo.x * dt; + pos.y += velo.y * dt; + pos.z += velo.z * dt; + + if(b.angularVelocity){ + w.set(angularVelo.x, angularVelo.y, angularVelo.z, 0); + w.mult(quat,wq); + quat.x += half_dt * wq.x; + quat.y += half_dt * wq.y; + quat.z += half_dt * wq.z; + quat.w += half_dt * wq.w; + if(quatNormalize){ + if(quatNormalizeFast){ + quat.normalizeFast(); + } else { + quat.normalize(); + } + } + } + + if(b.aabb){ + b.aabbNeedsUpdate = true; + } + + if(s){ + switch(s.type){ + case PLANE: + s.worldNormalNeedsUpdate = true; + break; + case CONVEX: + s.worldFaceNormalsNeedsUpdate = true; + s.worldVerticesNeedsUpdate = true; + break; + } + } + + // Update world inertia + if(b.updateInertiaWorld){ + b.updateInertiaWorld(); + } + } + b.force.set(0,0,0); + if(b.torque){ + b.torque.set(0,0,0); + } + + } + + this.broadphase.dirty = true; + + if(doProfiling){ + profile.integrate = performance.now() - profilingStart; + } + + // Update world time + this.time += dt; + this.stepnumber += 1; + + this.dispatchEvent(World_step_postStepEvent); + + // Invoke post-step callbacks + for(i=0; i!==N; i++){ + var bi = bodies[i]; + var postStep = bi.postStep; + if(postStep){ + postStep.call(bi); + } + } + + // Sleeping update + if(this.allowSleep){ + for(i=0; i!==N; i++){ + bodies[i].sleepTick(this.time); + } + } +}; + +},{"../collision/AABB":3,"../collision/ArrayCollisionMatrix":4,"../collision/NaiveBroadphase":7,"../collision/Ray":9,"../collision/RaycastResult":10,"../equations/ContactEquation":16,"../equations/FrictionEquation":18,"../material/ContactMaterial":21,"../material/Material":22,"../math/Quaternion":25,"../math/Vec3":27,"../objects/Body":28,"../shapes/Shape":40,"../solver/GSSolver":42,"../utils/EventTarget":45,"../utils/TupleDictionary":47,"../utils/Vec3Pool":49,"./Narrowphase":50}]},{},[2]) +(2) +}); \ No newline at end of file diff --git a/ajax/libs/cannon.js/0.6.1/cannon.min.js b/ajax/libs/cannon.js/0.6.1/cannon.min.js new file mode 100644 index 000000000..2dd2d2e3c --- /dev/null +++ b/ajax/libs/cannon.js/0.6.1/cannon.min.js @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2014 cannon.js Authors + * + * 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(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&false)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.CANNON=e()}}(function(){return function e(f,n,o){function d(t,l){if(!n[t]){if(!f[t]){var u="function"==typeof require&&require;if(!l&&u)return u(t,!0);if(i)return i(t,!0);throw new Error("Cannot find module '"+t+"'")}var p=n[t]={exports:{}};f[t][0].call(p.exports,function(e){var n=f[t][1][e];return d(n?n:e)},p,p.exports,e,f,n,o)}return n[t].exports}for(var i="function"==typeof require&&require,t=0;t (http://steffe.se)",keywords:["cannon.js","cannon","physics","engine","3d"],main:"./build/cannon.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/cannon.js.git"},bugs:{url:"https://github.com/schteppe/cannon.js/issues"},licenses:[{type:"MIT"}],devDependencies:{jshint:"latest","uglify-js":"latest",nodeunit:"^0.9.0",grunt:"~0.4.0","grunt-contrib-jshint":"~0.1.1","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-concat":"~0.1.3","grunt-contrib-uglify":"^0.5.1","grunt-browserify":"^2.1.4","grunt-contrib-yuidoc":"^0.5.2",browserify:"*"},dependencies:{}}},{}],2:[function(e,f){f.exports={version:e("../package.json").version,ArrayCollisionMatrix:e("./collision/ArrayCollisionMatrix"),Body:e("./objects/Body"),Box:e("./shapes/Box"),Broadphase:e("./collision/Broadphase"),Constraint:e("./constraints/Constraint"),ContactEquation:e("./equations/ContactEquation"),Narrowphase:e("./world/Narrowphase"),ContactMaterial:e("./material/ContactMaterial"),ConvexPolyhedron:e("./shapes/ConvexPolyhedron"),Cylinder:e("./shapes/Cylinder"),DistanceConstraint:e("./constraints/DistanceConstraint"),Equation:e("./equations/Equation"),EventTarget:e("./utils/EventTarget"),FrictionEquation:e("./equations/FrictionEquation"),GSSolver:e("./solver/GSSolver"),GridBroadphase:e("./collision/GridBroadphase"),Heightfield:e("./shapes/Heightfield"),HingeConstraint:e("./constraints/HingeConstraint"),Mat3:e("./math/Mat3"),Material:e("./material/Material"),NaiveBroadphase:e("./collision/NaiveBroadphase"),ObjectCollisionMatrix:e("./collision/ObjectCollisionMatrix"),Pool:e("./utils/Pool"),Particle:e("./shapes/Particle"),Plane:e("./shapes/Plane"),PointToPointConstraint:e("./constraints/PointToPointConstraint"),Quaternion:e("./math/Quaternion"),Ray:e("./collision/Ray"),RaycastVehicle:e("./objects/RaycastVehicle"),RaycastResult:e("./collision/RaycastResult"),RigidVehicle:e("./objects/RigidVehicle"),RotationalEquation:e("./equations/RotationalEquation"),RotationalMotorEquation:e("./equations/RotationalMotorEquation"),SAPBroadphase:e("./collision/SAPBroadphase"),SPHSystem:e("./objects/SPHSystem"),Shape:e("./shapes/Shape"),Solver:e("./solver/Solver"),Sphere:e("./shapes/Sphere"),SplitSolver:e("./solver/SplitSolver"),Spring:e("./objects/Spring"),Vec3:e("./math/Vec3"),Vec3Pool:e("./utils/Vec3Pool"),World:e("./world/World")}},{"../package.json":1,"./collision/ArrayCollisionMatrix":4,"./collision/Broadphase":5,"./collision/GridBroadphase":6,"./collision/NaiveBroadphase":7,"./collision/ObjectCollisionMatrix":8,"./collision/Ray":9,"./collision/RaycastResult":10,"./collision/SAPBroadphase":11,"./constraints/Constraint":12,"./constraints/DistanceConstraint":13,"./constraints/HingeConstraint":14,"./constraints/PointToPointConstraint":15,"./equations/ContactEquation":16,"./equations/Equation":17,"./equations/FrictionEquation":18,"./equations/RotationalEquation":19,"./equations/RotationalMotorEquation":20,"./material/ContactMaterial":21,"./material/Material":22,"./math/Mat3":24,"./math/Quaternion":25,"./math/Vec3":27,"./objects/Body":28,"./objects/RaycastVehicle":29,"./objects/RigidVehicle":30,"./objects/SPHSystem":31,"./objects/Spring":32,"./shapes/Box":34,"./shapes/ConvexPolyhedron":35,"./shapes/Cylinder":36,"./shapes/Heightfield":37,"./shapes/Particle":38,"./shapes/Plane":39,"./shapes/Shape":40,"./shapes/Sphere":41,"./solver/GSSolver":42,"./solver/Solver":43,"./solver/SplitSolver":44,"./utils/EventTarget":45,"./utils/Pool":46,"./utils/Vec3Pool":49,"./world/Narrowphase":50,"./world/World":51}],3:[function(e,f){function n(e){e=e||{},this.lowerBound=new o,e.lowerBound&&this.lowerBound.copy(e.lowerBound),this.upperBound=new o,e.upperBound&&this.upperBound.copy(e.upperBound)}{var o=e("../math/Vec3");e("../utils/Utils")}f.exports=n;var d=new o;n.prototype.setFromPoints=function(e,f,n,o){var i=this.lowerBound,t=this.upperBound,l=n;i.copy(e[0]),l&&l.vmult(i,i),t.copy(i);for(var u=1;ut.x&&(t.x=p.x),p.xt.y&&(t.y=p.y),p.yt.z&&(t.z=p.z),p.zf&&(this.lowerBound.x=f);var n=e.upperBound.x;this.upperBound.xf&&(this.lowerBound.y=f);var n=e.upperBound.y;this.upperBound.yf&&(this.lowerBound.z=f);var n=e.upperBound.z;this.upperBound.ze){var n=f;f=e,e=n}return this.matrix[(e*(e+1)>>1)+f-1]},n.prototype.set=function(e,f,n){if(e=e.index,f=f.index,f>e){var o=f;f=e,e=o}this.matrix[(e*(e+1)>>1)+f-1]=n?1:0},n.prototype.reset=function(){for(var e=0,f=this.matrix.length;e!==f;e++)this.matrix[e]=0},n.prototype.setNumObjects=function(e){this.matrix.length=e*(e-1)>>1}},{}],5:[function(e,f){function n(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}{var o=e("../objects/Body"),d=e("../math/Vec3"),i=e("../math/Quaternion");e("../shapes/Shape"),e("../shapes/Plane")}f.exports=n,n.prototype.collisionPairs=function(){throw new Error("collisionPairs not implemented for this BroadPhase class!")};var t=o.STATIC|o.KINEMATIC;n.prototype.needBroadphaseCollision=function(e,f){return 0===(e.collisionFilterGroup&f.collisionFilterMask)||0===(f.collisionFilterGroup&e.collisionFilterMask)?!1:0===(e.type&t)&&e.sleepState!==o.SLEEPING||0===(f.type&t)&&f.sleepState!==o.SLEEPING?!0:!1},n.prototype.intersectionTest=function(e,f,n,o){this.useBoundingBoxes?this.doBoundingBoxBroadphase(e,f,n,o):this.doBoundingSphereBroadphase(e,f,n,o)};{var l=new d;new d,new i,new d}n.prototype.doBoundingSphereBroadphase=function(e,f,n,o){var d=l;f.position.vsub(e.position,d);var i=Math.pow(e.boundingRadius+f.boundingRadius,2),t=d.norm2();i>t&&(n.push(e),o.push(f))},n.prototype.doBoundingBoxBroadphase=function(e,f,n,o){e.aabbNeedsUpdate&&e.computeAABB(),f.aabbNeedsUpdate&&f.computeAABB(),e.aabb.overlaps(f.aabb)&&(n.push(e),o.push(f))};var u={keys:[]},p=[],s=[];n.prototype.makePairsUnique=function(e,f){for(var n=u,o=p,d=s,i=e.length,t=0;t!==i;t++)o[t]=e[t],d[t]=f[t];e.length=0,f.length=0;for(var t=0;t!==i;t++){var l=o[t].id,y=d[t].id,c=y>l?l+","+y:y+","+l;n[c]=t,n.keys.push(c)}for(var t=0;t!==n.keys.length;t++){var c=n.keys.pop(),a=n[c];e.push(o[a]),f.push(d[a]),delete n[c]}},n.prototype.setWorld=function(){};var y=new d;n.boundingSphereCheck=function(e,f){var n=y;return e.position.vsub(f.position,n),Math.pow(e.shape.boundingSphereRadius+f.shape.boundingSphereRadius,2)>n.norm2()},n.prototype.aabbQuery=function(){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}},{"../math/Quaternion":25,"../math/Vec3":27,"../objects/Body":28,"../shapes/Plane":39,"../shapes/Shape":40}],6:[function(e,f){function n(e,f,n,i,t){o.apply(this),this.nx=n||10,this.ny=i||10,this.nz=t||10,this.aabbMin=e||new d(100,100,100),this.aabbMax=f||new d(-100,-100,-100);var l=this.nx*this.ny*this.nz;if(0>=l)throw"GridBroadphase: Each dimension's n must be >0";this.bins=[],this.binLengths=[],this.bins.length=l,this.binLengths.length=l;for(var u=0;l>u;u++)this.bins[u]=[],this.binLengths[u]=0}f.exports=n;var o=e("./Broadphase"),d=e("../math/Vec3"),i=e("../shapes/Shape");n.prototype=new o,n.prototype.constructor=n;{var t=new d;new d}n.prototype.collisionPairs=function(e,f,n){function o(e,f,n,o,d,i,t){var l=(e-g)*v|0,u=(f-x)*A|0,p=(n-j)*C|0,b=I((o-g)*v),m=I((d-x)*A),N=I((i-j)*C);0>l?l=0:l>=s&&(l=s-1),0>u?u=0:u>=y&&(u=y-1),0>p?p=0:p>=c&&(p=c-1),0>b?b=0:b>=s&&(b=s-1),0>m?m=0:m>=y&&(m=y-1),0>N?N=0:N>=c&&(N=c-1),l*=a,u*=r,p*=w,b*=a,m*=r,N*=w;for(var O=l;b>=O;O+=a)for(var h=u;m>=h;h+=r)for(var k=p;N>=k;k+=w){var q=O+h+k;E[q][F[q]++]=t}}for(var d=e.numObjects(),l=e.bodies,u=this.aabbMax,p=this.aabbMin,s=this.nx,y=this.ny,c=this.nz,a=y*c,r=c,w=1,b=u.x,m=u.y,N=u.z,g=p.x,x=p.y,j=p.z,v=s/(b-g),A=y/(m-x),C=c/(N-j),O=(b-g)/s,h=(m-x)/y,k=(N-j)/c,q=.5*Math.sqrt(O*O+h*h+k*k),z=i.types,B=z.SPHERE,D=z.PLANE,E=(z.BOX,z.COMPOUND,z.CONVEXPOLYHEDRON,this.bins),F=this.binLengths,G=this.bins.length,H=0;H!==G;H++)F[H]=0;for(var I=Math.ceil,p=Math.min,u=Math.max,H=0;H!==d;H++){var J=l[H],K=J.shape;switch(K.type){case B:var L=J.position.x,M=J.position.y,P=J.position.z,Q=K.radius;o(L-Q,M-Q,P-Q,L+Q,M+Q,P+Q,J);break;case D:K.worldNormalNeedsUpdate&&K.computeWorldNormal(J.quaternion);var R=K.worldNormal,S=g+.5*O-J.position.x,T=x+.5*h-J.position.y,U=j+.5*k-J.position.z,V=t;V.set(S,T,U);for(var W=0,X=0;W!==s;W++,X+=a,V.y=T,V.x+=O)for(var Y=0,Z=0;Y!==y;Y++,Z+=r,V.z=U,V.y+=h)for(var $=0,_=0;$!==c;$++,_+=w,V.z+=k)if(V.dot(R)1)for(var nf=E[H],W=0;W!==ff;W++)for(var J=nf[W],Y=0;Y!==W;Y++){var of=nf[Y];this.needBroadphaseCollision(J,of)&&this.intersectionTest(J,of,f,n)}}this.makePairsUnique(f,n)}},{"../math/Vec3":27,"../shapes/Shape":40,"./Broadphase":5}],7:[function(e,f){function n(){o.apply(this)}f.exports=n;var o=e("./Broadphase"),d=e("./AABB");n.prototype=new o,n.prototype.constructor=n,n.prototype.collisionPairs=function(e,f,n){var o,d,i,t,l=e.bodies,u=l.length;for(o=0;o!==u;o++)for(d=0;d!==o;d++)i=l[o],t=l[d],this.needBroadphaseCollision(i,t)&&this.intersectionTest(i,t,f,n)};new d;n.prototype.aabbQuery=function(e,f,n){n=n||[];for(var o=0;oe){var n=f;f=e,e=n}return e+"-"+f in this.matrix},n.prototype.set=function(e,f,n){if(e=e.id,f=f.id,f>e){var o=f;f=e,e=o}n?this.matrix[e+"-"+f]=!0:delete this.matrix[e+"-"+f]},n.prototype.reset=function(){this.matrix={}},n.prototype.setNumObjects=function(){}},{}],9:[function(e,f){function n(e,f){this.from=e?e.clone():new i,this.to=f?f.clone():new i,this._direction=new i,this.precision=1e-4,this.checkCollisionResponse=!0}function o(e,f,n,o){o.vsub(f,v),n.vsub(f,s),e.vsub(f,y);var d,i,t=v.dot(v),l=v.dot(s),u=v.dot(y),p=s.dot(s),c=s.dot(y);return(d=p*u-l*c)>=0&&(i=t*c-l*u)>=0&&t*p-l*l>d+i}function d(e,f,n){n.vsub(e,v);var o=v.dot(f);f.mult(o,A),A.vadd(e,A);var d=n.distanceTo(A);return d}f.exports=n;{var i=e("../math/Vec3"),t=e("../math/Quaternion"),l=e("../math/Transform"),u=(e("../shapes/ConvexPolyhedron"),e("../shapes/Box"),e("../collision/RaycastResult")),p=e("../shapes/Shape");e("../collision/AABB")}n.prototype.constructor=n;var s=new i,y=new i;n.prototype.intersectBody=function(e,f,n){var o=this.checkCollisionResponse;if(o&&!e.collisionResponse)return f;n||(this._updateDirection(),n=this._direction);for(var d=new i,l=new t,u=0;uo;o++)this.intersectBody(e[o],f,n)},n.prototype._updateDirection=function(){this.to.vsub(this.from,this._direction),this._direction.normalize()},n.prototype.intersectShape=function(e,f,n,o,i,t){var l=this.from,u=d(l,i,n);return u>e.boundingSphereRadius?t:(this[e.type](e,f,n,o,i,t),t)};var c=(new i,new i,new i),a=new i,r=new i,w=new i,b=(new i,new u);n.prototype.intersectBox=function(e,f,n,o,d,i){return this.intersectConvex(e.convexPolyhedronRepresentation,f,n,o,d,i)},n.prototype[p.types.BOX]=n.prototype.intersectBox,n.prototype.intersectPlane=function(e,f,n,o,d,t){var l=this.from,u=this.to,p=new i(0,0,1);f.vmult(p,p);var s=new i;l.vsub(n,s);var y=s.dot(p);u.vsub(n,s);var c=s.dot(p);if(y*c>0)return t;if(l.distanceTo(u)r)&&(r=y[0]),(null===a||y[1]w)&&(w=y[1])),null===c)return u;var N=[];e.getRectMinMax(c,a,r,w,N);for(var g=(N[0],N[1],c);r>=g;g++)for(var x=a;w>=x;x++)e.getConvexTrianglePillar(g,x,!1),l.pointToWorldFrame(o,f,e.pillarOffset,p),this.intersectConvex(e.pillarConvex,f,p,d,t,u,m),e.getConvexTrianglePillar(g,x,!0),l.pointToWorldFrame(o,f,e.pillarOffset,p),this.intersectConvex(e.pillarConvex,f,p,d,t,u,m);return u},n.prototype[p.types.HEIGHTFIELD]=n.prototype.intersectHeightfield,n.prototype.intersectSphere=function(e,f,n,o,d,t){var l=this.from,u=this.to,p=e.radius,s=Math.pow(u.x-l.x,2)+Math.pow(u.y-l.y,2)+Math.pow(u.z-l.z,2),y=2*((u.x-l.x)*(l.x-n.x)+(u.y-l.y)*(l.y-n.y)+(u.z-l.z)*(l.z-n.z)),c=Math.pow(l.x-n.x,2)+Math.pow(l.y-n.y,2)+Math.pow(l.z-n.z,2)-Math.pow(p,2),a=Math.pow(y,2)-4*s*c;if(0>a)return t;if(0===a){var r=new i;l.lerp(u,a,r);var w=new i;if(r.vsub(n,w),w.normalize(),this.reportIntersection(w,r,e,o,t))return t}else{var b=(-y-Math.sqrt(a))/(2*s),m=(-y+Math.sqrt(a))/(2*s),r=new i;l.lerp(u,b,r);var w=new i;if(r.vsub(n,w),w.normalize(),this.reportIntersection(w,r,e,o,t))return t;l.lerp(u,m,r);var w=new i;if(r.vsub(n,w),w.normalize(),this.reportIntersection(w,r,e,o,t))return t}return t},n.prototype[p.types.SPHERE]=n.prototype.intersectSphere;var N=new i,g=new i,x=new i,j=new i;n.prototype.intersectConvex=function(e,f,n,d,i,t,l){for(var u=g,p=N,s=j,y=x,b=l&&l.faceList||null,m=e.faces,v=e.vertices,A=e.faceNormals,C=this.from,O=this.to,h=C.distanceTo(O),k=-1,q=b?b.length:m.length,z=0;q>z;z++){var B=b?b[z]:z,D=m[B],E=A[B],F=f,G=n;s.copy(v[D[0]]),F.vmult(s,s),s.vadd(G,s),s.vsub(C,s),F.vmult(E,p);var H=i.dot(p);if(!(Math.abs(H)I)&&0>H){i.mult(I,c),c.vadd(C,c),a.copy(v[D[0]]),F.vmult(a,a),G.vadd(a,a);for(var J=1;Jh||(-1===k||k>K)&&(k=K,u.copy(p),y.copy(c))}}}}return-1!==k&&this.reportIntersection(u,y,e,d,t)?t:t},n.prototype[p.types.CONVEXPOLYHEDRON]=n.prototype.intersectConvex,n.prototype.reportIntersection=function(e,f,n,o,d){var i=this.from,t=this.to,l=i.distanceTo(f);return d instanceof u?((lf;f++){for(var o=e[f],d=f-1;d>=0&&!(e[d].aabb.lowerBound.x<=o.aabb.lowerBound.x);d--)e[d+1]=e[d];e[d+1]=o}return e},n.insertionSortY=function(e){for(var f=1,n=e.length;n>f;f++){for(var o=e[f],d=f-1;d>=0&&!(e[d].aabb.lowerBound.y<=o.aabb.lowerBound.y);d--)e[d+1]=e[d];e[d+1]=o}return e},n.insertionSortZ=function(e){for(var f=1,n=e.length;n>f;f++){for(var o=e[f],d=f-1;d>=0&&!(e[d].aabb.lowerBound.z<=o.aabb.lowerBound.z);d--)e[d+1]=e[d];e[d+1]=o}return e},n.prototype.collisionPairs=function(e,f,o){var d,i,t=this.axisList,l=t.length,u=this.axisIndex;for(this.dirty&&(this.sortList(),this.dirty=!1),d=0;d!==l;d++){var p=t[d];for(i=d+1;l>i;i++){var s=t[i];if(this.needBroadphaseCollision(p,s)){if(!n.checkBounds(p,s,u))break;this.intersectionTest(p,s,f,o)}}}},n.prototype.sortList=function(){for(var e=this.axisList,f=this.axisIndex,o=e.length,d=0;d!==o;d++){var i=e[d];i.aabbNeedsUpdate&&i.computeAABB()}0===f?n.insertionSortX(e):1===f?n.insertionSortY(e):2===f&&n.insertionSortZ(e)},n.checkBounds=function(e,f,n){var o;0===n&&(o="x"),1===n&&(o="y"),2===n&&(o="z");var d=e.position[o],i=e.boundingRadius,t=f.position[o],l=f.boundingRadius,u=d+i,p=t-l;return u>p},n.prototype.autoDetectAxis=function(){for(var e=0,f=0,n=0,o=0,d=0,i=0,t=this.axisList,l=t.length,u=1/l,p=0;p!==l;p++){var s=t[p],y=s.position.x;e+=y,f+=y*y;var c=s.position.y;n+=c,o+=c*c;var a=s.position.z;d+=a,i+=a*a}var r=f-e*e*u,w=o-n*n*u,b=i-d*d*u;this.axisIndex=r>w?r>b?0:2:w>b?1:2},n.prototype.aabbQuery=function(e,f,n){n=n||[],this.dirty&&(this.sortList(),this.dirty=!1);var o=this.axisIndex,d="x";1===o&&(d="y"),2===o&&(d="z");for(var i=this.axisList,t=(f.lowerBound[d],f.upperBound[d],0);td;d++)for(var i=0;3>i;i++){for(var t=0,l=0;3>l;l++)t+=e.elements[d+3*l]*this.elements[l+3*i];o.elements[d+3*i]=t}return o},n.prototype.scale=function(e,f){f=f||new n;for(var o=this.elements,d=f.elements,i=0;3!==i;i++)d[3*i+0]=e.x*o[3*i+0],d[3*i+1]=e.y*o[3*i+1],d[3*i+2]=e.z*o[3*i+2];return f},n.prototype.solve=function(e,f){f=f||new o;for(var n=3,d=4,i=[],t=0;n*d>t;t++)i.push(0);var t,l;for(t=0;3>t;t++)for(l=0;3>l;l++)i[t+d*l]=this.elements[t+3*l];i[3]=e.x,i[7]=e.y,i[11]=e.z;var u,p,s=3,y=s,c=4;do{if(t=y-s,0===i[t+d*t])for(l=t+1;y>l;l++)if(0!==i[t+d*l]){u=c;do p=c-u,i[p+d*t]+=i[p+d*l];while(--u);break}if(0!==i[t+d*t])for(l=t+1;y>l;l++){var a=i[t+d*l]/i[t+d*t];u=c;do p=c-u,i[p+d*l]=t>=p?0:i[p+d*l]-i[p+d*t]*a;while(--u)}}while(--s);if(f.z=i[2*d+3]/i[2*d+2],f.y=(i[1*d+3]-i[1*d+2]*f.z)/i[1*d+1],f.x=(i[0*d+3]-i[0*d+2]*f.z-i[0*d+1]*f.y)/i[0*d+0],isNaN(f.x)||isNaN(f.y)||isNaN(f.z)||1/0===f.x||1/0===f.y||1/0===f.z)throw"Could not solve equation! Got x=["+f.toString()+"], b=["+e.toString()+"], A=["+this.toString()+"]";return f},n.prototype.e=function(e,f,n){return void 0===n?this.elements[f+3*e]:void(this.elements[f+3*e]=n)},n.prototype.copy=function(e){for(var f=0;fn;n++)e+=this.elements[n]+f;return e},n.prototype.reverse=function(e){e=e||new n;for(var f=3,o=6,d=[],i=0;f*o>i;i++)d.push(0);var i,t;for(i=0;3>i;i++)for(t=0;3>t;t++)d[i+o*t]=this.elements[i+3*t];d[3]=1,d[9]=0,d[15]=0,d[4]=0,d[10]=1,d[16]=0,d[5]=0,d[11]=0,d[17]=1;var l,u,p=3,s=p,y=o;do{if(i=s-p,0===d[i+o*i])for(t=i+1;s>t;t++)if(0!==d[i+o*t]){l=y;do u=y-l,d[u+o*i]+=d[u+o*t];while(--l);break}if(0!==d[i+o*i])for(t=i+1;s>t;t++){var c=d[i+o*t]/d[i+o*i];l=y;do u=y-l,d[u+o*t]=i>=u?0:d[u+o*t]-d[u+o*i]*c;while(--l)}}while(--p);i=2;do{t=i-1;do{var c=d[i+o*t]/d[i+o*i];l=o;do u=o-l,d[u+o*t]=d[u+o*t]-d[u+o*i]*c;while(--l)}while(t--)}while(--i);i=2;do{var c=1/d[i+o*i];l=o;do u=o-l,d[u+o*i]=d[u+o*i]*c;while(--l)}while(i--);i=2;do{t=2;do{if(u=d[f+t+o*i],isNaN(u)||1/0===u)throw"Could not reverse! A=["+this.toString()+"]";e.e(i,t,u)}while(t--)}while(i--);return e},n.prototype.setRotationFromQuaternion=function(e){var f=e.x,n=e.y,o=e.z,d=e.w,i=f+f,t=n+n,l=o+o,u=f*i,p=f*t,s=f*l,y=n*t,c=n*l,a=o*l,r=d*i,w=d*t,b=d*l,m=this.elements;return m[0]=1-(y+a),m[1]=p-b,m[2]=s+w,m[3]=p+b,m[4]=1-(u+a),m[5]=c-r,m[6]=s-w,m[7]=c+r,m[8]=1-(u+y),this},n.prototype.transpose=function(e){e=e||new n;for(var f=e.elements,o=this.elements,d=0;3!==d;d++)for(var i=0;3!==i;i++)f[3*d+i]=o[3*i+d];return e}},{"./Vec3":27}],25:[function(e,f){function n(e,f,n,o){this.x=void 0!==e?e:0,this.y=void 0!==f?f:0,this.z=void 0!==n?n:0,this.w=void 0!==o?o:1}f.exports=n;var o=e("./Vec3");n.prototype.set=function(e,f,n,o){this.x=e,this.y=f,this.z=n,this.w=o},n.prototype.toString=function(){return this.x+","+this.y+","+this.z+","+this.w},n.prototype.toArray=function(){return[this.x,this.y,this.z,this.w]},n.prototype.setFromAxisAngle=function(e,f){var n=Math.sin(.5*f);this.x=e.x*n,this.y=e.y*n,this.z=e.z*n,this.w=Math.cos(.5*f)},n.prototype.toAxisAngle=function(e){e=e||new o,this.normalize();var f=2*Math.acos(this.w),n=Math.sqrt(1-this.w*this.w);return.001>n?(e.x=this.x,e.y=this.y,e.z=this.z):(e.x=this.x/n,e.y=this.y/n,e.z=this.z/n),[e,f]};var d=new o,i=new o;n.prototype.setFromVectors=function(e,f){if(e.isAntiparallelTo(f)){var n=d,o=i;e.tangents(n,o),this.setFromAxisAngle(n,Math.PI)}else{var t=e.cross(f);this.x=t.x,this.y=t.y,this.z=t.z,this.w=Math.sqrt(Math.pow(e.norm(),2)*Math.pow(f.norm(),2))+e.dot(f),this.normalize()}};var t=new o,l=new o,u=new o;n.prototype.mult=function(e,f){f=f||new n;var o=this.w,d=t,i=l,p=u;return d.set(this.x,this.y,this.z),i.set(e.x,e.y,e.z),f.w=o*e.w-d.dot(i),d.cross(i,p),f.x=o*i.x+e.w*d.x+p.x,f.y=o*i.y+e.w*d.y+p.y,f.z=o*i.z+e.w*d.z+p.z,f},n.prototype.inverse=function(e){var f=this.x,o=this.y,d=this.z,i=this.w;e=e||new n,this.conjugate(e);var t=1/(f*f+o*o+d*d+i*i);return e.x*=t,e.y*=t,e.z*=t,e.w*=t,e},n.prototype.conjugate=function(e){return e=e||new n,e.x=-this.x,e.y=-this.y,e.z=-this.z,e.w=this.w,e},n.prototype.normalize=function(){var e=Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);0===e?(this.x=0,this.y=0,this.z=0,this.w=0):(e=1/e,this.x*=e,this.y*=e,this.z*=e,this.w*=e)},n.prototype.normalizeFast=function(){var e=(3-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2;0===e?(this.x=0,this.y=0,this.z=0,this.w=0):(this.x*=e,this.y*=e,this.z*=e,this.w*=e)},n.prototype.vmult=function(e,f){f=f||new o;var n=e.x,d=e.y,i=e.z,t=this.x,l=this.y,u=this.z,p=this.w,s=p*n+l*i-u*d,y=p*d+u*n-t*i,c=p*i+t*d-l*n,a=-t*n-l*d-u*i;return f.x=s*p+a*-t+y*-u-c*-l,f.y=y*p+a*-l+c*-t-s*-u,f.z=c*p+a*-u+s*-l-y*-t,f},n.prototype.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},n.prototype.toEuler=function(e,f){f=f||"YZX";var n,o,d,i=this.x,t=this.y,l=this.z,u=this.w;switch(f){case"YZX":var p=i*t+l*u;if(p>.499&&(n=2*Math.atan2(i,u),o=Math.PI/2,d=0),-.499>p&&(n=-2*Math.atan2(i,u),o=-Math.PI/2,d=0),isNaN(n)){var s=i*i,y=t*t,c=l*l;n=Math.atan2(2*t*u-2*i*l,1-2*y-2*c),o=Math.asin(2*p),d=Math.atan2(2*i*u-2*t*l,1-2*s-2*c)}break;default:throw new Error("Euler order "+f+" not supported yet.")}e.y=n,e.z=o,e.x=d},n.prototype.setFromEuler=function(e,f,n,o){o=o||"XYZ";var d=Math.cos(e/2),i=Math.cos(f/2),t=Math.cos(n/2),l=Math.sin(e/2),u=Math.sin(f/2),p=Math.sin(n/2);return"XYZ"===o?(this.x=l*i*t+d*u*p,this.y=d*u*t-l*i*p,this.z=d*i*p+l*u*t,this.w=d*i*t-l*u*p):"YXZ"===o?(this.x=l*i*t+d*u*p,this.y=d*u*t-l*i*p,this.z=d*i*p-l*u*t,this.w=d*i*t+l*u*p):"ZXY"===o?(this.x=l*i*t-d*u*p,this.y=d*u*t+l*i*p,this.z=d*i*p+l*u*t,this.w=d*i*t-l*u*p):"ZYX"===o?(this.x=l*i*t-d*u*p,this.y=d*u*t+l*i*p,this.z=d*i*p-l*u*t,this.w=d*i*t+l*u*p):"YZX"===o?(this.x=l*i*t+d*u*p,this.y=d*u*t+l*i*p,this.z=d*i*p-l*u*t,this.w=d*i*t-l*u*p):"XZY"===o&&(this.x=l*i*t-d*u*p,this.y=d*u*t-l*i*p,this.z=d*i*p+l*u*t,this.w=d*i*t+l*u*p),this},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)}},{"./Vec3":27}],26:[function(e,f){function n(){this.position=new o,this.quaternion=new d}var o=e("./Vec3"),d=e("./Quaternion");f.exports=n;var i=new d;n.pointToLocalFrame=function(e,f,n,d){var d=d||new o;return n.vsub(e,d),f.conjugate(i),i.vmult(d,d),d},n.pointToWorldFrame=function(e,f,n,d){var d=d||new o;return f.vmult(n,d),d.vadd(e,d),d},n.prototype.vectorToWorldFrame=function(e,f){var f=f||new o;return this.quaternion.vmult(e,f),f},n.vectorToLocalFrame=function(e,f,n,d){var d=d||new o;return f.w*=-1,f.vmult(n,d),f.w*=-1,d}},{"./Quaternion":25,"./Vec3":27}],27:[function(e,f){function n(e,f,n){this.x=e||0,this.y=f||0,this.z=n||0}f.exports=n;var o=e("./Mat3");n.ZERO=new n(0,0,0),n.prototype.cross=function(e,f){var o=e.x,d=e.y,i=e.z,t=this.x,l=this.y,u=this.z;return f=f||new n,f.x=l*i-u*d,f.y=u*o-t*i,f.z=t*d-l*o,f},n.prototype.set=function(e,f,n){return this.x=e,this.y=f,this.z=n,this},n.prototype.setZero=function(){this.x=this.y=this.z=0},n.prototype.vadd=function(e,f){return f?(f.x=e.x+this.x,f.y=e.y+this.y,f.z=e.z+this.z,void 0):new n(this.x+e.x,this.y+e.y,this.z+e.z)},n.prototype.vsub=function(e,f){return f?(f.x=this.x-e.x,f.y=this.y-e.y,f.z=this.z-e.z,void 0):new n(this.x-e.x,this.y-e.y,this.z-e.z)},n.prototype.crossmat=function(){return new o([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])},n.prototype.normalize=function(){var e=this.x,f=this.y,n=this.z,o=Math.sqrt(e*e+f*f+n*n);if(o>0){var d=1/o;this.x*=d,this.y*=d,this.z*=d}else this.x=0,this.y=0,this.z=0;return o},n.prototype.unit=function(e){e=e||new n;var f=this.x,o=this.y,d=this.z,i=Math.sqrt(f*f+o*o+d*d);return i>0?(i=1/i,e.x=f*i,e.y=o*i,e.z=d*i):(e.x=1,e.y=0,e.z=0),e},n.prototype.norm=function(){var e=this.x,f=this.y,n=this.z;return Math.sqrt(e*e+f*f+n*n)},n.prototype.norm2=function(){return this.dot(this)},n.prototype.distanceTo=function(e){var f=this.x,n=this.y,o=this.z,d=e.x,i=e.y,t=e.z;return Math.sqrt((d-f)*(d-f)+(i-n)*(i-n)+(t-o)*(t-o))},n.prototype.mult=function(e,f){f=f||new n;var o=this.x,d=this.y,i=this.z;return f.x=e*o,f.y=e*d,f.z=e*i,f},n.prototype.scale=n.prototype.mult,n.prototype.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z},n.prototype.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},n.prototype.negate=function(e){return e=e||new n,e.x=-this.x,e.y=-this.y,e.z=-this.z,e};var d=new n,i=new n;n.prototype.tangents=function(e,f){var n=this.norm();if(n>0){var o=d,t=1/n;o.set(this.x*t,this.y*t,this.z*t);var l=i;Math.abs(o.x)<.9?(l.set(1,0,0),o.cross(l,e)):(l.set(0,1,0),o.cross(l,e)),o.cross(e,f)}else e.set(1,0,0).normalize(),f.set(0,1,0).normalize()},n.prototype.toString=function(){return this.x+","+this.y+","+this.z},n.prototype.toArray=function(){return[this.x,this.y,this.z]},n.prototype.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},n.prototype.lerp=function(e,f,n){var o=this.x,d=this.y,i=this.z;n.x=o+(e.x-o)*f,n.y=d+(e.y-d)*f,n.z=i+(e.z-i)*f},n.prototype.almostEquals=function(e,f){return void 0===f&&(f=1e-6),Math.abs(this.x-e.x)>f||Math.abs(this.y-e.y)>f||Math.abs(this.z-e.z)>f?!1:!0},n.prototype.almostZero=function(e){return void 0===e&&(e=1e-6),Math.abs(this.x)>e||Math.abs(this.y)>e||Math.abs(this.z)>e?!1:!0};var t=new n;n.prototype.isAntiparallelTo=function(e,f){return this.negate(t),t.almostEquals(e,f)},n.prototype.clone=function(){return new n(this.x,this.y,this.z)}},{"./Mat3":24}],28:[function(e,f){function n(e){e=e||{},o.apply(this),this.id=n.idCounter++,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new d,this.collisionFilterGroup=1,this.collisionFilterMask=1,this.collisionResponse=!0,this.position=new d,e.position&&this.position.copy(e.position),this.previousPosition=new d,this.initPosition=new d,this.velocity=new d,e.velocity&&this.velocity.copy(e.velocity),this.initVelocity=new d,this.force=new d;var f="number"==typeof e.mass?e.mass:0;this.mass=f,this.invMass=f>0?1/f:0,this.material=e.material||null,this.linearDamping="number"==typeof e.linearDamping?e.linearDamping:.01,this.type=0>=f?n.STATIC:n.DYNAMIC,typeof e.type==typeof n.STATIC&&(this.type=e.type),this.allowSleep=!0,this.sleepState=0,this.sleepSpeedLimit=.1,this.sleepTimeLimit=1,this.timeLastSleepy=0,this._wakeUpAfterNarrowphase=!1,this.torque=new d,this.quaternion=new t,e.quaternion&&this.quaternion.copy(e.quaternion),this.initQuaternion=new t,this.angularVelocity=new d,e.angularVelocity&&this.angularVelocity.copy(e.angularVelocity),this.initAngularVelocity=new d,this.interpolatedPosition=new d,this.interpolatedQuaternion=new t,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new d,this.invInertia=new d,this.invInertiaWorld=new i,this.invMassSolve=0,this.invInertiaSolve=new d,this.invInertiaWorldSolve=new i,this.fixedRotation=!1,this.angularDamping=.01,this.aabb=new l,this.aabbNeedsUpdate=!0,this.wlambda=new d,this.updateMassProperties()}f.exports=n;var o=e("../utils/EventTarget"),d=(e("../shapes/Shape"),e("../math/Vec3")),i=e("../math/Mat3"),t=e("../math/Quaternion"),l=(e("../material/Material"),e("../collision/AABB")),u=e("../shapes/Box");n.prototype=new o,n.prototype.constructor=n,n.DYNAMIC=1,n.STATIC=2,n.KINEMATIC=4,n.AWAKE=0,n.SLEEPY=1,n.SLEEPING=2,n.idCounter=0,n.prototype.wakeUp=function(){var e=this.sleepState;this.sleepState=0,e===n.SLEEPING&&this.dispatchEvent({type:"wakeup"})},n.prototype.sleep=function(){this.sleepState=n.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0)},n.sleepyEvent={type:"sleepy"},n.sleepEvent={type:"sleep"},n.prototype.sleepTick=function(e){if(this.allowSleep){var f=this.sleepState,o=this.velocity.norm2()+this.angularVelocity.norm2(),d=Math.pow(this.sleepSpeedLimit,2);f===n.AWAKE&&d>o?(this.sleepState=n.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(n.sleepyEvent)):f===n.SLEEPY&&o>d?this.wakeUp():f===n.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(n.sleepEvent))}},n.prototype.updateSolveMassProperties=function(){this.sleepState===n.SLEEPING||this.type===n.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))},n.prototype.pointToLocalFrame=function(e,f){var f=f||new d;return e.vsub(this.position,f),this.quaternion.conjugate().vmult(f,f),f},n.prototype.pointToWorldFrame=function(e,f){var f=f||new d;return this.quaternion.vmult(e,f),f.vadd(this.position,f),f},n.prototype.vectorToWorldFrame=function(e,f){var f=f||new d;return this.quaternion.vmult(e,f),f};var p=new d,s=new t;n.prototype.addShape=function(e,f,n){var o=new d,i=new t;f&&o.copy(f),n&&i.copy(n),this.shapes.push(e),this.shapeOffsets.push(o),this.shapeOrientations.push(i),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},n.prototype.updateBoundingRadius=function(){for(var e=this.shapes,f=this.shapeOffsets,n=e.length,o=0,d=0;d!==n;d++){var i=e[d];i.updateBoundingSphereRadius();var t=f[d].norm(),l=i.boundingSphereRadius;t+l>o&&(o=t+l)}this.boundingRadius=o};var y=new l;n.prototype.computeAABB=function(){for(var e=this.shapes,f=this.shapeOffsets,n=this.shapeOrientations,o=e.length,d=p,i=s,t=this.quaternion,l=this.aabb,u=y,c=0;c!==o;c++){var a=e[c];n[c].mult(t,i),i.vmult(f[c],d),d.vadd(this.position,d),a.calculateWorldAABB(d,i,u.lowerBound,u.upperBound),0===c?l.copy(u):l.extend(u)}this.aabbNeedsUpdate=!1};{var c=new i,a=new i;new i}n.prototype.updateInertiaWorld=function(e){var f=this.invInertia;if(f.x!==f.y||f.y!==f.z||e){var n=c,o=a;n.setRotationFromQuaternion(this.quaternion),n.transpose(o),n.scale(f,n),n.mmult(o,this.invInertiaWorld)}else;};var r=new d,w=new d;n.prototype.applyForce=function(e,f){if(this.type===n.DYNAMIC){var o=r;f.vsub(this.position,o);var d=w;o.cross(e,d),this.force.vadd(e,this.force),this.torque.vadd(d,this.torque)}};var b=new d,m=new d,N=new d;n.prototype.applyImpulse=function(e,f){if(this.type===n.DYNAMIC){var o=b;f.vsub(this.position,o);var d=m;d.copy(e),d.mult(this.invMass,d),this.velocity.vadd(d,this.velocity);var i=N;o.cross(e,i),this.invInertiaWorld.vmult(i,i),this.angularVelocity.vadd(i,this.angularVelocity)}},n.prototype.updateMassProperties=function(){new d;this.invMass=this.mass>0?1/this.mass:0;var e=this.inertia,f=this.fixedRotation;this.computeAABB(),u.calculateInertia(new d((this.aabb.upperBound.x-this.aabb.lowerBound.x)/2,(this.aabb.upperBound.y-this.aabb.lowerBound.y)/2,(this.aabb.upperBound.z-this.aabb.lowerBound.z)/2),this.mass,e),this.invInertia.set(e.x>0&&!f?1/e.x:0,e.y>0&&!f?1/e.y:0,e.z>0&&!f?1/e.z:0),this.updateInertiaWorld(!0)},n.prototype.getVelocityAtWorldPoint=function(e,f){var n=new d;return e.vsub(this.position,n),this.angularVelocity.cross(n,f),this.velocity.vadd(f,f),f}},{"../collision/AABB":3,"../material/Material":22,"../math/Mat3":24,"../math/Quaternion":25,"../math/Vec3":27,"../shapes/Box":34,"../shapes/Shape":40,"../utils/EventTarget":45}],29:[function(e,f){function n(e){this.chassisBody=e.chassisBody,this.wheelInfos=[],this.sliding=!1,this.world=null,this.indexRightAxis="undefined"!=typeof e.indexRightAxis?e.indexRightAxis:1,this.indexForwardAxis="undefined"!=typeof e.indexForwardAxis?e.indexForwardAxis:0,this.indexUpAxis="undefined"!=typeof e.indexUpAxis?e.indexUpAxis:2}function o(e,f,n,o,i){var t=0,l=n,u=x,p=j,s=v;e.getVelocityAtWorldPoint(l,u),f.getVelocityAtWorldPoint(l,p),u.vsub(p,s);var y=o.dot(s),c=d(e,n,o),a=d(f,n,o),r=1,w=r/(c+a);return t=-y*w,t>i&&(t=i),-i>t&&(t=-i),t}function d(e,f,n){var o=A,d=C,i=O,t=h;return f.vsub(e.position,o),o.cross(n,d),e.invInertiaWorld.vmult(d,t),t.cross(o,i),e.invMass+n.dot(i)}function i(e,f,n,o,d,i){var t=d.norm2();if(t>1.1)return 0;var l=k,u=q,p=z;e.getVelocityAtWorldPoint(f,l),n.getVelocityAtWorldPoint(o,u),l.vsub(u,p);var s=d.dot(p),y=.2,c=1/(e.invMass+n.invMass),i=-y*s*c;return i}var t=(e("./Body"),e("../math/Vec3")),l=e("../math/Quaternion"),u=(e("../collision/RaycastResult"),e("../collision/Ray")),p=e("../objects/WheelInfo");f.exports=n;{var s=(new t,new t,new t,new t),y=new t,c=new t;new u}n.prototype.addWheel=function(e){e=e||{};var f=new p(e),n=this.wheelInfos.length;return this.wheelInfos.push(f),n},n.prototype.setSteeringValue=function(e,f){var n=this.wheelInfos[f];n.steering=e};new t;n.prototype.applyEngineForce=function(e,f){this.wheelInfos[f].engineForce=e},n.prototype.setBrake=function(e,f){this.wheelInfos[f].brake=e},n.prototype.addToWorld=function(e){this.constraints;e.add(this.chassisBody);var f=this;e.addEventListener("preStep",function(){f.updateVehicle(e.dt)}),this.world=e},n.prototype.getVehicleAxisWorld=function(e,f){f.set(0===e?1:0,1===e?1:0,2===e?1:0),this.chassisBody.vectorToWorldFrame(f,f)},n.prototype.updateVehicle=function(e){for(var f=this.wheelInfos,n=f.length,o=this.chassisBody,d=0;n>d;d++)this.updateWheelTransform(d,!1);this.currentVehicleSpeedKmHour=3.6*o.velocity.norm();var i=new t;this.getVehicleAxisWorld(this.indexForwardAxis,i),i.dot(o.velocity)<0&&(this.currentVehicleSpeedKmHour*=-1);for(var d=0;n>d;d++)this.castRay(f[d]);this.updateSuspension(e);for(var l=new t,u=new t,d=0;n>d;d++){var p=f[d],s=p.suspensionForce;s>p.maxSuspensionForce&&(s=p.maxSuspensionForce),p.raycastResult.hitNormalWorld.scale(s*e,l),p.raycastResult.hitPointWorld.vsub(o.position,u),o.applyImpulse(l,p.raycastResult.hitPointWorld)}this.updateFriction(e);var y=new t,c=new t,a=new t;for(d=0;n>d;d++){var p=f[d];o.getVelocityAtWorldPoint(p.chassisConnectionPointWorld,a);var r=1;switch(this.indexUpAxis){case 1:r=-1}if(p.isInContact){this.getVehicleAxisWorld(this.indexForwardAxis,c);var w=c.dot(p.raycastResult.hitNormalWorld);p.raycastResult.hitNormalWorld.scale(w,y),c.vsub(y,c);var b=c.dot(a);p.deltaRotation=r*b*e/p.radius}!p.sliding&&p.isInContact||0===p.engineForce||!p.useCustomSlidingRotationalSpeed||(p.deltaRotation=(p.engineForce>0?1:-1)*p.customSlidingRotationalSpeed*e),Math.abs(p.brake)>Math.abs(p.engineForce)&&(p.deltaRotation=0),p.rotation+=p.deltaRotation,p.deltaRotation*=.99}},n.prototype.updateSuspension=function(){for(var e=this.chassisBody,f=e.mass,n=this.wheelInfos,o=n.length,d=0;o>d;d++){var i=n[d];if(i.isInContact){var t,l=i.suspensionRestLength,u=i.suspensionLength,p=l-u;t=i.suspensionStiffness*p*i.clippedInvContactDotSuspension;var s,y=i.suspensionRelativeVelocity;s=0>y?i.dampingCompression:i.dampingRelaxation,t-=s*y,i.suspensionForce=t*f,i.suspensionForce<0&&(i.suspensionForce=0)}else i.suspensionForce=0}},n.prototype.removeFromWorld=function(e){this.constraints;e.remove(this.chassisBody),e.removeEventListener("preStep",this.updateVehicle),this.world=null};var a=new t,r=new t;n.prototype.castRay=function(e){var f=a,n=r;this.updateWheelTransformWorld(e);var o=this.chassisBody,d=-1,i=e.suspensionRestLength+e.radius;e.directionWorld.scale(i,f);var l=e.chassisConnectionPointWorld;l.vadd(f,n);var u=e.raycastResult;u.reset();var p=o.collisionResponse;o.collisionResponse=!1,this.world.rayTest(l,n,u),o.collisionResponse=p;var s=u.body;if(e.raycastResult.groundObject=0,s){d=u.distance,e.raycastResult.hitNormalWorld=u.hitNormalWorld,e.isInContact=!0;var y=u.distance;e.suspensionLength=y-e.radius;var c=e.suspensionRestLength-e.maxSuspensionTravel,w=e.suspensionRestLength+e.maxSuspensionTravel;e.suspensionLengthw&&(e.suspensionLength=w,e.raycastResult.reset());var b=e.raycastResult.hitNormalWorld.dot(e.directionWorld),m=new t;o.getVelocityAtWorldPoint(e.raycastResult.hitPointWorld,m);var N=e.raycastResult.hitNormalWorld.dot(m);if(b>=-.1)e.suspensionRelativeVelocity=0,e.clippedInvContactDotSuspension=10;else{var g=-1/b;e.suspensionRelativeVelocity=N*g,e.clippedInvContactDotSuspension=g}}else e.suspensionLength=e.suspensionRestLength+0*e.maxSuspensionTravel,e.suspensionRelativeVelocity=0,e.directionWorld.scale(-1,e.raycastResult.hitNormalWorld),e.clippedInvContactDotSuspension=1;return d},n.prototype.updateWheelTransformWorld=function(e){e.isInContact=!1;var f=this.chassisBody;f.pointToWorldFrame(e.chassisConnectionPointLocal,e.chassisConnectionPointWorld),f.vectorToWorldFrame(e.directionLocal,e.directionWorld),f.vectorToWorldFrame(e.axleLocal,e.axleWorld)},n.prototype.updateWheelTransform=function(e){var f=s,n=y,o=c,d=this.wheelInfos[e];this.updateWheelTransformWorld(d),d.directionLocal.scale(-1,f),n.copy(d.axleLocal),f.cross(n,o),o.normalize(),n.normalize();var i=d.steering,t=new l;t.setFromAxisAngle(f,i);var u=new l;u.setFromAxisAngle(n,d.rotation);var p=d.worldTransform.quaternion;this.chassisBody.quaternion.mult(t,p),p.mult(u,p),p.normalize();var a=d.worldTransform.position;a.copy(d.directionWorld),a.scale(d.suspensionLength,a),a.vadd(d.chassisConnectionPointWorld,a)};var w=[new t(1,0,0),new t(0,1,0),new t(0,0,1)];n.prototype.getWheelTransformWorld=function(e){return this.wheelInfos[e].worldTransform};var b=new t,m=[],N=[],g=1;n.prototype.updateFriction=function(e){for(var f=b,n=this.wheelInfos,d=n.length,l=this.chassisBody,u=N,p=m,s=0,y=0;d>y;y++){var c=n[y],a=c.raycastResult.body;a&&s++,c.sideImpulse=0,c.forwardImpulse=0,u[y]||(u[y]=new t),p[y]||(p[y]=new t)}for(var y=0;d>y;y++){var c=n[y],a=c.raycastResult.body;if(a){var r=p[y],x=this.getWheelTransformWorld(y);x.vectorToWorldFrame(w[this.indexRightAxis],r);var j=c.raycastResult.hitNormalWorld,v=r.dot(j);j.scale(v,f),r.vsub(f,r),r.normalize(),j.cross(r,u[y]),u[y].normalize(),c.sideImpulse=i(l,c.raycastResult.hitPointWorld,a,c.raycastResult.hitPointWorld,r),c.sideImpulse*=g}}var A=1,C=.5;this.sliding=!1;for(var y=0;d>y;y++){var c=n[y],a=c.raycastResult.body,O=0;if(c.slipInfo=1,a){var h=0,k=c.brake?c.brake:h;O=o(l,a,c.raycastResult.hitPointWorld,u[y],k),O+=c.engineForce*e;var q=k/O;c.slipInfo*=q}if(c.forwardImpulse=0,c.skidInfo=1,a){c.skidInfo=1;var z=c.suspensionForce*e*c.frictionSlip,B=z,D=z*B;c.forwardImpulse=O;var E=c.forwardImpulse*C,F=c.sideImpulse*A,G=E*E+F*F;if(c.sliding=!1,G>D){this.sliding=!0,c.sliding=!0;var q=z/Math.sqrt(G);c.skidInfo*=q}}}if(this.sliding)for(var y=0;d>y;y++){var c=n[y];0!==c.sideImpulse&&c.skidInfo<1&&(c.forwardImpulse*=c.skidInfo,c.sideImpulse*=c.skidInfo)}for(var y=0;d>y;y++){var c=n[y],H=new t;if(H.copy(c.raycastResult.hitPointWorld),0!==c.forwardImpulse){var I=new t;u[y].scale(c.forwardImpulse,I),l.applyImpulse(I,H)}if(0!==c.sideImpulse){var a=c.raycastResult.body,J=new t;J.copy(c.raycastResult.hitPointWorld);var K=new t;p[y].scale(c.sideImpulse,K),l.pointToLocalFrame(H,H),H["xyz"[this.indexUpAxis]]*=c.rollInfluence,l.pointToWorldFrame(H,H),l.applyImpulse(K,H),K.scale(-1,K),a.applyImpulse(K,J)}}};var x=new t,j=new t,v=new t,A=new t,C=new t,O=new t,h=new t,k=new t,q=new t,z=new t},{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":25,"../math/Vec3":27,"../objects/WheelInfo":33,"./Body":28}],30:[function(e,f){function n(e){if(this.wheelBodies=[],this.coordinateSystem="undefined"==typeof e.coordinateSystem?new t(1,2,3):e.coordinateSystem.clone(),this.chassisBody=e.chassisBody,!this.chassisBody){var f=new i(new t(5,2,.5));this.chassisBody=new o(1,f)}this.constraints=[],this.wheelAxes=[],this.wheelForces=[]}var o=e("./Body"),d=e("../shapes/Sphere"),i=e("../shapes/Box"),t=e("../math/Vec3"),l=e("../constraints/HingeConstraint");f.exports=n,n.prototype.addWheel=function(e){e=e||{};var f=e.body;f||(f=new o(1,new d(1.2))),this.wheelBodies.push(f),this.wheelForces.push(0);var n=(new t,"undefined"!=typeof e.position?e.position.clone():new t),i=new t;this.chassisBody.pointToWorldFrame(n,i),f.position.set(i.x,i.y,i.z);var u="undefined"!=typeof e.axis?e.axis.clone():new t(0,1,0);this.wheelAxes.push(u);var p=new l(this.chassisBody,f,{pivotA:n,axisA:u,pivotB:t.ZERO,axisB:u,collideConnected:!1});return this.constraints.push(p),this.wheelBodies.length-1},n.prototype.setSteeringValue=function(e,f){var n=this.wheelAxes[f],o=Math.cos(e),d=Math.sin(e),i=n.x,t=n.y;this.constraints[f].axisA.set(o*i-d*t,d*i+o*t,0)},n.prototype.setMotorSpeed=function(e,f){var n=this.constraints[f];n.enableMotor(),n.motorTargetVelocity=e},n.prototype.disableMotor=function(e){var f=this.constraints[e];f.disableMotor()};var u=new t;n.prototype.setWheelForce=function(e,f){this.wheelForces[f]=e},n.prototype.applyWheelForce=function(e,f){var n=this.wheelAxes[f],o=this.wheelBodies[f],d=o.torque;n.scale(e,u),o.vectorToWorldFrame(u,u),d.vadd(u,d)},n.prototype.addToWorld=function(e){for(var f=this.constraints,n=this.wheelBodies.concat([this.chassisBody]),o=0;othis.particles.length&&this.neighbors.pop())};var d=new o;n.prototype.getNeighbors=function(e,f){for(var n=this.particles.length,o=e.id,i=this.smoothingRadius*this.smoothingRadius,t=d,l=0;l!==n;l++){var u=this.particles[l];u.position.vsub(e.position,t),o!==u.id&&t.norm2()=-.1)this.suspensionRelativeVelocity=0,this.clippedInvContactDotSuspension=10;else{var d=-1/n;this.suspensionRelativeVelocity=o*d,this.clippedInvContactDotSuspension=d}}else f.suspensionLength=this.suspensionRestLength,this.suspensionRelativeVelocity=0,f.directionWorld.scale(-1,f.hitNormalWorld),this.clippedInvContactDotSuspension=1}},{"../collision/RaycastResult":10,"../math/Transform":26,"../math/Vec3":27,"../utils/Utils":48}],34:[function(e,f){function n(e){o.call(this),this.type=o.types.BOX,this.halfExtents=e,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}f.exports=n;var o=e("./Shape"),d=e("../math/Vec3"),i=e("./ConvexPolyhedron");n.prototype=new o,n.prototype.constructor=n,n.prototype.updateConvexPolyhedronRepresentation=function(){var e=this.halfExtents.x,f=this.halfExtents.y,n=this.halfExtents.z,o=d,t=new i([new o(-e,-f,-n),new o(e,-f,-n),new o(e,f,-n),new o(-e,f,-n),new o(-e,-f,n),new o(e,-f,n),new o(e,f,n),new o(-e,f,n)],[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]],[new o(0,0,-1),new o(0,0,1),new o(0,-1,0),new o(0,1,0),new o(-1,0,0),new o(1,0,0)]);this.convexPolyhedronRepresentation=t},n.prototype.calculateLocalInertia=function(e,f){return f=f||new d,n.calculateInertia(this.halfExtents,e,f),f},n.calculateInertia=function(e,f,n){var o=e;n.x=1/12*f*(2*o.y*2*o.y+2*o.z*2*o.z),n.y=1/12*f*(2*o.x*2*o.x+2*o.z*2*o.z),n.z=1/12*f*(2*o.y*2*o.y+2*o.x*2*o.x)},n.prototype.getSideNormals=function(e,f){var n=e,o=this.halfExtents;if(n[0].set(o.x,0,0),n[1].set(0,o.y,0),n[2].set(0,0,o.z),n[3].set(-o.x,0,0),n[4].set(0,-o.y,0),n[5].set(0,0,-o.z),void 0!==f)for(var d=0;d!==n.length;d++)f.vmult(n[d],n[d]);return n},n.prototype.volume=function(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z},n.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.halfExtents.norm()};{var t=new d;new d}n.prototype.forEachWorldCorner=function(e,f,n){for(var o=this.halfExtents,d=[[o.x,o.y,o.z],[-o.x,o.y,o.z],[-o.x,-o.y,o.z],[-o.x,-o.y,-o.z],[o.x,-o.y,-o.z],[o.x,o.y,-o.z],[-o.x,o.y,-o.z],[o.x,-o.y,o.z]],i=0;it;t++){var i=l[t];f.vmult(i,i),e.vadd(i,i);var u=i.x,p=i.y,s=i.z;u>o.x&&(o.x=u),p>o.y&&(o.y=p),s>o.z&&(o.z=s),ui;i++){var t=f[i];if(!(t instanceof d))throw"Argument 1 must be instance of Vec3";this.uniqueEdges.push(t)}for(var l=0;ls;s++){var y=(s+1)%p,c=new d;f[u[s]].vsub(f[u[y]],c),c.normalize();for(var a=!1,t=0;tr&&(r=b,a=w)}for(var m=[],N=n.faces[a],g=N.length,x=0;g>x;x++){var j=n.vertices[N[x]],v=new d;v.copy(j),t.vmult(v,v),o.vadd(v,v),m.push(v)}a>=0&&this.clipFaceAgainstHull(l,e,f,m,u,s,y)};var s=new d,y=new d,c=new d,a=new d,r=new d,w=new d;n.prototype.findSeparatingAxis=function(e,f,n,o,d,i,t,l){for(var u=s,p=y,b=c,m=a,N=r,g=w,x=1/0,j=this,v=0,A=t?t.length:j.faces.length,C=0;A>C;C++){var O=t?t[C]:C;u.copy(j.faceNormals[O]),n.vmult(u,u);var h=j.testSepAxis(u,e,f,n,o,d);if(h===!1)return!1;x>h&&(x=h,i.copy(u))}for(var k=l?l.length:e.faces.length,C=0;k>C;C++){var O=l?l[C]:C;p.copy(e.faceNormals[O]),d.vmult(p,p),v++;var h=j.testSepAxis(p,e,f,n,o,d);if(h===!1)return!1;x>h&&(x=h,i.copy(p))}for(var q=0,z=0;zD&&(x=D,i.copy(g))}}return o.vsub(f,b),b.dot(i)>0&&i.negate(i),!0},n.prototype.testSepAxis=function(e,f,o,d,i,t){var l=[],u=[],p=this;n.project(p,e,o,d,l),n.project(f,e,i,t,u);var s=l[0],y=l[1],c=u[0],a=u[1];if(a>s||y>c)return!1;var r=s-a,w=c-y,b=w>r?r:w;return b};var b=new d,m=new d;n.prototype.calculateLocalInertia=function(e,f){this.computeLocalAABB(b,m);var n=m.x-b.x,o=m.y-b.y,d=m.z-b.z;f.x=1/12*e*(2*o*2*o+2*d*2*d),f.y=1/12*e*(2*n*2*n+2*d*2*d),f.z=1/12*e*(2*o*2*o+2*n*2*n)},n.prototype.getPlaneConstantOfFace=function(e){var f=this.faces[e],n=this.faceNormals[e],o=this.vertices[f[0]],d=-n.dot(o);return d};var N=new d,g=new d,x=new d,j=new d,v=new d,A=new d,C=new d,O=new d;n.prototype.clipFaceAgainstHull=function(e,f,n,o,i,t,l){if(!(e instanceof d))throw new Error("sep normal must be vector");if(!(o instanceof Array))throw new Error("world verts must be array");var u=N,p=g,s=x,y=j,c=v,a=A,r=C,w=O;i=Number(i),t=Number(t);for(var b=this,m=[],h=o,k=m,q=-1,z=1/0,B=0;BD&&(z=D,q=B)}if(0>q)return void console.log("--- did not find any closest face... ---");var E=b.faces[q];E.connectedFaces=[];for(var F=0;FI;I++){var J=b.vertices[E[I]],K=b.vertices[E[(I+1)%H]];J.vsub(K,p),s.copy(p),n.vmult(s,s),f.vadd(s,s),y.copy(this.faceNormals[q]),n.vmult(y,y),f.vadd(y,y),s.cross(y,c),c.negate(c),a.copy(J),n.vmult(a,a),f.vadd(a,a);var L,M=(-a.dot(c),E.connectedFaces[I]);r.copy(this.faceNormals[M]);var P=this.getPlaneConstantOfFace(M);w.copy(r),n.vmult(w,w);var L=P-w.dot(f);for(this.clipFaceAgainstPlane(h,k,w,L);h.length;)h.shift();for(;k.length;)h.push(k.shift())}r.copy(this.faceNormals[q]);var P=this.getPlaneConstantOfFace(q);w.copy(r),n.vmult(w,w);for(var L=P-w.dot(f),F=0;F=Q&&(console.log("clamped: depth="+Q+" to minDist="+(i+"")),Q=i),t>=Q){var R=h[F];if(0>=Q){var S={point:R,normal:w,depth:Q};l.push(S)}}}},n.prototype.clipFaceAgainstPlane=function(e,f,n,o){if(!(n instanceof d))throw new Error("planeNormal must be Vec3, "+n+" given");if(!(e instanceof Array))throw new Error("invertices must be Array, "+e+" given");if(!(f instanceof Array))throw new Error("outvertices must be Array, "+f+" given");var i,t,l=e.length;if(2>l)return f;var u=e[e.length-1],p=e[0];i=n.dot(u)+o;for(var s=0;l>s;s++){if(p=e[s],t=n.dot(p)+o,0>i)if(0>t){var y=new d;y.copy(p),f.push(y)}else{var y=new d;u.lerp(p,i/(i-t),y),f.push(y)}else if(0>t){var y=new d;u.lerp(p,i/(i-t),y),f.push(y),f.push(p)}u=p,i=t}return f},n.prototype.computeWorldVertices=function(e,f){for(var n=this.vertices.length;this.worldVertices.lengthd;d++){var i=o[d];i.xf.x&&(f.x=i.x),i.yf.y&&(f.y=i.y),i.zf.z&&(f.z=i.z)}},n.prototype.computeWorldFaceNormals=function(e){for(var f=this.faceNormals.length;this.worldFaceNormals.lengthe&&(e=d)}this.boundingSphereRadius=Math.sqrt(e)};var h=new d;n.prototype.calculateWorldAABB=function(e,f,n,o){for(var d,i,t,l,u,p,s=this.vertices.length,y=this.vertices,c=0;s>c;c++){h.copy(y[c]),f.vmult(h,h),e.vadd(h,h);var a=h;a.xl||void 0===l)&&(l=a.x),a.yu||void 0===u)&&(u=a.y),a.zp||void 0===p)&&(p=a.z)}n.set(d,i,t),o.set(l,u,p)},n.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},n.prototype.getAveragePointLocal=function(e){e=e||new d;for(var f=this.vertices.length,n=this.vertices,o=0;f>o;o++)e.vadd(n[o],e);return e.mult(1/f,e),e},n.prototype.transformAllPoints=function(e,f){var n=this.vertices.length,o=this.vertices;if(f){for(var d=0;n>d;d++){var i=o[d];f.vmult(i,i)}for(var d=0;dd;d++){var i=o[d];i.vadd(e,i)}};var k=new d,q=new d,z=new d;n.prototype.pointIsInside=function(e){var f=this.vertices.length,n=this.vertices,o=this.faces,d=this.faceNormals,i=null,t=this.faces.length,l=k;this.getAveragePointLocal(l);for(var u=0;t>u;u++){var f=(this.faces[u].length,d[u]),p=n[o[u][0]],s=q;e.vsub(p,s);var y=f.dot(s),c=z;l.vsub(p,c);var a=f.dot(c);if(0>y&&a>0||y>0&&0>a)return!1}return i?1:-1};var B=(new d,new d),D=new d;n.project=function(e,f,n,o,d){var i=e.vertices.length,l=B,u=0,p=0,s=D,y=e.vertices;s.setZero(),t.vectorToLocalFrame(n,o,f,l),t.pointToLocalFrame(n,o,s,s);var c=s.dot(l);p=u=y[0].dot(l);for(var a=1;i>a;a++){var r=y[a].dot(l);r>u&&(u=r),p>r&&(p=r)}if(p-=c,u-=c,p>u){var w=p;p=u,u=w}d[0]=u,d[1]=p}},{"../math/Quaternion":25,"../math/Transform":26,"../math/Vec3":27,"./Shape":40}],36:[function(e,f){function n(e,f,n,t){var l=t,u=[],p=[],s=[],y=[],c=[],a=Math.cos,r=Math.sin;u.push(new d(f*a(0),f*r(0),.5*-n)),y.push(0),u.push(new d(e*a(0),e*r(0),.5*n)),c.push(1);for(var w=0;l>w;w++){var b=2*Math.PI/l*(w+1),m=2*Math.PI/l*(w+.5);l-1>w?(u.push(new d(f*a(b),f*r(b),.5*-n)),y.push(2*w+2),u.push(new d(e*a(b),e*r(b),.5*n)),c.push(2*w+3),p.push(new d(a(m),r(m),0)),s.push([2*w+2,2*w+3,2*w+1,2*w])):(s.push([0,1,2*w+1,2*w]),p.push(new d(a(m),r(m),0)))}s.push(c),p.push(new d(0,0,1));for(var N=[],w=0;wd&&(f=d)}this.minValue=f},n.prototype.updateMaxValue=function(){for(var e=this.data,f=e[0][0],n=0;n!==e.length;n++)for(var o=0;o!==e[n].length;o++){var d=e[n][o];d>f&&(f=d)}this.maxValue=f},n.prototype.setHeightValueAtIndex=function(e,f,n){var o=this.data;o[e][f]=n,this.clearCachedConvexTrianglePillar(e,f,!1),e>0&&(this.clearCachedConvexTrianglePillar(e-1,f,!0),this.clearCachedConvexTrianglePillar(e-1,f,!1)),f>0&&(this.clearCachedConvexTrianglePillar(e,f-1,!0),this.clearCachedConvexTrianglePillar(e,f-1,!1)),f>0&&e>0&&this.clearCachedConvexTrianglePillar(e-1,f-1,!0)},n.prototype.getRectMinMax=function(e,f,n,o,d){d=d||[];for(var i=this.data,t=this.minValue,l=e;n>l;l++)for(var u=f;o>u;u++){var p=i[l][u];p>t&&(t=p)}d[0]=this.minValue,d[1]=t},n.prototype.getIndexOfPosition=function(e,f,n,o){var d=this.elementSize,i=this.data,t=Math.floor(e/d),l=Math.floor(f/d);return n[0]=t,n[1]=l,o&&(0>t&&(t=0),0>l&&(l=0),t>=i.length-1&&(t=i.length-1),l>=i[0].length-1&&(l=i[0].length-1)),0>t||0>l||t>=i.length-1||l>=i[0].length-1?!1:!0},n.prototype.getHeightAt=function(e,f,n){var o=[];this.getIndexOfPosition(e,f,o,n);var d=[];return this.getRectMinMax(o[0],o[1]+1,o[0],o[1]+1,d),(d[0]+d[1])/2},n.prototype.getCacheConvexTrianglePillarKey=function(e,f,n){return e+"_"+f+"_"+(n?1:0)},n.prototype.getCachedConvexTrianglePillar=function(e,f,n){return this._cachedPillars[this.getCacheConvexTrianglePillarKey(e,f,n)]},n.prototype.setCachedConvexTrianglePillar=function(e,f,n,o,d){this._cachedPillars[this.getCacheConvexTrianglePillarKey(e,f,n)]={convex:o,offset:d}},n.prototype.clearCachedConvexTrianglePillar=function(e,f,n){delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(e,f,n)]},n.prototype.getConvexTrianglePillar=function(e,f,n){var o=this.pillarConvex,t=this.pillarOffset;if(this.cacheEnabled){var l=this.getCachedConvexTrianglePillar(e,f,n);if(l)return this.pillarConvex=l.convex,void(this.pillarOffset=l.offset);o=new d,t=new i,this.pillarConvex=o,this.pillarOffset=t}var l=this.data,u=this.elementSize,p=o.faces;o.vertices.length=6;for(var s=0;6>s;s++)o.vertices[s]||(o.vertices[s]=new i);p.length=5;for(var s=0;5>s;s++)p[s]||(p[s]=[]);var y=o.vertices,c=(Math.min(l[e][f],l[e+1][f],l[e][f+1],l[e+1][f+1])-this.minValue)/2+this.minValue;n?(t.set((e+.75)*u,(f+.75)*u,c),y[0].set(.25*u,.25*u,l[e+1][f+1]-c),y[1].set(-.75*u,.25*u,l[e][f+1]-c),y[2].set(.25*u,-.75*u,l[e+1][f]-c),y[3].set(.25*u,.25*u,-c-1),y[4].set(-.75*u,.25*u,-c-1),y[5].set(.25*u,-.75*u,-c-1),p[0][0]=0,p[0][1]=1,p[0][2]=2,p[1][0]=5,p[1][1]=4,p[1][2]=3,p[2][0]=2,p[2][1]=5,p[2][2]=3,p[2][3]=0,p[3][0]=3,p[3][1]=4,p[3][2]=1,p[3][3]=0,p[4][0]=1,p[4][1]=4,p[4][2]=5,p[4][3]=2):(t.set((e+.25)*u,(f+.25)*u,c),y[0].set(-.25*u,-.25*u,l[e][f]-c),y[1].set(.75*u,-.25*u,l[e+1][f]-c),y[2].set(-.25*u,.75*u,l[e][f+1]-c),y[3].set(-.25*u,-.25*u,-c-1),y[4].set(.75*u,-.25*u,-c-1),y[5].set(-.25*u,.75*u,-c-1),p[0][0]=0,p[0][1]=1,p[0][2]=2,p[1][0]=5,p[1][1]=4,p[1][2]=3,p[2][0]=0,p[2][1]=2,p[2][2]=5,p[2][3]=3,p[3][0]=1,p[3][1]=0,p[3][2]=3,p[3][3]=4,p[4][0]=4,p[4][1]=5,p[4][2]=2,p[4][3]=1),o.computeNormals(),o.computeEdges(),o.updateBoundingSphereRadius(),this.setCachedConvexTrianglePillar(e,f,n,o,t)},n.prototype.calculateLocalInertia=function(e,f){return f=f||new i,f.set(0,0,0),f},n.prototype.volume=function(){return Number.MAX_VALUE},n.prototype.calculateWorldAABB=function(e,f,n,o){n.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),o.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},n.prototype.updateBoundingSphereRadius=function(){var e=this.data,f=this.elementSize;this.boundingSphereRadius=new i(e.length*f,e[0].length*f,Math.max(Math.abs(this.maxValue),Math.abs(this.minValue))).norm()}},{"../math/Vec3":27,"../utils/Utils":48,"./ConvexPolyhedron":35,"./Shape":40}],38:[function(e,f){function n(){o.call(this),this.type=o.types.PARTICLE}f.exports=n;var o=e("./Shape"),d=e("../math/Vec3");n.prototype=new o,n.prototype.constructor=n,n.prototype.calculateLocalInertia=function(e,f){return f=f||new d,f.set(0,0,0),f},n.prototype.volume=function(){return 0},n.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=0},n.prototype.calculateWorldAABB=function(e,f,n,o){n.copy(e),o.copy(e)}},{"../math/Vec3":27,"./Shape":40}],39:[function(e,f){function n(){o.call(this),this.type=o.types.PLANE,this.worldNormal=new d,this.worldNormalNeedsUpdate=!0,this.boundingSphereRadius=Number.MAX_VALUE}f.exports=n;var o=e("./Shape"),d=e("../math/Vec3");n.prototype=new o,n.prototype.constructor=n,n.prototype.computeWorldNormal=function(e){var f=this.worldNormal;f.set(0,0,1),e.vmult(f,f),this.worldNormalNeedsUpdate=!1},n.prototype.calculateLocalInertia=function(e,f){return f=f||new d},n.prototype.volume=function(){return Number.MAX_VALUE};var i=new d;n.prototype.calculateWorldAABB=function(e,f,n,o){i.set(0,0,1),f.vmult(i,i);var d=Number.MAX_VALUE;n.set(-d,-d,-d),o.set(d,d,d),1===i.x&&(o.x=e.x),1===i.y&&(o.y=e.y),1===i.z&&(o.z=e.z),-1===i.x&&(n.x=e.x),-1===i.y&&(n.y=e.y),-1===i.z&&(n.z=e.z)},n.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=Number.MAX_VALUE}},{"../math/Vec3":27,"./Shape":40}],40:[function(e,f){function n(){this.type=0,this.boundingSphereRadius=0,this.collisionResponse=!0}f.exports=n;{var n=e("./Shape");e("../math/Vec3"),e("../math/Quaternion"),e("../material/Material")}n.prototype.constructor=n,n.prototype.updateBoundingSphereRadius=function(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type},n.prototype.volume=function(){throw"volume() not implemented for shape type "+this.type},n.prototype.calculateLocalInertia=function(){throw"calculateLocalInertia() not implemented for shape type "+this.type},n.types={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128}},{"../material/Material":22,"../math/Quaternion":25,"../math/Vec3":27,"./Shape":40}],41:[function(e,f){function n(e){o.call(this),this.radius=void 0!==e?Number(e):1,this.type=o.types.SPHERE,this.updateBoundingSphereRadius()}f.exports=n;var o=e("./Shape"),d=e("../math/Vec3");n.prototype=new o,n.prototype.constructor=n,n.prototype.calculateLocalInertia=function(e,f){f=f||new d;var n=2*e*this.radius*this.radius/5;return f.x=n,f.y=n,f.z=n,f},n.prototype.volume=function(){return 4*Math.PI*this.radius/3},n.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.radius},n.prototype.calculateWorldAABB=function(e,f,n,o){for(var d=this.radius,i=["x","y","z"],t=0;tA.maxForce&&(l=A.maxForce-s),v[k]+=l,u+=l>0?l:-l,A.addToWlambda(l)}if(a>u*u)break}for(var g=0;g!==m;g++){var C=b[g],q=C.velocity,z=C.angularVelocity;q.vadd(C.vlambda,q),z&&z.vadd(C.wlambda,z)}}return y}},{"../math/Quaternion":25,"../math/Vec3":27,"./Solver":43}],43:[function(e,f){function n(){this.equations=[]}f.exports=n,n.prototype.solve=function(){return 0},n.prototype.addEquation=function(e){e.enabled&&this.equations.push(e)},n.prototype.removeEquation=function(e){var f=this.equations,n=f.indexOf(e);-1!==n&&f.splice(n,1)},n.prototype.removeAllEquations=function(){this.equations.length=0}},{}],44:[function(e,f){function n(e){o.call(this),this.subsolver=e}f.exports=n;var o=(e("../math/Vec3"),e("../math/Quaternion"),e("./Solver")),d=e("../objects/Body");n.prototype=new o;var i=[],t=[],l=[],u={bodies:null};n.prototype.solve=function(e,f){function n(e){for(var f=e.length,n=0;n!==f;n++){var o=e[n];if(!(o.visited||o.body.type&C))return o}return!1}function o(e,f){var o=[];for(o.push(e),e.visited=!0,f(e);o.length;)for(var d,i=o.pop();d=n(i.children);)d.visited=!0,f(d),o.push(d)}function p(e){k.push(e.body);for(var f=e.eqs.length,n=0;n!==f;n++){var o=e.eqs[n];-1===h.indexOf(o)&&h.push(o)}}var s=i,y=f.bodies,c=this.equations,a=c.length,r=y.length,w=this.subsolver;for(s.length>r&&(s.length=r);s.lengtho;o++)n[o].call(this,e)}return this}}},{}],46:[function(e,f){function n(){this.objects=[],this.type=Object}f.exports=n,n.prototype.release=function(){for(var e=arguments.length,f=0;f!==e;f++)this.objects.push(arguments[f])},n.prototype.get=function(){return 0===this.objects.length?this.constructObject():this.objects.pop()},n.prototype.constructObject=function(){throw new Error("constructObject() not implemented in this Pool subclass yet!")}},{}],47:[function(e,f){function n(){this.data={keys:[]}}f.exports=n,n.prototype.get=function(e,f){if(e>f){var n=f;f=e,e=n}return this.data[e+"-"+f]},n.prototype.set=function(e,f,n){if(e>f){var o=f;f=e,e=o}var d=e+"-"+f;this.get(e,f)||this.data.keys.push(d),this.data[d]=n},n.prototype.reset=function(){for(var e=this.data,f=e.keys;f.length>0;){var n=f.pop();delete e[n]}}},{}],48:[function(e,f){function n(){}f.exports=n,n.defaults=function(e,f){e=e||{};for(var n in f)n in e||(e[n]=f[n]);return e}},{}],49:[function(e,f){function n(){d.call(this),this.type=o}f.exports=n;var o=e("../math/Vec3"),d=e("./Pool");n.prototype=new d,n.prototype.constructObject=function(){return new o}},{"../math/Vec3":27,"./Pool":46}],50:[function(e,f){function n(){this.contactPointPool=[],this.v3pool=new u}function o(e,f,n){for(var o=null,d=e.length,i=0;i!==d;i++){var t=e[i],l=b;e[(i+1)%d].vsub(t,l);var u=m;l.cross(f,u);var p=N;n.vsub(t,p);var s=u.dot(p);if(!(null===o||s>0&&o===!0||0>=s&&o===!1))return!1;null===o&&(o=s>0)}return!0}f.exports=n;var d=e("../shapes/Shape"),i=e("../math/Vec3"),t=e("../math/Transform"),l=(e("../shapes/ConvexPolyhedron"),e("../math/Quaternion")),u=(e("../solver/Solver"),e("../utils/Vec3Pool")),p=e("../equations/ContactEquation");n.prototype.makeResult=function(e,f,n,o,d,i){var t;return this.contactPointPool.length?(t=this.contactPointPool.pop(),t.bi=e,t.bj=f):t=new p(e,f),t.enabled=!0,t.si=d||n,t.sj=i||o,t};var s=new i,y=new i,c=new l,a=new l;n.prototype.getContacts=function(e,f,n,o,d){this.contactPointPool=d;for(var i=c,t=a,l=s,u=y,p=0,r=e.length;p!==r;p++)for(var w=e[p],b=f[p],m=0;mN.boundingSphereRadius+x.boundingSphereRadius)){var j=this[N.type|x.type];j&&(N.typeG&&G>0){var H=j,I=v;H.copy(s[(B+1)%3]),I.copy(s[(B+2)%3]);var J=H.norm(),K=I.norm();H.normalize(),I.normalize();var L=g.dot(H),M=g.dot(I);if(J>L&&L>-J&&K>M&&M>-K){var P=Math.abs(G-F-y);(null===z||z>P)&&(z=P,N=L,q=M,b=F,a.copy(E),r.copy(H),w.copy(I),m++)}}}if(m){c=!0;var Q=this.makeResult(l,u,f,n);a.mult(-y,Q.ri),Q.ni.copy(a),Q.ni.negate(Q.ni),a.mult(b,a),r.mult(N,r),a.vadd(r,a),w.mult(q,w),a.vadd(w,Q.rj),Q.ri.vadd(o,Q.ri),Q.ri.vsub(l.position,Q.ri),Q.rj.vadd(d,Q.rj),Q.rj.vsub(u.position,Q.rj),e.push(Q)}for(var R=p.get(),S=C,T=0;2!==T&&!c;T++)for(var U=0;2!==U&&!c;U++)for(var V=0;2!==V&&!c;V++)if(R.set(0,0,0),T?R.vadd(s[0],R):R.vsub(s[0],R),U?R.vadd(s[1],R):R.vsub(s[1],R),V?R.vadd(s[2],R):R.vsub(s[2],R),d.vadd(R,S),S.vsub(o,S),S.norm2()ef){c=!0;var ff=this.makeResult(l,u,f,n);X.vadd(Y,ff.rj),ff.rj.copy(ff.rj),P.negate(ff.ni),ff.ni.normalize(),ff.ri.copy(ff.rj),ff.ri.vadd(d,ff.ri),ff.ri.vsub(o,ff.ri),ff.ri.normalize(),ff.ri.mult(y,ff.ri),ff.ri.vadd(o,ff.ri),ff.ri.vsub(l.position,ff.ri),ff.rj.vadd(d,ff.rj),ff.rj.vsub(u.position,ff.rj),e.push(ff)}}p.release(W,X,Q,Y,P)};var q=new i,z=new i,B=new i,D=new i,E=new i,F=new i,G=new i,H=new i,I=new i,J=new i;n.prototype[d.types.SPHERE|d.types.CONVEXPOLYHEDRON]=n.prototype.sphereConvex=function(e,f,n,d,i,t,l,u,p){var s=this.v3pool;d.vsub(i,q);for(var y=n.faceNormals,c=n.faces,a=n.vertices,r=f.radius,w=0;w!==a.length;w++){var b=a[w],m=E;l.vmult(b,m),i.vadd(m,m);var N=D;if(m.vsub(d,N),N.norm2()K&&L.dot(C)>0){for(var M=[],P=0,Q=A.length;P!==Q;P++){var R=s.get();l.vmult(a[A[P]],R),i.vadd(R,R),M.push(R)}if(o(M,C,d)){x=!0;var g=this.makeResult(u,p,f,n);C.mult(-r,g.ri),C.negate(g.ni);var S=s.get();C.mult(-K,S);var T=s.get();C.mult(-r,T),d.vsub(i,g.rj),g.rj.vadd(T,g.rj),g.rj.vadd(S,g.rj),g.rj.vadd(i,g.rj),g.rj.vsub(p.position,g.rj),g.ri.vadd(d,g.ri),g.ri.vsub(u.position,g.ri),s.release(S),s.release(T),e.push(g);for(var P=0,U=M.length;P!==U;P++)s.release(M[P]);return}for(var P=0;P!==A.length;P++){var V=s.get(),W=s.get();l.vmult(a[A[(P+1)%A.length]],V),l.vmult(a[A[(P+2)%A.length]],W),i.vadd(V,V),i.vadd(W,W);var X=z;W.vsub(V,X);var Y=B;X.unit(Y);var Z=s.get(),$=s.get();d.vsub(V,$);var _=$.dot(Y);Y.mult(_,Z),Z.vadd(V,Z);var ef=s.get();if(Z.vsub(d,ef),_>0&&_*_=a){var r=this.makeResult(l,u,f,n),w=P;s.mult(s.dot(y),w),p.vsub(w,w),w.vsub(o,r.ri),r.ni.copy(s),p.vsub(d,r.rj),r.ri.vadd(o,r.ri),r.ri.vsub(l.position,r.ri),r.rj.vadd(d,r.rj),r.rj.vsub(u.position,r.rj),e.push(r) +}}};var Q=new i,R=new i;n.prototype[d.types.CONVEXPOLYHEDRON]=n.prototype.convexConvex=function(e,f,n,o,d,i,t,l,u,p,s,y,c){var a=Q;if(!(o.distanceTo(d)>f.boundingSphereRadius+n.boundingSphereRadius)&&f.findSeparatingAxis(n,o,i,d,t,a,y,c)){var r=[],w=R;f.clipAgainstHull(o,i,n,d,t,a,-100,100,r);for(var b=0;b!==r.length;b++){var m=this.makeResult(l,u,f,n,p,s),N=m.ri,g=m.rj;a.negate(m.ni),r[b].normal.negate(w),w.mult(r[b].depth,w),r[b].point.vadd(w,N),g.copy(r[b].point),N.vsub(o,N),g.vsub(d,g),N.vadd(o,N),N.vsub(l.position,N),g.vadd(d,g),g.vsub(u.position,g),e.push(m)}}};var S=new i,T=new i,U=new i;n.prototype[d.types.PLANE|d.types.PARTICLE]=n.prototype.planeParticle=function(e,f,n,o,d,i,t,l,u){var p=S;p.set(0,0,1),l.quaternion.vmult(p,p);var s=T;d.vsub(l.position,s);var y=p.dot(s);if(0>=y){var c=this.makeResult(u,l,n,f);c.ni.copy(p),c.ni.negate(c.ni),c.ri.set(0,0,0);var a=U;p.mult(p.dot(d),a),d.vsub(a,a),c.rj.copy(a),e.push(c)}};var V=new i;n.prototype[d.types.PARTICLE|d.types.SPHERE]=n.prototype.sphereParticle=function(e,f,n,o,d,i,t,l,u){var p=V;p.set(0,0,1),d.vsub(o,p);var s=p.norm2();if(s<=f.radius*f.radius){var y=this.makeResult(u,l,n,f);p.normalize(),y.rj.copy(p),y.rj.mult(f.radius,y.rj),y.ni.copy(p),y.ni.negate(y.ni),y.ri.set(0,0,0),e.push(y)}};var W=new l,X=new i,Y=(new i,new i),Z=new i,$=new i;n.prototype[d.types.PARTICLE|d.types.CONVEXPOLYHEDRON]=n.prototype.convexParticle=function(e,f,n,o,d,i,t,l,u){var p=-1,s=Y,y=$,c=null,a=0,r=X;if(r.copy(d),r.vsub(o,r),i.conjugate(W),W.vmult(r,r),f.pointIsInside(r)){f.worldVerticesNeedsUpdate&&f.computeWorldVertices(o,i),f.worldFaceNormalsNeedsUpdate&&f.computeWorldFaceNormals(i);for(var w=0,b=f.faces.length;w!==b;w++){var m=[f.worldVertices[f.faces[w][0]]],N=f.worldFaceNormals[w];d.vsub(m[0],Z);var g=-N.dot(Z);(null===c||Math.abs(g)m||0>g||b>s.length||g>s[0].length)){0>b&&(b=0),0>m&&(m=0),0>N&&(N=0),0>g&&(g=0),b>=s.length&&(b=s.length-1),m>=s.length&&(m=s.length-1),g>=s[0].length&&(g=s[0].length-1),N>=s[0].length&&(N=s[0].length-1);var x=[];n.getRectMinMax(b,N,m,g,x);var j=x[0],v=x[1];if(!(w.z-c>v||w.z+cA;A++)for(var C=N;g>C;C++)n.getConvexTrianglePillar(A,C,!1),t.pointToWorldFrame(d,l,n.pillarOffset,a),o.distanceTo(a)b||0>N||w>s.length||N>s[0].length)){0>w&&(w=0),0>b&&(b=0),0>m&&(m=0),0>N&&(N=0),w>=s.length&&(w=s.length-1),b>=s.length&&(b=s.length-1),N>=s[0].length&&(N=s[0].length-1),m>=s[0].length&&(m=s[0].length-1);var g=[];n.getRectMinMax(w,m,b,N,g);var x=g[0],j=g[1];if(!(r.z-y>j||r.z+yv;v++)for(var A=m;N>A;A++){var C=e.length;n.getConvexTrianglePillar(v,A,!1),t.pointToWorldFrame(d,l,n.pillarOffset,a),o.distanceTo(a)2)return}}}},{"../equations/ContactEquation":16,"../math/Quaternion":25,"../math/Transform":26,"../math/Vec3":27,"../shapes/ConvexPolyhedron":35,"../shapes/Shape":40,"../solver/Solver":43,"../utils/Vec3Pool":49}],51:[function(e,f){function n(){p.apply(this),this.dt=-1,this.allowSleep=!1,this.contacts=[],this.frictionEquations=[],this.quatNormalizeSkip=0,this.quatNormalizeFast=!1,this.time=0,this.stepnumber=0,this.default_dt=1/60,this.nextId=0,this.gravity=new d,this.broadphase=new m,this.bodies=[],this.solver=new t,this.constraints=[],this.narrowphase=new u,this.collisionMatrix=new s,this.collisionMatrixPrevious=new s,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new r,this.defaultMaterial=new y("default"),this.defaultContactMaterial=new c(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null}}f.exports=n;var o=e("../shapes/Shape"),d=e("../math/Vec3"),i=e("../math/Quaternion"),t=e("../solver/GSSolver"),l=(e("../utils/Vec3Pool"),e("../equations/ContactEquation"),e("../equations/FrictionEquation")),u=e("./Narrowphase"),p=e("../utils/EventTarget"),s=e("../collision/ArrayCollisionMatrix"),y=e("../material/Material"),c=e("../material/ContactMaterial"),a=e("../objects/Body"),r=e("../utils/TupleDictionary"),w=(e("../collision/RaycastResult"),e("../collision/AABB")),b=e("../collision/Ray"),m=e("../collision/NaiveBroadphase");n.prototype=new p;var N=new w,g=[],x=new b;if(n.prototype.getContactMaterial=function(e,f){return this.contactMaterialTable.get(e.id,f.id)},n.prototype.numObjects=function(){return this.bodies.length},n.prototype.collisionMatrixTick=function(){var e=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=e,this.collisionMatrix.reset()},n.prototype.add=n.prototype.addBody=function(e){-1===this.bodies.indexOf(e)&&(e.index=this.bodies.length,this.bodies.push(e),e.world=this,e.initPosition.copy(e.position),e.initVelocity.copy(e.velocity),e.timeLastSleepy=this.time,e instanceof a&&(e.initAngularVelocity.copy(e.angularVelocity),e.initQuaternion.copy(e.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=e,this.dispatchEvent(this.addBodyEvent))},n.prototype.addConstraint=function(e){this.constraints.push(e)},n.prototype.removeConstraint=function(e){var f=this.constraints.indexOf(e);-1!==f&&this.constraints.splice(f,1)},n.prototype.rayTest=function(e,f,n){x.from.copy(e),x.to.copy(f),x.getAABB(N),g.length=0,this.broadphase.aabbQuery(this,N,g),x.intersectBodies(g,n)},n.prototype.remove=function(e){e.world=null;var f=this.bodies.length-1,n=this.bodies,o=n.indexOf(e);if(-1!==o){n.splice(o,1);for(var d=0;d!==n.length;d++)n[d].index=d;this.collisionMatrix.setNumObjects(f),this.removeBodyEvent.body=e,this.dispatchEvent(this.removeBodyEvent)}},n.prototype.addMaterial=function(e){this.materials.push(e)},n.prototype.addContactMaterial=function(e){this.contactmaterials.push(e),this.contactMaterialTable.set(e.materials[0].id,e.materials[1].id,e)},"undefined"==typeof performance&&(performance={}),!performance.now){var j=Date.now();performance.timing&&performance.timing.navigationStart&&(j=performance.timing.navigationStart),performance.now=function(){return Date.now()-j}}var v=new d;n.prototype.step=function(e,f,n){if(n=n||10,f=f||0,0===f)this.internalStep(e),this.time+=e;else{var o=Math.floor((this.time+f)/e)-Math.floor(this.time/e);o=Math.min(o,n);for(var d=performance.now(),i=0;i!==o&&(this.internalStep(e),!(performance.now()-d>1e3*e));i++);this.time+=f;for(var t=this.time%e,l=t/e,u=v,p=this.bodies,s=0;s!==p.length;s++){var y=p[s];y.type!==a.STATIC&&y.sleepState!==a.SLEEPING?(y.position.vsub(y.previousPosition,u),u.scale(l,u),y.position.vadd(u,y.interpolatedPosition)):(y.interpolatedPosition.copy(y.position),y.interpolatedQuaternion.copy(y.quaternion))}}};var A={type:"postStep"},C={type:"preStep"},O={type:"collide",body:null,contact:null},h=[],k=[],q=[],z=[],B=new d,D=(new d,new d,new d,new d,new d,new d,new d,new d,new i,new i),E=new i,F=new d;n.prototype.internalStep=function(e){this.dt=e;var f,n=this.contacts,d=q,i=z,t=this.numObjects(),u=this.bodies,p=this.solver,s=this.gravity,y=this.doProfiling,c=this.profile,r=a.DYNAMIC,w=this.constraints,b=k,m=s.norm(),N=s.x,g=s.y,x=s.z,j=0;for(y&&(f=performance.now()),j=0;j!==t;j++){var v=u[j];if(v.type&r){var G=v.force,H=v.mass;G.x+=H*N,G.y+=H*g,G.z+=H*x}}for(var j=0,I=this.subsystems.length;j!==I;j++)this.subsystems[j].update();y&&(f=performance.now()),d.length=0,i.length=0,this.broadphase.collisionPairs(this,d,i),y&&(c.broadphase=performance.now()-f);var J=w.length;for(j=0;j!==J;j++){var K=w[j];if(!K.collideConnected)for(var L=d.length-1;L>=0;L-=1)(K.bodyA===d[L]&&K.bodyB===i[L]||K.bodyB===d[L]&&K.bodyA===i[L])&&(d.splice(L,1),i.splice(L,1))}this.collisionMatrixTick(),y&&(f=performance.now());var M=h,P=n.length;for(j=0;j!==P;j++)M.push(n[j]);n.length=0,this.narrowphase.getContacts(d,i,this,n,M),y&&(c.narrowphase=performance.now()-f),y&&(f=performance.now());var Q=n.length,R=this.frictionEquations.length;for(j=0;j!==R;j++)b.push(this.frictionEquations[j]);this.frictionEquations.length=0;for(var S=0;S!==Q;S++){var T,K=n[S],v=K.bi,U=K.bj,V=K.si,W=K.sj,j=u.indexOf(v),L=u.indexOf(U);T=v.material&&U.material?this.getContactMaterial(v.material,U.material)||this.defaultContactMaterial:this.defaultContactMaterial;var X=T.friction,Y=B;Y.set(U.position.x+K.rj.x-v.position.x-K.ri.x,U.position.y+K.rj.y-v.position.y-K.ri.y,U.position.z+K.rj.z-v.position.z-K.ri.z);var Z=Y.dot(K.ni);if(0>Z){if(K.enabled=v.collisionResponse&&U.collisionResponse&&V.collisionResponse&&W.collisionResponse,K.restitution=T.restitution,K.penetration=Z,K.setSpookParams(T.contactEquationStiffness,T.contactEquationRelaxation,e),p.addEquation(K),X>0){var $=X*m,_=v.invMass+U.invMass;_>0&&(_=1/_);var ef=b,ff=ef.length?ef.pop():new l(v,U,$*_),nf=ef.length?ef.pop():new l(v,U,$*_);this.frictionEquations.push(ff),this.frictionEquations.push(nf),ff.bi=nf.bi=v,ff.bj=nf.bj=U,ff.minForce=nf.minForce=-$*_,ff.maxForce=nf.maxForce=$*_,ff.ri.copy(K.ri),ff.rj.copy(K.rj),nf.ri.copy(K.ri),nf.rj.copy(K.rj),K.ni.tangents(ff.t,nf.t),ff.setSpookParams(T.frictionEquationStiffness,T.frictionEquationRelaxation,e),nf.setSpookParams(T.frictionEquationStiffness,T.frictionEquationRelaxation,e),ff.enabled=nf.enabled=K.enabled,p.addEquation(ff),p.addEquation(nf)}if(v.allowSleep&&v.type===a.DYNAMIC&&v.sleepState===a.SLEEPING&&U.sleepState===a.AWAKE&&U.type!==a.STATIC){var of=U.velocity.norm2()+U.angularVelocity.norm2(),df=Math.pow(U.sleepSpeedLimit,2);of>=2*df&&(v._wakeUpAfterNarrowphase=!0)}if(U.allowSleep&&U.type===a.DYNAMIC&&U.sleepState===a.SLEEPING&&v.sleepState===a.AWAKE&&v.type!==a.STATIC){var tf=v.velocity.norm2()+v.angularVelocity.norm2(),lf=Math.pow(v.sleepSpeedLimit,2);tf>=2*lf&&(U._wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(v,U,!0),this.collisionMatrix.get(v,U)!==this.collisionMatrixPrevious.get(v,U)&&(O.body=U,O.contact=K,v.dispatchEvent(O),O.body=v,U.dispatchEvent(O))}}for(y&&(c.makeContactConstraints=performance.now()-f,f=performance.now()),j=0;j!==t;j++){var v=u[j];v._wakeUpAfterNarrowphase&&(v.wakeUp(),v._wakeUpAfterNarrowphase=!1)}var J=w.length;for(j=0;j!==J;j++){var K=w[j];K.update();for(var L=0,uf=K.equations.length;L!==uf;L++){var pf=K.equations[L];p.addEquation(pf)}}p.solve(e,this),y&&(c.solve=performance.now()-f),p.removeAllEquations();var sf=Math.pow;for(j=0;j!==t;j++){var v=u[j];if(v.type&r){var yf=sf(1-v.linearDamping,e),cf=v.velocity;cf.mult(yf,cf);var af=v.angularVelocity;if(af){var rf=sf(1-v.angularDamping,e);af.mult(rf,af)}}}for(this.dispatchEvent(C),j=0;j!==t;j++){var v=u[j];v.preStep&&v.preStep.call(v)}y&&(f=performance.now());var wf=D,bf=E,mf=this.stepnumber,Nf=a.DYNAMIC|a.KINEMATIC,gf=mf%(this.quatNormalizeSkip+1)===0,xf=this.quatNormalizeFast,jf=.5*e,vf=o.types.PLANE,Af=o.types.CONVEXPOLYHEDRON;for(j=0;j!==t;j++){var Cf=u[j],Of=Cf.shape,hf=Cf.force,kf=Cf.torque;if(Cf.type&Nf&&Cf.sleepState!==a.SLEEPING){var qf=Cf.velocity,zf=Cf.angularVelocity,Bf=Cf.position,Df=Cf.quaternion,Ef=Cf.invMass,Ff=Cf.invInertiaWorld;if(qf.x+=hf.x*Ef*e,qf.y+=hf.y*Ef*e,qf.z+=hf.z*Ef*e,Cf.angularVelocity&&(Ff.vmult(kf,F),F.mult(e,F),F.vadd(zf,zf)),Bf.x+=qf.x*e,Bf.y+=qf.y*e,Bf.z+=qf.z*e,Cf.angularVelocity&&(wf.set(zf.x,zf.y,zf.z,0),wf.mult(Df,bf),Df.x+=jf*bf.x,Df.y+=jf*bf.y,Df.z+=jf*bf.z,Df.w+=jf*bf.w,gf&&(xf?Df.normalizeFast():Df.normalize())),Cf.aabb&&(Cf.aabbNeedsUpdate=!0),Of)switch(Of.type){case vf:Of.worldNormalNeedsUpdate=!0;break;case Af:Of.worldFaceNormalsNeedsUpdate=!0,Of.worldVerticesNeedsUpdate=!0}Cf.updateInertiaWorld&&Cf.updateInertiaWorld()}Cf.force.set(0,0,0),Cf.torque&&Cf.torque.set(0,0,0)}for(this.broadphase.dirty=!0,y&&(c.integrate=performance.now()-f),this.time+=e,this.stepnumber+=1,this.dispatchEvent(A),j=0;j!==t;j++){var v=u[j],Gf=v.postStep;Gf&&Gf.call(v)}if(this.allowSleep)for(j=0;j!==t;j++)u[j].sleepTick(this.time)}},{"../collision/AABB":3,"../collision/ArrayCollisionMatrix":4,"../collision/NaiveBroadphase":7,"../collision/Ray":9,"../collision/RaycastResult":10,"../equations/ContactEquation":16,"../equations/FrictionEquation":18,"../material/ContactMaterial":21,"../material/Material":22,"../math/Quaternion":25,"../math/Vec3":27,"../objects/Body":28,"../shapes/Shape":40,"../solver/GSSolver":42,"../utils/EventTarget":45,"../utils/TupleDictionary":47,"../utils/Vec3Pool":49,"./Narrowphase":50}]},{},[2])(2)}); \ No newline at end of file diff --git a/ajax/libs/cannon.js/package.json b/ajax/libs/cannon.js/package.json index c677b7c55..ece4c0f88 100644 --- a/ajax/libs/cannon.js/package.json +++ b/ajax/libs/cannon.js/package.json @@ -1,7 +1,7 @@ { "name": "cannon.js", "filename": "cannon.min.js", - "version": "0.6.0", + "version": "0.6.1", "description": "A lightweight 3D physics engine written in JavaScript.", "homepage": "http://schteppe.github.com/cannon.js", "keywords": [