From ddbf9bcba0229289a5d75daffe49ae38cc9dc26d Mon Sep 17 00:00:00 2001 From: Don McCurdy Date: Mon, 12 Mar 2018 20:03:05 -0700 Subject: [PATCH] 3.0.2 --- README.md | 8 ++++---- dist/aframe-physics-system.js | 7 ++++--- dist/aframe-physics-system.min.js | 2 +- package-lock.json | 2 +- package.json | 2 +- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3f81c49..92d3d71 100644 --- a/README.md +++ b/README.md @@ -25,13 +25,13 @@ Components for A-Frame physics integration, built on [CANNON.js](http://schteppe In the [dist/](https://github.com/donmccurdy/aframe-physics-system/tree/master/dist) folder, download the full or minified build. Include the script on your page, and all components are automatically registered for you: ```html - + ``` -CDN builds for aframe-physics-system/v3.0.1: +CDN builds for aframe-physics-system/v3.0.2: -- [aframe-physics-system.js](https://cdn.rawgit.com/donmccurdy/aframe-physics-system/v3.0.1/dist/aframe-physics-system.js) *(development)* -- [aframe-physics-system.min.js](https://cdn.rawgit.com/donmccurdy/aframe-physics-system/v3.0.1/dist/aframe-physics-system.min.js) *(production)* +- [aframe-physics-system.js](https://cdn.rawgit.com/donmccurdy/aframe-physics-system/v3.0.2/dist/aframe-physics-system.js) *(development)* +- [aframe-physics-system.min.js](https://cdn.rawgit.com/donmccurdy/aframe-physics-system/v3.0.2/dist/aframe-physics-system.min.js) *(production)* ### npm diff --git a/dist/aframe-physics-system.js b/dist/aframe-physics-system.js index 2725cc4..cdaf52b 100644 --- a/dist/aframe-physics-system.js +++ b/dist/aframe-physics-system.js @@ -15746,7 +15746,7 @@ var Body = { var data = this.data; - if (data.type !== prevData.type) { + if (prevData.type != undefined && data.type !== prevData.type) { console.warn('CANNON.Body type cannot be changed after instantiation'); } @@ -15758,7 +15758,7 @@ var Body = { if (data.mass !== prevData.mass) { this.body.updateMassProperties(); } - this.body.updateProperties(); + if (this.body.updateProperties) this.body.updateProperties(); }, /** @@ -15934,7 +15934,8 @@ var Body = require('./body'); var StaticBody = AFRAME.utils.extend({}, Body.definition); StaticBody.schema = AFRAME.utils.extend({}, Body.definition.schema, { - type: {default: 'static', oneOf: ['static', 'dynamic']} + type: {default: 'static', oneOf: ['static', 'dynamic']}, + mass: {default: 0} }); module.exports = AFRAME.registerComponent('static-body', StaticBody); diff --git a/dist/aframe-physics-system.min.js b/dist/aframe-physics-system.min.js index 26cff8c..08cb799 100644 --- a/dist/aframe-physics-system.min.js +++ b/dist/aframe-physics-system.min.js @@ -1 +1 @@ -!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n||e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<\/script>\n```\n\n### Node.js install\n\nInstall the cannon package via NPM:\n\n```bash\nnpm install --save cannon\n```\n\nAlternatively, point to the Github repo directly to get the very latest version:\n\n```bash\nnpm install --save schteppe/cannon.js\n```\n\n### Example\n\nThe sample code below creates a sphere on a plane, steps the simulation, and prints the sphere simulation to the console. Note that Cannon.js uses [SI units](http://en.wikipedia.org/wiki/International_System_of_Units) (metre, kilogram, second, etc.).\n\n```javascript\n// Setup our world\nvar world = new CANNON.World();\nworld.gravity.set(0, 0, -9.82); // m/s²\n\n// Create a sphere\nvar radius = 1; // m\nvar sphereBody = new CANNON.Body({\n mass: 5, // kg\n position: new CANNON.Vec3(0, 0, 10), // m\n shape: new CANNON.Sphere(radius)\n});\nworld.addBody(sphereBody);\n\n// Create a plane\nvar groundBody = new CANNON.Body({\n mass: 0 // mass == 0 makes the body static\n});\nvar groundShape = new CANNON.Plane();\ngroundBody.addShape(groundShape);\nworld.addBody(groundBody);\n\nvar fixedTimeStep = 1.0 / 60.0; // seconds\nvar maxSubSteps = 3;\n\n// Start the simulation loop\nvar lastTime;\n(function simloop(time){\n requestAnimationFrame(simloop);\n if(lastTime !== undefined){\n var dt = (time - lastTime) / 1000;\n world.step(fixedTimeStep, dt, maxSubSteps);\n }\n console.log("Sphere z position: " + sphereBody.position.z);\n lastTime = time;\n})();\n```\n\nIf you want to know how to use cannon.js with a rendering engine, for example Three.js, see the [Examples](examples).\n\n### Features\n* Rigid body dynamics\n* Discrete collision detection\n* Contacts, friction and restitution\n* Constraints\n * PointToPoint (a.k.a. ball/socket joint)\n * Distance\n * Hinge (with optional motor)\n * Lock\n * ConeTwist\n* Gauss-Seidel constraint solver and an island split algorithm\n* Collision filters\n* Body sleeping\n* Experimental SPH / fluid support\n* Various shapes and collision algorithms (see table below)\n\n| | [Sphere](http://schteppe.github.io/cannon.js/docs/classes/Sphere.html) | [Plane](http://schteppe.github.io/cannon.js/docs/classes/Plane.html) | [Box](http://schteppe.github.io/cannon.js/docs/classes/Box.html) | [Convex](http://schteppe.github.io/cannon.js/docs/classes/ConvexPolyhedron.html) | [Particle](http://schteppe.github.io/cannon.js/docs/classes/Particle.html) | [Heightfield](http://schteppe.github.io/cannon.js/docs/classes/Heightfield.html) | [Trimesh](http://schteppe.github.io/cannon.js/docs/classes/Trimesh.html) |\n| :-----------|:------:|:-----:|:---:|:------:|:--------:|:-----------:|:-------:|\n| Sphere | Yes | Yes | Yes | Yes | Yes | Yes | Yes |\n| Plane | - | - | Yes | Yes | Yes | - | Yes |\n| Box | - | - | Yes | Yes | Yes | Yes | (todo) |\n| Cylinder | - | - | Yes | Yes | Yes | Yes | (todo) |\n| Convex | - | - | - | Yes | Yes | Yes | (todo) |\n| Particle | - | - | - | - | - | (todo) | (todo) |\n| Heightfield | - | - | - | - | - | - | (todo) |\n| Trimesh | - | - | - | - | - | - | - |\n\n### Todo\nThe simpler todos are marked with ```@todo``` in the code. Github Issues can and should also be used for todos.\n\n### Help\nCreate an [issue](https://github.com/schteppe/cannon.js/issues) if you need help.\n',readmeFilename:"README.markdown",repository:{type:"git",url:"git+https://github.com/schteppe/cannon.js.git"},version:"0.6.2"}},{}],4:[function(require,module,exports){module.exports={version:require("../package.json").version,AABB:require("./collision/AABB"),ArrayCollisionMatrix:require("./collision/ArrayCollisionMatrix"),Body:require("./objects/Body"),Box:require("./shapes/Box"),Broadphase:require("./collision/Broadphase"),Constraint:require("./constraints/Constraint"),ContactEquation:require("./equations/ContactEquation"),Narrowphase:require("./world/Narrowphase"),ConeTwistConstraint:require("./constraints/ConeTwistConstraint"),ContactMaterial:require("./material/ContactMaterial"),ConvexPolyhedron:require("./shapes/ConvexPolyhedron"),Cylinder:require("./shapes/Cylinder"),DistanceConstraint:require("./constraints/DistanceConstraint"),Equation:require("./equations/Equation"),EventTarget:require("./utils/EventTarget"),FrictionEquation:require("./equations/FrictionEquation"),GSSolver:require("./solver/GSSolver"),GridBroadphase:require("./collision/GridBroadphase"),Heightfield:require("./shapes/Heightfield"),HingeConstraint:require("./constraints/HingeConstraint"),LockConstraint:require("./constraints/LockConstraint"),Mat3:require("./math/Mat3"),Material:require("./material/Material"),NaiveBroadphase:require("./collision/NaiveBroadphase"),ObjectCollisionMatrix:require("./collision/ObjectCollisionMatrix"),Pool:require("./utils/Pool"),Particle:require("./shapes/Particle"),Plane:require("./shapes/Plane"),PointToPointConstraint:require("./constraints/PointToPointConstraint"),Quaternion:require("./math/Quaternion"),Ray:require("./collision/Ray"),RaycastVehicle:require("./objects/RaycastVehicle"),RaycastResult:require("./collision/RaycastResult"),RigidVehicle:require("./objects/RigidVehicle"),RotationalEquation:require("./equations/RotationalEquation"),RotationalMotorEquation:require("./equations/RotationalMotorEquation"),SAPBroadphase:require("./collision/SAPBroadphase"),SPHSystem:require("./objects/SPHSystem"),Shape:require("./shapes/Shape"),Solver:require("./solver/Solver"),Sphere:require("./shapes/Sphere"),SplitSolver:require("./solver/SplitSolver"),Spring:require("./objects/Spring"),Transform:require("./math/Transform"),Trimesh:require("./shapes/Trimesh"),Vec3:require("./math/Vec3"),Vec3Pool:require("./utils/Vec3Pool"),World:require("./world/World")}},{"../package.json":3,"./collision/AABB":5,"./collision/ArrayCollisionMatrix":6,"./collision/Broadphase":7,"./collision/GridBroadphase":8,"./collision/NaiveBroadphase":9,"./collision/ObjectCollisionMatrix":10,"./collision/Ray":12,"./collision/RaycastResult":13,"./collision/SAPBroadphase":14,"./constraints/ConeTwistConstraint":15,"./constraints/Constraint":16,"./constraints/DistanceConstraint":17,"./constraints/HingeConstraint":18,"./constraints/LockConstraint":19,"./constraints/PointToPointConstraint":20,"./equations/ContactEquation":22,"./equations/Equation":23,"./equations/FrictionEquation":24,"./equations/RotationalEquation":25,"./equations/RotationalMotorEquation":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/Mat3":30,"./math/Quaternion":31,"./math/Transform":32,"./math/Vec3":33,"./objects/Body":34,"./objects/RaycastVehicle":35,"./objects/RigidVehicle":36,"./objects/SPHSystem":37,"./objects/Spring":38,"./shapes/Box":40,"./shapes/ConvexPolyhedron":41,"./shapes/Cylinder":42,"./shapes/Heightfield":43,"./shapes/Particle":44,"./shapes/Plane":45,"./shapes/Shape":46,"./shapes/Sphere":47,"./shapes/Trimesh":48,"./solver/GSSolver":49,"./solver/Solver":50,"./solver/SplitSolver":51,"./utils/EventTarget":52,"./utils/Pool":54,"./utils/Vec3Pool":57,"./world/Narrowphase":58,"./world/World":59}],5:[function(require,module,exports){function AABB(options){options=options||{},this.lowerBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),this.upperBound=new Vec3,options.upperBound&&this.upperBound.copy(options.upperBound)}var Vec3=require("../math/Vec3");require("../utils/Utils");module.exports=AABB;var tmp=new Vec3;AABB.prototype.setFromPoints=function(points,position,quaternion,skinSize){var l=this.lowerBound,u=this.upperBound,q=quaternion;l.copy(points[0]),q&&q.vmult(l,l),u.copy(l);for(var i=1;iu.x&&(u.x=p.x),p.xu.y&&(u.y=p.y),p.yu.z&&(u.z=p.z),p.z=u2.x&&l1.y<=l2.y&&u1.y>=u2.y&&l1.z<=l2.z&&u1.z>=u2.z},AABB.prototype.getCorners=function(a,b,c,d,e,f,g,h){var l=this.lowerBound,u=this.upperBound;a.copy(l),b.set(u.x,l.y,l.z),c.set(u.x,u.y,l.z),d.set(l.x,u.y,u.z),e.set(u.x,l.y,l.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)};var transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3];AABB.prototype.toLocalFrame=function(frame,target){var corners=transformIntoFrame_corners,a=corners[0],b=corners[1],c=corners[2],d=corners[3],e=corners[4],f=corners[5],g=corners[6],h=corners[7];this.getCorners(a,b,c,d,e,f,g,h);for(var i=0;8!==i;i++){var corner=corners[i];frame.pointToLocal(corner,corner)}return target.setFromPoints(corners)},AABB.prototype.toWorldFrame=function(frame,target){var corners=transformIntoFrame_corners,a=corners[0],b=corners[1],c=corners[2],d=corners[3],e=corners[4],f=corners[5],g=corners[6],h=corners[7];this.getCorners(a,b,c,d,e,f,g,h);for(var i=0;8!==i;i++){var corner=corners[i];frame.pointToWorld(corner,corner)}return target.setFromPoints(corners)},AABB.prototype.overlapsRay=function(ray){var dirFracX=1/ray._direction.x,dirFracY=1/ray._direction.y,dirFracZ=1/ray._direction.z,t1=(this.lowerBound.x-ray.from.x)*dirFracX,t2=(this.upperBound.x-ray.from.x)*dirFracX,t3=(this.lowerBound.y-ray.from.y)*dirFracY,t4=(this.upperBound.y-ray.from.y)*dirFracY,t5=(this.lowerBound.z-ray.from.z)*dirFracZ,t6=(this.upperBound.z-ray.from.z)*dirFracZ,tmin=Math.max(Math.max(Math.min(t1,t2),Math.min(t3,t4)),Math.min(t5,t6)),tmax=Math.min(Math.min(Math.max(t1,t2),Math.max(t3,t4)),Math.max(t5,t6));return!(tmax<0)&&!(tmin>tmax)}},{"../math/Vec3":33,"../utils/Utils":56}],6:[function(require,module,exports){function ArrayCollisionMatrix(){this.matrix=[]}module.exports=ArrayCollisionMatrix,ArrayCollisionMatrix.prototype.get=function(i,j){if(i=i.index,(j=j.index)>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},ArrayCollisionMatrix.prototype.set=function(i,j,value){if(i=i.index,(j=j.index)>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},ArrayCollisionMatrix.prototype.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},ArrayCollisionMatrix.prototype.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1}},{}],7:[function(require,module,exports){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var Body=require("../objects/Body"),Vec3=require("../math/Vec3"),Quaternion=require("../math/Quaternion");require("../shapes/Shape"),require("../shapes/Plane");module.exports=Broadphase,Broadphase.prototype.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},Broadphase.prototype.needBroadphaseCollision=function(bodyA,bodyB){return 0!=(bodyA.collisionFilterGroup&bodyB.collisionFilterMask)&&0!=(bodyB.collisionFilterGroup&bodyA.collisionFilterMask)&&(0==(bodyA.type&Body.STATIC)&&bodyA.sleepState!==Body.SLEEPING||0==(bodyB.type&Body.STATIC)&&bodyB.sleepState!==Body.SLEEPING)},Broadphase.prototype.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)};var Broadphase_collisionPairs_r=new Vec3;new Vec3,new Quaternion,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);r.norm2()dist.norm2()},Broadphase.prototype.aabbQuery=function(world,aabb,result){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}},{"../math/Quaternion":31,"../math/Vec3":33,"../objects/Body":34,"../shapes/Plane":45,"../shapes/Shape":46}],8:[function(require,module,exports){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=[],this.bins.length=nbins,this.binLengths.length=nbins;for(var i=0;i=nx&&(xoff0=nx-1),yoff0<0?yoff0=0:yoff0>=ny&&(yoff0=ny-1),zoff0<0?zoff0=0:zoff0>=nz&&(zoff0=nz-1),xoff1<0?xoff1=0:xoff1>=nx&&(xoff1=nx-1),yoff1<0?yoff1=0:yoff1>=ny&&(yoff1=ny-1),zoff1<0?zoff1=0:zoff1>=nz&&(zoff1=nz-1),yoff0*=ystep,zoff0*=zstep,xoff1*=xstep,yoff1*=ystep,zoff1*=zstep;for(var xoff=xoff0*=xstep;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}}for(var N=world.numObjects(),bodies=world.bodies,max=this.aabbMax,min=this.aabbMin,nx=this.nx,ny=this.ny,nz=this.nz,xstep=ny*nz,ystep=nz,zstep=1,xmax=max.x,ymax=max.y,zmax=max.z,xmin=min.x,ymin=min.y,zmin=min.z,xmult=nx/(xmax-xmin),ymult=ny/(ymax-ymin),zmult=nz/(zmax-zmin),binsizeX=(xmax-xmin)/nx,binsizeY=(ymax-ymin)/ny,binsizeZ=(zmax-zmin)/nz,binRadius=.5*Math.sqrt(binsizeX*binsizeX+binsizeY*binsizeY+binsizeZ*binsizeZ),types=Shape.types,SPHERE=types.SPHERE,PLANE=types.PLANE,bins=(types.BOX,types.COMPOUND,types.CONVEXPOLYHEDRON,this.bins),binLengths=this.binLengths,Nbins=this.bins.length,i=0;i!==Nbins;i++)binLengths[i]=0;for(var ceil=Math.ceil,min=Math.min,max=Math.max,i=0;i!==N;i++){var si=(bi=bodies[i]).shape;switch(si.type){case SPHERE:var x=bi.position.x,y=bi.position.y,z=bi.position.z,r=si.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:si.worldNormalNeedsUpdate&&si.computeWorldNormal(bi.quaternion);var planeNormal=si.worldNormal,xreset=xmin+.5*binsizeX-bi.position.x,yreset=ymin+.5*binsizeY-bi.position.y,zreset=zmin+.5*binsizeZ-bi.position.z,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)1)for(var bin=bins[i],xi=0;xi!==binLength;xi++)for(var bi=bin[xi],yi=0;yi!==xi;yi++){var bj=bin[yi];this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)}}this.makePairsUnique(pairs1,pairs2)}},{"../math/Vec3":33,"../shapes/Shape":46,"./Broadphase":7}],9:[function(require,module,exports){function NaiveBroadphase(){Broadphase.apply(this)}module.exports=NaiveBroadphase;var Broadphase=require("./Broadphase"),AABB=require("./AABB");NaiveBroadphase.prototype=new Broadphase,NaiveBroadphase.prototype.constructor=NaiveBroadphase,NaiveBroadphase.prototype.collisionPairs=function(world,pairs1,pairs2){var i,j,bi,bj,bodies=world.bodies,n=bodies.length;for(i=0;i!==n;i++)for(j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)};new AABB;NaiveBroadphase.prototype.aabbQuery=function(world,aabb,result){result=result||[];for(var i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},ObjectCollisionMatrix.prototype.set=function(i,j,value){if(i=i.id,(j=j.id)>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},ObjectCollisionMatrix.prototype.reset=function(){this.matrix={}},ObjectCollisionMatrix.prototype.setNumObjects=function(n){}},{}],11:[function(require,module,exports){function OverlapKeeper(){this.current=[],this.previous=[]}function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}module.exports=OverlapKeeper,OverlapKeeper.prototype.getKey=function(i,j){if(jcurrent[index];)index++;if(key!==current[index]){for(var j=current.length-1;j>=index;j--)current[j+1]=current[j];current[index]=key}},OverlapKeeper.prototype.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},OverlapKeeper.prototype.getDiff=function(additions,removals){for(var a=this.current,b=this.previous,al=a.length,bl=b.length,j=0,i=0;ib[j];)j++;keyA===b[j]||unpackAndPush(additions,keyA)}j=0;for(i=0;ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}}},{}],12:[function(require,module,exports){function Ray(from,to){this.from=from?from.clone():new Vec3,this.to=to?to.clone():new Vec3,this._direction=new Vec3,this.precision=1e-4,this.checkCollisionResponse=!0,this.skipBackfaces=!1,this.collisionFilterMask=-1,this.collisionFilterGroup=-1,this.mode=Ray.ANY,this.result=new RaycastResult,this.hasHit=!1,this.callback=function(result){}}function pointInTriangle(p,a,b,c){c.vsub(a,v0),b.vsub(a,v1),p.vsub(a,v2);var u,v,dot00=v0.dot(v0),dot01=v0.dot(v1),dot02=v0.dot(v2),dot11=v1.dot(v1),dot12=v1.dot(v2);return(u=dot11*dot02-dot01*dot12)>=0&&(v=dot00*dot12-dot01*dot02)>=0&&u+vshape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}};new Vec3,new Vec3;var intersectPoint=new Vec3,a=new Vec3,b=new Vec3,c=new Vec3;new Vec3,new RaycastResult;Ray.prototype.intersectBox=function(shape,quat,position,body,reportedShape){return this.intersectConvex(shape.convexPolyhedronRepresentation,quat,position,body,reportedShape)},Ray.prototype[Shape.types.BOX]=Ray.prototype.intersectBox,Ray.prototype.intersectPlane=function(shape,quat,position,body,reportedShape){var from=this.from,to=this.to,direction=this._direction,worldNormal=new Vec3(0,0,1);quat.vmult(worldNormal,worldNormal);var len=new Vec3;from.vsub(position,len);var planeToFrom=len.dot(worldNormal);if(to.vsub(position,len),!(planeToFrom*len.dot(worldNormal)>0||from.distanceTo(to)=0&&d1<=1&&(from.lerp(to,d1,intersectionPoint),intersectionPoint.vsub(position,normal),normal.normalize(),this.reportIntersection(normal,intersectionPoint,reportedShape,body,-1)),this.result._shouldStop)return;d2>=0&&d2<=1&&(from.lerp(to,d2,intersectionPoint),intersectionPoint.vsub(position,normal),normal.normalize(),this.reportIntersection(normal,intersectionPoint,reportedShape,body,-1))}},Ray.prototype[Shape.types.SPHERE]=Ray.prototype.intersectSphere;var intersectConvex_normal=new Vec3,intersectConvex_vector=(new Vec3,new Vec3,new Vec3);Ray.prototype.intersectConvex=function(shape,quat,position,body,reportedShape,options){for(var normal=intersectConvex_normal,vector=intersectConvex_vector,faceList=options&&options.faceList||null,faces=shape.faces,vertices=shape.vertices,normals=shape.faceNormals,direction=this._direction,from=this.from,to=this.to,fromToDistance=from.distanceTo(to),Nfaces=faceList?faceList.length:faces.length,result=this.result,j=0;!result._shouldStop&&jfromToDistance||this.reportIntersection(normal,intersectPoint,reportedShape,body,fi)}}}}},Ray.prototype[Shape.types.CONVEXPOLYHEDRON]=Ray.prototype.intersectConvex;var intersectTrimesh_normal=new Vec3,intersectTrimesh_localDirection=new Vec3,intersectTrimesh_localFrom=new Vec3,intersectTrimesh_localTo=new Vec3,intersectTrimesh_worldNormal=new Vec3,intersectTrimesh_worldIntersectPoint=new Vec3,intersectTrimesh_triangles=(new AABB,[]),intersectTrimesh_treeTransform=new Transform;Ray.prototype.intersectTrimesh=function(mesh,quat,position,body,reportedShape,options){var normal=intersectTrimesh_normal,triangles=intersectTrimesh_triangles,treeTransform=intersectTrimesh_treeTransform,vector=intersectConvex_vector,localDirection=intersectTrimesh_localDirection,localFrom=intersectTrimesh_localFrom,localTo=intersectTrimesh_localTo,worldIntersectPoint=intersectTrimesh_worldIntersectPoint,worldNormal=intersectTrimesh_worldNormal,indices=(options&&options.faceList,mesh.indices),from=(mesh.vertices,mesh.faceNormals,this.from),to=this.to,direction=this._direction;treeTransform.position.copy(position),treeTransform.quaternion.copy(quat),Transform.vectorToLocalFrame(position,quat,direction,localDirection),Transform.pointToLocalFrame(position,quat,from,localFrom),Transform.pointToLocalFrame(position,quat,to,localTo),localTo.x*=mesh.scale.x,localTo.y*=mesh.scale.y,localTo.z*=mesh.scale.z,localFrom.x*=mesh.scale.x,localFrom.y*=mesh.scale.y,localFrom.z*=mesh.scale.z,localTo.vsub(localFrom,localDirection),localDirection.normalize();var fromToDistanceSquared=localFrom.distanceSquared(localTo);mesh.tree.rayQuery(this,treeTransform,triangles);for(var i=0,N=triangles.length;!this.result._shouldStop&&i!==N;i++){var trianglesIndex=triangles[i];mesh.getNormal(trianglesIndex,normal),mesh.getVertex(indices[3*trianglesIndex],a),a.vsub(localFrom,vector);var dot=localDirection.dot(normal),scalar=normal.dot(vector)/dot;if(!(scalar<0)){localDirection.scale(scalar,intersectPoint),intersectPoint.vadd(localFrom,intersectPoint),mesh.getVertex(indices[3*trianglesIndex+1],b),mesh.getVertex(indices[3*trianglesIndex+2],c);var squaredDistance=intersectPoint.distanceSquared(localFrom);!pointInTriangle(intersectPoint,b,a,c)&&!pointInTriangle(intersectPoint,a,b,c)||squaredDistance>fromToDistanceSquared||(Transform.vectorToWorldFrame(quat,normal,worldNormal),Transform.pointToWorldFrame(position,quat,intersectPoint,worldIntersectPoint),this.reportIntersection(worldNormal,worldIntersectPoint,reportedShape,body,trianglesIndex))}}triangles.length=0},Ray.prototype[Shape.types.TRIMESH]=Ray.prototype.intersectTrimesh,Ray.prototype.reportIntersection=function(normal,hitPointWorld,shape,body,hitFaceIndex){var from=this.from,to=this.to,distance=from.distanceTo(hitPointWorld),result=this.result;if(!(this.skipBackfaces&&normal.dot(this._direction)>0))switch(result.hitFaceIndex=void 0!==hitFaceIndex?hitFaceIndex:-1,this.mode){case Ray.ALL:this.hasHit=!0,result.set(from,to,normal,hitPointWorld,shape,body,distance),result.hasHit=!0,this.callback(result);break;case Ray.CLOSEST:(distance=0&&!(a[j].aabb.lowerBound.x<=v.aabb.lowerBound.x);j--)a[j+1]=a[j];a[j+1]=v}return a},SAPBroadphase.insertionSortY=function(a){for(var i=1,l=a.length;i=0&&!(a[j].aabb.lowerBound.y<=v.aabb.lowerBound.y);j--)a[j+1]=a[j];a[j+1]=v}return a},SAPBroadphase.insertionSortZ=function(a){for(var i=1,l=a.length;i=0&&!(a[j].aabb.lowerBound.z<=v.aabb.lowerBound.z);j--)a[j+1]=a[j];a[j+1]=v}return a},SAPBroadphase.prototype.collisionPairs=function(world,p1,p2){var i,j,bodies=this.axisList,N=bodies.length,axisIndex=this.axisIndex;for(this.dirty&&(this.sortList(),this.dirty=!1),i=0;i!==N;i++){var bi=bodies[i];for(j=i+1;jvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},SAPBroadphase.prototype.aabbQuery=function(world,aabb,result){result=result||[],this.dirty&&(this.sortList(),this.dirty=!1);var axisIndex=this.axisIndex,axis="x";1===axisIndex&&(axis="y"),2===axisIndex&&(axis="z");for(var axisList=this.axisList,i=(aabb.lowerBound[axis],aabb.upperBound[axis],0);i.499&&(heading=2*Math.atan2(x,w),attitude=Math.PI/2,bank=0),test<-.499&&(heading=-2*Math.atan2(x,w),attitude=-Math.PI/2,bank=0),isNaN(heading)){var sqx=x*x,sqy=y*y,sqz=z*z;heading=Math.atan2(2*y*w-2*x*z,1-2*sqy-2*sqz),attitude=Math.asin(2*test),bank=Math.atan2(2*x*w-2*y*z,1-2*sqx-2*sqz)}break;default:throw new Error("Euler order "+order+" not supported yet.")}target.y=heading,target.z=attitude,target.x=bank},Quaternion.prototype.setFromEuler=function(x,y,z,order){order=order||"XYZ";var c1=Math.cos(x/2),c2=Math.cos(y/2),c3=Math.cos(z/2),s1=Math.sin(x/2),s2=Math.sin(y/2),s3=Math.sin(z/2);return"XYZ"===order?(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):"YXZ"===order?(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):"ZXY"===order?(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):"ZYX"===order?(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):"YZX"===order?(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):"XZY"===order&&(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),this},Quaternion.prototype.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},Quaternion.prototype.slerp=function(toQuat,t,target){target=target||new Quaternion;var omega,cosom,sinom,scale0,scale1,ax=this.x,ay=this.y,az=this.z,aw=this.w,bx=toQuat.x,by=toQuat.y,bz=toQuat.z,bw=toQuat.w;return(cosom=ax*bx+ay*by+az*bz+aw*bw)<0&&(cosom=-cosom,bx=-bx,by=-by,bz=-bz,bw=-bw),1-cosom>1e-6?(omega=Math.acos(cosom),sinom=Math.sin(omega),scale0=Math.sin((1-t)*omega)/sinom,scale1=Math.sin(t*omega)/sinom):(scale0=1-t,scale1=t),target.x=scale0*ax+scale1*bx,target.y=scale0*ay+scale1*by,target.z=scale0*az+scale1*bz,target.w=scale0*aw+scale1*bw,target},Quaternion.prototype.integrate=function(angularVelocity,dt,angularFactor,target){target=target||new Quaternion;var ax=angularVelocity.x*angularFactor.x,ay=angularVelocity.y*angularFactor.y,az=angularVelocity.z*angularFactor.z,bx=this.x,by=this.y,bz=this.z,bw=this.w,half_dt=.5*dt;return target.x+=half_dt*(ax*bw+ay*bz-az*by),target.y+=half_dt*(ay*bw+az*bx-ax*bz),target.z+=half_dt*(az*bw+ax*by-ay*bx),target.w+=half_dt*(-ax*bx-ay*by-az*bz),target}},{"./Vec3":33}],32:[function(require,module,exports){function Transform(options){options=options||{},this.position=new Vec3,options.position&&this.position.copy(options.position),this.quaternion=new Quaternion,options.quaternion&&this.quaternion.copy(options.quaternion)}var Vec3=require("./Vec3"),Quaternion=require("./Quaternion");module.exports=Transform;var tmpQuat=new Quaternion;Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){var result=result||new Vec3;return worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.prototype.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){var result=result||new Vec3;return quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.prototype.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},Transform.prototype.vectorToWorldFrame=function(localVector,result){var result=result||new Vec3;return this.quaternion.vmult(localVector,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){var result=result||new Vec3;return quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result}},{"./Quaternion":31,"./Vec3":33}],33:[function(require,module,exports){function Vec3(x,y,z){this.x=x||0,this.y=y||0,this.z=z||0}module.exports=Vec3;var Mat3=require("./Mat3");Vec3.ZERO=new Vec3(0,0,0),Vec3.UNIT_X=new Vec3(1,0,0),Vec3.UNIT_Y=new Vec3(0,1,0),Vec3.UNIT_Z=new Vec3(0,0,1),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;return target=target||new Vec3,target.x=y*vz-z*vy,target.y=z*vx-x*vz,target.z=x*vy-y*vx,target},Vec3.prototype.set=function(x,y,z){return this.x=x,this.y=y,this.z=z,this},Vec3.prototype.setZero=function(){this.x=this.y=this.z=0},Vec3.prototype.vadd=function(v,target){if(!target)return new Vec3(this.x+v.x,this.y+v.y,this.z+v.z);target.x=v.x+this.x,target.y=v.y+this.y,target.z=v.z+this.z},Vec3.prototype.vsub=function(v,target){if(!target)return new Vec3(this.x-v.x,this.y-v.y,this.z-v.z);target.x=this.x-v.x,target.y=this.y-v.y,target.z=this.z-v.z},Vec3.prototype.crossmat=function(){return new Mat3([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])},Vec3.prototype.normalize=function(){var x=this.x,y=this.y,z=this.z,n=Math.sqrt(x*x+y*y+z*z);if(n>0){var invN=1/n;this.x*=invN,this.y*=invN,this.z*=invN}else this.x=0,this.y=0,this.z=0;return n},Vec3.prototype.unit=function(target){target=target||new Vec3;var x=this.x,y=this.y,z=this.z,ninv=Math.sqrt(x*x+y*y+z*z);return ninv>0?(ninv=1/ninv,target.x=x*ninv,target.y=y*ninv,target.z=z*ninv):(target.x=1,target.y=0,target.z=0),target},Vec3.prototype.norm=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},Vec3.prototype.length=Vec3.prototype.norm,Vec3.prototype.norm2=function(){return this.dot(this)},Vec3.prototype.lengthSquared=Vec3.prototype.norm2,Vec3.prototype.distanceTo=function(p){var x=this.x,y=this.y,z=this.z,px=p.x,py=p.y,pz=p.z;return Math.sqrt((px-x)*(px-x)+(py-y)*(py-y)+(pz-z)*(pz-z))},Vec3.prototype.distanceSquared=function(p){var x=this.x,y=this.y,z=this.z,px=p.x,py=p.y,pz=p.z;return(px-x)*(px-x)+(py-y)*(py-y)+(pz-z)*(pz-z)},Vec3.prototype.mult=function(scalar,target){target=target||new Vec3;var x=this.x,y=this.y,z=this.z;return target.x=scalar*x,target.y=scalar*y,target.z=scalar*z,target},Vec3.prototype.vmul=function(vector,target){return target=target||new Vec3,target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},Vec3.prototype.scale=Vec3.prototype.mult,Vec3.prototype.addScaledVector=function(scalar,vector,target){return target=target||new Vec3,target.x=this.x+scalar*vector.x,target.y=this.y+scalar*vector.y,target.z=this.z+scalar*vector.z,target},Vec3.prototype.dot=function(v){return this.x*v.x+this.y*v.y+this.z*v.z},Vec3.prototype.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},Vec3.prototype.negate=function(target){return target=target||new Vec3,target.x=-this.x,target.y=-this.y,target.z=-this.z,target};var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3;Vec3.prototype.tangents=function(t1,t2){var norm=this.norm();if(norm>0){var n=Vec3_tangents_n,inorm=1/norm;n.set(this.x*inorm,this.y*inorm,this.z*inorm);var randVec=Vec3_tangents_randVec;Math.abs(n.x)<.9?(randVec.set(1,0,0),n.cross(randVec,t1)):(randVec.set(0,1,0),n.cross(randVec,t1)),n.cross(t1,t2)}else t1.set(1,0,0),t2.set(0,1,0)},Vec3.prototype.toString=function(){return this.x+","+this.y+","+this.z},Vec3.prototype.toArray=function(){return[this.x,this.y,this.z]},Vec3.prototype.copy=function(source){return this.x=source.x,this.y=source.y,this.z=source.z,this},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},Vec3.prototype.almostEquals=function(v,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-v.x)>precision||Math.abs(this.y-v.y)>precision||Math.abs(this.z-v.z)>precision)},Vec3.prototype.almostZero=function(precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x)>precision||Math.abs(this.y)>precision||Math.abs(this.z)>precision)};var antip_neg=new Vec3;Vec3.prototype.isAntiparallelTo=function(v,precision){return this.negate(antip_neg),antip_neg.almostEquals(v,precision)},Vec3.prototype.clone=function(){return new Vec3(this.x,this.y,this.z)}},{"./Mat3":30}],34:[function(require,module,exports){function Body(options){options=options||{},EventTarget.apply(this),this.id=Body.idCounter++,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new Vec3,this.collisionFilterGroup="number"==typeof options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask="number"==typeof options.collisionFilterMask?options.collisionFilterMask:1,this.collisionResponse=!0,this.position=new Vec3,this.previousPosition=new Vec3,this.interpolatedPosition=new Vec3,this.initPosition=new Vec3,options.position&&(this.position.copy(options.position),this.previousPosition.copy(options.position),this.interpolatedPosition.copy(options.position),this.initPosition.copy(options.position)),this.velocity=new Vec3,options.velocity&&this.velocity.copy(options.velocity),this.initVelocity=new Vec3,this.force=new Vec3;var mass="number"==typeof options.mass?options.mass:0;this.mass=mass,this.invMass=mass>0?1/mass:0,this.material=options.material||null,this.linearDamping="number"==typeof options.linearDamping?options.linearDamping:.01,this.type=mass<=0?Body.STATIC:Body.DYNAMIC,typeof options.type==typeof Body.STATIC&&(this.type=options.type),this.allowSleep=void 0===options.allowSleep||options.allowSleep,this.sleepState=0,this.sleepSpeedLimit=void 0!==options.sleepSpeedLimit?options.sleepSpeedLimit:.1,this.sleepTimeLimit=void 0!==options.sleepTimeLimit?options.sleepTimeLimit:1,this.timeLastSleepy=0,this._wakeUpAfterNarrowphase=!1,this.torque=new Vec3,this.quaternion=new Quaternion,this.initQuaternion=new Quaternion,this.previousQuaternion=new Quaternion,this.interpolatedQuaternion=new Quaternion,options.quaternion&&(this.quaternion.copy(options.quaternion),this.initQuaternion.copy(options.quaternion),this.previousQuaternion.copy(options.quaternion),this.interpolatedQuaternion.copy(options.quaternion)),this.angularVelocity=new Vec3,options.angularVelocity&&this.angularVelocity.copy(options.angularVelocity),this.initAngularVelocity=new Vec3,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new Vec3,this.invInertia=new Vec3,this.invInertiaWorld=new Mat3,this.invMassSolve=0,this.invInertiaSolve=new Vec3,this.invInertiaWorldSolve=new Mat3,this.fixedRotation=void 0!==options.fixedRotation&&options.fixedRotation,this.angularDamping=void 0!==options.angularDamping?options.angularDamping:.01,this.linearFactor=new Vec3(1,1,1),options.linearFactor&&this.linearFactor.copy(options.linearFactor),this.angularFactor=new Vec3(1,1,1),options.angularFactor&&this.angularFactor.copy(options.angularFactor),this.aabb=new AABB,this.aabbNeedsUpdate=!0,this.wlambda=new Vec3,options.shape&&this.addShape(options.shape),this.updateMassProperties()}module.exports=Body;var EventTarget=require("../utils/EventTarget"),Vec3=(require("../shapes/Shape"),require("../math/Vec3")),Mat3=require("../math/Mat3"),Quaternion=require("../math/Quaternion"),AABB=(require("../material/Material"),require("../collision/AABB")),Box=require("../shapes/Box");Body.prototype=new EventTarget,Body.prototype.constructor=Body,Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=0,Body.SLEEPY=1,Body.SLEEPING=2,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.prototype.wakeUp=function(){var s=this.sleepState;this.sleepState=0,this._wakeUpAfterNarrowphase=!1,s===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},Body.prototype.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this._wakeUpAfterNarrowphase=!1},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"},Body.prototype.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.norm2()+this.angularVelocity.norm2(),speedLimitSquared=Math.pow(this.sleepSpeedLimit,2);sleepState===Body.AWAKE&&speedSquaredspeedLimitSquared?this.wakeUp():sleepState===Body.SLEEPY&&time-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(Body.sleepEvent))}},Body.prototype.updateSolveMassProperties=function(){this.sleepState===Body.SLEEPING||this.type===Body.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))},Body.prototype.pointToLocalFrame=function(worldPoint,result){var result=result||new Vec3;return worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},Body.prototype.vectorToLocalFrame=function(worldVector,result){var result=result||new Vec3;return this.quaternion.conjugate().vmult(worldVector,result),result},Body.prototype.pointToWorldFrame=function(localPoint,result){var result=result||new Vec3;return this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},Body.prototype.vectorToWorldFrame=function(localVector,result){var result=result||new Vec3;return this.quaternion.vmult(localVector,result),result};var tmpVec=new Vec3,tmpQuat=new Quaternion;Body.prototype.addShape=function(shape,_offset,_orientation){var offset=new Vec3,orientation=new Quaternion;return _offset&&offset.copy(_offset),_orientation&&orientation.copy(_orientation),this.shapes.push(shape),this.shapeOffsets.push(offset),this.shapeOrientations.push(orientation),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,shape.body=this,this},Body.prototype.updateBoundingRadius=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,N=shapes.length,radius=0,i=0;i!==N;i++){var shape=shapes[i];shape.updateBoundingSphereRadius();var offset=shapeOffsets[i].norm(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius};var computeAABB_shapeAABB=new AABB;Body.prototype.computeAABB=function(){for(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,i=0;i!==N;i++){var shape=shapes[i];bodyQuat.vmult(shapeOffsets[i],offset),offset.vadd(this.position,offset),shapeOrientations[i].mult(bodyQuat,orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1};var uiw_m1=new Mat3,uiw_m2=new Mat3;new Mat3;Body.prototype.updateInertiaWorld=function(force){var I=this.invInertia;if(I.x!==I.y||I.y!==I.z||force){var m1=uiw_m1,m2=uiw_m2;m1.setRotationFromQuaternion(this.quaternion),m1.transpose(m2),m1.scale(I,m1),m1.mmult(m2,this.invInertiaWorld)}else;};new Vec3;var Body_applyForce_rotForce=new Vec3;Body.prototype.applyForce=function(force,relativePoint){if(this.type===Body.DYNAMIC){var rotForce=Body_applyForce_rotForce;relativePoint.cross(force,rotForce),this.force.vadd(force,this.force),this.torque.vadd(rotForce,this.torque)}};var Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3;Body.prototype.applyLocalForce=function(localForce,localPoint){if(this.type===Body.DYNAMIC){var worldForce=Body_applyLocalForce_worldForce,relativePointWorld=Body_applyLocalForce_relativePointWorld;this.vectorToWorldFrame(localForce,worldForce),this.vectorToWorldFrame(localPoint,relativePointWorld),this.applyForce(worldForce,relativePointWorld)}};new Vec3;var Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3;Body.prototype.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.mult(this.invMass,velo),this.velocity.vadd(velo,this.velocity);var rotVelo=Body_applyImpulse_rotVelo;r.cross(impulse,rotVelo),this.invInertiaWorld.vmult(rotVelo,rotVelo),this.angularVelocity.vadd(rotVelo,this.angularVelocity)}};var Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3;Body.prototype.applyLocalImpulse=function(localImpulse,localPoint){if(this.type===Body.DYNAMIC){var worldImpulse=Body_applyLocalImpulse_worldImpulse,relativePointWorld=Body_applyLocalImpulse_relativePoint;this.vectorToWorldFrame(localImpulse,worldImpulse),this.vectorToWorldFrame(localPoint,relativePointWorld),this.applyImpulse(worldImpulse,relativePointWorld)}};var Body_updateMassProperties_halfExtents=new Vec3;Body.prototype.updateMassProperties=function(){var halfExtents=Body_updateMassProperties_halfExtents;this.invMass=this.mass>0?1/this.mass:0;var I=this.inertia,fixed=this.fixedRotation;this.computeAABB(),halfExtents.set((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),Box.calculateInertia(halfExtents,this.mass,I),this.invInertia.set(I.x>0&&!fixed?1/I.x:0,I.y>0&&!fixed?1/I.y:0,I.z>0&&!fixed?1/I.z:0),this.updateInertiaWorld(!0)},Body.prototype.getVelocityAtWorldPoint=function(worldPoint,result){var r=new Vec3;return worldPoint.vsub(this.position,r),this.angularVelocity.cross(r,result),this.velocity.vadd(result,result),result};new Vec3,new Vec3,new Quaternion,new Quaternion;Body.prototype.integrate=function(dt,quatNormalize,quatNormalizeFast){if(this.previousPosition.copy(this.position),this.previousQuaternion.copy(this.quaternion),(this.type===Body.DYNAMIC||this.type===Body.KINEMATIC)&&this.sleepState!==Body.SLEEPING){var velo=this.velocity,angularVelo=this.angularVelocity,pos=this.position,force=this.force,torque=this.torque,quat=this.quaternion,invMass=this.invMass,invInertia=this.invInertiaWorld,linearFactor=this.linearFactor,iMdt=invMass*dt;velo.x+=force.x*iMdt*linearFactor.x,velo.y+=force.y*iMdt*linearFactor.y,velo.z+=force.z*iMdt*linearFactor.z;var e=invInertia.elements,angularFactor=this.angularFactor,tx=torque.x*angularFactor.x,ty=torque.y*angularFactor.y,tz=torque.z*angularFactor.z;angularVelo.x+=dt*(e[0]*tx+e[1]*ty+e[2]*tz),angularVelo.y+=dt*(e[3]*tx+e[4]*ty+e[5]*tz),angularVelo.z+=dt*(e[6]*tx+e[7]*ty+e[8]*tz),pos.x+=velo.x*dt,pos.y+=velo.y*dt,pos.z+=velo.z*dt,quat.integrate(this.angularVelocity,dt,this.angularFactor,quat),quatNormalize&&(quatNormalizeFast?quat.normalizeFast():quat.normalize()),this.aabbNeedsUpdate=!0,this.updateInertiaWorld()}}},{"../collision/AABB":5,"../material/Material":28,"../math/Mat3":30,"../math/Quaternion":31,"../math/Vec3":33,"../shapes/Box":40,"../shapes/Shape":46,"../utils/EventTarget":52}],35:[function(require,module,exports){function RaycastVehicle(options){this.chassisBody=options.chassisBody,this.wheelInfos=[],this.sliding=!1,this.world=null,this.indexRightAxis=void 0!==options.indexRightAxis?options.indexRightAxis:1,this.indexForwardAxis=void 0!==options.indexForwardAxis?options.indexForwardAxis:0,this.indexUpAxis=void 0!==options.indexUpAxis?options.indexUpAxis:2}function calcRollingFriction(body0,body1,frictionPosWorld,frictionDirectionWorld,maxImpulse){var j1=0,contactPosWorld=frictionPosWorld,vel1=calcRollingFriction_vel1,vel2=calcRollingFriction_vel2,vel=calcRollingFriction_vel;body0.getVelocityAtWorldPoint(contactPosWorld,vel1),body1.getVelocityAtWorldPoint(contactPosWorld,vel2),vel1.vsub(vel2,vel);return j1=-frictionDirectionWorld.dot(vel)*(1/(computeImpulseDenominator(body0,frictionPosWorld,frictionDirectionWorld)+computeImpulseDenominator(body1,frictionPosWorld,frictionDirectionWorld))),maxImpulse1.1)return 0;var vel1=resolveSingleBilateral_vel1,vel2=resolveSingleBilateral_vel2,vel=resolveSingleBilateral_vel;body1.getVelocityAtWorldPoint(pos1,vel1),body2.getVelocityAtWorldPoint(pos2,vel2),vel1.vsub(vel2,vel);return-.2*normal.dot(vel)*(1/(body1.invMass+body2.invMass))}require("./Body");var Vec3=require("../math/Vec3"),Quaternion=require("../math/Quaternion"),Ray=(require("../collision/RaycastResult"),require("../collision/Ray")),WheelInfo=require("../objects/WheelInfo");module.exports=RaycastVehicle;new Vec3,new Vec3,new Vec3;var tmpVec4=new Vec3,tmpVec5=new Vec3,tmpVec6=new Vec3;new Ray;RaycastVehicle.prototype.addWheel=function(options){var info=new WheelInfo(options=options||{}),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},RaycastVehicle.prototype.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value};new Vec3;RaycastVehicle.prototype.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},RaycastVehicle.prototype.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},RaycastVehicle.prototype.addToWorld=function(world){this.constraints;world.addBody(this.chassisBody);var that=this;this.preStepCallback=function(){that.updateVehicle(world.dt)},world.addEventListener("preStep",this.preStepCallback),this.world=world},RaycastVehicle.prototype.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},RaycastVehicle.prototype.updateVehicle=function(timeStep){for(var wheelInfos=this.wheelInfos,numWheels=wheelInfos.length,chassisBody=this.chassisBody,i=0;iwheel.maxSuspensionForce&&(suspensionForce=wheel.maxSuspensionForce),wheel.raycastResult.hitNormalWorld.scale(suspensionForce*timeStep,impulse),wheel.raycastResult.hitPointWorld.vsub(chassisBody.position,relpos),chassisBody.applyImpulse(impulse,relpos)}this.updateFriction(timeStep);var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3;for(i=0;i0?1:-1)*wheel.customSlidingRotationalSpeed*timeStep),Math.abs(wheel.brake)>Math.abs(wheel.engineForce)&&(wheel.deltaRotation=0),wheel.rotation+=wheel.deltaRotation,wheel.deltaRotation*=.99}},RaycastVehicle.prototype.updateSuspension=function(deltaTime){for(var chassisMass=this.chassisBody.mass,wheelInfos=this.wheelInfos,numWheels=wheelInfos.length,w_it=0;w_itmaxSuspensionLength&&(wheel.suspensionLength=maxSuspensionLength,wheel.raycastResult.reset());var denominator=wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld),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>=-.1)wheel.suspensionRelativeVelocity=0,wheel.clippedInvContactDotSuspension=10;else{var inv=-1/denominator;wheel.suspensionRelativeVelocity=projVel*inv,wheel.clippedInvContactDotSuspension=inv}}else wheel.suspensionLength=wheel.suspensionRestLength+0*wheel.maxSuspensionTravel,wheel.suspensionRelativeVelocity=0,wheel.directionWorld.scale(-1,wheel.raycastResult.hitNormalWorld),wheel.clippedInvContactDotSuspension=1;return depth},RaycastVehicle.prototype.updateWheelTransformWorld=function(wheel){wheel.isInContact=!1;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,right=tmpVec5,fwd=tmpVec6,wheel=this.wheelInfos[wheelIndex];this.updateWheelTransformWorld(wheel),wheel.directionLocal.scale(-1,up),right.copy(wheel.axleLocal),up.cross(right,fwd),fwd.normalize(),right.normalize();var steering=wheel.steering,steeringOrn=new Quaternion;steeringOrn.setFromAxisAngle(up,steering);var rotatingOrn=new Quaternion;rotatingOrn.setFromAxisAngle(right,wheel.rotation);var q=wheel.worldTransform.quaternion;this.chassisBody.quaternion.mult(steeringOrn,q),q.mult(rotatingOrn,q),q.normalize();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)];RaycastVehicle.prototype.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform};var updateFriction_surfNormalWS_scaled_proj=new Vec3,updateFriction_axle=[],updateFriction_forwardWS=[];RaycastVehicle.prototype.updateFriction=function(timeStep){for(var surfNormalWS_scaled_proj=updateFriction_surfNormalWS_scaled_proj,wheelInfos=this.wheelInfos,numWheels=wheelInfos.length,chassisBody=this.chassisBody,forwardWS=updateFriction_forwardWS,axle=updateFriction_axle,numWheelsOnGround=0,i=0;imaximpSquared){this.sliding=!0,wheel.sliding=!0;var factor=maximp/Math.sqrt(impulseSquared);wheel.skidInfo*=factor}}}if(this.sliding)for(i=0;ithis.particles.length&&this.neighbors.pop())};var SPHSystem_getNeighbors_dist=new Vec3;SPHSystem.prototype.getNeighbors=function(particle,neighbors){for(var N=this.particles.length,id=particle.id,R2=this.smoothingRadius*this.smoothingRadius,dist=SPHSystem_getNeighbors_dist,i=0;i!==N;i++){var p=this.particles[i];p.position.vsub(particle.position,dist),id!==p.id&&dist.norm2()=-.1)this.suspensionRelativeVelocity=0,this.clippedInvContactDotSuspension=10;else{var inv=-1/project;this.suspensionRelativeVelocity=projVel*inv,this.clippedInvContactDotSuspension=inv}}else raycastResult.suspensionLength=this.suspensionRestLength,this.suspensionRelativeVelocity=0,raycastResult.directionWorld.scale(-1,raycastResult.hitNormalWorld),this.clippedInvContactDotSuspension=1}},{"../collision/RaycastResult":13,"../math/Transform":32,"../math/Vec3":33,"../utils/Utils":56}],40:[function(require,module,exports){function Box(halfExtents){Shape.call(this),this.type=Shape.types.BOX,this.halfExtents=halfExtents,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}module.exports=Box;var Shape=require("./Shape"),Vec3=require("../math/Vec3"),ConvexPolyhedron=require("./ConvexPolyhedron");Box.prototype=new Shape,Box.prototype.constructor=Box,Box.prototype.updateConvexPolyhedronRepresentation=function(){var sx=this.halfExtents.x,sy=this.halfExtents.y,sz=this.halfExtents.z,V=Vec3,vertices=[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)],indices=[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]],h=(new V(0,0,1),new V(0,1,0),new V(1,0,0),new ConvexPolyhedron(vertices,indices));this.convexPolyhedronRepresentation=h,h.material=this.material},Box.prototype.calculateLocalInertia=function(mass,target){return target=target||new Vec3,Box.calculateInertia(this.halfExtents,mass,target),target},Box.calculateInertia=function(halfExtents,mass,target){var e=halfExtents;target.x=1/12*mass*(2*e.y*2*e.y+2*e.z*2*e.z),target.y=1/12*mass*(2*e.x*2*e.x+2*e.z*2*e.z),target.z=1/12*mass*(2*e.y*2*e.y+2*e.x*2*e.x)},Box.prototype.getSideNormals=function(sixTargetVectors,quat){var sides=sixTargetVectors,ex=this.halfExtents;if(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),void 0!==quat)for(var i=0;i!==sides.length;i++)quat.vmult(sides[i],sides[i]);return sides},Box.prototype.volume=function(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z},Box.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.halfExtents.norm()};var worldCornerTempPos=new Vec3;new Vec3;Box.prototype.forEachWorldCorner=function(pos,quat,callback){for(var e=this.halfExtents,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]],i=0;imax.x&&(max.x=x),y>max.y&&(max.y=y),z>max.z&&(max.z=z),xdmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],polyB=hullB.faces[closestFaceB],numVertices=polyB.length,e0=0;e0=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)};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,dmin=Number.MAX_VALUE,hullA=this,curPlaneTests=0;if(hullA.uniqueAxes)for(i=0;i!==hullA.uniqueAxes.length;i++){if(quatA.vmult(hullA.uniqueAxes[i],faceANormalWS3),!1===(d=hullA.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB)))return!1;d0&&target.negate(target),!0};var maxminA=[],maxminB=[];ConvexPolyhedron.prototype.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){var hullA=this;ConvexPolyhedron.project(hullA,axis,posA,quatA,maxminA),ConvexPolyhedron.project(hullB,axis,posB,quatB,maxminB);var maxA=maxminA[0],minA=maxminA[1],maxB=maxminB[0],minB=maxminB[1];if(maxAmaxValue&&(maxValue=v)}this.maxValue=maxValue},Heightfield.prototype.setHeightValueAtIndex=function(xi,yi,value){this.data[xi][yi]=value,this.clearCachedConvexTrianglePillar(xi,yi,!1),xi>0&&(this.clearCachedConvexTrianglePillar(xi-1,yi,!0),this.clearCachedConvexTrianglePillar(xi-1,yi,!1)),yi>0&&(this.clearCachedConvexTrianglePillar(xi,yi-1,!0),this.clearCachedConvexTrianglePillar(xi,yi-1,!1)),yi>0&&xi>0&&this.clearCachedConvexTrianglePillar(xi-1,yi-1,!0)},Heightfield.prototype.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){result=result||[];for(var data=this.data,max=this.minValue,i=iMinX;i<=iMaxX;i++)for(var j=iMinY;j<=iMaxY;j++){var height=data[i][j];height>max&&(max=height)}result[0]=this.minValue,result[1]=max},Heightfield.prototype.getIndexOfPosition=function(x,y,result,clamp){var w=this.elementSize,data=this.data,xi=Math.floor(x/w),yi=Math.floor(y/w);return result[0]=xi,result[1]=yi,clamp&&(xi<0&&(xi=0),yi<0&&(yi=0),xi>=data.length-1&&(xi=data.length-1),yi>=data[0].length-1&&(yi=data[0].length-1)),!(xi<0||yi<0||xi>=data.length-1||yi>=data[0].length-1)};var getHeightAt_idx=[],getHeightAt_weights=new Vec3,getHeightAt_a=new Vec3,getHeightAt_b=new Vec3,getHeightAt_c=new Vec3;Heightfield.prototype.getTriangleAt=function(x,y,edgeClamp,a,b,c){var idx=getHeightAt_idx;this.getIndexOfPosition(x,y,idx,edgeClamp);var xi=idx[0],yi=idx[1],data=this.data;edgeClamp&&(xi=Math.min(data.length-2,Math.max(0,xi)),yi=Math.min(data[0].length-2,Math.max(0,yi)));var elementSize=this.elementSize,upper=Math.pow(x/elementSize-xi,2)+Math.pow(y/elementSize-yi,2)>Math.pow(x/elementSize-(xi+1),2)+Math.pow(y/elementSize-(yi+1),2);return this.getTriangle(xi,yi,upper,a,b,c),upper};var getNormalAt_a=new Vec3,getNormalAt_b=new Vec3,getNormalAt_c=new Vec3,getNormalAt_e0=new Vec3,getNormalAt_e1=new Vec3;Heightfield.prototype.getNormalAt=function(x,y,edgeClamp,result){var a=getNormalAt_a,b=getNormalAt_b,c=getNormalAt_c,e0=getNormalAt_e0,e1=getNormalAt_e1;this.getTriangleAt(x,y,edgeClamp,a,b,c),b.vsub(a,e0),c.vsub(a,e1),e0.cross(e1,result),result.normalize()},Heightfield.prototype.getAabbAtIndex=function(xi,yi,result){var data=this.data,elementSize=this.elementSize;result.lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),result.upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},Heightfield.prototype.getHeightAt=function(x,y,edgeClamp){var data=this.data,a=getHeightAt_a,b=getHeightAt_b,c=getHeightAt_c,idx=getHeightAt_idx;this.getIndexOfPosition(x,y,idx,edgeClamp);var xi=idx[0],yi=idx[1];edgeClamp&&(xi=Math.min(data.length-2,Math.max(0,xi)),yi=Math.min(data[0].length-2,Math.max(0,yi)));var upper=this.getTriangleAt(x,y,edgeClamp,a,b,c);barycentricWeights(x,y,a.x,a.y,b.x,b.y,c.x,c.y,getHeightAt_weights);var w=getHeightAt_weights;return upper?data[xi+1][yi+1]*w.x+data[xi][yi+1]*w.y+data[xi+1][yi]*w.z:data[xi][yi]*w.x+data[xi+1][yi]*w.y+data[xi][yi+1]*w.z},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)]},Heightfield.prototype.getTriangle=function(xi,yi,upper,a,b,c){var data=this.data,elementSize=this.elementSize;upper?(a.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1]),b.set(xi*elementSize,(yi+1)*elementSize,data[xi][yi+1]),c.set((xi+1)*elementSize,yi*elementSize,data[xi+1][yi])):(a.set(xi*elementSize,yi*elementSize,data[xi][yi]),b.set((xi+1)*elementSize,yi*elementSize,data[xi+1][yi]),c.set(xi*elementSize,(yi+1)*elementSize,data[xi][yi+1]))},Heightfield.prototype.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){if(data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle))return this.pillarConvex=data.convex,void(this.pillarOffset=data.offset);result=new ConvexPolyhedron,offsetResult=new Vec3,this.pillarConvex=result,this.pillarOffset=offsetResult}var data=this.data,elementSize=this.elementSize,faces=result.faces;result.vertices.length=6;for(i=0;i<6;i++)result.vertices[i]||(result.vertices[i]=new Vec3);faces.length=5;for(var i=0;i<5;i++)faces[i]||(faces[i]=[]);var verts=result.vertices,h=(Math.min(data[xi][yi],data[xi+1][yi],data[xi][yi+1],data[xi+1][yi+1])-this.minValue)/2+this.minValue;getUpperTriangle?(offsetResult.set((xi+.75)*elementSize,(yi+.75)*elementSize,h),verts[0].set(.25*elementSize,.25*elementSize,data[xi+1][yi+1]-h),verts[1].set(-.75*elementSize,.25*elementSize,data[xi][yi+1]-h),verts[2].set(.25*elementSize,-.75*elementSize,data[xi+1][yi]-h),verts[3].set(.25*elementSize,.25*elementSize,-h-1),verts[4].set(-.75*elementSize,.25*elementSize,-h-1),verts[5].set(.25*elementSize,-.75*elementSize,-h-1),faces[0][0]=0,faces[0][1]=1,faces[0][2]=2,faces[1][0]=5,faces[1][1]=4,faces[1][2]=3,faces[2][0]=2,faces[2][1]=5,faces[2][2]=3,faces[2][3]=0,faces[3][0]=3,faces[3][1]=4,faces[3][2]=1,faces[3][3]=0,faces[4][0]=1,faces[4][1]=4,faces[4][2]=5,faces[4][3]=2):(offsetResult.set((xi+.25)*elementSize,(yi+.25)*elementSize,h),verts[0].set(-.25*elementSize,-.25*elementSize,data[xi][yi]-h),verts[1].set(.75*elementSize,-.25*elementSize,data[xi+1][yi]-h),verts[2].set(-.25*elementSize,.75*elementSize,data[xi][yi+1]-h),verts[3].set(-.25*elementSize,-.25*elementSize,-h-1),verts[4].set(.75*elementSize,-.25*elementSize,-h-1),verts[5].set(-.25*elementSize,.75*elementSize,-h-1),faces[0][0]=0,faces[0][1]=1,faces[0][2]=2,faces[1][0]=5,faces[1][1]=4,faces[1][2]=3,faces[2][0]=0,faces[2][1]=2,faces[2][2]=5,faces[2][3]=3,faces[3][0]=1,faces[3][1]=0,faces[3][2]=3,faces[3][3]=4,faces[4][0]=4,faces[4][1]=5,faces[4][2]=2,faces[4][3]=1),result.computeNormals(),result.computeEdges(),result.updateBoundingSphereRadius(),this.setCachedConvexTrianglePillar(xi,yi,getUpperTriangle,result,offsetResult)},Heightfield.prototype.calculateLocalInertia=function(mass,target){return(target=target||new Vec3).set(0,0,0),target},Heightfield.prototype.volume=function(){return Number.MAX_VALUE},Heightfield.prototype.calculateWorldAABB=function(pos,quat,min,max){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(){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()},Heightfield.prototype.setHeightsFromImage=function(image,scale){var canvas=document.createElement("canvas");canvas.width=image.width,canvas.height=image.height;var context=canvas.getContext("2d");context.drawImage(image,0,0);var imageData=context.getImageData(0,0,image.width,image.height),matrix=this.data;matrix.length=0,this.elementSize=Math.abs(scale.x)/imageData.width;for(var i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},Trimesh.prototype.updateAABB=function(){this.computeLocalAABB(this.aabb)},Trimesh.prototype.updateBoundingSphereRadius=function(){for(var max2=0,vertices=this.vertices,v=new Vec3,i=0,N=vertices.length/3;i!==N;i++){this.getVertex(i,v);var norm2=v.norm2();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)};new Vec3;var calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.prototype.calculateWorldAABB=function(pos,quat,min,max){var frame=calculateWorldAABB_frame,result=calculateWorldAABB_aabb;frame.position=pos,frame.quaternion=quat,this.aabb.toWorldFrame(frame,result),min.copy(result.lowerBound),max.copy(result.upperBound)},Trimesh.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){radius=radius||1,tube=tube||.5,radialSegments=radialSegments||8,tubularSegments=tubularSegments||6,arc=arc||2*Math.PI;for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(i=0;i<=tubularSegments;i++){var u=i/tubularSegments*arc,v=j/radialSegments*Math.PI*2,x=(radius+tube*Math.cos(v))*Math.cos(u),y=(radius+tube*Math.cos(v))*Math.sin(u),z=tube*Math.sin(v);vertices.push(x,y,z)}for(j=1;j<=radialSegments;j++)for(var i=1;i<=tubularSegments;i++){var a=(tubularSegments+1)*j+i-1,b=(tubularSegments+1)*(j-1)+i-1,c=(tubularSegments+1)*(j-1)+i,d=(tubularSegments+1)*j+i;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)}},{"../collision/AABB":5,"../math/Quaternion":31,"../math/Transform":32,"../math/Vec3":33,"../utils/Octree":53,"./Shape":46}],49:[function(require,module,exports){function GSSolver(){Solver.call(this),this.iterations=10,this.tolerance=1e-7}module.exports=GSSolver;require("../math/Vec3"),require("../math/Quaternion");var Solver=require("./Solver");GSSolver.prototype=new Solver;var GSSolver_solve_lambda=[],GSSolver_solve_invCs=[],GSSolver_solve_Bs=[];GSSolver.prototype.solve=function(dt,world){var B,invC,deltalambda,deltalambdaTot,lambdaj,iter=0,maxIter=this.iterations,tolSquared=this.tolerance*this.tolerance,equations=this.equations,Neq=equations.length,bodies=world.bodies,Nbodies=bodies.length,h=dt;if(0!==Neq)for(i=0;i!==Nbodies;i++)bodies[i].updateSolveMassProperties();var invCs=GSSolver_solve_invCs,Bs=GSSolver_solve_Bs,lambda=GSSolver_solve_lambda;invCs.length=Neq,Bs.length=Neq,lambda.length=Neq;for(i=0;i!==Neq;i++){c=equations[i];lambda[i]=0,Bs[i]=c.computeB(h),invCs[i]=1/c.computeC()}if(0!==Neq){for(i=0;i!==Nbodies;i++){var vlambda=(b=bodies[i]).vlambda,wlambda=b.wlambda;vlambda.set(0,0,0),wlambda.set(0,0,0)}for(iter=0;iter!==maxIter;iter++){deltalambdaTot=0;for(var j=0;j!==Neq;j++){var c=equations[j];B=Bs[j],invC=invCs[j],(lambdaj=lambda[j])+(deltalambda=invC*(B-c.computeGWlambda()-c.eps*lambdaj))c.maxForce&&(deltalambda=c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTot=0;i--)node.children[i].data.length||node.children.splice(i,1);Array.prototype.push.apply(queue,node.children)}}},{"../collision/AABB":5,"../math/Vec3":33}],54:[function(require,module,exports){function Pool(){this.objects=[],this.type=Object}module.exports=Pool,Pool.prototype.release=function(){for(var Nargs=arguments.length,i=0;i!==Nargs;i++)this.objects.push(arguments[i]);return this},Pool.prototype.get=function(){return 0===this.objects.length?this.constructObject():this.objects.pop()},Pool.prototype.constructObject=function(){throw new Error("constructObject() not implemented in this Pool subclass yet!")},Pool.prototype.resize=function(size){for(var objects=this.objects;objects.length>size;)objects.pop();for(;objects.lengthj){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},TupleDictionary.prototype.set=function(i,j,value){if(i>j){var temp=j;j=i,i=temp}var key=i+"-"+j;this.get(i,j)||this.data.keys.push(key),this.data[key]=value},TupleDictionary.prototype.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;)delete data[keys.pop()]}},{}],56:[function(require,module,exports){function Utils(){}module.exports=Utils,Utils.defaults=function(options,defaults){options=options||{};for(var key in defaults)key in options||(options[key]=defaults[key]);return options}},{}],57:[function(require,module,exports){function Vec3Pool(){Pool.call(this),this.type=Vec3}module.exports=Vec3Pool;var Vec3=require("../math/Vec3"),Pool=require("./Pool");Vec3Pool.prototype=new Pool,Vec3Pool.prototype.constructObject=function(){return new Vec3}},{"../math/Vec3":33,"./Pool":54}],58:[function(require,module,exports){function Narrowphase(world){this.contactPointPool=[],this.frictionEquationPool=[],this.result=[],this.frictionResult=[],this.v3pool=new Vec3Pool,this.world=world,this.currentContactMaterial=null,this.enableFrictionReduction=!1}function pointInPolygon(verts,normal,p){for(var positiveResult=null,N=verts.length,i=0;i!==N;i++){var v=verts[i],edge=pointInPolygon_edge;verts[(i+1)%N].vsub(v,edge);var edge_x_normal=pointInPolygon_edge_x_normal;edge.cross(normal,edge_x_normal);var vertex_to_p=pointInPolygon_vtp;p.vsub(v,vertex_to_p);var r=edge_x_normal.dot(vertex_to_p);if(!(null===positiveResult||r>0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}module.exports=Narrowphase;var AABB=require("../collision/AABB"),Body=require("../objects/Body"),Shape=require("../shapes/Shape"),Ray=require("../collision/Ray"),Vec3=require("../math/Vec3"),Transform=require("../math/Transform"),Quaternion=(require("../shapes/ConvexPolyhedron"),require("../math/Quaternion")),Vec3Pool=(require("../solver/Solver"),require("../utils/Vec3Pool")),ContactEquation=require("../equations/ContactEquation"),FrictionEquation=require("../equations/FrictionEquation");Narrowphase.prototype.createContactEquation=function(bi,bj,si,sj,overrideShapeA,overrideShapeB){var c;this.contactPointPool.length?((c=this.contactPointPool.pop()).bi=bi,c.bj=bj):c=new ContactEquation(bi,bj),c.enabled=bi.collisionResponse&&bj.collisionResponse&&si.collisionResponse&&sj.collisionResponse;var cm=this.currentContactMaterial;c.restitution=cm.restitution,c.setSpookParams(cm.contactEquationStiffness,cm.contactEquationRelaxation,this.world.dt);var matA=si.material||bi.material,matB=sj.material||bj.material;return matA&&matB&&matA.restitution>=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},Narrowphase.prototype.createFrictionEquationsFromContact=function(contactEquation,outArray){var bodyA=contactEquation.bi,bodyB=contactEquation.bj,shapeA=contactEquation.si,shapeB=contactEquation.sj,world=this.world,cm=this.currentContactMaterial,friction=cm.friction,matA=shapeA.material||bodyA.material,matB=shapeB.material||bodyB.material;if(matA&&matB&&matA.friction>=0&&matB.friction>=0&&(friction=matA.friction*matB.friction),friction>0){var mug=friction*world.gravity.length(),reducedMass=bodyA.invMass+bodyB.invMass;reducedMass>0&&(reducedMass=1/reducedMass);var pool=this.frictionEquationPool,c1=pool.length?pool.pop():new FrictionEquation(bodyA,bodyB,mug*reducedMass),c2=pool.length?pool.pop():new FrictionEquation(bodyA,bodyB,mug*reducedMass);return c1.bi=c2.bi=bodyA,c1.bj=c2.bj=bodyB,c1.minForce=c2.minForce=-mug*reducedMass,c1.maxForce=c2.maxForce=mug*reducedMass,c1.ri.copy(contactEquation.ri),c1.rj.copy(contactEquation.rj),c2.ri.copy(contactEquation.ri),c2.rj.copy(contactEquation.rj),contactEquation.ni.tangents(c1.t,c2.t),c1.setSpookParams(cm.frictionEquationStiffness,cm.frictionEquationRelaxation,world.dt),c2.setSpookParams(cm.frictionEquationStiffness,cm.frictionEquationRelaxation,world.dt),c1.enabled=c2.enabled=contactEquation.enabled,outArray.push(c1,c2),!0}return!1};var averageNormal=new Vec3,averageContactPointA=new Vec3,averageContactPointB=new Vec3;Narrowphase.prototype.createFrictionFromAverage=function(numContacts){var c=this.result[this.result.length-1];if(this.createFrictionEquationsFromContact(c,this.frictionResult)&&1!==numContacts){var f1=this.frictionResult[this.frictionResult.length-2],f2=this.frictionResult[this.frictionResult.length-1];averageNormal.setZero(),averageContactPointA.setZero(),averageContactPointB.setZero();for(var bodyA=c.bi,i=(c.bj,0);i!==numContacts;i++)(c=this.result[this.result.length-1-i]).bodyA!==bodyA?(averageNormal.vadd(c.ni,averageNormal),averageContactPointA.vadd(c.ri,averageContactPointA),averageContactPointB.vadd(c.rj,averageContactPointB)):(averageNormal.vsub(c.ni,averageNormal),averageContactPointA.vadd(c.rj,averageContactPointA),averageContactPointB.vadd(c.ri,averageContactPointB));var invNumContacts=1/numContacts;averageContactPointA.scale(invNumContacts,f1.ri),averageContactPointB.scale(invNumContacts,f1.rj),f2.ri.copy(f1.ri),f2.rj.copy(f1.rj),averageNormal.normalize(),averageNormal.tangents(f1.t,f2.t)}};var tmpVec1=new Vec3,tmpVec2=new Vec3,tmpQuat1=new Quaternion,tmpQuat2=new Quaternion;Narrowphase.prototype.getContacts=function(p1,p2,world,result,oldcontacts,frictionResult,frictionPool){this.contactPointPool=oldcontacts,this.frictionEquationPool=frictionPool,this.result=result,this.frictionResult=frictionResult;for(var qi=tmpQuat1,qj=tmpQuat2,xi=tmpVec1,xj=tmpVec2,k=0,N=p1.length;k!==N;k++){var bi=p1[k],bj=p2[k],bodyContactMaterial=null;bi.material&&bj.material&&(bodyContactMaterial=world.getContactMaterial(bi.material,bj.material)||null);for(var justTest=bi.type&Body.KINEMATIC&&bj.type&Body.STATIC||bi.type&Body.STATIC&&bj.type&Body.KINEMATIC||bi.type&Body.KINEMATIC&&bj.type&Body.KINEMATIC,i=0;isi.boundingSphereRadius+sj.boundingSphereRadius)){var shapeContactMaterial=null;si.material&&sj.material&&(shapeContactMaterial=world.getContactMaterial(si.material,sj.material)||null),this.currentContactMaterial=shapeContactMaterial||bodyContactMaterial||world.defaultContactMaterial;var resolver=this[si.type|sj.type];if(resolver){(si.type0&&positionAlongEdgeB<0&&(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),(dist=tmp.distanceTo(localSpherePos))0){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.norm(),h2=ns2.norm();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){dist=Math.abs(dot-h-R);if((null===side_distance||dist0){for(var faceVerts=[],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)){if(justTest)return!0;found=!0;r=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.mult(-R,r.ri),worldNormal.negate(r.ni);var penetrationVec2=v3pool.get();worldNormal.mult(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.mult(-R,penetrationSpherePoint),xi.vsub(xj,r.rj),r.rj.vadd(penetrationSpherePoint,r.rj),r.rj.vadd(penetrationVec2,r.rj),r.rj.vadd(xj,r.rj),r.rj.vsub(bj.position,r.rj),r.ri.vadd(xi,r.ri),r.ri.vsub(bi.position,r.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(r),this.createFrictionEquationsFromContact(r,this.frictionResult);for(var j=0,Nfaceverts=faceVerts.length;j!==Nfaceverts;j++)v3pool.release(faceVerts[j]);return}for(j=0;j!==face.length;j++){var v1=v3pool.get(),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);var edge=sphereConvex_edge;v2.vsub(v1,edge);var edgeUnit=sphereConvex_edgeUnit;edge.unit(edgeUnit);var p=v3pool.get(),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);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotsi.boundingSphereRadius+sj.boundingSphereRadius)&&si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){var res=[],q=convexConvex_q;si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res);for(var numContacts=0,j=0;j!==res.length;j++){if(justTest)return!0;var r=this.createContactEquation(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),ri.vsub(xi,ri),rj.vsub(xj,rj),ri.vadd(xi,ri),ri.vsub(bi.position,ri),rj.vadd(xj,rj),rj.vsub(bj.position,rj),this.result.push(r),numContacts++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(r,this.frictionResult)}this.enableFrictionReduction&&numContacts&&this.createFrictionFromAverage(numContacts)}};var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[Shape.types.PLANE|Shape.types.PARTICLE]=Narrowphase.prototype.planeParticle=function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){var normal=particlePlane_normal;normal.set(0,0,1),bj.quaternion.vmult(normal,normal);var relpos=particlePlane_relpos;if(xi.vsub(bj.position,relpos),normal.dot(relpos)<=0){if(justTest)return!0;var r=this.createContactEquation(bi,bj,si,sj,rsi,rsj);r.ni.copy(normal),r.ni.negate(r.ni),r.ri.set(0,0,0);var projected=particlePlane_projected;normal.mult(normal.dot(xi),projected),xi.vsub(projected,projected),r.rj.copy(projected),this.result.push(r),this.createFrictionEquationsFromContact(r,this.frictionResult)}};var particleSphere_normal=new Vec3;Narrowphase.prototype[Shape.types.PARTICLE|Shape.types.SPHERE]=Narrowphase.prototype.sphereParticle=function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){var normal=particleSphere_normal;if(normal.set(0,0,1),xi.vsub(xj,normal),normal.norm2()<=sj.radius*sj.radius){if(justTest)return!0;var r=this.createContactEquation(bi,bj,si,sj,rsi,rsj);normal.normalize(),r.rj.copy(normal),r.rj.mult(sj.radius,r.rj),r.ni.copy(normal),r.ni.negate(r.ni),r.ri.set(0,0,0),this.result.push(r),this.createFrictionEquationsFromContact(r,this.frictionResult)}};var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[Shape.types.PARTICLE|Shape.types.CONVEXPOLYHEDRON]=Narrowphase.prototype.convexParticle=function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){var penetratedFaceIndex=-1,penetratedFaceNormal=convexParticle_penetratedFaceNormal,worldPenetrationVec=convexParticle_worldPenetrationVec,minPenetration=null,numDetectedFaces=0,local=convexParticle_local;if(local.copy(xi),local.vsub(xj,local),qj.conjugate(cqj),cqj.vmult(local,local),sj.pointIsInside(local)){sj.worldVerticesNeedsUpdate&&sj.computeWorldVertices(xj,qj),sj.worldFaceNormalsNeedsUpdate&&sj.computeWorldFaceNormals(qj);for(var i=0,nfaces=sj.faces.length;i!==nfaces;i++){var verts=[sj.worldVertices[sj.faces[i][0]]],normal=sj.worldFaceNormals[i];xi.vsub(verts[0],convexParticle_vertexToParticle);var penetration=-normal.dot(convexParticle_vertexToParticle);if(null===minPenetration||Math.abs(penetration)data.length||iMinY>data[0].length)){iMinX<0&&(iMinX=0),iMaxX<0&&(iMaxX=0),iMinY<0&&(iMinY=0),iMaxY<0&&(iMaxY=0),iMinX>=data.length&&(iMinX=data.length-1),iMaxX>=data.length&&(iMaxX=data.length-1),iMaxY>=data[0].length&&(iMaxY=data[0].length-1),iMinY>=data[0].length&&(iMinY=data[0].length-1);var minMax=[];hfShape.getRectMinMax(iMinX,iMinY,iMaxX,iMaxY,minMax);var min=minMax[0],max=minMax[1];if(!(localConvexPos.z-radius>max||localConvexPos.z+radiusdata.length||iMaxY>data[0].length)){iMinX<0&&(iMinX=0),iMaxX<0&&(iMaxX=0),iMinY<0&&(iMinY=0),iMaxY<0&&(iMaxY=0),iMinX>=data.length&&(iMinX=data.length-1),iMaxX>=data.length&&(iMaxX=data.length-1),iMaxY>=data[0].length&&(iMaxY=data[0].length-1),iMinY>=data[0].length&&(iMinY=data[0].length-1);var minMax=[];hfShape.getRectMinMax(iMinX,iMinY,iMaxX,iMaxY,minMax);var min=minMax[0],max=minMax[1];if(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}}},{"../collision/AABB":5,"../collision/Ray":12,"../equations/ContactEquation":22,"../equations/FrictionEquation":24,"../math/Quaternion":31,"../math/Transform":32,"../math/Vec3":33,"../objects/Body":34,"../shapes/ConvexPolyhedron":41,"../shapes/Shape":46,"../solver/Solver":50,"../utils/Vec3Pool":57}],59:[function(require,module,exports){function World(options){options=options||{},EventTarget.apply(this),this.dt=-1,this.allowSleep=!!options.allowSleep,this.contacts=[],this.frictionEquations=[],this.quatNormalizeSkip=void 0!==options.quatNormalizeSkip?options.quatNormalizeSkip:0,this.quatNormalizeFast=void 0!==options.quatNormalizeFast&&options.quatNormalizeFast,this.time=0,this.stepnumber=0,this.default_dt=1/60,this.nextId=0,this.gravity=new Vec3,options.gravity&&this.gravity.copy(options.gravity),this.broadphase=void 0!==options.broadphase?options.broadphase:new NaiveBroadphase,this.bodies=[],this.solver=void 0!==options.solver?options.solver:new GSSolver,this.constraints=[],this.narrowphase=new Narrowphase(this),this.collisionMatrix=new ArrayCollisionMatrix,this.collisionMatrixPrevious=new ArrayCollisionMatrix,this.bodyOverlapKeeper=new OverlapKeeper,this.shapeOverlapKeeper=new OverlapKeeper,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new TupleDictionary,this.defaultMaterial=new Material("default"),this.defaultContactMaterial=new ContactMaterial(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.accumulator=0,this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.idToBodyMap={},this.broadphase.setWorld(this)}module.exports=World;require("../shapes/Shape");var Vec3=require("../math/Vec3"),Quaternion=require("../math/Quaternion"),GSSolver=require("../solver/GSSolver"),Narrowphase=(require("../equations/ContactEquation"),require("../equations/FrictionEquation"),require("./Narrowphase")),EventTarget=require("../utils/EventTarget"),ArrayCollisionMatrix=require("../collision/ArrayCollisionMatrix"),OverlapKeeper=require("../collision/OverlapKeeper"),Material=require("../material/Material"),ContactMaterial=require("../material/ContactMaterial"),Body=require("../objects/Body"),TupleDictionary=require("../utils/TupleDictionary"),RaycastResult=require("../collision/RaycastResult"),AABB=require("../collision/AABB"),Ray=require("../collision/Ray"),NaiveBroadphase=require("../collision/NaiveBroadphase");World.prototype=new EventTarget;new AABB;var tmpRay=new Ray;if(World.prototype.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},World.prototype.numObjects=function(){return this.bodies.length},World.prototype.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},World.prototype.add=World.prototype.addBody=function(body){-1===this.bodies.indexOf(body)&&(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,body instanceof Body&&(body.initAngularVelocity.copy(body.angularVelocity),body.initQuaternion.copy(body.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=body,this.idToBodyMap[body.id]=body,this.dispatchEvent(this.addBodyEvent))},World.prototype.addConstraint=function(c){this.constraints.push(c)},World.prototype.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},World.prototype.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},World.prototype.raycastAll=function(from,to,options,callback){return options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay.intersectWorld(this,options)},World.prototype.raycastAny=function(from,to,options,result){return options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay.intersectWorld(this,options)},World.prototype.raycastClosest=function(from,to,options,result){return options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay.intersectWorld(this,options)},World.prototype.remove=function(body){body.world=null;var n=this.bodies.length-1,bodies=this.bodies,idx=bodies.indexOf(body);if(-1!==idx){bodies.splice(idx,1);for(var i=0;i!==bodies.length;i++)bodies[i].index=i;this.collisionMatrix.setNumObjects(n),this.removeBodyEvent.body=body,delete this.idToBodyMap[body.id],this.dispatchEvent(this.removeBodyEvent)}},World.prototype.removeBody=World.prototype.remove,World.prototype.getBodyById=function(id){return this.idToBodyMap[id]},World.prototype.getShapeById=function(id){for(var bodies=this.bodies,i=0,bl=bodies.length;i=dt&&substeps=0;j-=1)(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(),doProfiling&&(profilingStart=performance.now());var oldcontacts=World_step_oldContacts,NoldContacts=contacts.length;for(i=0;i!==NoldContacts;i++)oldcontacts.push(contacts[i]);contacts.length=0;var NoldFrictionEquations=this.frictionEquations.length;for(i=0;i!==NoldFrictionEquations;i++)frictionEquationPool.push(this.frictionEquations[i]);this.frictionEquations.length=0,this.narrowphase.getContacts(p1,p2,this,contacts,oldcontacts,this.frictionEquations,frictionEquationPool),doProfiling&&(profile.narrowphase=performance.now()-profilingStart),doProfiling&&(profilingStart=performance.now());for(i=0;i=0&&bj.material.friction>=0&&bi.material.friction*bj.material.friction,bi.material.restitution>=0&&bj.material.restitution>=0&&(c.restitution=bi.material.restitution*bj.material.restitution)),solver.addEquation(c),bi.allowSleep&&bi.type===Body.DYNAMIC&&bi.sleepState===Body.SLEEPING&&bj.sleepState===Body.AWAKE&&bj.type!==Body.STATIC&&bj.velocity.norm2()+bj.angularVelocity.norm2()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(bi._wakeUpAfterNarrowphase=!0),bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&bi.sleepState===Body.AWAKE&&bi.type!==Body.STATIC&&bi.velocity.norm2()+bi.angularVelocity.norm2()>=2*Math.pow(bi.sleepSpeedLimit,2)&&(bj._wakeUpAfterNarrowphase=!0),this.collisionMatrix.set(bi,bj,!0),this.collisionMatrixPrevious.get(bi,bj)||(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)),this.bodyOverlapKeeper.set(bi.id,bj.id),this.shapeOverlapKeeper.set(si.id,sj.id)}for(this.emitContactEvents(),doProfiling&&(profile.makeContactConstraints=performance.now()-profilingStart,profilingStart=performance.now()),i=0;i!==N;i++)(bi=bodies[i])._wakeUpAfterNarrowphase&&(bi.wakeUp(),bi._wakeUpAfterNarrowphase=!1);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)}}solver.solve(dt,this),doProfiling&&(profile.solve=performance.now()-profilingStart),solver.removeAllEquations();var pow=Math.pow;for(i=0;i!==N;i++)if((bi=bodies[i]).type&DYNAMIC){var ld=pow(1-bi.linearDamping,dt),v=bi.velocity;v.mult(ld,v);var av=bi.angularVelocity;if(av){var ad=pow(1-bi.angularDamping,dt);av.mult(ad,av)}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++)(bi=bodies[i]).preStep&&bi.preStep.call(bi);doProfiling&&(profilingStart=performance.now());var quatNormalize=this.stepnumber%(this.quatNormalizeSkip+1)==0,quatNormalizeFast=this.quatNormalizeFast;for(i=0;i!==N;i++)bodies[i].integrate(dt,quatNormalize,quatNormalizeFast);for(this.clearForces(),this.broadphase.dirty=!0,doProfiling&&(profile.integrate=performance.now()-profilingStart),this.time+=dt,this.stepnumber+=1,this.dispatchEvent(World_step_postStepEvent),i=0;i!==N;i++){var postStep=(bi=bodies[i]).postStep;postStep&&postStep.call(bi)}if(this.allowSleep)for(i=0;i!==N;i++)bodies[i].sleepTick(this.time)},World.prototype.emitContactEvents=function(){var additions=[],removals=[],beginContactEvent={type:"beginContact",bodyA:null,bodyB:null},endContactEvent={type:"endContact",bodyA:null,bodyB:null},beginShapeContactEvent={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},endShapeContactEvent={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};return function(){var hasBeginContact=this.hasAnyEventListener("beginContact"),hasEndContact=this.hasAnyEventListener("endContact");if((hasBeginContact||hasEndContact)&&this.bodyOverlapKeeper.getDiff(additions,removals),hasBeginContact){for(var i=0,l=additions.length;i2&&tmp.fromBufferGeometry(meshes[0].geometry):tmp=meshes[0].geometry.clone(),tmp.metadata=meshes[0].geometry.metadata,meshes[0].updateMatrixWorld(),meshes[0].matrixWorld.decompose(position,quaternion,scale),tmp.scale(scale.x,scale.y,scale.z)}for(;mesh=meshes.pop();)if(mesh.updateMatrixWorld(),mesh.geometry.isBufferGeometry){if(mesh.geometry.attributes.position&&mesh.geometry.attributes.position.itemSize>2){var tmpGeom=new THREE.Geometry;tmpGeom.fromBufferGeometry(mesh.geometry),combined.merge(tmpGeom,mesh.matrixWorld),tmpGeom.dispose()}}else combined.merge(mesh.geometry,mesh.matrixWorld);return(matrix=new THREE.Matrix4).scale(object.scale),combined.applyMatrix(matrix),combined}function getVertices(geometry){return geometry.attributes||(geometry=(new THREE.BufferGeometry).fromGeometry(geometry)),(geometry.attributes.position||{}).array||[]}function getMeshes(object){var meshes=[];return object.traverse(function(o){"Mesh"===o.type&&meshes.push(o)}),meshes}var CANNON=require("cannon"),quickhull=require("./lib/THREE.quickhull"),PI_2=Math.PI/2,Type={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},mesh2shape=function(object,options){var geometry;if((options=options||{}).type===Type.BOX)return createBoundingBoxShape(object);if(options.type===Type.CYLINDER)return createBoundingCylinderShape(object,options);if(options.type===Type.SPHERE)return createBoundingSphereShape(object,options);if(options.type===Type.HULL)return createConvexPolyhedron(object);if(options.type===Type.MESH)return geometry=getGeometry(object),geometry?createTrimeshShape(geometry):null;if(options.type)throw new Error('[CANNON.mesh2shape] Invalid type "%s".',options.type);if(!(geometry=getGeometry(object)))return null;switch(geometry.metadata?geometry.metadata.type:geometry.type){case"BoxGeometry":case"BoxBufferGeometry":return createBoxShape(geometry);case"CylinderGeometry":case"CylinderBufferGeometry":return createCylinderShape(geometry);case"PlaneGeometry":case"PlaneBufferGeometry":return createPlaneShape(geometry);case"SphereGeometry":case"SphereBufferGeometry":return createSphereShape(geometry);case"TubeGeometry":case"Geometry":case"BufferGeometry":return createBoundingBoxShape(object);default:return console.warn('Unrecognized geometry: "%s". Using bounding box as shape.',geometry.type),createBoxShape(geometry)}};mesh2shape.Type=Type,module.exports=CANNON.mesh2shape=mesh2shape},{"./lib/THREE.quickhull":61,cannon:4}],61:[function(require,module,exports){module.exports=function(){function reset(){ab=new THREE.Vector3,ac=new THREE.Vector3,ax=new THREE.Vector3,suba=new THREE.Vector3,subb=new THREE.Vector3,normal=new THREE.Vector3,diff=new THREE.Vector3,subaA=new THREE.Vector3,subaB=new THREE.Vector3,subC=new THREE.Vector3}function process(points){for(;faceStack.length>0;)cull(faceStack.shift(),points)}function getNormal(face,points){if(void 0!==face.normal)return face.normal;var p0=points[face[0]],p1=points[face[1]],p2=points[face[2]];return ab.subVectors(p1,p0),ac.subVectors(p2,p0),normal.crossVectors(ac,ab),normal.normalize(),face.normal=normal.clone()}function assignPoints(face,pointset,points){var p0=points[face[0]],dots=[],norm=getNormal(face,points);pointset.sort(function(aItem,bItem){return dots[aItem.x/3]=void 0!==dots[aItem.x/3]?dots[aItem.x/3]:norm.dot(suba.subVectors(aItem,p0)),dots[bItem.x/3]=void 0!==dots[bItem.x/3]?dots[bItem.x/3]:norm.dot(subb.subVectors(bItem,p0)),dots[aItem.x/3]-dots[bItem.x/3]});var index=pointset.length;for(1===index&&(dots[pointset[0].x/3]=norm.dot(suba.subVectors(pointset[0],p0)));index-- >0&&dots[pointset[index].x/3]>0;);index+10&&(face.visiblePoints=pointset.splice(index+1))}function cull(face,points){for(var currentFace,i=faces.length,visibleFaces=[face],apex=points.indexOf(face.visiblePoints.pop());i-- >0;)(currentFace=faces[i])!==face&&getNormal(currentFace,points).dot(diff.subVectors(points[apex],points[currentFace[0]]))>0&&visibleFaces.push(currentFace);var compareFace,nextIndex,a,b,j=i=visibleFaces.length,hasOneVisibleFace=1===i,perimeter=[],edgeIndex=0,allPoints=[];visibleFaces[0][0],visibleFaces[0][1],visibleFaces[0][1],visibleFaces[0][2],visibleFaces[0][2],visibleFaces[0][0];if(1===visibleFaces.length)perimeter=[(currentFace=visibleFaces[0])[0],currentFace[1],currentFace[1],currentFace[2],currentFace[2],currentFace[0]],faceStack.indexOf(currentFace)>-1&&faceStack.splice(faceStack.indexOf(currentFace),1),currentFace.visiblePoints&&(allPoints=allPoints.concat(currentFace.visiblePoints)),faces.splice(faces.indexOf(currentFace),1);else for(;i-- >0;){currentFace=visibleFaces[i],faceStack.indexOf(currentFace)>-1&&faceStack.splice(faceStack.indexOf(currentFace),1),currentFace.visiblePoints&&(allPoints=allPoints.concat(currentFace.visiblePoints)),faces.splice(faces.indexOf(currentFace),1);var isSharedEdge;for(cEdgeIndex=0;cEdgeIndex<3;){for(isSharedEdge=!1,j=visibleFaces.length,a=currentFace[cEdgeIndex],b=currentFace[(cEdgeIndex+1)%3];j-- >0&&!isSharedEdge;)if(compareFace=visibleFaces[j],edgeIndex=0,compareFace!==currentFace)for(;edgeIndex<3&&!isSharedEdge;)nextIndex=edgeIndex+1,isSharedEdge=compareFace[edgeIndex]===a&&compareFace[nextIndex%3]===b||compareFace[edgeIndex]===b&&compareFace[nextIndex%3]===a,edgeIndex++;isSharedEdge&&!hasOneVisibleFace||(perimeter.push(a),perimeter.push(b)),cEdgeIndex++}}i=0;for(var f,l=perimeter.length/2;i=f?bc.dot(bc):ac.dot(ac)-e*e/f}}();return function(geometry){for(reset(),points=geometry.vertices,faces=[],faceStack=[],i=NUM_POINTS=points.length,extremes=points.slice(0,6),max=0;i-- >0;)points[i].xextremes[1].x&&(extremes[1]=points[i]),points[i].y0;)for(j=i-1;j-- >0;)max<(dcur=extremes[i].distanceToSquared(extremes[j]))&&(max=dcur,v0=extremes[i],v1=extremes[j]);for(i=6,max=0;i-- >0;)dcur=distSqPointSegment(v0,v1,extremes[i]),max0;)dcur=Math.abs(points[i].dot(N)-D),max0;)assignPoints(tetrahedron[i],pointsCloned,points),void 0!==tetrahedron[i].visiblePoints&&faceStack.push(tetrahedron[i]),faces.push(tetrahedron[i]);process(points);for(var ll=faces.length;ll-- >0;)geometry.faces[ll]=new THREE.Face3(faces[ll][2],faces[ll][1],faces[ll][0],faces[ll].normal);return geometry.normalsNeedUpdate=!0,geometry}}()},{}],62:[function(require,module,exports){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){function resolveSources(key){workerSources[key]=!0;for(var depPath in sources[key][1]){var depKey=sources[key][1][depPath];workerSources[depKey]||resolveSources(depKey)}}for(var wkey,cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize;for(var id in prevFrame.bodies)prevFrame.bodies.hasOwnProperty(id)&&nextFrame.bodies.hasOwnProperty(id)&&protocol.deserializeInterpBodyUpdate(prevFrame.bodies[id],nextFrame.bodies[id],this.bodies[id],mix)}}},WorkerDriver.prototype.destroy=function(){this.worker.terminate(),delete this.worker},WorkerDriver.prototype._onMessage=function(event){if(event.data.type!==Event.STEP)throw new Error("[WorkerDriver] Unexpected message type.");var bodies=event.data.bodies;if(this.contacts=event.data.contacts,this.interpolate)this.frameBuffer.push({timestamp:performance.now(),bodies:bodies});else for(var id in bodies)bodies.hasOwnProperty(id)&&protocol.deserializeBodyUpdate(bodies[id],this.bodies[id])},WorkerDriver.prototype.addBody=function(body){protocol.assignID("body",body),this.bodies[body[ID]]=body,this.worker.postMessage({type:Event.ADD_BODY,body:protocol.serializeBody(body)})},WorkerDriver.prototype.removeBody=function(body){this.worker.postMessage({type:Event.REMOVE_BODY,bodyID:body[ID]}),delete this.bodies[body[ID]]},WorkerDriver.prototype.applyBodyMethod=function(body,methodName,args){switch(methodName){case"applyForce":case"applyImpulse":this.worker.postMessage({type:Event.APPLY_BODY_METHOD,bodyID:body[ID],methodName:methodName,args:[args[0].toArray(),args[1].toArray()]});break;default:throw new Error("Unexpected methodName: %s",methodName)}},WorkerDriver.prototype.updateBodyProperties=function(body){this.worker.postMessage({type:Event.UPDATE_BODY_PROPERTIES,body:protocol.serializeBody(body)})},WorkerDriver.prototype.getMaterial=function(name){},WorkerDriver.prototype.addMaterial=function(materialConfig){this.worker.postMessage({type:Event.ADD_MATERIAL,materialConfig:materialConfig})},WorkerDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){this.worker.postMessage({type:Event.ADD_CONTACT_MATERIAL,materialName1:matName1,materialName2:matName2,contactMaterialConfig:contactMaterialConfig})},WorkerDriver.prototype.addConstraint=function(constraint){protocol.assignID("constraint",constraint),this.worker.postMessage({type:Event.ADD_CONSTRAINT,constraint:protocol.serializeConstraint(constraint)})},WorkerDriver.prototype.removeConstraint=function(constraint){this.worker.postMessage({type:Event.REMOVE_CONSTRAINT,constraintID:constraint[ID]})},WorkerDriver.prototype.getContacts=function(){var bodies=this.bodies;return this.contacts.map(function(message){return protocol.deserializeContact(message,bodies)})}},{"../utils/protocol":80,"./driver":71,"./event":72,"./webworkify-debug":75,"./worker":77,webworkify:62}],77:[function(require,module,exports){var Event=require("./event"),LocalDriver=require("./local-driver"),AmmoDriver=require("./ammo-driver"),protocol=require("../utils/protocol"),ID=protocol.ID;module.exports=function(self){function step(){driver.step(stepSize);var bodyMessages={};Object.keys(bodies).forEach(function(id){bodyMessages[id]=protocol.serializeBody(bodies[id])}),self.postMessage({type:Event.STEP,bodies:bodyMessages,contacts:driver.getContacts().map(protocol.serializeContact)})}var stepSize,driver=null,bodies={},constraints={};self.addEventListener("message",function(event){var data=event.data;switch(data.type){case Event.INIT:(driver="cannon"===data.engine?new LocalDriver:new AmmoDriver).init(data.worldConfig),stepSize=1/data.fps,setInterval(step,1e3/data.fps);break;case Event.ADD_BODY:var body=protocol.deserializeBody(data.body);body.material=driver.getMaterial("defaultMaterial"),bodies[body[ID]]=body,driver.addBody(body);break;case Event.REMOVE_BODY:driver.removeBody(bodies[data.bodyID]),delete bodies[data.bodyID];break;case Event.APPLY_BODY_METHOD:bodies[data.bodyID][data.methodName](protocol.deserializeVec3(data.args[0]),protocol.deserializeVec3(data.args[1]));break;case Event.UPDATE_BODY_PROPERTIES:protocol.deserializeBodyUpdate(data.body,bodies[data.body.id]);break;case Event.ADD_MATERIAL:driver.addMaterial(data.materialConfig);break;case Event.ADD_CONTACT_MATERIAL:driver.addContactMaterial(data.materialName1,data.materialName2,data.contactMaterialConfig);break;case Event.ADD_CONSTRAINT:var constraint=protocol.deserializeConstraint(data.constraint,bodies);constraints[constraint[ID]]=constraint,driver.addConstraint(constraint);break;case Event.REMOVE_CONSTRAINT:driver.removeConstraint(constraints[data.constraintID]),delete constraints[data.constraintID];break;default:throw new Error("[Worker] Unexpected event type: %s",data.type)}})}},{"../utils/protocol":80,"./ammo-driver":70,"./event":72,"./local-driver":73}],78:[function(require,module,exports){var CANNON=require("cannon"),CONSTANTS=require("./constants"),C_GRAV=CONSTANTS.GRAVITY,C_MAT=CONSTANTS.CONTACT_MATERIAL,LocalDriver=require("./drivers/local-driver"),WorkerDriver=require("./drivers/worker-driver"),NetworkDriver=require("./drivers/network-driver");require("./drivers/ammo-driver");module.exports=AFRAME.registerSystem("physics",{schema:{driver:{default:"local",oneOf:["local","worker","network","ammo"]},networkUrl:{default:"",if:{driver:"network"}},workerFps:{default:60,if:{driver:"worker"}},workerInterpolate:{default:!0,if:{driver:"worker"}},workerInterpBufferSize:{default:2,if:{driver:"worker"}},workerEngine:{default:"cannon",if:{driver:"worker"},oneOf:["cannon"]},workerDebug:{default:!1,if:{driver:"worker"}},gravity:{default:C_GRAV},iterations:{default:CONSTANTS.ITERATIONS},friction:{default:C_MAT.friction},restitution:{default:C_MAT.restitution},contactEquationStiffness:{default:C_MAT.contactEquationStiffness},contactEquationRelaxation:{default:C_MAT.contactEquationRelaxation},frictionEquationStiffness:{default:C_MAT.frictionEquationStiffness},frictionEquationRegularization:{default:C_MAT.frictionEquationRegularization},maxInterval:{default:4/60},debug:{default:!1}},init:function(){var data=this.data;switch(this.debug=data.debug,this.callbacks={beforeStep:[],step:[],afterStep:[]},this.listeners={},this.driver=null,data.driver){case"local":this.driver=new LocalDriver;break;case"network":this.driver=new NetworkDriver(data.networkUrl);break;case"worker":this.driver=new WorkerDriver({fps:data.workerFps,engine:data.workerEngine,interpolate:data.workerInterpolate,interpolationBufferSize:data.workerInterpBufferSize,debug:data.workerDebug});break;default:throw new Error('[physics] Driver not recognized: "%s".',data.driver)}this.driver.init({quatNormalizeSkip:0,quatNormalizeFast:!1,solverIterations:data.iterations,gravity:data.gravity}),this.driver.addMaterial({name:"defaultMaterial"}),this.driver.addContactMaterial("defaultMaterial","defaultMaterial",{friction:data.friction,restitution:data.restitution,contactEquationStiffness:data.contactEquationStiffness,contactEquationRelaxation:data.contactEquationRelaxation,frictionEquationStiffness:data.frictionEquationStiffness,frictionEquationRegularization:data.frictionEquationRegularization})},tick:function(t,dt){if(dt){var i,callbacks=this.callbacks;for(i=0;i=1)return b;var x=a[0],y=a[1],z=a[2],w=a[3],cosHalfTheta=w*b[3]+x*b[0]+y*b[1]+z*b[2];if(!(cosHalfTheta<0))return b;if((a=a.slice())[3]=-b[3],a[0]=-b[0],a[1]=-b[1],a[2]=-b[2],(cosHalfTheta=-cosHalfTheta)>=1)return a[3]=w,a[0]=x,a[1]=y,a[2]=z,this;var sinHalfTheta=Math.sqrt(1-cosHalfTheta*cosHalfTheta);if(Math.abs(sinHalfTheta)<.001)return a[3]=.5*(w+a[3]),a[0]=.5*(x+a[0]),a[1]=.5*(y+a[1]),a[2]=.5*(z+a[2]),this;var halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta),ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta,ratioB=Math.sin(t*halfTheta)/sinHalfTheta;return a[3]=w*ratioA+a[3]*ratioB,a[0]=x*ratioA+a[0]*ratioB,a[1]=y*ratioA+a[1]*ratioB,a[2]=z*ratioA+a[2]*ratioB,a}},{}],80:[function(require,module,exports){function serializeShape(shape){var shapeMsg={type:shape.type};if(shape.type===CANNON.Shape.types.BOX)shapeMsg.halfExtents=serializeVec3(shape.halfExtents);else if(shape.type===CANNON.Shape.types.SPHERE)shapeMsg.radius=shape.radius;else{if(shape._type!==CANNON.Shape.types.CYLINDER)throw new Error("Unimplemented shape type: %s",shape.type);shapeMsg.type=CANNON.Shape.types.CYLINDER,shapeMsg.radiusTop=shape.radiusTop,shapeMsg.radiusBottom=shape.radiusBottom,shapeMsg.height=shape.height,shapeMsg.numSegments=shape.numSegments}return shapeMsg}function deserializeShape(message){var shape;if(message.type===CANNON.Shape.types.BOX)shape=new CANNON.Box(deserializeVec3(message.halfExtents));else if(message.type===CANNON.Shape.types.SPHERE)shape=new CANNON.Sphere(message.radius);else{if(message.type!==CANNON.Shape.types.CYLINDER)throw new Error("Unimplemented shape type: %s",message.type);(shape=new CANNON.Cylinder(message.radiusTop,message.radiusBottom,message.height,message.numSegments))._type=CANNON.Shape.types.CYLINDER}return shape}function serializeVec3(vec3){return vec3.toArray()}function deserializeVec3(message){return new CANNON.Vec3(message[0],message[1],message[2])}function serializeQuaternion(quat){return quat.toArray()}function deserializeQuaternion(message){return new CANNON.Quaternion(message[0],message[1],message[2],message[3])}var CANNON=require("cannon"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};module.exports.assignID=function(prefix,object){object[ID]||(nextID[prefix]=nextID[prefix]||1,object[ID]=prefix+"_"+nextID[prefix]++)},module.exports.serializeBody=function(body){return{shapes:body.shapes.map(serializeShape),shapeOffsets:body.shapeOffsets.map(serializeVec3),shapeOrientations:body.shapeOrientations.map(serializeQuaternion),position:serializeVec3(body.position),quaternion:body.quaternion.toArray(),velocity:serializeVec3(body.velocity),angularVelocity:serializeVec3(body.angularVelocity),id:body[ID],mass:body.mass,linearDamping:body.linearDamping,angularDamping:body.angularDamping,fixedRotation:body.fixedRotation,allowSleep:body.allowSleep,sleepSpeedLimit:body.sleepSpeedLimit,sleepTimeLimit:body.sleepTimeLimit}},module.exports.deserializeBodyUpdate=function(message,body){return body.position.set(message.position[0],message.position[1],message.position[2]),body.quaternion.set(message.quaternion[0],message.quaternion[1],message.quaternion[2],message.quaternion[3]),body.velocity.set(message.velocity[0],message.velocity[1],message.velocity[2]),body.angularVelocity.set(message.angularVelocity[0],message.angularVelocity[1],message.angularVelocity[2]),body.linearDamping=message.linearDamping,body.angularDamping=message.angularDamping,body.fixedRotation=message.fixedRotation,body.allowSleep=message.allowSleep,body.sleepSpeedLimit=message.sleepSpeedLimit,body.sleepTimeLimit=message.sleepTimeLimit,body.mass!==message.mass&&(body.mass=message.mass,body.updateMassProperties()),body},module.exports.deserializeInterpBodyUpdate=function(message1,message2,body,mix){var weight1=1-mix,weight2=mix;body.position.set(message1.position[0]*weight1+message2.position[0]*weight2,message1.position[1]*weight1+message2.position[1]*weight2,message1.position[2]*weight1+message2.position[2]*weight2);var quaternion=mathUtils.slerp(message1.quaternion,message2.quaternion,mix);return body.quaternion.set(quaternion[0],quaternion[1],quaternion[2],quaternion[3]),body.velocity.set(message1.velocity[0]*weight1+message2.velocity[0]*weight2,message1.velocity[1]*weight1+message2.velocity[1]*weight2,message1.velocity[2]*weight1+message2.velocity[2]*weight2),body.angularVelocity.set(message1.angularVelocity[0]*weight1+message2.angularVelocity[0]*weight2,message1.angularVelocity[1]*weight1+message2.angularVelocity[1]*weight2,message1.angularVelocity[2]*weight1+message2.angularVelocity[2]*weight2),body.linearDamping=message2.linearDamping,body.angularDamping=message2.angularDamping,body.fixedRotation=message2.fixedRotation,body.allowSleep=message2.allowSleep,body.sleepSpeedLimit=message2.sleepSpeedLimit,body.sleepTimeLimit=message2.sleepTimeLimit,body.mass!==message2.mass&&(body.mass=message2.mass,body.updateMassProperties()),body},module.exports.deserializeBody=function(message){for(var shapeMsg,body=new CANNON.Body({mass:message.mass,position:deserializeVec3(message.position),quaternion:deserializeQuaternion(message.quaternion),velocity:deserializeVec3(message.velocity),angularVelocity:deserializeVec3(message.angularVelocity),linearDamping:message.linearDamping,angularDamping:message.angularDamping,fixedRotation:message.fixedRotation,allowSleep:message.allowSleep,sleepSpeedLimit:message.sleepSpeedLimit,sleepTimeLimit:message.sleepTimeLimit}),i=0;shapeMsg=message.shapes[i];i++)body.addShape(deserializeShape(shapeMsg),deserializeVec3(message.shapeOffsets[i]),deserializeQuaternion(message.shapeOrientations[i]));return body[ID]=message.id,body},module.exports.serializeShape=serializeShape,module.exports.deserializeShape=deserializeShape,module.exports.serializeConstraint=function(constraint){var message={id:constraint[ID],type:constraint.type,maxForce:constraint.maxForce,bodyA:constraint.bodyA[ID],bodyB:constraint.bodyB[ID]};switch(constraint.type){case"LockConstraint":break;case"DistanceConstraint":message.distance=constraint.distance;break;case"HingeConstraint":case"ConeTwistConstraint":message.axisA=serializeVec3(constraint.axisA),message.axisB=serializeVec3(constraint.axisB),message.pivotA=serializeVec3(constraint.pivotA),message.pivotB=serializeVec3(constraint.pivotB);break;case"PointToPointConstraint":message.pivotA=serializeVec3(constraint.pivotA),message.pivotB=serializeVec3(constraint.pivotB);break;default:throw new Error("Unexpected constraint type: "+constraint.type+'. You may need to manually set `constraint.type = "FooConstraint";`.')}return message},module.exports.deserializeConstraint=function(message,bodies){var constraint,TypedConstraint=CANNON[message.type],bodyA=bodies[message.bodyA],bodyB=bodies[message.bodyB];switch(message.type){case"LockConstraint":constraint=new CANNON.LockConstraint(bodyA,bodyB,message);break;case"DistanceConstraint":constraint=new CANNON.DistanceConstraint(bodyA,bodyB,message.distance,message.maxForce);break;case"HingeConstraint":case"ConeTwistConstraint":constraint=new TypedConstraint(bodyA,bodyB,{pivotA:deserializeVec3(message.pivotA),pivotB:deserializeVec3(message.pivotB),axisA:deserializeVec3(message.axisA),axisB:deserializeVec3(message.axisB),maxForce:message.maxForce});break;case"PointToPointConstraint":constraint=new CANNON.PointToPointConstraint(bodyA,deserializeVec3(message.pivotA),bodyB,deserializeVec3(message.pivotB),message.maxForce);break;default:throw new Error("Unexpected constraint type: "+message.type)}return constraint[ID]=message.id,constraint},module.exports.serializeContact=function(contact){return{bi:contact.bi[ID],bj:contact.bj[ID],ni:serializeVec3(contact.ni),ri:serializeVec3(contact.ri),rj:serializeVec3(contact.rj)}},module.exports.deserializeContact=function(message,bodies){return{bi:bodies[message.bi],bj:bodies[message.bj],ni:deserializeVec3(message.ni),ri:deserializeVec3(message.ri),rj:deserializeVec3(message.rj)}},module.exports.serializeVec3=serializeVec3,module.exports.deserializeVec3=deserializeVec3,module.exports.serializeQuaternion=serializeQuaternion,module.exports.deserializeQuaternion=deserializeQuaternion},{"./math":79,cannon:4}]},{},[1]); \ No newline at end of file +!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n||e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<\/script>\n```\n\n### Node.js install\n\nInstall the cannon package via NPM:\n\n```bash\nnpm install --save cannon\n```\n\nAlternatively, point to the Github repo directly to get the very latest version:\n\n```bash\nnpm install --save schteppe/cannon.js\n```\n\n### Example\n\nThe sample code below creates a sphere on a plane, steps the simulation, and prints the sphere simulation to the console. Note that Cannon.js uses [SI units](http://en.wikipedia.org/wiki/International_System_of_Units) (metre, kilogram, second, etc.).\n\n```javascript\n// Setup our world\nvar world = new CANNON.World();\nworld.gravity.set(0, 0, -9.82); // m/s²\n\n// Create a sphere\nvar radius = 1; // m\nvar sphereBody = new CANNON.Body({\n mass: 5, // kg\n position: new CANNON.Vec3(0, 0, 10), // m\n shape: new CANNON.Sphere(radius)\n});\nworld.addBody(sphereBody);\n\n// Create a plane\nvar groundBody = new CANNON.Body({\n mass: 0 // mass == 0 makes the body static\n});\nvar groundShape = new CANNON.Plane();\ngroundBody.addShape(groundShape);\nworld.addBody(groundBody);\n\nvar fixedTimeStep = 1.0 / 60.0; // seconds\nvar maxSubSteps = 3;\n\n// Start the simulation loop\nvar lastTime;\n(function simloop(time){\n requestAnimationFrame(simloop);\n if(lastTime !== undefined){\n var dt = (time - lastTime) / 1000;\n world.step(fixedTimeStep, dt, maxSubSteps);\n }\n console.log("Sphere z position: " + sphereBody.position.z);\n lastTime = time;\n})();\n```\n\nIf you want to know how to use cannon.js with a rendering engine, for example Three.js, see the [Examples](examples).\n\n### Features\n* Rigid body dynamics\n* Discrete collision detection\n* Contacts, friction and restitution\n* Constraints\n * PointToPoint (a.k.a. ball/socket joint)\n * Distance\n * Hinge (with optional motor)\n * Lock\n * ConeTwist\n* Gauss-Seidel constraint solver and an island split algorithm\n* Collision filters\n* Body sleeping\n* Experimental SPH / fluid support\n* Various shapes and collision algorithms (see table below)\n\n| | [Sphere](http://schteppe.github.io/cannon.js/docs/classes/Sphere.html) | [Plane](http://schteppe.github.io/cannon.js/docs/classes/Plane.html) | [Box](http://schteppe.github.io/cannon.js/docs/classes/Box.html) | [Convex](http://schteppe.github.io/cannon.js/docs/classes/ConvexPolyhedron.html) | [Particle](http://schteppe.github.io/cannon.js/docs/classes/Particle.html) | [Heightfield](http://schteppe.github.io/cannon.js/docs/classes/Heightfield.html) | [Trimesh](http://schteppe.github.io/cannon.js/docs/classes/Trimesh.html) |\n| :-----------|:------:|:-----:|:---:|:------:|:--------:|:-----------:|:-------:|\n| Sphere | Yes | Yes | Yes | Yes | Yes | Yes | Yes |\n| Plane | - | - | Yes | Yes | Yes | - | Yes |\n| Box | - | - | Yes | Yes | Yes | Yes | (todo) |\n| Cylinder | - | - | Yes | Yes | Yes | Yes | (todo) |\n| Convex | - | - | - | Yes | Yes | Yes | (todo) |\n| Particle | - | - | - | - | - | (todo) | (todo) |\n| Heightfield | - | - | - | - | - | - | (todo) |\n| Trimesh | - | - | - | - | - | - | - |\n\n### Todo\nThe simpler todos are marked with ```@todo``` in the code. Github Issues can and should also be used for todos.\n\n### Help\nCreate an [issue](https://github.com/schteppe/cannon.js/issues) if you need help.\n',readmeFilename:"README.markdown",repository:{type:"git",url:"git+https://github.com/schteppe/cannon.js.git"},version:"0.6.2"}},{}],4:[function(require,module,exports){module.exports={version:require("../package.json").version,AABB:require("./collision/AABB"),ArrayCollisionMatrix:require("./collision/ArrayCollisionMatrix"),Body:require("./objects/Body"),Box:require("./shapes/Box"),Broadphase:require("./collision/Broadphase"),Constraint:require("./constraints/Constraint"),ContactEquation:require("./equations/ContactEquation"),Narrowphase:require("./world/Narrowphase"),ConeTwistConstraint:require("./constraints/ConeTwistConstraint"),ContactMaterial:require("./material/ContactMaterial"),ConvexPolyhedron:require("./shapes/ConvexPolyhedron"),Cylinder:require("./shapes/Cylinder"),DistanceConstraint:require("./constraints/DistanceConstraint"),Equation:require("./equations/Equation"),EventTarget:require("./utils/EventTarget"),FrictionEquation:require("./equations/FrictionEquation"),GSSolver:require("./solver/GSSolver"),GridBroadphase:require("./collision/GridBroadphase"),Heightfield:require("./shapes/Heightfield"),HingeConstraint:require("./constraints/HingeConstraint"),LockConstraint:require("./constraints/LockConstraint"),Mat3:require("./math/Mat3"),Material:require("./material/Material"),NaiveBroadphase:require("./collision/NaiveBroadphase"),ObjectCollisionMatrix:require("./collision/ObjectCollisionMatrix"),Pool:require("./utils/Pool"),Particle:require("./shapes/Particle"),Plane:require("./shapes/Plane"),PointToPointConstraint:require("./constraints/PointToPointConstraint"),Quaternion:require("./math/Quaternion"),Ray:require("./collision/Ray"),RaycastVehicle:require("./objects/RaycastVehicle"),RaycastResult:require("./collision/RaycastResult"),RigidVehicle:require("./objects/RigidVehicle"),RotationalEquation:require("./equations/RotationalEquation"),RotationalMotorEquation:require("./equations/RotationalMotorEquation"),SAPBroadphase:require("./collision/SAPBroadphase"),SPHSystem:require("./objects/SPHSystem"),Shape:require("./shapes/Shape"),Solver:require("./solver/Solver"),Sphere:require("./shapes/Sphere"),SplitSolver:require("./solver/SplitSolver"),Spring:require("./objects/Spring"),Transform:require("./math/Transform"),Trimesh:require("./shapes/Trimesh"),Vec3:require("./math/Vec3"),Vec3Pool:require("./utils/Vec3Pool"),World:require("./world/World")}},{"../package.json":3,"./collision/AABB":5,"./collision/ArrayCollisionMatrix":6,"./collision/Broadphase":7,"./collision/GridBroadphase":8,"./collision/NaiveBroadphase":9,"./collision/ObjectCollisionMatrix":10,"./collision/Ray":12,"./collision/RaycastResult":13,"./collision/SAPBroadphase":14,"./constraints/ConeTwistConstraint":15,"./constraints/Constraint":16,"./constraints/DistanceConstraint":17,"./constraints/HingeConstraint":18,"./constraints/LockConstraint":19,"./constraints/PointToPointConstraint":20,"./equations/ContactEquation":22,"./equations/Equation":23,"./equations/FrictionEquation":24,"./equations/RotationalEquation":25,"./equations/RotationalMotorEquation":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/Mat3":30,"./math/Quaternion":31,"./math/Transform":32,"./math/Vec3":33,"./objects/Body":34,"./objects/RaycastVehicle":35,"./objects/RigidVehicle":36,"./objects/SPHSystem":37,"./objects/Spring":38,"./shapes/Box":40,"./shapes/ConvexPolyhedron":41,"./shapes/Cylinder":42,"./shapes/Heightfield":43,"./shapes/Particle":44,"./shapes/Plane":45,"./shapes/Shape":46,"./shapes/Sphere":47,"./shapes/Trimesh":48,"./solver/GSSolver":49,"./solver/Solver":50,"./solver/SplitSolver":51,"./utils/EventTarget":52,"./utils/Pool":54,"./utils/Vec3Pool":57,"./world/Narrowphase":58,"./world/World":59}],5:[function(require,module,exports){function AABB(options){options=options||{},this.lowerBound=new Vec3,options.lowerBound&&this.lowerBound.copy(options.lowerBound),this.upperBound=new Vec3,options.upperBound&&this.upperBound.copy(options.upperBound)}var Vec3=require("../math/Vec3");require("../utils/Utils");module.exports=AABB;var tmp=new Vec3;AABB.prototype.setFromPoints=function(points,position,quaternion,skinSize){var l=this.lowerBound,u=this.upperBound,q=quaternion;l.copy(points[0]),q&&q.vmult(l,l),u.copy(l);for(var i=1;iu.x&&(u.x=p.x),p.xu.y&&(u.y=p.y),p.yu.z&&(u.z=p.z),p.z=u2.x&&l1.y<=l2.y&&u1.y>=u2.y&&l1.z<=l2.z&&u1.z>=u2.z},AABB.prototype.getCorners=function(a,b,c,d,e,f,g,h){var l=this.lowerBound,u=this.upperBound;a.copy(l),b.set(u.x,l.y,l.z),c.set(u.x,u.y,l.z),d.set(l.x,u.y,u.z),e.set(u.x,l.y,l.z),f.set(l.x,u.y,l.z),g.set(l.x,l.y,u.z),h.copy(u)};var transformIntoFrame_corners=[new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3,new Vec3];AABB.prototype.toLocalFrame=function(frame,target){var corners=transformIntoFrame_corners,a=corners[0],b=corners[1],c=corners[2],d=corners[3],e=corners[4],f=corners[5],g=corners[6],h=corners[7];this.getCorners(a,b,c,d,e,f,g,h);for(var i=0;8!==i;i++){var corner=corners[i];frame.pointToLocal(corner,corner)}return target.setFromPoints(corners)},AABB.prototype.toWorldFrame=function(frame,target){var corners=transformIntoFrame_corners,a=corners[0],b=corners[1],c=corners[2],d=corners[3],e=corners[4],f=corners[5],g=corners[6],h=corners[7];this.getCorners(a,b,c,d,e,f,g,h);for(var i=0;8!==i;i++){var corner=corners[i];frame.pointToWorld(corner,corner)}return target.setFromPoints(corners)},AABB.prototype.overlapsRay=function(ray){var dirFracX=1/ray._direction.x,dirFracY=1/ray._direction.y,dirFracZ=1/ray._direction.z,t1=(this.lowerBound.x-ray.from.x)*dirFracX,t2=(this.upperBound.x-ray.from.x)*dirFracX,t3=(this.lowerBound.y-ray.from.y)*dirFracY,t4=(this.upperBound.y-ray.from.y)*dirFracY,t5=(this.lowerBound.z-ray.from.z)*dirFracZ,t6=(this.upperBound.z-ray.from.z)*dirFracZ,tmin=Math.max(Math.max(Math.min(t1,t2),Math.min(t3,t4)),Math.min(t5,t6)),tmax=Math.min(Math.min(Math.max(t1,t2),Math.max(t3,t4)),Math.max(t5,t6));return!(tmax<0)&&!(tmin>tmax)}},{"../math/Vec3":33,"../utils/Utils":56}],6:[function(require,module,exports){function ArrayCollisionMatrix(){this.matrix=[]}module.exports=ArrayCollisionMatrix,ArrayCollisionMatrix.prototype.get=function(i,j){if(i=i.index,(j=j.index)>i){var temp=j;j=i,i=temp}return this.matrix[(i*(i+1)>>1)+j-1]},ArrayCollisionMatrix.prototype.set=function(i,j,value){if(i=i.index,(j=j.index)>i){var temp=j;j=i,i=temp}this.matrix[(i*(i+1)>>1)+j-1]=value?1:0},ArrayCollisionMatrix.prototype.reset=function(){for(var i=0,l=this.matrix.length;i!==l;i++)this.matrix[i]=0},ArrayCollisionMatrix.prototype.setNumObjects=function(n){this.matrix.length=n*(n-1)>>1}},{}],7:[function(require,module,exports){function Broadphase(){this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}var Body=require("../objects/Body"),Vec3=require("../math/Vec3"),Quaternion=require("../math/Quaternion");require("../shapes/Shape"),require("../shapes/Plane");module.exports=Broadphase,Broadphase.prototype.collisionPairs=function(world,p1,p2){throw new Error("collisionPairs not implemented for this BroadPhase class!")},Broadphase.prototype.needBroadphaseCollision=function(bodyA,bodyB){return 0!=(bodyA.collisionFilterGroup&bodyB.collisionFilterMask)&&0!=(bodyB.collisionFilterGroup&bodyA.collisionFilterMask)&&(0==(bodyA.type&Body.STATIC)&&bodyA.sleepState!==Body.SLEEPING||0==(bodyB.type&Body.STATIC)&&bodyB.sleepState!==Body.SLEEPING)},Broadphase.prototype.intersectionTest=function(bodyA,bodyB,pairs1,pairs2){this.useBoundingBoxes?this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2):this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2)};var Broadphase_collisionPairs_r=new Vec3;new Vec3,new Quaternion,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);r.norm2()dist.norm2()},Broadphase.prototype.aabbQuery=function(world,aabb,result){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}},{"../math/Quaternion":31,"../math/Vec3":33,"../objects/Body":34,"../shapes/Plane":45,"../shapes/Shape":46}],8:[function(require,module,exports){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=[],this.bins.length=nbins,this.binLengths.length=nbins;for(var i=0;i=nx&&(xoff0=nx-1),yoff0<0?yoff0=0:yoff0>=ny&&(yoff0=ny-1),zoff0<0?zoff0=0:zoff0>=nz&&(zoff0=nz-1),xoff1<0?xoff1=0:xoff1>=nx&&(xoff1=nx-1),yoff1<0?yoff1=0:yoff1>=ny&&(yoff1=ny-1),zoff1<0?zoff1=0:zoff1>=nz&&(zoff1=nz-1),yoff0*=ystep,zoff0*=zstep,xoff1*=xstep,yoff1*=ystep,zoff1*=zstep;for(var xoff=xoff0*=xstep;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}}for(var N=world.numObjects(),bodies=world.bodies,max=this.aabbMax,min=this.aabbMin,nx=this.nx,ny=this.ny,nz=this.nz,xstep=ny*nz,ystep=nz,zstep=1,xmax=max.x,ymax=max.y,zmax=max.z,xmin=min.x,ymin=min.y,zmin=min.z,xmult=nx/(xmax-xmin),ymult=ny/(ymax-ymin),zmult=nz/(zmax-zmin),binsizeX=(xmax-xmin)/nx,binsizeY=(ymax-ymin)/ny,binsizeZ=(zmax-zmin)/nz,binRadius=.5*Math.sqrt(binsizeX*binsizeX+binsizeY*binsizeY+binsizeZ*binsizeZ),types=Shape.types,SPHERE=types.SPHERE,PLANE=types.PLANE,bins=(types.BOX,types.COMPOUND,types.CONVEXPOLYHEDRON,this.bins),binLengths=this.binLengths,Nbins=this.bins.length,i=0;i!==Nbins;i++)binLengths[i]=0;for(var ceil=Math.ceil,min=Math.min,max=Math.max,i=0;i!==N;i++){var si=(bi=bodies[i]).shape;switch(si.type){case SPHERE:var x=bi.position.x,y=bi.position.y,z=bi.position.z,r=si.radius;addBoxToBins(x-r,y-r,z-r,x+r,y+r,z+r,bi);break;case PLANE:si.worldNormalNeedsUpdate&&si.computeWorldNormal(bi.quaternion);var planeNormal=si.worldNormal,xreset=xmin+.5*binsizeX-bi.position.x,yreset=ymin+.5*binsizeY-bi.position.y,zreset=zmin+.5*binsizeZ-bi.position.z,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)1)for(var bin=bins[i],xi=0;xi!==binLength;xi++)for(var bi=bin[xi],yi=0;yi!==xi;yi++){var bj=bin[yi];this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)}}this.makePairsUnique(pairs1,pairs2)}},{"../math/Vec3":33,"../shapes/Shape":46,"./Broadphase":7}],9:[function(require,module,exports){function NaiveBroadphase(){Broadphase.apply(this)}module.exports=NaiveBroadphase;var Broadphase=require("./Broadphase"),AABB=require("./AABB");NaiveBroadphase.prototype=new Broadphase,NaiveBroadphase.prototype.constructor=NaiveBroadphase,NaiveBroadphase.prototype.collisionPairs=function(world,pairs1,pairs2){var i,j,bi,bj,bodies=world.bodies,n=bodies.length;for(i=0;i!==n;i++)for(j=0;j!==i;j++)bi=bodies[i],bj=bodies[j],this.needBroadphaseCollision(bi,bj)&&this.intersectionTest(bi,bj,pairs1,pairs2)};new AABB;NaiveBroadphase.prototype.aabbQuery=function(world,aabb,result){result=result||[];for(var i=0;ii){var temp=j;j=i,i=temp}return i+"-"+j in this.matrix},ObjectCollisionMatrix.prototype.set=function(i,j,value){if(i=i.id,(j=j.id)>i){var temp=j;j=i,i=temp}value?this.matrix[i+"-"+j]=!0:delete this.matrix[i+"-"+j]},ObjectCollisionMatrix.prototype.reset=function(){this.matrix={}},ObjectCollisionMatrix.prototype.setNumObjects=function(n){}},{}],11:[function(require,module,exports){function OverlapKeeper(){this.current=[],this.previous=[]}function unpackAndPush(array,key){array.push((4294901760&key)>>16,65535&key)}module.exports=OverlapKeeper,OverlapKeeper.prototype.getKey=function(i,j){if(jcurrent[index];)index++;if(key!==current[index]){for(var j=current.length-1;j>=index;j--)current[j+1]=current[j];current[index]=key}},OverlapKeeper.prototype.tick=function(){var tmp=this.current;this.current=this.previous,this.previous=tmp,this.current.length=0},OverlapKeeper.prototype.getDiff=function(additions,removals){for(var a=this.current,b=this.previous,al=a.length,bl=b.length,j=0,i=0;ib[j];)j++;keyA===b[j]||unpackAndPush(additions,keyA)}j=0;for(i=0;ia[j];)j++;a[j]===keyB||unpackAndPush(removals,keyB)}}},{}],12:[function(require,module,exports){function Ray(from,to){this.from=from?from.clone():new Vec3,this.to=to?to.clone():new Vec3,this._direction=new Vec3,this.precision=1e-4,this.checkCollisionResponse=!0,this.skipBackfaces=!1,this.collisionFilterMask=-1,this.collisionFilterGroup=-1,this.mode=Ray.ANY,this.result=new RaycastResult,this.hasHit=!1,this.callback=function(result){}}function pointInTriangle(p,a,b,c){c.vsub(a,v0),b.vsub(a,v1),p.vsub(a,v2);var u,v,dot00=v0.dot(v0),dot01=v0.dot(v1),dot02=v0.dot(v2),dot11=v1.dot(v1),dot12=v1.dot(v2);return(u=dot11*dot02-dot01*dot12)>=0&&(v=dot00*dot12-dot01*dot02)>=0&&u+vshape.boundingSphereRadius)){var intersectMethod=this[shape.type];intersectMethod&&intersectMethod.call(this,shape,quat,position,body,shape)}};new Vec3,new Vec3;var intersectPoint=new Vec3,a=new Vec3,b=new Vec3,c=new Vec3;new Vec3,new RaycastResult;Ray.prototype.intersectBox=function(shape,quat,position,body,reportedShape){return this.intersectConvex(shape.convexPolyhedronRepresentation,quat,position,body,reportedShape)},Ray.prototype[Shape.types.BOX]=Ray.prototype.intersectBox,Ray.prototype.intersectPlane=function(shape,quat,position,body,reportedShape){var from=this.from,to=this.to,direction=this._direction,worldNormal=new Vec3(0,0,1);quat.vmult(worldNormal,worldNormal);var len=new Vec3;from.vsub(position,len);var planeToFrom=len.dot(worldNormal);if(to.vsub(position,len),!(planeToFrom*len.dot(worldNormal)>0||from.distanceTo(to)=0&&d1<=1&&(from.lerp(to,d1,intersectionPoint),intersectionPoint.vsub(position,normal),normal.normalize(),this.reportIntersection(normal,intersectionPoint,reportedShape,body,-1)),this.result._shouldStop)return;d2>=0&&d2<=1&&(from.lerp(to,d2,intersectionPoint),intersectionPoint.vsub(position,normal),normal.normalize(),this.reportIntersection(normal,intersectionPoint,reportedShape,body,-1))}},Ray.prototype[Shape.types.SPHERE]=Ray.prototype.intersectSphere;var intersectConvex_normal=new Vec3,intersectConvex_vector=(new Vec3,new Vec3,new Vec3);Ray.prototype.intersectConvex=function(shape,quat,position,body,reportedShape,options){for(var normal=intersectConvex_normal,vector=intersectConvex_vector,faceList=options&&options.faceList||null,faces=shape.faces,vertices=shape.vertices,normals=shape.faceNormals,direction=this._direction,from=this.from,to=this.to,fromToDistance=from.distanceTo(to),Nfaces=faceList?faceList.length:faces.length,result=this.result,j=0;!result._shouldStop&&jfromToDistance||this.reportIntersection(normal,intersectPoint,reportedShape,body,fi)}}}}},Ray.prototype[Shape.types.CONVEXPOLYHEDRON]=Ray.prototype.intersectConvex;var intersectTrimesh_normal=new Vec3,intersectTrimesh_localDirection=new Vec3,intersectTrimesh_localFrom=new Vec3,intersectTrimesh_localTo=new Vec3,intersectTrimesh_worldNormal=new Vec3,intersectTrimesh_worldIntersectPoint=new Vec3,intersectTrimesh_triangles=(new AABB,[]),intersectTrimesh_treeTransform=new Transform;Ray.prototype.intersectTrimesh=function(mesh,quat,position,body,reportedShape,options){var normal=intersectTrimesh_normal,triangles=intersectTrimesh_triangles,treeTransform=intersectTrimesh_treeTransform,vector=intersectConvex_vector,localDirection=intersectTrimesh_localDirection,localFrom=intersectTrimesh_localFrom,localTo=intersectTrimesh_localTo,worldIntersectPoint=intersectTrimesh_worldIntersectPoint,worldNormal=intersectTrimesh_worldNormal,indices=(options&&options.faceList,mesh.indices),from=(mesh.vertices,mesh.faceNormals,this.from),to=this.to,direction=this._direction;treeTransform.position.copy(position),treeTransform.quaternion.copy(quat),Transform.vectorToLocalFrame(position,quat,direction,localDirection),Transform.pointToLocalFrame(position,quat,from,localFrom),Transform.pointToLocalFrame(position,quat,to,localTo),localTo.x*=mesh.scale.x,localTo.y*=mesh.scale.y,localTo.z*=mesh.scale.z,localFrom.x*=mesh.scale.x,localFrom.y*=mesh.scale.y,localFrom.z*=mesh.scale.z,localTo.vsub(localFrom,localDirection),localDirection.normalize();var fromToDistanceSquared=localFrom.distanceSquared(localTo);mesh.tree.rayQuery(this,treeTransform,triangles);for(var i=0,N=triangles.length;!this.result._shouldStop&&i!==N;i++){var trianglesIndex=triangles[i];mesh.getNormal(trianglesIndex,normal),mesh.getVertex(indices[3*trianglesIndex],a),a.vsub(localFrom,vector);var dot=localDirection.dot(normal),scalar=normal.dot(vector)/dot;if(!(scalar<0)){localDirection.scale(scalar,intersectPoint),intersectPoint.vadd(localFrom,intersectPoint),mesh.getVertex(indices[3*trianglesIndex+1],b),mesh.getVertex(indices[3*trianglesIndex+2],c);var squaredDistance=intersectPoint.distanceSquared(localFrom);!pointInTriangle(intersectPoint,b,a,c)&&!pointInTriangle(intersectPoint,a,b,c)||squaredDistance>fromToDistanceSquared||(Transform.vectorToWorldFrame(quat,normal,worldNormal),Transform.pointToWorldFrame(position,quat,intersectPoint,worldIntersectPoint),this.reportIntersection(worldNormal,worldIntersectPoint,reportedShape,body,trianglesIndex))}}triangles.length=0},Ray.prototype[Shape.types.TRIMESH]=Ray.prototype.intersectTrimesh,Ray.prototype.reportIntersection=function(normal,hitPointWorld,shape,body,hitFaceIndex){var from=this.from,to=this.to,distance=from.distanceTo(hitPointWorld),result=this.result;if(!(this.skipBackfaces&&normal.dot(this._direction)>0))switch(result.hitFaceIndex=void 0!==hitFaceIndex?hitFaceIndex:-1,this.mode){case Ray.ALL:this.hasHit=!0,result.set(from,to,normal,hitPointWorld,shape,body,distance),result.hasHit=!0,this.callback(result);break;case Ray.CLOSEST:(distance=0&&!(a[j].aabb.lowerBound.x<=v.aabb.lowerBound.x);j--)a[j+1]=a[j];a[j+1]=v}return a},SAPBroadphase.insertionSortY=function(a){for(var i=1,l=a.length;i=0&&!(a[j].aabb.lowerBound.y<=v.aabb.lowerBound.y);j--)a[j+1]=a[j];a[j+1]=v}return a},SAPBroadphase.insertionSortZ=function(a){for(var i=1,l=a.length;i=0&&!(a[j].aabb.lowerBound.z<=v.aabb.lowerBound.z);j--)a[j+1]=a[j];a[j+1]=v}return a},SAPBroadphase.prototype.collisionPairs=function(world,p1,p2){var i,j,bodies=this.axisList,N=bodies.length,axisIndex=this.axisIndex;for(this.dirty&&(this.sortList(),this.dirty=!1),i=0;i!==N;i++){var bi=bodies[i];for(j=i+1;jvarianceY?varianceX>varianceZ?0:2:varianceY>varianceZ?1:2},SAPBroadphase.prototype.aabbQuery=function(world,aabb,result){result=result||[],this.dirty&&(this.sortList(),this.dirty=!1);var axisIndex=this.axisIndex,axis="x";1===axisIndex&&(axis="y"),2===axisIndex&&(axis="z");for(var axisList=this.axisList,i=(aabb.lowerBound[axis],aabb.upperBound[axis],0);i.499&&(heading=2*Math.atan2(x,w),attitude=Math.PI/2,bank=0),test<-.499&&(heading=-2*Math.atan2(x,w),attitude=-Math.PI/2,bank=0),isNaN(heading)){var sqx=x*x,sqy=y*y,sqz=z*z;heading=Math.atan2(2*y*w-2*x*z,1-2*sqy-2*sqz),attitude=Math.asin(2*test),bank=Math.atan2(2*x*w-2*y*z,1-2*sqx-2*sqz)}break;default:throw new Error("Euler order "+order+" not supported yet.")}target.y=heading,target.z=attitude,target.x=bank},Quaternion.prototype.setFromEuler=function(x,y,z,order){order=order||"XYZ";var c1=Math.cos(x/2),c2=Math.cos(y/2),c3=Math.cos(z/2),s1=Math.sin(x/2),s2=Math.sin(y/2),s3=Math.sin(z/2);return"XYZ"===order?(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):"YXZ"===order?(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):"ZXY"===order?(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):"ZYX"===order?(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):"YZX"===order?(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):"XZY"===order&&(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),this},Quaternion.prototype.clone=function(){return new Quaternion(this.x,this.y,this.z,this.w)},Quaternion.prototype.slerp=function(toQuat,t,target){target=target||new Quaternion;var omega,cosom,sinom,scale0,scale1,ax=this.x,ay=this.y,az=this.z,aw=this.w,bx=toQuat.x,by=toQuat.y,bz=toQuat.z,bw=toQuat.w;return(cosom=ax*bx+ay*by+az*bz+aw*bw)<0&&(cosom=-cosom,bx=-bx,by=-by,bz=-bz,bw=-bw),1-cosom>1e-6?(omega=Math.acos(cosom),sinom=Math.sin(omega),scale0=Math.sin((1-t)*omega)/sinom,scale1=Math.sin(t*omega)/sinom):(scale0=1-t,scale1=t),target.x=scale0*ax+scale1*bx,target.y=scale0*ay+scale1*by,target.z=scale0*az+scale1*bz,target.w=scale0*aw+scale1*bw,target},Quaternion.prototype.integrate=function(angularVelocity,dt,angularFactor,target){target=target||new Quaternion;var ax=angularVelocity.x*angularFactor.x,ay=angularVelocity.y*angularFactor.y,az=angularVelocity.z*angularFactor.z,bx=this.x,by=this.y,bz=this.z,bw=this.w,half_dt=.5*dt;return target.x+=half_dt*(ax*bw+ay*bz-az*by),target.y+=half_dt*(ay*bw+az*bx-ax*bz),target.z+=half_dt*(az*bw+ax*by-ay*bx),target.w+=half_dt*(-ax*bx-ay*by-az*bz),target}},{"./Vec3":33}],32:[function(require,module,exports){function Transform(options){options=options||{},this.position=new Vec3,options.position&&this.position.copy(options.position),this.quaternion=new Quaternion,options.quaternion&&this.quaternion.copy(options.quaternion)}var Vec3=require("./Vec3"),Quaternion=require("./Quaternion");module.exports=Transform;var tmpQuat=new Quaternion;Transform.pointToLocalFrame=function(position,quaternion,worldPoint,result){var result=result||new Vec3;return worldPoint.vsub(position,result),quaternion.conjugate(tmpQuat),tmpQuat.vmult(result,result),result},Transform.prototype.pointToLocal=function(worldPoint,result){return Transform.pointToLocalFrame(this.position,this.quaternion,worldPoint,result)},Transform.pointToWorldFrame=function(position,quaternion,localPoint,result){var result=result||new Vec3;return quaternion.vmult(localPoint,result),result.vadd(position,result),result},Transform.prototype.pointToWorld=function(localPoint,result){return Transform.pointToWorldFrame(this.position,this.quaternion,localPoint,result)},Transform.prototype.vectorToWorldFrame=function(localVector,result){var result=result||new Vec3;return this.quaternion.vmult(localVector,result),result},Transform.vectorToWorldFrame=function(quaternion,localVector,result){return quaternion.vmult(localVector,result),result},Transform.vectorToLocalFrame=function(position,quaternion,worldVector,result){var result=result||new Vec3;return quaternion.w*=-1,quaternion.vmult(worldVector,result),quaternion.w*=-1,result}},{"./Quaternion":31,"./Vec3":33}],33:[function(require,module,exports){function Vec3(x,y,z){this.x=x||0,this.y=y||0,this.z=z||0}module.exports=Vec3;var Mat3=require("./Mat3");Vec3.ZERO=new Vec3(0,0,0),Vec3.UNIT_X=new Vec3(1,0,0),Vec3.UNIT_Y=new Vec3(0,1,0),Vec3.UNIT_Z=new Vec3(0,0,1),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;return target=target||new Vec3,target.x=y*vz-z*vy,target.y=z*vx-x*vz,target.z=x*vy-y*vx,target},Vec3.prototype.set=function(x,y,z){return this.x=x,this.y=y,this.z=z,this},Vec3.prototype.setZero=function(){this.x=this.y=this.z=0},Vec3.prototype.vadd=function(v,target){if(!target)return new Vec3(this.x+v.x,this.y+v.y,this.z+v.z);target.x=v.x+this.x,target.y=v.y+this.y,target.z=v.z+this.z},Vec3.prototype.vsub=function(v,target){if(!target)return new Vec3(this.x-v.x,this.y-v.y,this.z-v.z);target.x=this.x-v.x,target.y=this.y-v.y,target.z=this.z-v.z},Vec3.prototype.crossmat=function(){return new Mat3([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])},Vec3.prototype.normalize=function(){var x=this.x,y=this.y,z=this.z,n=Math.sqrt(x*x+y*y+z*z);if(n>0){var invN=1/n;this.x*=invN,this.y*=invN,this.z*=invN}else this.x=0,this.y=0,this.z=0;return n},Vec3.prototype.unit=function(target){target=target||new Vec3;var x=this.x,y=this.y,z=this.z,ninv=Math.sqrt(x*x+y*y+z*z);return ninv>0?(ninv=1/ninv,target.x=x*ninv,target.y=y*ninv,target.z=z*ninv):(target.x=1,target.y=0,target.z=0),target},Vec3.prototype.norm=function(){var x=this.x,y=this.y,z=this.z;return Math.sqrt(x*x+y*y+z*z)},Vec3.prototype.length=Vec3.prototype.norm,Vec3.prototype.norm2=function(){return this.dot(this)},Vec3.prototype.lengthSquared=Vec3.prototype.norm2,Vec3.prototype.distanceTo=function(p){var x=this.x,y=this.y,z=this.z,px=p.x,py=p.y,pz=p.z;return Math.sqrt((px-x)*(px-x)+(py-y)*(py-y)+(pz-z)*(pz-z))},Vec3.prototype.distanceSquared=function(p){var x=this.x,y=this.y,z=this.z,px=p.x,py=p.y,pz=p.z;return(px-x)*(px-x)+(py-y)*(py-y)+(pz-z)*(pz-z)},Vec3.prototype.mult=function(scalar,target){target=target||new Vec3;var x=this.x,y=this.y,z=this.z;return target.x=scalar*x,target.y=scalar*y,target.z=scalar*z,target},Vec3.prototype.vmul=function(vector,target){return target=target||new Vec3,target.x=vector.x*this.x,target.y=vector.y*this.y,target.z=vector.z*this.z,target},Vec3.prototype.scale=Vec3.prototype.mult,Vec3.prototype.addScaledVector=function(scalar,vector,target){return target=target||new Vec3,target.x=this.x+scalar*vector.x,target.y=this.y+scalar*vector.y,target.z=this.z+scalar*vector.z,target},Vec3.prototype.dot=function(v){return this.x*v.x+this.y*v.y+this.z*v.z},Vec3.prototype.isZero=function(){return 0===this.x&&0===this.y&&0===this.z},Vec3.prototype.negate=function(target){return target=target||new Vec3,target.x=-this.x,target.y=-this.y,target.z=-this.z,target};var Vec3_tangents_n=new Vec3,Vec3_tangents_randVec=new Vec3;Vec3.prototype.tangents=function(t1,t2){var norm=this.norm();if(norm>0){var n=Vec3_tangents_n,inorm=1/norm;n.set(this.x*inorm,this.y*inorm,this.z*inorm);var randVec=Vec3_tangents_randVec;Math.abs(n.x)<.9?(randVec.set(1,0,0),n.cross(randVec,t1)):(randVec.set(0,1,0),n.cross(randVec,t1)),n.cross(t1,t2)}else t1.set(1,0,0),t2.set(0,1,0)},Vec3.prototype.toString=function(){return this.x+","+this.y+","+this.z},Vec3.prototype.toArray=function(){return[this.x,this.y,this.z]},Vec3.prototype.copy=function(source){return this.x=source.x,this.y=source.y,this.z=source.z,this},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},Vec3.prototype.almostEquals=function(v,precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x-v.x)>precision||Math.abs(this.y-v.y)>precision||Math.abs(this.z-v.z)>precision)},Vec3.prototype.almostZero=function(precision){return void 0===precision&&(precision=1e-6),!(Math.abs(this.x)>precision||Math.abs(this.y)>precision||Math.abs(this.z)>precision)};var antip_neg=new Vec3;Vec3.prototype.isAntiparallelTo=function(v,precision){return this.negate(antip_neg),antip_neg.almostEquals(v,precision)},Vec3.prototype.clone=function(){return new Vec3(this.x,this.y,this.z)}},{"./Mat3":30}],34:[function(require,module,exports){function Body(options){options=options||{},EventTarget.apply(this),this.id=Body.idCounter++,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new Vec3,this.collisionFilterGroup="number"==typeof options.collisionFilterGroup?options.collisionFilterGroup:1,this.collisionFilterMask="number"==typeof options.collisionFilterMask?options.collisionFilterMask:1,this.collisionResponse=!0,this.position=new Vec3,this.previousPosition=new Vec3,this.interpolatedPosition=new Vec3,this.initPosition=new Vec3,options.position&&(this.position.copy(options.position),this.previousPosition.copy(options.position),this.interpolatedPosition.copy(options.position),this.initPosition.copy(options.position)),this.velocity=new Vec3,options.velocity&&this.velocity.copy(options.velocity),this.initVelocity=new Vec3,this.force=new Vec3;var mass="number"==typeof options.mass?options.mass:0;this.mass=mass,this.invMass=mass>0?1/mass:0,this.material=options.material||null,this.linearDamping="number"==typeof options.linearDamping?options.linearDamping:.01,this.type=mass<=0?Body.STATIC:Body.DYNAMIC,typeof options.type==typeof Body.STATIC&&(this.type=options.type),this.allowSleep=void 0===options.allowSleep||options.allowSleep,this.sleepState=0,this.sleepSpeedLimit=void 0!==options.sleepSpeedLimit?options.sleepSpeedLimit:.1,this.sleepTimeLimit=void 0!==options.sleepTimeLimit?options.sleepTimeLimit:1,this.timeLastSleepy=0,this._wakeUpAfterNarrowphase=!1,this.torque=new Vec3,this.quaternion=new Quaternion,this.initQuaternion=new Quaternion,this.previousQuaternion=new Quaternion,this.interpolatedQuaternion=new Quaternion,options.quaternion&&(this.quaternion.copy(options.quaternion),this.initQuaternion.copy(options.quaternion),this.previousQuaternion.copy(options.quaternion),this.interpolatedQuaternion.copy(options.quaternion)),this.angularVelocity=new Vec3,options.angularVelocity&&this.angularVelocity.copy(options.angularVelocity),this.initAngularVelocity=new Vec3,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new Vec3,this.invInertia=new Vec3,this.invInertiaWorld=new Mat3,this.invMassSolve=0,this.invInertiaSolve=new Vec3,this.invInertiaWorldSolve=new Mat3,this.fixedRotation=void 0!==options.fixedRotation&&options.fixedRotation,this.angularDamping=void 0!==options.angularDamping?options.angularDamping:.01,this.linearFactor=new Vec3(1,1,1),options.linearFactor&&this.linearFactor.copy(options.linearFactor),this.angularFactor=new Vec3(1,1,1),options.angularFactor&&this.angularFactor.copy(options.angularFactor),this.aabb=new AABB,this.aabbNeedsUpdate=!0,this.wlambda=new Vec3,options.shape&&this.addShape(options.shape),this.updateMassProperties()}module.exports=Body;var EventTarget=require("../utils/EventTarget"),Vec3=(require("../shapes/Shape"),require("../math/Vec3")),Mat3=require("../math/Mat3"),Quaternion=require("../math/Quaternion"),AABB=(require("../material/Material"),require("../collision/AABB")),Box=require("../shapes/Box");Body.prototype=new EventTarget,Body.prototype.constructor=Body,Body.COLLIDE_EVENT_NAME="collide",Body.DYNAMIC=1,Body.STATIC=2,Body.KINEMATIC=4,Body.AWAKE=0,Body.SLEEPY=1,Body.SLEEPING=2,Body.idCounter=0,Body.wakeupEvent={type:"wakeup"},Body.prototype.wakeUp=function(){var s=this.sleepState;this.sleepState=0,this._wakeUpAfterNarrowphase=!1,s===Body.SLEEPING&&this.dispatchEvent(Body.wakeupEvent)},Body.prototype.sleep=function(){this.sleepState=Body.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this._wakeUpAfterNarrowphase=!1},Body.sleepyEvent={type:"sleepy"},Body.sleepEvent={type:"sleep"},Body.prototype.sleepTick=function(time){if(this.allowSleep){var sleepState=this.sleepState,speedSquared=this.velocity.norm2()+this.angularVelocity.norm2(),speedLimitSquared=Math.pow(this.sleepSpeedLimit,2);sleepState===Body.AWAKE&&speedSquaredspeedLimitSquared?this.wakeUp():sleepState===Body.SLEEPY&&time-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(Body.sleepEvent))}},Body.prototype.updateSolveMassProperties=function(){this.sleepState===Body.SLEEPING||this.type===Body.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))},Body.prototype.pointToLocalFrame=function(worldPoint,result){var result=result||new Vec3;return worldPoint.vsub(this.position,result),this.quaternion.conjugate().vmult(result,result),result},Body.prototype.vectorToLocalFrame=function(worldVector,result){var result=result||new Vec3;return this.quaternion.conjugate().vmult(worldVector,result),result},Body.prototype.pointToWorldFrame=function(localPoint,result){var result=result||new Vec3;return this.quaternion.vmult(localPoint,result),result.vadd(this.position,result),result},Body.prototype.vectorToWorldFrame=function(localVector,result){var result=result||new Vec3;return this.quaternion.vmult(localVector,result),result};var tmpVec=new Vec3,tmpQuat=new Quaternion;Body.prototype.addShape=function(shape,_offset,_orientation){var offset=new Vec3,orientation=new Quaternion;return _offset&&offset.copy(_offset),_orientation&&orientation.copy(_orientation),this.shapes.push(shape),this.shapeOffsets.push(offset),this.shapeOrientations.push(orientation),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,shape.body=this,this},Body.prototype.updateBoundingRadius=function(){for(var shapes=this.shapes,shapeOffsets=this.shapeOffsets,N=shapes.length,radius=0,i=0;i!==N;i++){var shape=shapes[i];shape.updateBoundingSphereRadius();var offset=shapeOffsets[i].norm(),r=shape.boundingSphereRadius;offset+r>radius&&(radius=offset+r)}this.boundingRadius=radius};var computeAABB_shapeAABB=new AABB;Body.prototype.computeAABB=function(){for(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,i=0;i!==N;i++){var shape=shapes[i];bodyQuat.vmult(shapeOffsets[i],offset),offset.vadd(this.position,offset),shapeOrientations[i].mult(bodyQuat,orientation),shape.calculateWorldAABB(offset,orientation,shapeAABB.lowerBound,shapeAABB.upperBound),0===i?aabb.copy(shapeAABB):aabb.extend(shapeAABB)}this.aabbNeedsUpdate=!1};var uiw_m1=new Mat3,uiw_m2=new Mat3;new Mat3;Body.prototype.updateInertiaWorld=function(force){var I=this.invInertia;if(I.x!==I.y||I.y!==I.z||force){var m1=uiw_m1,m2=uiw_m2;m1.setRotationFromQuaternion(this.quaternion),m1.transpose(m2),m1.scale(I,m1),m1.mmult(m2,this.invInertiaWorld)}else;};new Vec3;var Body_applyForce_rotForce=new Vec3;Body.prototype.applyForce=function(force,relativePoint){if(this.type===Body.DYNAMIC){var rotForce=Body_applyForce_rotForce;relativePoint.cross(force,rotForce),this.force.vadd(force,this.force),this.torque.vadd(rotForce,this.torque)}};var Body_applyLocalForce_worldForce=new Vec3,Body_applyLocalForce_relativePointWorld=new Vec3;Body.prototype.applyLocalForce=function(localForce,localPoint){if(this.type===Body.DYNAMIC){var worldForce=Body_applyLocalForce_worldForce,relativePointWorld=Body_applyLocalForce_relativePointWorld;this.vectorToWorldFrame(localForce,worldForce),this.vectorToWorldFrame(localPoint,relativePointWorld),this.applyForce(worldForce,relativePointWorld)}};new Vec3;var Body_applyImpulse_velo=new Vec3,Body_applyImpulse_rotVelo=new Vec3;Body.prototype.applyImpulse=function(impulse,relativePoint){if(this.type===Body.DYNAMIC){var r=relativePoint,velo=Body_applyImpulse_velo;velo.copy(impulse),velo.mult(this.invMass,velo),this.velocity.vadd(velo,this.velocity);var rotVelo=Body_applyImpulse_rotVelo;r.cross(impulse,rotVelo),this.invInertiaWorld.vmult(rotVelo,rotVelo),this.angularVelocity.vadd(rotVelo,this.angularVelocity)}};var Body_applyLocalImpulse_worldImpulse=new Vec3,Body_applyLocalImpulse_relativePoint=new Vec3;Body.prototype.applyLocalImpulse=function(localImpulse,localPoint){if(this.type===Body.DYNAMIC){var worldImpulse=Body_applyLocalImpulse_worldImpulse,relativePointWorld=Body_applyLocalImpulse_relativePoint;this.vectorToWorldFrame(localImpulse,worldImpulse),this.vectorToWorldFrame(localPoint,relativePointWorld),this.applyImpulse(worldImpulse,relativePointWorld)}};var Body_updateMassProperties_halfExtents=new Vec3;Body.prototype.updateMassProperties=function(){var halfExtents=Body_updateMassProperties_halfExtents;this.invMass=this.mass>0?1/this.mass:0;var I=this.inertia,fixed=this.fixedRotation;this.computeAABB(),halfExtents.set((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),Box.calculateInertia(halfExtents,this.mass,I),this.invInertia.set(I.x>0&&!fixed?1/I.x:0,I.y>0&&!fixed?1/I.y:0,I.z>0&&!fixed?1/I.z:0),this.updateInertiaWorld(!0)},Body.prototype.getVelocityAtWorldPoint=function(worldPoint,result){var r=new Vec3;return worldPoint.vsub(this.position,r),this.angularVelocity.cross(r,result),this.velocity.vadd(result,result),result};new Vec3,new Vec3,new Quaternion,new Quaternion;Body.prototype.integrate=function(dt,quatNormalize,quatNormalizeFast){if(this.previousPosition.copy(this.position),this.previousQuaternion.copy(this.quaternion),(this.type===Body.DYNAMIC||this.type===Body.KINEMATIC)&&this.sleepState!==Body.SLEEPING){var velo=this.velocity,angularVelo=this.angularVelocity,pos=this.position,force=this.force,torque=this.torque,quat=this.quaternion,invMass=this.invMass,invInertia=this.invInertiaWorld,linearFactor=this.linearFactor,iMdt=invMass*dt;velo.x+=force.x*iMdt*linearFactor.x,velo.y+=force.y*iMdt*linearFactor.y,velo.z+=force.z*iMdt*linearFactor.z;var e=invInertia.elements,angularFactor=this.angularFactor,tx=torque.x*angularFactor.x,ty=torque.y*angularFactor.y,tz=torque.z*angularFactor.z;angularVelo.x+=dt*(e[0]*tx+e[1]*ty+e[2]*tz),angularVelo.y+=dt*(e[3]*tx+e[4]*ty+e[5]*tz),angularVelo.z+=dt*(e[6]*tx+e[7]*ty+e[8]*tz),pos.x+=velo.x*dt,pos.y+=velo.y*dt,pos.z+=velo.z*dt,quat.integrate(this.angularVelocity,dt,this.angularFactor,quat),quatNormalize&&(quatNormalizeFast?quat.normalizeFast():quat.normalize()),this.aabbNeedsUpdate=!0,this.updateInertiaWorld()}}},{"../collision/AABB":5,"../material/Material":28,"../math/Mat3":30,"../math/Quaternion":31,"../math/Vec3":33,"../shapes/Box":40,"../shapes/Shape":46,"../utils/EventTarget":52}],35:[function(require,module,exports){function RaycastVehicle(options){this.chassisBody=options.chassisBody,this.wheelInfos=[],this.sliding=!1,this.world=null,this.indexRightAxis=void 0!==options.indexRightAxis?options.indexRightAxis:1,this.indexForwardAxis=void 0!==options.indexForwardAxis?options.indexForwardAxis:0,this.indexUpAxis=void 0!==options.indexUpAxis?options.indexUpAxis:2}function calcRollingFriction(body0,body1,frictionPosWorld,frictionDirectionWorld,maxImpulse){var j1=0,contactPosWorld=frictionPosWorld,vel1=calcRollingFriction_vel1,vel2=calcRollingFriction_vel2,vel=calcRollingFriction_vel;body0.getVelocityAtWorldPoint(contactPosWorld,vel1),body1.getVelocityAtWorldPoint(contactPosWorld,vel2),vel1.vsub(vel2,vel);return j1=-frictionDirectionWorld.dot(vel)*(1/(computeImpulseDenominator(body0,frictionPosWorld,frictionDirectionWorld)+computeImpulseDenominator(body1,frictionPosWorld,frictionDirectionWorld))),maxImpulse1.1)return 0;var vel1=resolveSingleBilateral_vel1,vel2=resolveSingleBilateral_vel2,vel=resolveSingleBilateral_vel;body1.getVelocityAtWorldPoint(pos1,vel1),body2.getVelocityAtWorldPoint(pos2,vel2),vel1.vsub(vel2,vel);return-.2*normal.dot(vel)*(1/(body1.invMass+body2.invMass))}require("./Body");var Vec3=require("../math/Vec3"),Quaternion=require("../math/Quaternion"),Ray=(require("../collision/RaycastResult"),require("../collision/Ray")),WheelInfo=require("../objects/WheelInfo");module.exports=RaycastVehicle;new Vec3,new Vec3,new Vec3;var tmpVec4=new Vec3,tmpVec5=new Vec3,tmpVec6=new Vec3;new Ray;RaycastVehicle.prototype.addWheel=function(options){var info=new WheelInfo(options=options||{}),index=this.wheelInfos.length;return this.wheelInfos.push(info),index},RaycastVehicle.prototype.setSteeringValue=function(value,wheelIndex){this.wheelInfos[wheelIndex].steering=value};new Vec3;RaycastVehicle.prototype.applyEngineForce=function(value,wheelIndex){this.wheelInfos[wheelIndex].engineForce=value},RaycastVehicle.prototype.setBrake=function(brake,wheelIndex){this.wheelInfos[wheelIndex].brake=brake},RaycastVehicle.prototype.addToWorld=function(world){this.constraints;world.addBody(this.chassisBody);var that=this;this.preStepCallback=function(){that.updateVehicle(world.dt)},world.addEventListener("preStep",this.preStepCallback),this.world=world},RaycastVehicle.prototype.getVehicleAxisWorld=function(axisIndex,result){result.set(0===axisIndex?1:0,1===axisIndex?1:0,2===axisIndex?1:0),this.chassisBody.vectorToWorldFrame(result,result)},RaycastVehicle.prototype.updateVehicle=function(timeStep){for(var wheelInfos=this.wheelInfos,numWheels=wheelInfos.length,chassisBody=this.chassisBody,i=0;iwheel.maxSuspensionForce&&(suspensionForce=wheel.maxSuspensionForce),wheel.raycastResult.hitNormalWorld.scale(suspensionForce*timeStep,impulse),wheel.raycastResult.hitPointWorld.vsub(chassisBody.position,relpos),chassisBody.applyImpulse(impulse,relpos)}this.updateFriction(timeStep);var hitNormalWorldScaledWithProj=new Vec3,fwd=new Vec3,vel=new Vec3;for(i=0;i0?1:-1)*wheel.customSlidingRotationalSpeed*timeStep),Math.abs(wheel.brake)>Math.abs(wheel.engineForce)&&(wheel.deltaRotation=0),wheel.rotation+=wheel.deltaRotation,wheel.deltaRotation*=.99}},RaycastVehicle.prototype.updateSuspension=function(deltaTime){for(var chassisMass=this.chassisBody.mass,wheelInfos=this.wheelInfos,numWheels=wheelInfos.length,w_it=0;w_itmaxSuspensionLength&&(wheel.suspensionLength=maxSuspensionLength,wheel.raycastResult.reset());var denominator=wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld),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>=-.1)wheel.suspensionRelativeVelocity=0,wheel.clippedInvContactDotSuspension=10;else{var inv=-1/denominator;wheel.suspensionRelativeVelocity=projVel*inv,wheel.clippedInvContactDotSuspension=inv}}else wheel.suspensionLength=wheel.suspensionRestLength+0*wheel.maxSuspensionTravel,wheel.suspensionRelativeVelocity=0,wheel.directionWorld.scale(-1,wheel.raycastResult.hitNormalWorld),wheel.clippedInvContactDotSuspension=1;return depth},RaycastVehicle.prototype.updateWheelTransformWorld=function(wheel){wheel.isInContact=!1;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,right=tmpVec5,fwd=tmpVec6,wheel=this.wheelInfos[wheelIndex];this.updateWheelTransformWorld(wheel),wheel.directionLocal.scale(-1,up),right.copy(wheel.axleLocal),up.cross(right,fwd),fwd.normalize(),right.normalize();var steering=wheel.steering,steeringOrn=new Quaternion;steeringOrn.setFromAxisAngle(up,steering);var rotatingOrn=new Quaternion;rotatingOrn.setFromAxisAngle(right,wheel.rotation);var q=wheel.worldTransform.quaternion;this.chassisBody.quaternion.mult(steeringOrn,q),q.mult(rotatingOrn,q),q.normalize();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)];RaycastVehicle.prototype.getWheelTransformWorld=function(wheelIndex){return this.wheelInfos[wheelIndex].worldTransform};var updateFriction_surfNormalWS_scaled_proj=new Vec3,updateFriction_axle=[],updateFriction_forwardWS=[];RaycastVehicle.prototype.updateFriction=function(timeStep){for(var surfNormalWS_scaled_proj=updateFriction_surfNormalWS_scaled_proj,wheelInfos=this.wheelInfos,numWheels=wheelInfos.length,chassisBody=this.chassisBody,forwardWS=updateFriction_forwardWS,axle=updateFriction_axle,numWheelsOnGround=0,i=0;imaximpSquared){this.sliding=!0,wheel.sliding=!0;var factor=maximp/Math.sqrt(impulseSquared);wheel.skidInfo*=factor}}}if(this.sliding)for(i=0;ithis.particles.length&&this.neighbors.pop())};var SPHSystem_getNeighbors_dist=new Vec3;SPHSystem.prototype.getNeighbors=function(particle,neighbors){for(var N=this.particles.length,id=particle.id,R2=this.smoothingRadius*this.smoothingRadius,dist=SPHSystem_getNeighbors_dist,i=0;i!==N;i++){var p=this.particles[i];p.position.vsub(particle.position,dist),id!==p.id&&dist.norm2()=-.1)this.suspensionRelativeVelocity=0,this.clippedInvContactDotSuspension=10;else{var inv=-1/project;this.suspensionRelativeVelocity=projVel*inv,this.clippedInvContactDotSuspension=inv}}else raycastResult.suspensionLength=this.suspensionRestLength,this.suspensionRelativeVelocity=0,raycastResult.directionWorld.scale(-1,raycastResult.hitNormalWorld),this.clippedInvContactDotSuspension=1}},{"../collision/RaycastResult":13,"../math/Transform":32,"../math/Vec3":33,"../utils/Utils":56}],40:[function(require,module,exports){function Box(halfExtents){Shape.call(this),this.type=Shape.types.BOX,this.halfExtents=halfExtents,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}module.exports=Box;var Shape=require("./Shape"),Vec3=require("../math/Vec3"),ConvexPolyhedron=require("./ConvexPolyhedron");Box.prototype=new Shape,Box.prototype.constructor=Box,Box.prototype.updateConvexPolyhedronRepresentation=function(){var sx=this.halfExtents.x,sy=this.halfExtents.y,sz=this.halfExtents.z,V=Vec3,vertices=[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)],indices=[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]],h=(new V(0,0,1),new V(0,1,0),new V(1,0,0),new ConvexPolyhedron(vertices,indices));this.convexPolyhedronRepresentation=h,h.material=this.material},Box.prototype.calculateLocalInertia=function(mass,target){return target=target||new Vec3,Box.calculateInertia(this.halfExtents,mass,target),target},Box.calculateInertia=function(halfExtents,mass,target){var e=halfExtents;target.x=1/12*mass*(2*e.y*2*e.y+2*e.z*2*e.z),target.y=1/12*mass*(2*e.x*2*e.x+2*e.z*2*e.z),target.z=1/12*mass*(2*e.y*2*e.y+2*e.x*2*e.x)},Box.prototype.getSideNormals=function(sixTargetVectors,quat){var sides=sixTargetVectors,ex=this.halfExtents;if(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),void 0!==quat)for(var i=0;i!==sides.length;i++)quat.vmult(sides[i],sides[i]);return sides},Box.prototype.volume=function(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z},Box.prototype.updateBoundingSphereRadius=function(){this.boundingSphereRadius=this.halfExtents.norm()};var worldCornerTempPos=new Vec3;new Vec3;Box.prototype.forEachWorldCorner=function(pos,quat,callback){for(var e=this.halfExtents,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]],i=0;imax.x&&(max.x=x),y>max.y&&(max.y=y),z>max.z&&(max.z=z),xdmax&&(dmax=d,closestFaceB=face)}for(var worldVertsB1=[],polyB=hullB.faces[closestFaceB],numVertices=polyB.length,e0=0;e0=0&&this.clipFaceAgainstHull(separatingNormal,posA,quatA,worldVertsB1,minDist,maxDist,result)};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,dmin=Number.MAX_VALUE,hullA=this,curPlaneTests=0;if(hullA.uniqueAxes)for(i=0;i!==hullA.uniqueAxes.length;i++){if(quatA.vmult(hullA.uniqueAxes[i],faceANormalWS3),!1===(d=hullA.testSepAxis(faceANormalWS3,hullB,posA,quatA,posB,quatB)))return!1;d0&&target.negate(target),!0};var maxminA=[],maxminB=[];ConvexPolyhedron.prototype.testSepAxis=function(axis,hullB,posA,quatA,posB,quatB){var hullA=this;ConvexPolyhedron.project(hullA,axis,posA,quatA,maxminA),ConvexPolyhedron.project(hullB,axis,posB,quatB,maxminB);var maxA=maxminA[0],minA=maxminA[1],maxB=maxminB[0],minB=maxminB[1];if(maxAmaxValue&&(maxValue=v)}this.maxValue=maxValue},Heightfield.prototype.setHeightValueAtIndex=function(xi,yi,value){this.data[xi][yi]=value,this.clearCachedConvexTrianglePillar(xi,yi,!1),xi>0&&(this.clearCachedConvexTrianglePillar(xi-1,yi,!0),this.clearCachedConvexTrianglePillar(xi-1,yi,!1)),yi>0&&(this.clearCachedConvexTrianglePillar(xi,yi-1,!0),this.clearCachedConvexTrianglePillar(xi,yi-1,!1)),yi>0&&xi>0&&this.clearCachedConvexTrianglePillar(xi-1,yi-1,!0)},Heightfield.prototype.getRectMinMax=function(iMinX,iMinY,iMaxX,iMaxY,result){result=result||[];for(var data=this.data,max=this.minValue,i=iMinX;i<=iMaxX;i++)for(var j=iMinY;j<=iMaxY;j++){var height=data[i][j];height>max&&(max=height)}result[0]=this.minValue,result[1]=max},Heightfield.prototype.getIndexOfPosition=function(x,y,result,clamp){var w=this.elementSize,data=this.data,xi=Math.floor(x/w),yi=Math.floor(y/w);return result[0]=xi,result[1]=yi,clamp&&(xi<0&&(xi=0),yi<0&&(yi=0),xi>=data.length-1&&(xi=data.length-1),yi>=data[0].length-1&&(yi=data[0].length-1)),!(xi<0||yi<0||xi>=data.length-1||yi>=data[0].length-1)};var getHeightAt_idx=[],getHeightAt_weights=new Vec3,getHeightAt_a=new Vec3,getHeightAt_b=new Vec3,getHeightAt_c=new Vec3;Heightfield.prototype.getTriangleAt=function(x,y,edgeClamp,a,b,c){var idx=getHeightAt_idx;this.getIndexOfPosition(x,y,idx,edgeClamp);var xi=idx[0],yi=idx[1],data=this.data;edgeClamp&&(xi=Math.min(data.length-2,Math.max(0,xi)),yi=Math.min(data[0].length-2,Math.max(0,yi)));var elementSize=this.elementSize,upper=Math.pow(x/elementSize-xi,2)+Math.pow(y/elementSize-yi,2)>Math.pow(x/elementSize-(xi+1),2)+Math.pow(y/elementSize-(yi+1),2);return this.getTriangle(xi,yi,upper,a,b,c),upper};var getNormalAt_a=new Vec3,getNormalAt_b=new Vec3,getNormalAt_c=new Vec3,getNormalAt_e0=new Vec3,getNormalAt_e1=new Vec3;Heightfield.prototype.getNormalAt=function(x,y,edgeClamp,result){var a=getNormalAt_a,b=getNormalAt_b,c=getNormalAt_c,e0=getNormalAt_e0,e1=getNormalAt_e1;this.getTriangleAt(x,y,edgeClamp,a,b,c),b.vsub(a,e0),c.vsub(a,e1),e0.cross(e1,result),result.normalize()},Heightfield.prototype.getAabbAtIndex=function(xi,yi,result){var data=this.data,elementSize=this.elementSize;result.lowerBound.set(xi*elementSize,yi*elementSize,data[xi][yi]),result.upperBound.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1])},Heightfield.prototype.getHeightAt=function(x,y,edgeClamp){var data=this.data,a=getHeightAt_a,b=getHeightAt_b,c=getHeightAt_c,idx=getHeightAt_idx;this.getIndexOfPosition(x,y,idx,edgeClamp);var xi=idx[0],yi=idx[1];edgeClamp&&(xi=Math.min(data.length-2,Math.max(0,xi)),yi=Math.min(data[0].length-2,Math.max(0,yi)));var upper=this.getTriangleAt(x,y,edgeClamp,a,b,c);barycentricWeights(x,y,a.x,a.y,b.x,b.y,c.x,c.y,getHeightAt_weights);var w=getHeightAt_weights;return upper?data[xi+1][yi+1]*w.x+data[xi][yi+1]*w.y+data[xi+1][yi]*w.z:data[xi][yi]*w.x+data[xi+1][yi]*w.y+data[xi][yi+1]*w.z},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)]},Heightfield.prototype.getTriangle=function(xi,yi,upper,a,b,c){var data=this.data,elementSize=this.elementSize;upper?(a.set((xi+1)*elementSize,(yi+1)*elementSize,data[xi+1][yi+1]),b.set(xi*elementSize,(yi+1)*elementSize,data[xi][yi+1]),c.set((xi+1)*elementSize,yi*elementSize,data[xi+1][yi])):(a.set(xi*elementSize,yi*elementSize,data[xi][yi]),b.set((xi+1)*elementSize,yi*elementSize,data[xi+1][yi]),c.set(xi*elementSize,(yi+1)*elementSize,data[xi][yi+1]))},Heightfield.prototype.getConvexTrianglePillar=function(xi,yi,getUpperTriangle){var result=this.pillarConvex,offsetResult=this.pillarOffset;if(this.cacheEnabled){if(data=this.getCachedConvexTrianglePillar(xi,yi,getUpperTriangle))return this.pillarConvex=data.convex,void(this.pillarOffset=data.offset);result=new ConvexPolyhedron,offsetResult=new Vec3,this.pillarConvex=result,this.pillarOffset=offsetResult}var data=this.data,elementSize=this.elementSize,faces=result.faces;result.vertices.length=6;for(i=0;i<6;i++)result.vertices[i]||(result.vertices[i]=new Vec3);faces.length=5;for(var i=0;i<5;i++)faces[i]||(faces[i]=[]);var verts=result.vertices,h=(Math.min(data[xi][yi],data[xi+1][yi],data[xi][yi+1],data[xi+1][yi+1])-this.minValue)/2+this.minValue;getUpperTriangle?(offsetResult.set((xi+.75)*elementSize,(yi+.75)*elementSize,h),verts[0].set(.25*elementSize,.25*elementSize,data[xi+1][yi+1]-h),verts[1].set(-.75*elementSize,.25*elementSize,data[xi][yi+1]-h),verts[2].set(.25*elementSize,-.75*elementSize,data[xi+1][yi]-h),verts[3].set(.25*elementSize,.25*elementSize,-h-1),verts[4].set(-.75*elementSize,.25*elementSize,-h-1),verts[5].set(.25*elementSize,-.75*elementSize,-h-1),faces[0][0]=0,faces[0][1]=1,faces[0][2]=2,faces[1][0]=5,faces[1][1]=4,faces[1][2]=3,faces[2][0]=2,faces[2][1]=5,faces[2][2]=3,faces[2][3]=0,faces[3][0]=3,faces[3][1]=4,faces[3][2]=1,faces[3][3]=0,faces[4][0]=1,faces[4][1]=4,faces[4][2]=5,faces[4][3]=2):(offsetResult.set((xi+.25)*elementSize,(yi+.25)*elementSize,h),verts[0].set(-.25*elementSize,-.25*elementSize,data[xi][yi]-h),verts[1].set(.75*elementSize,-.25*elementSize,data[xi+1][yi]-h),verts[2].set(-.25*elementSize,.75*elementSize,data[xi][yi+1]-h),verts[3].set(-.25*elementSize,-.25*elementSize,-h-1),verts[4].set(.75*elementSize,-.25*elementSize,-h-1),verts[5].set(-.25*elementSize,.75*elementSize,-h-1),faces[0][0]=0,faces[0][1]=1,faces[0][2]=2,faces[1][0]=5,faces[1][1]=4,faces[1][2]=3,faces[2][0]=0,faces[2][1]=2,faces[2][2]=5,faces[2][3]=3,faces[3][0]=1,faces[3][1]=0,faces[3][2]=3,faces[3][3]=4,faces[4][0]=4,faces[4][1]=5,faces[4][2]=2,faces[4][3]=1),result.computeNormals(),result.computeEdges(),result.updateBoundingSphereRadius(),this.setCachedConvexTrianglePillar(xi,yi,getUpperTriangle,result,offsetResult)},Heightfield.prototype.calculateLocalInertia=function(mass,target){return(target=target||new Vec3).set(0,0,0),target},Heightfield.prototype.volume=function(){return Number.MAX_VALUE},Heightfield.prototype.calculateWorldAABB=function(pos,quat,min,max){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(){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()},Heightfield.prototype.setHeightsFromImage=function(image,scale){var canvas=document.createElement("canvas");canvas.width=image.width,canvas.height=image.height;var context=canvas.getContext("2d");context.drawImage(image,0,0);var imageData=context.getImageData(0,0,image.width,image.height),matrix=this.data;matrix.length=0,this.elementSize=Math.abs(scale.x)/imageData.width;for(var i=0;iu.x&&(u.x=v.x),v.yu.y&&(u.y=v.y),v.zu.z&&(u.z=v.z)},Trimesh.prototype.updateAABB=function(){this.computeLocalAABB(this.aabb)},Trimesh.prototype.updateBoundingSphereRadius=function(){for(var max2=0,vertices=this.vertices,v=new Vec3,i=0,N=vertices.length/3;i!==N;i++){this.getVertex(i,v);var norm2=v.norm2();norm2>max2&&(max2=norm2)}this.boundingSphereRadius=Math.sqrt(max2)};new Vec3;var calculateWorldAABB_frame=new Transform,calculateWorldAABB_aabb=new AABB;Trimesh.prototype.calculateWorldAABB=function(pos,quat,min,max){var frame=calculateWorldAABB_frame,result=calculateWorldAABB_aabb;frame.position=pos,frame.quaternion=quat,this.aabb.toWorldFrame(frame,result),min.copy(result.lowerBound),max.copy(result.upperBound)},Trimesh.prototype.volume=function(){return 4*Math.PI*this.boundingSphereRadius/3},Trimesh.createTorus=function(radius,tube,radialSegments,tubularSegments,arc){radius=radius||1,tube=tube||.5,radialSegments=radialSegments||8,tubularSegments=tubularSegments||6,arc=arc||2*Math.PI;for(var vertices=[],indices=[],j=0;j<=radialSegments;j++)for(i=0;i<=tubularSegments;i++){var u=i/tubularSegments*arc,v=j/radialSegments*Math.PI*2,x=(radius+tube*Math.cos(v))*Math.cos(u),y=(radius+tube*Math.cos(v))*Math.sin(u),z=tube*Math.sin(v);vertices.push(x,y,z)}for(j=1;j<=radialSegments;j++)for(var i=1;i<=tubularSegments;i++){var a=(tubularSegments+1)*j+i-1,b=(tubularSegments+1)*(j-1)+i-1,c=(tubularSegments+1)*(j-1)+i,d=(tubularSegments+1)*j+i;indices.push(a,b,d),indices.push(b,c,d)}return new Trimesh(vertices,indices)}},{"../collision/AABB":5,"../math/Quaternion":31,"../math/Transform":32,"../math/Vec3":33,"../utils/Octree":53,"./Shape":46}],49:[function(require,module,exports){function GSSolver(){Solver.call(this),this.iterations=10,this.tolerance=1e-7}module.exports=GSSolver;require("../math/Vec3"),require("../math/Quaternion");var Solver=require("./Solver");GSSolver.prototype=new Solver;var GSSolver_solve_lambda=[],GSSolver_solve_invCs=[],GSSolver_solve_Bs=[];GSSolver.prototype.solve=function(dt,world){var B,invC,deltalambda,deltalambdaTot,lambdaj,iter=0,maxIter=this.iterations,tolSquared=this.tolerance*this.tolerance,equations=this.equations,Neq=equations.length,bodies=world.bodies,Nbodies=bodies.length,h=dt;if(0!==Neq)for(i=0;i!==Nbodies;i++)bodies[i].updateSolveMassProperties();var invCs=GSSolver_solve_invCs,Bs=GSSolver_solve_Bs,lambda=GSSolver_solve_lambda;invCs.length=Neq,Bs.length=Neq,lambda.length=Neq;for(i=0;i!==Neq;i++){c=equations[i];lambda[i]=0,Bs[i]=c.computeB(h),invCs[i]=1/c.computeC()}if(0!==Neq){for(i=0;i!==Nbodies;i++){var vlambda=(b=bodies[i]).vlambda,wlambda=b.wlambda;vlambda.set(0,0,0),wlambda.set(0,0,0)}for(iter=0;iter!==maxIter;iter++){deltalambdaTot=0;for(var j=0;j!==Neq;j++){var c=equations[j];B=Bs[j],invC=invCs[j],(lambdaj=lambda[j])+(deltalambda=invC*(B-c.computeGWlambda()-c.eps*lambdaj))c.maxForce&&(deltalambda=c.maxForce-lambdaj),lambda[j]+=deltalambda,deltalambdaTot+=deltalambda>0?deltalambda:-deltalambda,c.addToWlambda(deltalambda)}if(deltalambdaTot*deltalambdaTot=0;i--)node.children[i].data.length||node.children.splice(i,1);Array.prototype.push.apply(queue,node.children)}}},{"../collision/AABB":5,"../math/Vec3":33}],54:[function(require,module,exports){function Pool(){this.objects=[],this.type=Object}module.exports=Pool,Pool.prototype.release=function(){for(var Nargs=arguments.length,i=0;i!==Nargs;i++)this.objects.push(arguments[i]);return this},Pool.prototype.get=function(){return 0===this.objects.length?this.constructObject():this.objects.pop()},Pool.prototype.constructObject=function(){throw new Error("constructObject() not implemented in this Pool subclass yet!")},Pool.prototype.resize=function(size){for(var objects=this.objects;objects.length>size;)objects.pop();for(;objects.lengthj){var temp=j;j=i,i=temp}return this.data[i+"-"+j]},TupleDictionary.prototype.set=function(i,j,value){if(i>j){var temp=j;j=i,i=temp}var key=i+"-"+j;this.get(i,j)||this.data.keys.push(key),this.data[key]=value},TupleDictionary.prototype.reset=function(){for(var data=this.data,keys=data.keys;keys.length>0;)delete data[keys.pop()]}},{}],56:[function(require,module,exports){function Utils(){}module.exports=Utils,Utils.defaults=function(options,defaults){options=options||{};for(var key in defaults)key in options||(options[key]=defaults[key]);return options}},{}],57:[function(require,module,exports){function Vec3Pool(){Pool.call(this),this.type=Vec3}module.exports=Vec3Pool;var Vec3=require("../math/Vec3"),Pool=require("./Pool");Vec3Pool.prototype=new Pool,Vec3Pool.prototype.constructObject=function(){return new Vec3}},{"../math/Vec3":33,"./Pool":54}],58:[function(require,module,exports){function Narrowphase(world){this.contactPointPool=[],this.frictionEquationPool=[],this.result=[],this.frictionResult=[],this.v3pool=new Vec3Pool,this.world=world,this.currentContactMaterial=null,this.enableFrictionReduction=!1}function pointInPolygon(verts,normal,p){for(var positiveResult=null,N=verts.length,i=0;i!==N;i++){var v=verts[i],edge=pointInPolygon_edge;verts[(i+1)%N].vsub(v,edge);var edge_x_normal=pointInPolygon_edge_x_normal;edge.cross(normal,edge_x_normal);var vertex_to_p=pointInPolygon_vtp;p.vsub(v,vertex_to_p);var r=edge_x_normal.dot(vertex_to_p);if(!(null===positiveResult||r>0&&!0===positiveResult||r<=0&&!1===positiveResult))return!1;null===positiveResult&&(positiveResult=r>0)}return!0}module.exports=Narrowphase;var AABB=require("../collision/AABB"),Body=require("../objects/Body"),Shape=require("../shapes/Shape"),Ray=require("../collision/Ray"),Vec3=require("../math/Vec3"),Transform=require("../math/Transform"),Quaternion=(require("../shapes/ConvexPolyhedron"),require("../math/Quaternion")),Vec3Pool=(require("../solver/Solver"),require("../utils/Vec3Pool")),ContactEquation=require("../equations/ContactEquation"),FrictionEquation=require("../equations/FrictionEquation");Narrowphase.prototype.createContactEquation=function(bi,bj,si,sj,overrideShapeA,overrideShapeB){var c;this.contactPointPool.length?((c=this.contactPointPool.pop()).bi=bi,c.bj=bj):c=new ContactEquation(bi,bj),c.enabled=bi.collisionResponse&&bj.collisionResponse&&si.collisionResponse&&sj.collisionResponse;var cm=this.currentContactMaterial;c.restitution=cm.restitution,c.setSpookParams(cm.contactEquationStiffness,cm.contactEquationRelaxation,this.world.dt);var matA=si.material||bi.material,matB=sj.material||bj.material;return matA&&matB&&matA.restitution>=0&&matB.restitution>=0&&(c.restitution=matA.restitution*matB.restitution),c.si=overrideShapeA||si,c.sj=overrideShapeB||sj,c},Narrowphase.prototype.createFrictionEquationsFromContact=function(contactEquation,outArray){var bodyA=contactEquation.bi,bodyB=contactEquation.bj,shapeA=contactEquation.si,shapeB=contactEquation.sj,world=this.world,cm=this.currentContactMaterial,friction=cm.friction,matA=shapeA.material||bodyA.material,matB=shapeB.material||bodyB.material;if(matA&&matB&&matA.friction>=0&&matB.friction>=0&&(friction=matA.friction*matB.friction),friction>0){var mug=friction*world.gravity.length(),reducedMass=bodyA.invMass+bodyB.invMass;reducedMass>0&&(reducedMass=1/reducedMass);var pool=this.frictionEquationPool,c1=pool.length?pool.pop():new FrictionEquation(bodyA,bodyB,mug*reducedMass),c2=pool.length?pool.pop():new FrictionEquation(bodyA,bodyB,mug*reducedMass);return c1.bi=c2.bi=bodyA,c1.bj=c2.bj=bodyB,c1.minForce=c2.minForce=-mug*reducedMass,c1.maxForce=c2.maxForce=mug*reducedMass,c1.ri.copy(contactEquation.ri),c1.rj.copy(contactEquation.rj),c2.ri.copy(contactEquation.ri),c2.rj.copy(contactEquation.rj),contactEquation.ni.tangents(c1.t,c2.t),c1.setSpookParams(cm.frictionEquationStiffness,cm.frictionEquationRelaxation,world.dt),c2.setSpookParams(cm.frictionEquationStiffness,cm.frictionEquationRelaxation,world.dt),c1.enabled=c2.enabled=contactEquation.enabled,outArray.push(c1,c2),!0}return!1};var averageNormal=new Vec3,averageContactPointA=new Vec3,averageContactPointB=new Vec3;Narrowphase.prototype.createFrictionFromAverage=function(numContacts){var c=this.result[this.result.length-1];if(this.createFrictionEquationsFromContact(c,this.frictionResult)&&1!==numContacts){var f1=this.frictionResult[this.frictionResult.length-2],f2=this.frictionResult[this.frictionResult.length-1];averageNormal.setZero(),averageContactPointA.setZero(),averageContactPointB.setZero();for(var bodyA=c.bi,i=(c.bj,0);i!==numContacts;i++)(c=this.result[this.result.length-1-i]).bodyA!==bodyA?(averageNormal.vadd(c.ni,averageNormal),averageContactPointA.vadd(c.ri,averageContactPointA),averageContactPointB.vadd(c.rj,averageContactPointB)):(averageNormal.vsub(c.ni,averageNormal),averageContactPointA.vadd(c.rj,averageContactPointA),averageContactPointB.vadd(c.ri,averageContactPointB));var invNumContacts=1/numContacts;averageContactPointA.scale(invNumContacts,f1.ri),averageContactPointB.scale(invNumContacts,f1.rj),f2.ri.copy(f1.ri),f2.rj.copy(f1.rj),averageNormal.normalize(),averageNormal.tangents(f1.t,f2.t)}};var tmpVec1=new Vec3,tmpVec2=new Vec3,tmpQuat1=new Quaternion,tmpQuat2=new Quaternion;Narrowphase.prototype.getContacts=function(p1,p2,world,result,oldcontacts,frictionResult,frictionPool){this.contactPointPool=oldcontacts,this.frictionEquationPool=frictionPool,this.result=result,this.frictionResult=frictionResult;for(var qi=tmpQuat1,qj=tmpQuat2,xi=tmpVec1,xj=tmpVec2,k=0,N=p1.length;k!==N;k++){var bi=p1[k],bj=p2[k],bodyContactMaterial=null;bi.material&&bj.material&&(bodyContactMaterial=world.getContactMaterial(bi.material,bj.material)||null);for(var justTest=bi.type&Body.KINEMATIC&&bj.type&Body.STATIC||bi.type&Body.STATIC&&bj.type&Body.KINEMATIC||bi.type&Body.KINEMATIC&&bj.type&Body.KINEMATIC,i=0;isi.boundingSphereRadius+sj.boundingSphereRadius)){var shapeContactMaterial=null;si.material&&sj.material&&(shapeContactMaterial=world.getContactMaterial(si.material,sj.material)||null),this.currentContactMaterial=shapeContactMaterial||bodyContactMaterial||world.defaultContactMaterial;var resolver=this[si.type|sj.type];if(resolver){(si.type0&&positionAlongEdgeB<0&&(localSpherePos.vsub(edgeVertexA,tmp),edgeVectorUnit.copy(edgeVector),edgeVectorUnit.normalize(),positionAlongEdgeA=tmp.dot(edgeVectorUnit),edgeVectorUnit.scale(positionAlongEdgeA,tmp),tmp.vadd(edgeVertexA,tmp),(dist=tmp.distanceTo(localSpherePos))0){var ns1=sphereBox_ns1,ns2=sphereBox_ns2;ns1.copy(sides[(idx+1)%3]),ns2.copy(sides[(idx+2)%3]);var h1=ns1.norm(),h2=ns2.norm();ns1.normalize(),ns2.normalize();var dot1=box_to_sphere.dot(ns1),dot2=box_to_sphere.dot(ns2);if(dot1-h1&&dot2-h2){dist=Math.abs(dot-h-R);if((null===side_distance||dist0){for(var faceVerts=[],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)){if(justTest)return!0;found=!0;r=this.createContactEquation(bi,bj,si,sj,rsi,rsj);worldNormal.mult(-R,r.ri),worldNormal.negate(r.ni);var penetrationVec2=v3pool.get();worldNormal.mult(-penetration,penetrationVec2);var penetrationSpherePoint=v3pool.get();worldNormal.mult(-R,penetrationSpherePoint),xi.vsub(xj,r.rj),r.rj.vadd(penetrationSpherePoint,r.rj),r.rj.vadd(penetrationVec2,r.rj),r.rj.vadd(xj,r.rj),r.rj.vsub(bj.position,r.rj),r.ri.vadd(xi,r.ri),r.ri.vsub(bi.position,r.ri),v3pool.release(penetrationVec2),v3pool.release(penetrationSpherePoint),this.result.push(r),this.createFrictionEquationsFromContact(r,this.frictionResult);for(var j=0,Nfaceverts=faceVerts.length;j!==Nfaceverts;j++)v3pool.release(faceVerts[j]);return}for(j=0;j!==face.length;j++){var v1=v3pool.get(),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);var edge=sphereConvex_edge;v2.vsub(v1,edge);var edgeUnit=sphereConvex_edgeUnit;edge.unit(edgeUnit);var p=v3pool.get(),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);var xi_to_p=v3pool.get();if(p.vsub(xi,xi_to_p),dot>0&&dot*dotsi.boundingSphereRadius+sj.boundingSphereRadius)&&si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){var res=[],q=convexConvex_q;si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res);for(var numContacts=0,j=0;j!==res.length;j++){if(justTest)return!0;var r=this.createContactEquation(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),ri.vsub(xi,ri),rj.vsub(xj,rj),ri.vadd(xi,ri),ri.vsub(bi.position,ri),rj.vadd(xj,rj),rj.vsub(bj.position,rj),this.result.push(r),numContacts++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(r,this.frictionResult)}this.enableFrictionReduction&&numContacts&&this.createFrictionFromAverage(numContacts)}};var particlePlane_normal=new Vec3,particlePlane_relpos=new Vec3,particlePlane_projected=new Vec3;Narrowphase.prototype[Shape.types.PLANE|Shape.types.PARTICLE]=Narrowphase.prototype.planeParticle=function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){var normal=particlePlane_normal;normal.set(0,0,1),bj.quaternion.vmult(normal,normal);var relpos=particlePlane_relpos;if(xi.vsub(bj.position,relpos),normal.dot(relpos)<=0){if(justTest)return!0;var r=this.createContactEquation(bi,bj,si,sj,rsi,rsj);r.ni.copy(normal),r.ni.negate(r.ni),r.ri.set(0,0,0);var projected=particlePlane_projected;normal.mult(normal.dot(xi),projected),xi.vsub(projected,projected),r.rj.copy(projected),this.result.push(r),this.createFrictionEquationsFromContact(r,this.frictionResult)}};var particleSphere_normal=new Vec3;Narrowphase.prototype[Shape.types.PARTICLE|Shape.types.SPHERE]=Narrowphase.prototype.sphereParticle=function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){var normal=particleSphere_normal;if(normal.set(0,0,1),xi.vsub(xj,normal),normal.norm2()<=sj.radius*sj.radius){if(justTest)return!0;var r=this.createContactEquation(bi,bj,si,sj,rsi,rsj);normal.normalize(),r.rj.copy(normal),r.rj.mult(sj.radius,r.rj),r.ni.copy(normal),r.ni.negate(r.ni),r.ri.set(0,0,0),this.result.push(r),this.createFrictionEquationsFromContact(r,this.frictionResult)}};var cqj=new Quaternion,convexParticle_local=new Vec3,convexParticle_penetratedFaceNormal=(new Vec3,new Vec3),convexParticle_vertexToParticle=new Vec3,convexParticle_worldPenetrationVec=new Vec3;Narrowphase.prototype[Shape.types.PARTICLE|Shape.types.CONVEXPOLYHEDRON]=Narrowphase.prototype.convexParticle=function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){var penetratedFaceIndex=-1,penetratedFaceNormal=convexParticle_penetratedFaceNormal,worldPenetrationVec=convexParticle_worldPenetrationVec,minPenetration=null,numDetectedFaces=0,local=convexParticle_local;if(local.copy(xi),local.vsub(xj,local),qj.conjugate(cqj),cqj.vmult(local,local),sj.pointIsInside(local)){sj.worldVerticesNeedsUpdate&&sj.computeWorldVertices(xj,qj),sj.worldFaceNormalsNeedsUpdate&&sj.computeWorldFaceNormals(qj);for(var i=0,nfaces=sj.faces.length;i!==nfaces;i++){var verts=[sj.worldVertices[sj.faces[i][0]]],normal=sj.worldFaceNormals[i];xi.vsub(verts[0],convexParticle_vertexToParticle);var penetration=-normal.dot(convexParticle_vertexToParticle);if(null===minPenetration||Math.abs(penetration)data.length||iMinY>data[0].length)){iMinX<0&&(iMinX=0),iMaxX<0&&(iMaxX=0),iMinY<0&&(iMinY=0),iMaxY<0&&(iMaxY=0),iMinX>=data.length&&(iMinX=data.length-1),iMaxX>=data.length&&(iMaxX=data.length-1),iMaxY>=data[0].length&&(iMaxY=data[0].length-1),iMinY>=data[0].length&&(iMinY=data[0].length-1);var minMax=[];hfShape.getRectMinMax(iMinX,iMinY,iMaxX,iMaxY,minMax);var min=minMax[0],max=minMax[1];if(!(localConvexPos.z-radius>max||localConvexPos.z+radiusdata.length||iMaxY>data[0].length)){iMinX<0&&(iMinX=0),iMaxX<0&&(iMaxX=0),iMinY<0&&(iMinY=0),iMaxY<0&&(iMaxY=0),iMinX>=data.length&&(iMinX=data.length-1),iMaxX>=data.length&&(iMaxX=data.length-1),iMaxY>=data[0].length&&(iMaxY=data[0].length-1),iMinY>=data[0].length&&(iMinY=data[0].length-1);var minMax=[];hfShape.getRectMinMax(iMinX,iMinY,iMaxX,iMaxY,minMax);var min=minMax[0],max=minMax[1];if(!(localSpherePos.z-radius>max||localSpherePos.z+radius2)return}}}},{"../collision/AABB":5,"../collision/Ray":12,"../equations/ContactEquation":22,"../equations/FrictionEquation":24,"../math/Quaternion":31,"../math/Transform":32,"../math/Vec3":33,"../objects/Body":34,"../shapes/ConvexPolyhedron":41,"../shapes/Shape":46,"../solver/Solver":50,"../utils/Vec3Pool":57}],59:[function(require,module,exports){function World(options){options=options||{},EventTarget.apply(this),this.dt=-1,this.allowSleep=!!options.allowSleep,this.contacts=[],this.frictionEquations=[],this.quatNormalizeSkip=void 0!==options.quatNormalizeSkip?options.quatNormalizeSkip:0,this.quatNormalizeFast=void 0!==options.quatNormalizeFast&&options.quatNormalizeFast,this.time=0,this.stepnumber=0,this.default_dt=1/60,this.nextId=0,this.gravity=new Vec3,options.gravity&&this.gravity.copy(options.gravity),this.broadphase=void 0!==options.broadphase?options.broadphase:new NaiveBroadphase,this.bodies=[],this.solver=void 0!==options.solver?options.solver:new GSSolver,this.constraints=[],this.narrowphase=new Narrowphase(this),this.collisionMatrix=new ArrayCollisionMatrix,this.collisionMatrixPrevious=new ArrayCollisionMatrix,this.bodyOverlapKeeper=new OverlapKeeper,this.shapeOverlapKeeper=new OverlapKeeper,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new TupleDictionary,this.defaultMaterial=new Material("default"),this.defaultContactMaterial=new ContactMaterial(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.accumulator=0,this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.idToBodyMap={},this.broadphase.setWorld(this)}module.exports=World;require("../shapes/Shape");var Vec3=require("../math/Vec3"),Quaternion=require("../math/Quaternion"),GSSolver=require("../solver/GSSolver"),Narrowphase=(require("../equations/ContactEquation"),require("../equations/FrictionEquation"),require("./Narrowphase")),EventTarget=require("../utils/EventTarget"),ArrayCollisionMatrix=require("../collision/ArrayCollisionMatrix"),OverlapKeeper=require("../collision/OverlapKeeper"),Material=require("../material/Material"),ContactMaterial=require("../material/ContactMaterial"),Body=require("../objects/Body"),TupleDictionary=require("../utils/TupleDictionary"),RaycastResult=require("../collision/RaycastResult"),AABB=require("../collision/AABB"),Ray=require("../collision/Ray"),NaiveBroadphase=require("../collision/NaiveBroadphase");World.prototype=new EventTarget;new AABB;var tmpRay=new Ray;if(World.prototype.getContactMaterial=function(m1,m2){return this.contactMaterialTable.get(m1.id,m2.id)},World.prototype.numObjects=function(){return this.bodies.length},World.prototype.collisionMatrixTick=function(){var temp=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=temp,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()},World.prototype.add=World.prototype.addBody=function(body){-1===this.bodies.indexOf(body)&&(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,body instanceof Body&&(body.initAngularVelocity.copy(body.angularVelocity),body.initQuaternion.copy(body.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=body,this.idToBodyMap[body.id]=body,this.dispatchEvent(this.addBodyEvent))},World.prototype.addConstraint=function(c){this.constraints.push(c)},World.prototype.removeConstraint=function(c){var idx=this.constraints.indexOf(c);-1!==idx&&this.constraints.splice(idx,1)},World.prototype.rayTest=function(from,to,result){result instanceof RaycastResult?this.raycastClosest(from,to,{skipBackfaces:!0},result):this.raycastAll(from,to,{skipBackfaces:!0},result)},World.prototype.raycastAll=function(from,to,options,callback){return options.mode=Ray.ALL,options.from=from,options.to=to,options.callback=callback,tmpRay.intersectWorld(this,options)},World.prototype.raycastAny=function(from,to,options,result){return options.mode=Ray.ANY,options.from=from,options.to=to,options.result=result,tmpRay.intersectWorld(this,options)},World.prototype.raycastClosest=function(from,to,options,result){return options.mode=Ray.CLOSEST,options.from=from,options.to=to,options.result=result,tmpRay.intersectWorld(this,options)},World.prototype.remove=function(body){body.world=null;var n=this.bodies.length-1,bodies=this.bodies,idx=bodies.indexOf(body);if(-1!==idx){bodies.splice(idx,1);for(var i=0;i!==bodies.length;i++)bodies[i].index=i;this.collisionMatrix.setNumObjects(n),this.removeBodyEvent.body=body,delete this.idToBodyMap[body.id],this.dispatchEvent(this.removeBodyEvent)}},World.prototype.removeBody=World.prototype.remove,World.prototype.getBodyById=function(id){return this.idToBodyMap[id]},World.prototype.getShapeById=function(id){for(var bodies=this.bodies,i=0,bl=bodies.length;i=dt&&substeps=0;j-=1)(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(),doProfiling&&(profilingStart=performance.now());var oldcontacts=World_step_oldContacts,NoldContacts=contacts.length;for(i=0;i!==NoldContacts;i++)oldcontacts.push(contacts[i]);contacts.length=0;var NoldFrictionEquations=this.frictionEquations.length;for(i=0;i!==NoldFrictionEquations;i++)frictionEquationPool.push(this.frictionEquations[i]);this.frictionEquations.length=0,this.narrowphase.getContacts(p1,p2,this,contacts,oldcontacts,this.frictionEquations,frictionEquationPool),doProfiling&&(profile.narrowphase=performance.now()-profilingStart),doProfiling&&(profilingStart=performance.now());for(i=0;i=0&&bj.material.friction>=0&&bi.material.friction*bj.material.friction,bi.material.restitution>=0&&bj.material.restitution>=0&&(c.restitution=bi.material.restitution*bj.material.restitution)),solver.addEquation(c),bi.allowSleep&&bi.type===Body.DYNAMIC&&bi.sleepState===Body.SLEEPING&&bj.sleepState===Body.AWAKE&&bj.type!==Body.STATIC&&bj.velocity.norm2()+bj.angularVelocity.norm2()>=2*Math.pow(bj.sleepSpeedLimit,2)&&(bi._wakeUpAfterNarrowphase=!0),bj.allowSleep&&bj.type===Body.DYNAMIC&&bj.sleepState===Body.SLEEPING&&bi.sleepState===Body.AWAKE&&bi.type!==Body.STATIC&&bi.velocity.norm2()+bi.angularVelocity.norm2()>=2*Math.pow(bi.sleepSpeedLimit,2)&&(bj._wakeUpAfterNarrowphase=!0),this.collisionMatrix.set(bi,bj,!0),this.collisionMatrixPrevious.get(bi,bj)||(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)),this.bodyOverlapKeeper.set(bi.id,bj.id),this.shapeOverlapKeeper.set(si.id,sj.id)}for(this.emitContactEvents(),doProfiling&&(profile.makeContactConstraints=performance.now()-profilingStart,profilingStart=performance.now()),i=0;i!==N;i++)(bi=bodies[i])._wakeUpAfterNarrowphase&&(bi.wakeUp(),bi._wakeUpAfterNarrowphase=!1);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)}}solver.solve(dt,this),doProfiling&&(profile.solve=performance.now()-profilingStart),solver.removeAllEquations();var pow=Math.pow;for(i=0;i!==N;i++)if((bi=bodies[i]).type&DYNAMIC){var ld=pow(1-bi.linearDamping,dt),v=bi.velocity;v.mult(ld,v);var av=bi.angularVelocity;if(av){var ad=pow(1-bi.angularDamping,dt);av.mult(ad,av)}}for(this.dispatchEvent(World_step_preStepEvent),i=0;i!==N;i++)(bi=bodies[i]).preStep&&bi.preStep.call(bi);doProfiling&&(profilingStart=performance.now());var quatNormalize=this.stepnumber%(this.quatNormalizeSkip+1)==0,quatNormalizeFast=this.quatNormalizeFast;for(i=0;i!==N;i++)bodies[i].integrate(dt,quatNormalize,quatNormalizeFast);for(this.clearForces(),this.broadphase.dirty=!0,doProfiling&&(profile.integrate=performance.now()-profilingStart),this.time+=dt,this.stepnumber+=1,this.dispatchEvent(World_step_postStepEvent),i=0;i!==N;i++){var postStep=(bi=bodies[i]).postStep;postStep&&postStep.call(bi)}if(this.allowSleep)for(i=0;i!==N;i++)bodies[i].sleepTick(this.time)},World.prototype.emitContactEvents=function(){var additions=[],removals=[],beginContactEvent={type:"beginContact",bodyA:null,bodyB:null},endContactEvent={type:"endContact",bodyA:null,bodyB:null},beginShapeContactEvent={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},endShapeContactEvent={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};return function(){var hasBeginContact=this.hasAnyEventListener("beginContact"),hasEndContact=this.hasAnyEventListener("endContact");if((hasBeginContact||hasEndContact)&&this.bodyOverlapKeeper.getDiff(additions,removals),hasBeginContact){for(var i=0,l=additions.length;i2&&tmp.fromBufferGeometry(meshes[0].geometry):tmp=meshes[0].geometry.clone(),tmp.metadata=meshes[0].geometry.metadata,meshes[0].updateMatrixWorld(),meshes[0].matrixWorld.decompose(position,quaternion,scale),tmp.scale(scale.x,scale.y,scale.z)}for(;mesh=meshes.pop();)if(mesh.updateMatrixWorld(),mesh.geometry.isBufferGeometry){if(mesh.geometry.attributes.position&&mesh.geometry.attributes.position.itemSize>2){var tmpGeom=new THREE.Geometry;tmpGeom.fromBufferGeometry(mesh.geometry),combined.merge(tmpGeom,mesh.matrixWorld),tmpGeom.dispose()}}else combined.merge(mesh.geometry,mesh.matrixWorld);return(matrix=new THREE.Matrix4).scale(object.scale),combined.applyMatrix(matrix),combined}function getVertices(geometry){return geometry.attributes||(geometry=(new THREE.BufferGeometry).fromGeometry(geometry)),(geometry.attributes.position||{}).array||[]}function getMeshes(object){var meshes=[];return object.traverse(function(o){"Mesh"===o.type&&meshes.push(o)}),meshes}var CANNON=require("cannon"),quickhull=require("./lib/THREE.quickhull"),PI_2=Math.PI/2,Type={BOX:"Box",CYLINDER:"Cylinder",SPHERE:"Sphere",HULL:"ConvexPolyhedron",MESH:"Trimesh"},mesh2shape=function(object,options){var geometry;if((options=options||{}).type===Type.BOX)return createBoundingBoxShape(object);if(options.type===Type.CYLINDER)return createBoundingCylinderShape(object,options);if(options.type===Type.SPHERE)return createBoundingSphereShape(object,options);if(options.type===Type.HULL)return createConvexPolyhedron(object);if(options.type===Type.MESH)return geometry=getGeometry(object),geometry?createTrimeshShape(geometry):null;if(options.type)throw new Error('[CANNON.mesh2shape] Invalid type "%s".',options.type);if(!(geometry=getGeometry(object)))return null;switch(geometry.metadata?geometry.metadata.type:geometry.type){case"BoxGeometry":case"BoxBufferGeometry":return createBoxShape(geometry);case"CylinderGeometry":case"CylinderBufferGeometry":return createCylinderShape(geometry);case"PlaneGeometry":case"PlaneBufferGeometry":return createPlaneShape(geometry);case"SphereGeometry":case"SphereBufferGeometry":return createSphereShape(geometry);case"TubeGeometry":case"Geometry":case"BufferGeometry":return createBoundingBoxShape(object);default:return console.warn('Unrecognized geometry: "%s". Using bounding box as shape.',geometry.type),createBoxShape(geometry)}};mesh2shape.Type=Type,module.exports=CANNON.mesh2shape=mesh2shape},{"./lib/THREE.quickhull":61,cannon:4}],61:[function(require,module,exports){module.exports=function(){function reset(){ab=new THREE.Vector3,ac=new THREE.Vector3,ax=new THREE.Vector3,suba=new THREE.Vector3,subb=new THREE.Vector3,normal=new THREE.Vector3,diff=new THREE.Vector3,subaA=new THREE.Vector3,subaB=new THREE.Vector3,subC=new THREE.Vector3}function process(points){for(;faceStack.length>0;)cull(faceStack.shift(),points)}function getNormal(face,points){if(void 0!==face.normal)return face.normal;var p0=points[face[0]],p1=points[face[1]],p2=points[face[2]];return ab.subVectors(p1,p0),ac.subVectors(p2,p0),normal.crossVectors(ac,ab),normal.normalize(),face.normal=normal.clone()}function assignPoints(face,pointset,points){var p0=points[face[0]],dots=[],norm=getNormal(face,points);pointset.sort(function(aItem,bItem){return dots[aItem.x/3]=void 0!==dots[aItem.x/3]?dots[aItem.x/3]:norm.dot(suba.subVectors(aItem,p0)),dots[bItem.x/3]=void 0!==dots[bItem.x/3]?dots[bItem.x/3]:norm.dot(subb.subVectors(bItem,p0)),dots[aItem.x/3]-dots[bItem.x/3]});var index=pointset.length;for(1===index&&(dots[pointset[0].x/3]=norm.dot(suba.subVectors(pointset[0],p0)));index-- >0&&dots[pointset[index].x/3]>0;);index+10&&(face.visiblePoints=pointset.splice(index+1))}function cull(face,points){for(var currentFace,i=faces.length,visibleFaces=[face],apex=points.indexOf(face.visiblePoints.pop());i-- >0;)(currentFace=faces[i])!==face&&getNormal(currentFace,points).dot(diff.subVectors(points[apex],points[currentFace[0]]))>0&&visibleFaces.push(currentFace);var compareFace,nextIndex,a,b,j=i=visibleFaces.length,hasOneVisibleFace=1===i,perimeter=[],edgeIndex=0,allPoints=[];visibleFaces[0][0],visibleFaces[0][1],visibleFaces[0][1],visibleFaces[0][2],visibleFaces[0][2],visibleFaces[0][0];if(1===visibleFaces.length)perimeter=[(currentFace=visibleFaces[0])[0],currentFace[1],currentFace[1],currentFace[2],currentFace[2],currentFace[0]],faceStack.indexOf(currentFace)>-1&&faceStack.splice(faceStack.indexOf(currentFace),1),currentFace.visiblePoints&&(allPoints=allPoints.concat(currentFace.visiblePoints)),faces.splice(faces.indexOf(currentFace),1);else for(;i-- >0;){currentFace=visibleFaces[i],faceStack.indexOf(currentFace)>-1&&faceStack.splice(faceStack.indexOf(currentFace),1),currentFace.visiblePoints&&(allPoints=allPoints.concat(currentFace.visiblePoints)),faces.splice(faces.indexOf(currentFace),1);var isSharedEdge;for(cEdgeIndex=0;cEdgeIndex<3;){for(isSharedEdge=!1,j=visibleFaces.length,a=currentFace[cEdgeIndex],b=currentFace[(cEdgeIndex+1)%3];j-- >0&&!isSharedEdge;)if(compareFace=visibleFaces[j],edgeIndex=0,compareFace!==currentFace)for(;edgeIndex<3&&!isSharedEdge;)nextIndex=edgeIndex+1,isSharedEdge=compareFace[edgeIndex]===a&&compareFace[nextIndex%3]===b||compareFace[edgeIndex]===b&&compareFace[nextIndex%3]===a,edgeIndex++;isSharedEdge&&!hasOneVisibleFace||(perimeter.push(a),perimeter.push(b)),cEdgeIndex++}}i=0;for(var f,l=perimeter.length/2;i=f?bc.dot(bc):ac.dot(ac)-e*e/f}}();return function(geometry){for(reset(),points=geometry.vertices,faces=[],faceStack=[],i=NUM_POINTS=points.length,extremes=points.slice(0,6),max=0;i-- >0;)points[i].xextremes[1].x&&(extremes[1]=points[i]),points[i].y0;)for(j=i-1;j-- >0;)max<(dcur=extremes[i].distanceToSquared(extremes[j]))&&(max=dcur,v0=extremes[i],v1=extremes[j]);for(i=6,max=0;i-- >0;)dcur=distSqPointSegment(v0,v1,extremes[i]),max0;)dcur=Math.abs(points[i].dot(N)-D),max0;)assignPoints(tetrahedron[i],pointsCloned,points),void 0!==tetrahedron[i].visiblePoints&&faceStack.push(tetrahedron[i]),faces.push(tetrahedron[i]);process(points);for(var ll=faces.length;ll-- >0;)geometry.faces[ll]=new THREE.Face3(faces[ll][2],faces[ll][1],faces[ll][0],faces[ll].normal);return geometry.normalsNeedUpdate=!0,geometry}}()},{}],62:[function(require,module,exports){var bundleFn=arguments[3],sources=arguments[4],cache=arguments[5],stringify=JSON.stringify;module.exports=function(fn,options){function resolveSources(key){workerSources[key]=!0;for(var depPath in sources[key][1]){var depKey=sources[key][1][depPath];workerSources[depKey]||resolveSources(depKey)}}for(var wkey,cacheKeys=Object.keys(cache),i=0,l=cacheKeys.length;ithis.frameDelay;)this.frameBuffer.shift(),prevFrame=this.frameBuffer[0],nextFrame=this.frameBuffer[1];if(prevFrame&&nextFrame){var mix=(timestamp-prevFrame.timestamp)/this.frameDelay;mix=(mix-(1-1/this.interpBufferSize))*this.interpBufferSize;for(var id in prevFrame.bodies)prevFrame.bodies.hasOwnProperty(id)&&nextFrame.bodies.hasOwnProperty(id)&&protocol.deserializeInterpBodyUpdate(prevFrame.bodies[id],nextFrame.bodies[id],this.bodies[id],mix)}}},WorkerDriver.prototype.destroy=function(){this.worker.terminate(),delete this.worker},WorkerDriver.prototype._onMessage=function(event){if(event.data.type!==Event.STEP)throw new Error("[WorkerDriver] Unexpected message type.");var bodies=event.data.bodies;if(this.contacts=event.data.contacts,this.interpolate)this.frameBuffer.push({timestamp:performance.now(),bodies:bodies});else for(var id in bodies)bodies.hasOwnProperty(id)&&protocol.deserializeBodyUpdate(bodies[id],this.bodies[id])},WorkerDriver.prototype.addBody=function(body){protocol.assignID("body",body),this.bodies[body[ID]]=body,this.worker.postMessage({type:Event.ADD_BODY,body:protocol.serializeBody(body)})},WorkerDriver.prototype.removeBody=function(body){this.worker.postMessage({type:Event.REMOVE_BODY,bodyID:body[ID]}),delete this.bodies[body[ID]]},WorkerDriver.prototype.applyBodyMethod=function(body,methodName,args){switch(methodName){case"applyForce":case"applyImpulse":this.worker.postMessage({type:Event.APPLY_BODY_METHOD,bodyID:body[ID],methodName:methodName,args:[args[0].toArray(),args[1].toArray()]});break;default:throw new Error("Unexpected methodName: %s",methodName)}},WorkerDriver.prototype.updateBodyProperties=function(body){this.worker.postMessage({type:Event.UPDATE_BODY_PROPERTIES,body:protocol.serializeBody(body)})},WorkerDriver.prototype.getMaterial=function(name){},WorkerDriver.prototype.addMaterial=function(materialConfig){this.worker.postMessage({type:Event.ADD_MATERIAL,materialConfig:materialConfig})},WorkerDriver.prototype.addContactMaterial=function(matName1,matName2,contactMaterialConfig){this.worker.postMessage({type:Event.ADD_CONTACT_MATERIAL,materialName1:matName1,materialName2:matName2,contactMaterialConfig:contactMaterialConfig})},WorkerDriver.prototype.addConstraint=function(constraint){protocol.assignID("constraint",constraint),this.worker.postMessage({type:Event.ADD_CONSTRAINT,constraint:protocol.serializeConstraint(constraint)})},WorkerDriver.prototype.removeConstraint=function(constraint){this.worker.postMessage({type:Event.REMOVE_CONSTRAINT,constraintID:constraint[ID]})},WorkerDriver.prototype.getContacts=function(){var bodies=this.bodies;return this.contacts.map(function(message){return protocol.deserializeContact(message,bodies)})}},{"../utils/protocol":80,"./driver":71,"./event":72,"./webworkify-debug":75,"./worker":77,webworkify:62}],77:[function(require,module,exports){var Event=require("./event"),LocalDriver=require("./local-driver"),AmmoDriver=require("./ammo-driver"),protocol=require("../utils/protocol"),ID=protocol.ID;module.exports=function(self){function step(){driver.step(stepSize);var bodyMessages={};Object.keys(bodies).forEach(function(id){bodyMessages[id]=protocol.serializeBody(bodies[id])}),self.postMessage({type:Event.STEP,bodies:bodyMessages,contacts:driver.getContacts().map(protocol.serializeContact)})}var stepSize,driver=null,bodies={},constraints={};self.addEventListener("message",function(event){var data=event.data;switch(data.type){case Event.INIT:(driver="cannon"===data.engine?new LocalDriver:new AmmoDriver).init(data.worldConfig),stepSize=1/data.fps,setInterval(step,1e3/data.fps);break;case Event.ADD_BODY:var body=protocol.deserializeBody(data.body);body.material=driver.getMaterial("defaultMaterial"),bodies[body[ID]]=body,driver.addBody(body);break;case Event.REMOVE_BODY:driver.removeBody(bodies[data.bodyID]),delete bodies[data.bodyID];break;case Event.APPLY_BODY_METHOD:bodies[data.bodyID][data.methodName](protocol.deserializeVec3(data.args[0]),protocol.deserializeVec3(data.args[1]));break;case Event.UPDATE_BODY_PROPERTIES:protocol.deserializeBodyUpdate(data.body,bodies[data.body.id]);break;case Event.ADD_MATERIAL:driver.addMaterial(data.materialConfig);break;case Event.ADD_CONTACT_MATERIAL:driver.addContactMaterial(data.materialName1,data.materialName2,data.contactMaterialConfig);break;case Event.ADD_CONSTRAINT:var constraint=protocol.deserializeConstraint(data.constraint,bodies);constraints[constraint[ID]]=constraint,driver.addConstraint(constraint);break;case Event.REMOVE_CONSTRAINT:driver.removeConstraint(constraints[data.constraintID]),delete constraints[data.constraintID];break;default:throw new Error("[Worker] Unexpected event type: %s",data.type)}})}},{"../utils/protocol":80,"./ammo-driver":70,"./event":72,"./local-driver":73}],78:[function(require,module,exports){var CANNON=require("cannon"),CONSTANTS=require("./constants"),C_GRAV=CONSTANTS.GRAVITY,C_MAT=CONSTANTS.CONTACT_MATERIAL,LocalDriver=require("./drivers/local-driver"),WorkerDriver=require("./drivers/worker-driver"),NetworkDriver=require("./drivers/network-driver");require("./drivers/ammo-driver");module.exports=AFRAME.registerSystem("physics",{schema:{driver:{default:"local",oneOf:["local","worker","network","ammo"]},networkUrl:{default:"",if:{driver:"network"}},workerFps:{default:60,if:{driver:"worker"}},workerInterpolate:{default:!0,if:{driver:"worker"}},workerInterpBufferSize:{default:2,if:{driver:"worker"}},workerEngine:{default:"cannon",if:{driver:"worker"},oneOf:["cannon"]},workerDebug:{default:!1,if:{driver:"worker"}},gravity:{default:C_GRAV},iterations:{default:CONSTANTS.ITERATIONS},friction:{default:C_MAT.friction},restitution:{default:C_MAT.restitution},contactEquationStiffness:{default:C_MAT.contactEquationStiffness},contactEquationRelaxation:{default:C_MAT.contactEquationRelaxation},frictionEquationStiffness:{default:C_MAT.frictionEquationStiffness},frictionEquationRegularization:{default:C_MAT.frictionEquationRegularization},maxInterval:{default:4/60},debug:{default:!1}},init:function(){var data=this.data;switch(this.debug=data.debug,this.callbacks={beforeStep:[],step:[],afterStep:[]},this.listeners={},this.driver=null,data.driver){case"local":this.driver=new LocalDriver;break;case"network":this.driver=new NetworkDriver(data.networkUrl);break;case"worker":this.driver=new WorkerDriver({fps:data.workerFps,engine:data.workerEngine,interpolate:data.workerInterpolate,interpolationBufferSize:data.workerInterpBufferSize,debug:data.workerDebug});break;default:throw new Error('[physics] Driver not recognized: "%s".',data.driver)}this.driver.init({quatNormalizeSkip:0,quatNormalizeFast:!1,solverIterations:data.iterations,gravity:data.gravity}),this.driver.addMaterial({name:"defaultMaterial"}),this.driver.addContactMaterial("defaultMaterial","defaultMaterial",{friction:data.friction,restitution:data.restitution,contactEquationStiffness:data.contactEquationStiffness,contactEquationRelaxation:data.contactEquationRelaxation,frictionEquationStiffness:data.frictionEquationStiffness,frictionEquationRegularization:data.frictionEquationRegularization})},tick:function(t,dt){if(dt){var i,callbacks=this.callbacks;for(i=0;i=1)return b;var x=a[0],y=a[1],z=a[2],w=a[3],cosHalfTheta=w*b[3]+x*b[0]+y*b[1]+z*b[2];if(!(cosHalfTheta<0))return b;if((a=a.slice())[3]=-b[3],a[0]=-b[0],a[1]=-b[1],a[2]=-b[2],(cosHalfTheta=-cosHalfTheta)>=1)return a[3]=w,a[0]=x,a[1]=y,a[2]=z,this;var sinHalfTheta=Math.sqrt(1-cosHalfTheta*cosHalfTheta);if(Math.abs(sinHalfTheta)<.001)return a[3]=.5*(w+a[3]),a[0]=.5*(x+a[0]),a[1]=.5*(y+a[1]),a[2]=.5*(z+a[2]),this;var halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta),ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta,ratioB=Math.sin(t*halfTheta)/sinHalfTheta;return a[3]=w*ratioA+a[3]*ratioB,a[0]=x*ratioA+a[0]*ratioB,a[1]=y*ratioA+a[1]*ratioB,a[2]=z*ratioA+a[2]*ratioB,a}},{}],80:[function(require,module,exports){function serializeShape(shape){var shapeMsg={type:shape.type};if(shape.type===CANNON.Shape.types.BOX)shapeMsg.halfExtents=serializeVec3(shape.halfExtents);else if(shape.type===CANNON.Shape.types.SPHERE)shapeMsg.radius=shape.radius;else{if(shape._type!==CANNON.Shape.types.CYLINDER)throw new Error("Unimplemented shape type: %s",shape.type);shapeMsg.type=CANNON.Shape.types.CYLINDER,shapeMsg.radiusTop=shape.radiusTop,shapeMsg.radiusBottom=shape.radiusBottom,shapeMsg.height=shape.height,shapeMsg.numSegments=shape.numSegments}return shapeMsg}function deserializeShape(message){var shape;if(message.type===CANNON.Shape.types.BOX)shape=new CANNON.Box(deserializeVec3(message.halfExtents));else if(message.type===CANNON.Shape.types.SPHERE)shape=new CANNON.Sphere(message.radius);else{if(message.type!==CANNON.Shape.types.CYLINDER)throw new Error("Unimplemented shape type: %s",message.type);(shape=new CANNON.Cylinder(message.radiusTop,message.radiusBottom,message.height,message.numSegments))._type=CANNON.Shape.types.CYLINDER}return shape}function serializeVec3(vec3){return vec3.toArray()}function deserializeVec3(message){return new CANNON.Vec3(message[0],message[1],message[2])}function serializeQuaternion(quat){return quat.toArray()}function deserializeQuaternion(message){return new CANNON.Quaternion(message[0],message[1],message[2],message[3])}var CANNON=require("cannon"),mathUtils=require("./math"),ID="__id";module.exports.ID=ID;var nextID={};module.exports.assignID=function(prefix,object){object[ID]||(nextID[prefix]=nextID[prefix]||1,object[ID]=prefix+"_"+nextID[prefix]++)},module.exports.serializeBody=function(body){return{shapes:body.shapes.map(serializeShape),shapeOffsets:body.shapeOffsets.map(serializeVec3),shapeOrientations:body.shapeOrientations.map(serializeQuaternion),position:serializeVec3(body.position),quaternion:body.quaternion.toArray(),velocity:serializeVec3(body.velocity),angularVelocity:serializeVec3(body.angularVelocity),id:body[ID],mass:body.mass,linearDamping:body.linearDamping,angularDamping:body.angularDamping,fixedRotation:body.fixedRotation,allowSleep:body.allowSleep,sleepSpeedLimit:body.sleepSpeedLimit,sleepTimeLimit:body.sleepTimeLimit}},module.exports.deserializeBodyUpdate=function(message,body){return body.position.set(message.position[0],message.position[1],message.position[2]),body.quaternion.set(message.quaternion[0],message.quaternion[1],message.quaternion[2],message.quaternion[3]),body.velocity.set(message.velocity[0],message.velocity[1],message.velocity[2]),body.angularVelocity.set(message.angularVelocity[0],message.angularVelocity[1],message.angularVelocity[2]),body.linearDamping=message.linearDamping,body.angularDamping=message.angularDamping,body.fixedRotation=message.fixedRotation,body.allowSleep=message.allowSleep,body.sleepSpeedLimit=message.sleepSpeedLimit,body.sleepTimeLimit=message.sleepTimeLimit,body.mass!==message.mass&&(body.mass=message.mass,body.updateMassProperties()),body},module.exports.deserializeInterpBodyUpdate=function(message1,message2,body,mix){var weight1=1-mix,weight2=mix;body.position.set(message1.position[0]*weight1+message2.position[0]*weight2,message1.position[1]*weight1+message2.position[1]*weight2,message1.position[2]*weight1+message2.position[2]*weight2);var quaternion=mathUtils.slerp(message1.quaternion,message2.quaternion,mix);return body.quaternion.set(quaternion[0],quaternion[1],quaternion[2],quaternion[3]),body.velocity.set(message1.velocity[0]*weight1+message2.velocity[0]*weight2,message1.velocity[1]*weight1+message2.velocity[1]*weight2,message1.velocity[2]*weight1+message2.velocity[2]*weight2),body.angularVelocity.set(message1.angularVelocity[0]*weight1+message2.angularVelocity[0]*weight2,message1.angularVelocity[1]*weight1+message2.angularVelocity[1]*weight2,message1.angularVelocity[2]*weight1+message2.angularVelocity[2]*weight2),body.linearDamping=message2.linearDamping,body.angularDamping=message2.angularDamping,body.fixedRotation=message2.fixedRotation,body.allowSleep=message2.allowSleep,body.sleepSpeedLimit=message2.sleepSpeedLimit,body.sleepTimeLimit=message2.sleepTimeLimit,body.mass!==message2.mass&&(body.mass=message2.mass,body.updateMassProperties()),body},module.exports.deserializeBody=function(message){for(var shapeMsg,body=new CANNON.Body({mass:message.mass,position:deserializeVec3(message.position),quaternion:deserializeQuaternion(message.quaternion),velocity:deserializeVec3(message.velocity),angularVelocity:deserializeVec3(message.angularVelocity),linearDamping:message.linearDamping,angularDamping:message.angularDamping,fixedRotation:message.fixedRotation,allowSleep:message.allowSleep,sleepSpeedLimit:message.sleepSpeedLimit,sleepTimeLimit:message.sleepTimeLimit}),i=0;shapeMsg=message.shapes[i];i++)body.addShape(deserializeShape(shapeMsg),deserializeVec3(message.shapeOffsets[i]),deserializeQuaternion(message.shapeOrientations[i]));return body[ID]=message.id,body},module.exports.serializeShape=serializeShape,module.exports.deserializeShape=deserializeShape,module.exports.serializeConstraint=function(constraint){var message={id:constraint[ID],type:constraint.type,maxForce:constraint.maxForce,bodyA:constraint.bodyA[ID],bodyB:constraint.bodyB[ID]};switch(constraint.type){case"LockConstraint":break;case"DistanceConstraint":message.distance=constraint.distance;break;case"HingeConstraint":case"ConeTwistConstraint":message.axisA=serializeVec3(constraint.axisA),message.axisB=serializeVec3(constraint.axisB),message.pivotA=serializeVec3(constraint.pivotA),message.pivotB=serializeVec3(constraint.pivotB);break;case"PointToPointConstraint":message.pivotA=serializeVec3(constraint.pivotA),message.pivotB=serializeVec3(constraint.pivotB);break;default:throw new Error("Unexpected constraint type: "+constraint.type+'. You may need to manually set `constraint.type = "FooConstraint";`.')}return message},module.exports.deserializeConstraint=function(message,bodies){var constraint,TypedConstraint=CANNON[message.type],bodyA=bodies[message.bodyA],bodyB=bodies[message.bodyB];switch(message.type){case"LockConstraint":constraint=new CANNON.LockConstraint(bodyA,bodyB,message);break;case"DistanceConstraint":constraint=new CANNON.DistanceConstraint(bodyA,bodyB,message.distance,message.maxForce);break;case"HingeConstraint":case"ConeTwistConstraint":constraint=new TypedConstraint(bodyA,bodyB,{pivotA:deserializeVec3(message.pivotA),pivotB:deserializeVec3(message.pivotB),axisA:deserializeVec3(message.axisA),axisB:deserializeVec3(message.axisB),maxForce:message.maxForce});break;case"PointToPointConstraint":constraint=new CANNON.PointToPointConstraint(bodyA,deserializeVec3(message.pivotA),bodyB,deserializeVec3(message.pivotB),message.maxForce);break;default:throw new Error("Unexpected constraint type: "+message.type)}return constraint[ID]=message.id,constraint},module.exports.serializeContact=function(contact){return{bi:contact.bi[ID],bj:contact.bj[ID],ni:serializeVec3(contact.ni),ri:serializeVec3(contact.ri),rj:serializeVec3(contact.rj)}},module.exports.deserializeContact=function(message,bodies){return{bi:bodies[message.bi],bj:bodies[message.bj],ni:deserializeVec3(message.ni),ri:deserializeVec3(message.ri),rj:deserializeVec3(message.rj)}},module.exports.serializeVec3=serializeVec3,module.exports.deserializeVec3=deserializeVec3,module.exports.serializeQuaternion=serializeQuaternion,module.exports.deserializeQuaternion=deserializeQuaternion},{"./math":79,cannon:4}]},{},[1]); \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 40a2394..3e732ae 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "aframe-physics-system", - "version": "3.0.1", + "version": "3.0.2", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 11f8a6b..6e588d3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "aframe-physics-system", - "version": "3.0.1", + "version": "3.0.2", "description": "Physics system for A-Frame VR, built on Cannon.js", "main": "index.js", "scripts": {